blob: 104f0171d28e62547ccfdaf18438b30afd69f36d [file] [log] [blame]
rootff0769a2025-05-18 17:24:41 +00001package trackertest;
rootd4959a82025-05-27 07:07:37 +00002
3import java.io.File;
rootff0769a2025-05-18 17:24:41 +00004import java.util.Collection;
5import java.util.HashMap;
6import java.util.List;
7import java.util.Map;
8import java.util.Random;
rootf35409f2025-05-19 04:41:57 +00009import java.util.UUID;
rootff0769a2025-05-18 17:24:41 +000010import java.util.stream.Collectors;
rootf35409f2025-05-19 04:41:57 +000011import java.util.stream.IntStream;
rootff0769a2025-05-18 17:24:41 +000012
13import javax.persistence.EntityManager;
14import javax.persistence.EntityManagerFactory;
rootf35409f2025-05-19 04:41:57 +000015import javax.persistence.EntityTransaction;
rootff0769a2025-05-18 17:24:41 +000016import javax.persistence.Persistence;
17
18import org.junit.jupiter.api.AfterAll;
19import org.junit.jupiter.api.Assertions;
20import org.junit.jupiter.api.BeforeAll;
21import org.junit.jupiter.api.DynamicTest;
22import org.junit.jupiter.api.TestFactory;
23
rootd4959a82025-05-27 07:07:37 +000024import entity.Seed;
rootf35409f2025-05-19 04:41:57 +000025import entity.TransRecord;
26import entity.TransportId;
rootff0769a2025-05-18 17:24:41 +000027import entity.config;
28import tracker.Tracker;
29
30public class TrackerTest {
31 private static EntityManagerFactory emf;
32 private static EntityManager em;
33 private static List<String> userIds;
34 private static Map<String, Long> originalUploads;
35 private static Tracker tracker;
36
37 @BeforeAll
38 static void setup() throws Exception {
39 // 强制加载 MySQL 驱动,否则无法建立连接
40 Class.forName("com.mysql.cj.jdbc.Driver");
41 config cfg = new config();
42 Map<String,Object> props = new HashMap<>();
43 // 添加时区和 SSL 参数
44 String jdbcUrl = String.format(
45 "jdbc:mysql://%s/%s?useSSL=false&serverTimezone=UTC",
46 cfg.SqlURL, cfg.TestDatabase);
47 props.put("javax.persistence.jdbc.url", jdbcUrl);
48 props.put("javax.persistence.jdbc.user", cfg.SqlUsername);
49 props.put("javax.persistence.jdbc.password", cfg.SqlPassword);
50 props.put("javax.persistence.jdbc.driver", "com.mysql.cj.jdbc.Driver");
51 emf = Persistence.createEntityManagerFactory("myPersistenceUnit", props);
52 em = emf.createEntityManager();
53 // 使用简单实体名而非带包名前缀
54 userIds = em.createQuery(
55 "select u.userid from UserPT u", String.class
56 ).getResultList();
57
58 // 保存初始 upload 值
59 originalUploads = new HashMap<>();
60 for (String uid : userIds) {
61 Long up = em.createQuery(
62 "select u.upload from UserPT u where u.userid = :uid", Long.class
63 ).setParameter("uid", uid)
64 .getSingleResult();
65 originalUploads.put(uid, up != null ? up : 0L);
66 }
67 tracker = new Tracker(emf);
68 }
69
70 @AfterAll
71 static void teardown() {
rootd4959a82025-05-27 07:07:37 +000072 // 清理:删除测试过程中保存的所有 torrent 文件
73 File storageDir = new File(config.TORRENT_STORAGE_DIR);
74 if (storageDir.exists() && storageDir.isDirectory()) {
75 File[] files = storageDir.listFiles();
76 if (files != null) {
77 for (File f : files) {
78 if (f.isFile()) {
79 f.delete();
80 }
81 }
82 }
83 }
84
rootff0769a2025-05-18 17:24:41 +000085 if (em != null && em.isOpen()) em.close();
86 if (emf != null && emf.isOpen()) emf.close();
87 }
88
89 @TestFactory
90 Collection<DynamicTest> testAddUpLoad() {
91 Random rnd = new Random();
92 return userIds.stream()
93 .map(uid -> DynamicTest.dynamicTest("AddUpLoad for user " + uid, () -> {
94 int delta = rnd.nextInt(1000) + 1; // Ensure non-zero value
95 long before = originalUploads.get(uid);
96
rootf35409f2025-05-19 04:41:57 +000097 // AddUpLoad 前打印
98 System.out.println("Running AddUpLoad assert for user=" + uid + ", delta=" + delta);
rootff0769a2025-05-18 17:24:41 +000099 Assertions.assertFalse(tracker.AddUpLoad(uid, delta),
100 "AddUpLoad should return false on successful operation");
rootf35409f2025-05-19 04:41:57 +0000101 System.out.println("AddUpLoad assert passed for user=" + uid);
102
rootff0769a2025-05-18 17:24:41 +0000103 // Clear the persistence context to ensure fresh data is fetched
104 em.clear();
105
106 // Fetch updated value
107 Long after = em.createQuery(
108 "select u.upload from UserPT u where u.userid = :uid", Long.class
109 ).setParameter("uid", uid)
110 .getSingleResult();
rootf35409f2025-05-19 04:41:57 +0000111
112 // upload 值断言前打印
113 System.out.println("Running upload-value assert for user=" + uid);
rootff0769a2025-05-18 17:24:41 +0000114 Assertions.assertEquals(before + delta, after,
115 "Upload value should be increased by " + delta);
rootf35409f2025-05-19 04:41:57 +0000116 System.out.println("Upload-value assert passed for user=" + uid);
rootff0769a2025-05-18 17:24:41 +0000117
rootf35409f2025-05-19 04:41:57 +0000118 // ReduceUpLoad 前打印
119 System.out.println("Running ReduceUpLoad assert for user=" + uid + ", delta=" + delta);
rootff0769a2025-05-18 17:24:41 +0000120 Assertions.assertFalse(tracker.ReduceUpLoad(uid, delta),
121 "ReduceUpLoad should return false on successful operation");
rootf35409f2025-05-19 04:41:57 +0000122 System.out.println("ReduceUpLoad assert passed for user=" + uid);
rootff0769a2025-05-18 17:24:41 +0000123 }))
124 .collect(Collectors.toList());
125 }
126
127 @TestFactory
128 Collection<DynamicTest> testReduceUpLoad() {
129 Random rnd = new Random();
130 return userIds.stream()
131 .map(uid -> DynamicTest.dynamicTest("ReduceUpLoad for user " + uid, () -> {
132 long before = originalUploads.get(uid);
133 int max = (int)Math.min(before, 1000);
134 int delta = max > 0 ? rnd.nextInt(max) + 1 : 0;
135 if (delta == 0) return; // 无可减量时跳过
rootf35409f2025-05-19 04:41:57 +0000136
137 // ReduceUpLoad 前打印
138 System.out.println("Running ReduceUpLoad assert for user=" + uid + ", delta=" + delta);
rootff0769a2025-05-18 17:24:41 +0000139 Assertions.assertFalse(tracker.ReduceUpLoad(uid, delta));
rootf35409f2025-05-19 04:41:57 +0000140 System.out.println("ReduceUpLoad assert passed for user=" + uid);
141
rootff0769a2025-05-18 17:24:41 +0000142 Long after = em.createQuery(
143 "select u.upload from UserPT u where u.userid = :uid", Long.class
144 ).setParameter("uid", uid)
145 .getSingleResult();
rootf35409f2025-05-19 04:41:57 +0000146
147 // 减少后值断言前打印
148 System.out.println("Running post-reduce-value assert for user=" + uid);
rootff0769a2025-05-18 17:24:41 +0000149 Assertions.assertEquals(before - delta, after);
rootf35409f2025-05-19 04:41:57 +0000150 System.out.println("Post-reduce-value assert passed for user=" + uid);
151
152 // 回滚 AddUpLoad 前打印
153 System.out.println("Running rollback AddUpLoad assert for user=" + uid + ", delta=" + delta);
rootff0769a2025-05-18 17:24:41 +0000154 Assertions.assertFalse(tracker.AddUpLoad(uid, delta));
rootf35409f2025-05-19 04:41:57 +0000155 System.out.println("Rollback AddUpLoad assert passed for user=" + uid);
156 }))
157 .collect(Collectors.toList());
158 }
159
160 @TestFactory
161 Collection<DynamicTest> testAddDownload() {
162 Random rnd = new Random();
163 return userIds.stream()
164 .map(uid -> DynamicTest.dynamicTest("AddDownload for user " + uid, () -> {
165 int delta = rnd.nextInt(1000) + 1;
166 Long before = em.createQuery(
167 "select u.download from UserPT u where u.userid = :uid", Long.class
168 ).setParameter("uid", uid).getSingleResult();
169 before = before != null ? before : 0L;
170
171 System.out.println("Running AddDownload assert for user=" + uid + ", delta=" + delta);
172 Assertions.assertFalse(tracker.AddDownload(uid, delta),
173 "AddDownload should return false on successful operation");
174 em.clear();
175
176 Long after = em.createQuery(
177 "select u.download from UserPT u where u.userid = :uid", Long.class
178 ).setParameter("uid", uid).getSingleResult();
179 System.out.println("Running download-value assert for user=" + uid);
180 Assertions.assertEquals(before + delta, after,
181 "Download value should be increased by " + delta);
182
183 System.out.println("Running rollback ReduceDownload assert for user=" + uid + ", delta=" + delta);
184 Assertions.assertFalse(tracker.ReduceDownload(uid, delta),
185 "Rollback ReduceDownload should return false");
186 }))
187 .collect(Collectors.toList());
188 }
189
190 @TestFactory
191 Collection<DynamicTest> testReduceDownload() {
192 Random rnd = new Random();
193 return userIds.stream()
194 .map(uid -> DynamicTest.dynamicTest("ReduceDownload for user " + uid, () -> {
195 Long before = em.createQuery(
196 "select u.download from UserPT u where u.userid = :uid", Long.class
197 ).setParameter("uid", uid).getSingleResult();
198 before = before != null ? before : 0L;
199 int max = before.intValue();
200 int delta = max > 0 ? rnd.nextInt(max) + 1 : 0;
201 if (delta == 0) return;
202
203 System.out.println("Running ReduceDownload assert for user=" + uid + ", delta=" + delta);
204 Assertions.assertFalse(tracker.ReduceDownload(uid, delta));
205 Long after = em.createQuery(
206 "select u.download from UserPT u where u.userid = :uid", Long.class
207 ).setParameter("uid", uid).getSingleResult();
208 System.out.println("Running post-reduce-download-value assert for user=" + uid);
209 Assertions.assertEquals(before - delta, after);
210
211 System.out.println("Running rollback AddDownload assert for user=" + uid + ", delta=" + delta);
212 Assertions.assertFalse(tracker.AddDownload(uid, delta));
213 }))
214 .collect(Collectors.toList());
215 }
216
217 @TestFactory
218 Collection<DynamicTest> testAddMagic() {
219 Random rnd = new Random();
220 return userIds.stream()
221 .map(uid -> DynamicTest.dynamicTest("AddMagic for user " + uid, () -> {
222 int delta = rnd.nextInt(1000) + 1;
223 Integer before = em.createQuery(
224 "select u.magic from UserPT u where u.userid = :uid", Integer.class
225 ).setParameter("uid", uid).getSingleResult();
226 before = before != null ? before : 0;
227
228 System.out.println("Running AddMagic assert for user=" + uid + ", delta=" + delta);
229 Assertions.assertFalse(tracker.AddMagic(uid, delta));
230 em.clear();
231
232 Integer after = em.createQuery(
233 "select u.magic from UserPT u where u.userid = :uid", Integer.class
234 ).setParameter("uid", uid).getSingleResult();
235 System.out.println("Running magic-value assert for user=" + uid);
236 Assertions.assertEquals(before + delta, after.intValue());
237
238 System.out.println("Running rollback ReduceMagic assert for user=" + uid + ", delta=" + delta);
239 Assertions.assertFalse(tracker.ReduceMagic(uid, delta));
240 }))
241 .collect(Collectors.toList());
242 }
243
244 @TestFactory
245 Collection<DynamicTest> testReduceMagic() {
246 Random rnd = new Random();
247 return userIds.stream()
248 .map(uid -> DynamicTest.dynamicTest("ReduceMagic for user " + uid, () -> {
249 Integer before = em.createQuery(
250 "select u.magic from UserPT u where u.userid = :uid", Integer.class
251 ).setParameter("uid", uid).getSingleResult();
252 before = before != null ? before : 0;
253 int max = before.intValue();
254 int delta = max > 0 ? rnd.nextInt(max) + 1 : 0;
255 if (delta == 0) return;
256
257 System.out.println("Running ReduceMagic assert for user=" + uid + ", delta=" + delta);
258 Assertions.assertFalse(tracker.ReduceMagic(uid, delta));
259 Integer after = em.createQuery(
260 "select u.magic from UserPT u where u.userid = :uid", Integer.class
261 ).setParameter("uid", uid).getSingleResult();
262 System.out.println("Running post-reduce-magic-value assert for user=" + uid);
263 Assertions.assertEquals(before - delta, after.intValue());
264
265 System.out.println("Running rollback AddMagic assert for user=" + uid + ", delta=" + delta);
266 Assertions.assertFalse(tracker.AddMagic(uid, delta));
267 }))
268 .collect(Collectors.toList());
269 }
270
271 @TestFactory
272 Collection<DynamicTest> testAddRecord() {
273 Random rnd = new Random();
274 // 取所有 seed_id 用于外键测试
275 List<String> seedIds = em.createQuery(
276 "select s.seedid from Seed s", String.class
277 ).getResultList();
278 // 若无可用 seedId 则跳过此组测试,避免 rnd.nextInt(0) 抛错
279 // if (seedIds.isEmpty()) {
280 // return Collections.emptyList();
281 // }
282 return IntStream.range(0, 10)
283 .mapToObj(i -> DynamicTest.dynamicTest("AddRecord test #" + i, () -> {
284 // 随机构造 TransRecord
285 String uploaderId = userIds.get(rnd.nextInt(userIds.size()));
286 String downloaderId = userIds.get(rnd.nextInt(userIds.size()));
287 String seedId = seedIds.get(rnd.nextInt(seedIds.size()));
288 String taskId = UUID.randomUUID().toString();
289
290 TransRecord rd = new TransRecord();
291 rd.taskid = taskId;
292 rd.uploaduserid = uploaderId;
293 rd.downloaduserid = downloaderId;
294 rd.seedid = seedId;
295 rd.upload = rnd.nextInt(10000);
296 rd.download = rnd.nextInt(10000);
297 rd.maxupload = rd.upload + rnd.nextInt(10000);
298 rd.maxdownload = rd.download + rnd.nextInt(10000);
299
300 // 调用待测方法
301 int ret = tracker.AddRecord(rd);
302 Assertions.assertTrue(ret > 0, "返回值应为新记录主键");
303
304 // 验证已插入
305 TransportId pk = new TransportId(taskId, uploaderId, downloaderId);
306 TransRecord fetched = em.find(TransRecord.class, pk);
307 Assertions.assertNotNull(fetched, "应查询到新增的 TransRecord");
308
309 // 清理:删除测试记录
310 EntityTransaction tx = em.getTransaction();
311 tx.begin();
312 em.remove(fetched);
313 tx.commit();
rootff0769a2025-05-18 17:24:41 +0000314 }))
315 .collect(Collectors.toList());
316 }
rootd4959a82025-05-27 07:07:37 +0000317
318 @TestFactory
319 Collection<DynamicTest> testSaveTorrent() {
320 List<String> seedIds = em.createQuery(
321 "select s.seedid from Seed s", String.class
322 ).getResultList();
323 return seedIds.stream()
324 .map(sid -> DynamicTest.dynamicTest("SaveTorrent for seed " + sid, () -> {
325 // 准备一个临时空文件
326 File temp = File.createTempFile(sid + "_test", ".torrent");
327 // 调用 SaveTorrent
328 int ret = tracker.SaveTorrent(sid, temp);
329 Assertions.assertEquals(0, ret, "SaveTorrent 应返回 0");
330
331 // 验证文件已按约定存储
332 File stored = new File(config.TORRENT_STORAGE_DIR,
333 sid + "_" + temp.getName());
334 Assertions.assertTrue(stored.exists(), "存储文件应存在");
335
336 // 验证数据库中 url 字段已更新
337 em.clear();
338 Seed seed = em.find(Seed.class, sid);
339 // 将 seed.url 转为 File 再取绝对路径进行比较
340 Assertions.assertEquals(
341 stored.getAbsolutePath(),
342 new File(seed.url).getAbsolutePath(),
343 "Seed.url 应更新为存储路径"
344 );
345
346 // 清理测试文件
347 stored.delete();
348 temp.delete();
349 }))
350 .collect(Collectors.toList());
351 }
352
353 @TestFactory
354 Collection<DynamicTest> testGetTTorent() {
355 // 拿到所有 seedid
356 List<String> seedIds = em.createQuery(
357 "select s.seedid from Seed s", String.class
358 ).getResultList();
359 return seedIds.stream()
360 .map(sid -> DynamicTest.dynamicTest("GetTTorent for seed " + sid, () -> {
361 // 准备一个临时空文件并 SaveTorrent
362 File temp = File.createTempFile(sid + "_test", ".torrent");
363 int saveRet = tracker.SaveTorrent(sid, temp);
364 Assertions.assertEquals(0, saveRet, "SaveTorrent 应返回 0");
365
366 // 刷新上下文并取回更新后的 seed 实体
367 em.clear();
368 Seed seed = em.find(Seed.class, sid);
369 Assertions.assertNotNull(seed.url, "Seed.url 应已被更新");
370
371 // 调用 GetTTorent 并断言路径一致
372 String uid = userIds.get(0), ip = "127.0.0.1";
373 File ret = tracker.GetTTorent(sid, uid, ip);
374 File expected = new File(seed.url);
375 Assertions.assertNotNull(ret, "应返回文件对象");
376 Assertions.assertEquals(
377 expected.getAbsolutePath(),
378 ret.getAbsolutePath(),
379 "返回文件路径应与Seed.url一致"
380 );
381
382 // 清理:删掉本地文件,回滚 DB url 字段,删掉 temp
383 expected.delete();
384 EntityTransaction tx = em.getTransaction();
385 tx.begin();
386 seed.url = null;
387 em.merge(seed);
388 tx.commit();
389 temp.delete();
390 }))
391 .collect(Collectors.toList());
392 }
rootff0769a2025-05-18 17:24:41 +0000393}