blob: c307ba655d3489006ba26dea1359e8a22bb7d534 [file] [log] [blame]
rootff0769a2025-05-18 17:24:41 +00001package trackertest;
rootd4959a82025-05-27 07:07:37 +00002import java.io.File;
rootff0769a2025-05-18 17:24:41 +00003import java.util.Collection;
4import java.util.HashMap;
5import java.util.List;
6import java.util.Map;
7import java.util.Random;
rootf35409f2025-05-19 04:41:57 +00008import java.util.UUID;
rootff0769a2025-05-18 17:24:41 +00009import java.util.stream.Collectors;
rootf35409f2025-05-19 04:41:57 +000010import java.util.stream.IntStream;
Raveraae06122025-06-05 08:13:35 +000011
rootff0769a2025-05-18 17:24:41 +000012import javax.persistence.EntityManager;
13import javax.persistence.EntityManagerFactory;
rootf35409f2025-05-19 04:41:57 +000014import javax.persistence.EntityTransaction;
rootff0769a2025-05-18 17:24:41 +000015import javax.persistence.Persistence;
Raveraae06122025-06-05 08:13:35 +000016
rootff0769a2025-05-18 17:24:41 +000017import org.junit.jupiter.api.AfterAll;
18import org.junit.jupiter.api.Assertions;
19import org.junit.jupiter.api.BeforeAll;
20import org.junit.jupiter.api.DynamicTest;
21import org.junit.jupiter.api.TestFactory;
Raveraae06122025-06-05 08:13:35 +000022
rootd4959a82025-05-27 07:07:37 +000023import entity.Seed;
rootf35409f2025-05-19 04:41:57 +000024import entity.TransRecord;
25import entity.TransportId;
rootff0769a2025-05-18 17:24:41 +000026import entity.config;
27import tracker.Tracker;
rootff0769a2025-05-18 17:24:41 +000028public class TrackerTest {
29 private static EntityManagerFactory emf;
30 private static EntityManager em;
31 private static List<String> userIds;
32 private static Map<String, Long> originalUploads;
33 private static Tracker tracker;
rootff0769a2025-05-18 17:24:41 +000034 @BeforeAll
35 static void setup() throws Exception {
36 // 强制加载 MySQL 驱动,否则无法建立连接
37 Class.forName("com.mysql.cj.jdbc.Driver");
38 config cfg = new config();
39 Map<String,Object> props = new HashMap<>();
40 // 添加时区和 SSL 参数
41 String jdbcUrl = String.format(
42 "jdbc:mysql://%s/%s?useSSL=false&serverTimezone=UTC",
43 cfg.SqlURL, cfg.TestDatabase);
44 props.put("javax.persistence.jdbc.url", jdbcUrl);
45 props.put("javax.persistence.jdbc.user", cfg.SqlUsername);
46 props.put("javax.persistence.jdbc.password", cfg.SqlPassword);
47 props.put("javax.persistence.jdbc.driver", "com.mysql.cj.jdbc.Driver");
48 emf = Persistence.createEntityManagerFactory("myPersistenceUnit", props);
49 em = emf.createEntityManager();
50 // 使用简单实体名而非带包名前缀
51 userIds = em.createQuery(
52 "select u.userid from UserPT u", String.class
53 ).getResultList();
rootff0769a2025-05-18 17:24:41 +000054 // 保存初始 upload 值
55 originalUploads = new HashMap<>();
56 for (String uid : userIds) {
57 Long up = em.createQuery(
58 "select u.upload from UserPT u where u.userid = :uid", Long.class
59 ).setParameter("uid", uid)
60 .getSingleResult();
61 originalUploads.put(uid, up != null ? up : 0L);
62 }
63 tracker = new Tracker(emf);
64 }
rootff0769a2025-05-18 17:24:41 +000065 @AfterAll
66 static void teardown() {
rootd4959a82025-05-27 07:07:37 +000067 // 清理:删除测试过程中保存的所有 torrent 文件
68 File storageDir = new File(config.TORRENT_STORAGE_DIR);
69 if (storageDir.exists() && storageDir.isDirectory()) {
70 File[] files = storageDir.listFiles();
71 if (files != null) {
72 for (File f : files) {
73 if (f.isFile()) {
74 f.delete();
75 }
76 }
77 }
78 }
rootff0769a2025-05-18 17:24:41 +000079 if (em != null && em.isOpen()) em.close();
80 if (emf != null && emf.isOpen()) emf.close();
81 }
rootff0769a2025-05-18 17:24:41 +000082 @TestFactory
83 Collection<DynamicTest> testAddUpLoad() {
84 Random rnd = new Random();
85 return userIds.stream()
86 .map(uid -> DynamicTest.dynamicTest("AddUpLoad for user " + uid, () -> {
87 int delta = rnd.nextInt(1000) + 1; // Ensure non-zero value
88 long before = originalUploads.get(uid);
89
rootf35409f2025-05-19 04:41:57 +000090 // AddUpLoad 前打印
91 System.out.println("Running AddUpLoad assert for user=" + uid + ", delta=" + delta);
rootff0769a2025-05-18 17:24:41 +000092 Assertions.assertFalse(tracker.AddUpLoad(uid, delta),
93 "AddUpLoad should return false on successful operation");
rootf35409f2025-05-19 04:41:57 +000094 System.out.println("AddUpLoad assert passed for user=" + uid);
rootff0769a2025-05-18 17:24:41 +000095 // Clear the persistence context to ensure fresh data is fetched
96 em.clear();
97
98 // Fetch updated value
99 Long after = em.createQuery(
100 "select u.upload from UserPT u where u.userid = :uid", Long.class
101 ).setParameter("uid", uid)
102 .getSingleResult();
rootf35409f2025-05-19 04:41:57 +0000103 // upload 值断言前打印
104 System.out.println("Running upload-value assert for user=" + uid);
rootff0769a2025-05-18 17:24:41 +0000105 Assertions.assertEquals(before + delta, after,
106 "Upload value should be increased by " + delta);
rootf35409f2025-05-19 04:41:57 +0000107 System.out.println("Upload-value assert passed for user=" + uid);
rootff0769a2025-05-18 17:24:41 +0000108
rootf35409f2025-05-19 04:41:57 +0000109 // ReduceUpLoad 前打印
110 System.out.println("Running ReduceUpLoad assert for user=" + uid + ", delta=" + delta);
rootff0769a2025-05-18 17:24:41 +0000111 Assertions.assertFalse(tracker.ReduceUpLoad(uid, delta),
112 "ReduceUpLoad should return false on successful operation");
rootf35409f2025-05-19 04:41:57 +0000113 System.out.println("ReduceUpLoad assert passed for user=" + uid);
rootff0769a2025-05-18 17:24:41 +0000114 }))
115 .collect(Collectors.toList());
116 }
rootff0769a2025-05-18 17:24:41 +0000117 @TestFactory
118 Collection<DynamicTest> testReduceUpLoad() {
119 Random rnd = new Random();
120 return userIds.stream()
121 .map(uid -> DynamicTest.dynamicTest("ReduceUpLoad for user " + uid, () -> {
122 long before = originalUploads.get(uid);
123 int max = (int)Math.min(before, 1000);
124 int delta = max > 0 ? rnd.nextInt(max) + 1 : 0;
125 if (delta == 0) return; // 无可减量时跳过
rootf35409f2025-05-19 04:41:57 +0000126 // ReduceUpLoad 前打印
127 System.out.println("Running ReduceUpLoad assert for user=" + uid + ", delta=" + delta);
rootff0769a2025-05-18 17:24:41 +0000128 Assertions.assertFalse(tracker.ReduceUpLoad(uid, delta));
rootf35409f2025-05-19 04:41:57 +0000129 System.out.println("ReduceUpLoad assert passed for user=" + uid);
rootff0769a2025-05-18 17:24:41 +0000130 Long after = em.createQuery(
131 "select u.upload from UserPT u where u.userid = :uid", Long.class
132 ).setParameter("uid", uid)
133 .getSingleResult();
rootf35409f2025-05-19 04:41:57 +0000134 // 减少后值断言前打印
135 System.out.println("Running post-reduce-value assert for user=" + uid);
rootff0769a2025-05-18 17:24:41 +0000136 Assertions.assertEquals(before - delta, after);
rootf35409f2025-05-19 04:41:57 +0000137 System.out.println("Post-reduce-value assert passed for user=" + uid);
rootf35409f2025-05-19 04:41:57 +0000138 // 回滚 AddUpLoad 前打印
139 System.out.println("Running rollback AddUpLoad assert for user=" + uid + ", delta=" + delta);
rootff0769a2025-05-18 17:24:41 +0000140 Assertions.assertFalse(tracker.AddUpLoad(uid, delta));
rootf35409f2025-05-19 04:41:57 +0000141 System.out.println("Rollback AddUpLoad assert passed for user=" + uid);
142 }))
143 .collect(Collectors.toList());
144 }
rootf35409f2025-05-19 04:41:57 +0000145 @TestFactory
146 Collection<DynamicTest> testAddDownload() {
147 Random rnd = new Random();
148 return userIds.stream()
149 .map(uid -> DynamicTest.dynamicTest("AddDownload for user " + uid, () -> {
150 int delta = rnd.nextInt(1000) + 1;
151 Long before = em.createQuery(
152 "select u.download from UserPT u where u.userid = :uid", Long.class
153 ).setParameter("uid", uid).getSingleResult();
154 before = before != null ? before : 0L;
rootf35409f2025-05-19 04:41:57 +0000155 System.out.println("Running AddDownload assert for user=" + uid + ", delta=" + delta);
156 Assertions.assertFalse(tracker.AddDownload(uid, delta),
157 "AddDownload should return false on successful operation");
158 em.clear();
rootf35409f2025-05-19 04:41:57 +0000159 Long after = em.createQuery(
160 "select u.download from UserPT u where u.userid = :uid", Long.class
161 ).setParameter("uid", uid).getSingleResult();
162 System.out.println("Running download-value assert for user=" + uid);
163 Assertions.assertEquals(before + delta, after,
164 "Download value should be increased by " + delta);
rootf35409f2025-05-19 04:41:57 +0000165 System.out.println("Running rollback ReduceDownload assert for user=" + uid + ", delta=" + delta);
166 Assertions.assertFalse(tracker.ReduceDownload(uid, delta),
167 "Rollback ReduceDownload should return false");
168 }))
169 .collect(Collectors.toList());
170 }
rootf35409f2025-05-19 04:41:57 +0000171 @TestFactory
172 Collection<DynamicTest> testReduceDownload() {
173 Random rnd = new Random();
174 return userIds.stream()
175 .map(uid -> DynamicTest.dynamicTest("ReduceDownload for user " + uid, () -> {
176 Long before = em.createQuery(
177 "select u.download from UserPT u where u.userid = :uid", Long.class
178 ).setParameter("uid", uid).getSingleResult();
179 before = before != null ? before : 0L;
180 int max = before.intValue();
181 int delta = max > 0 ? rnd.nextInt(max) + 1 : 0;
182 if (delta == 0) return;
rootf35409f2025-05-19 04:41:57 +0000183 System.out.println("Running ReduceDownload assert for user=" + uid + ", delta=" + delta);
184 Assertions.assertFalse(tracker.ReduceDownload(uid, delta));
185 Long after = em.createQuery(
186 "select u.download from UserPT u where u.userid = :uid", Long.class
187 ).setParameter("uid", uid).getSingleResult();
188 System.out.println("Running post-reduce-download-value assert for user=" + uid);
189 Assertions.assertEquals(before - delta, after);
rootf35409f2025-05-19 04:41:57 +0000190 System.out.println("Running rollback AddDownload assert for user=" + uid + ", delta=" + delta);
191 Assertions.assertFalse(tracker.AddDownload(uid, delta));
192 }))
193 .collect(Collectors.toList());
194 }
rootf35409f2025-05-19 04:41:57 +0000195 @TestFactory
196 Collection<DynamicTest> testAddMagic() {
197 Random rnd = new Random();
198 return userIds.stream()
199 .map(uid -> DynamicTest.dynamicTest("AddMagic for user " + uid, () -> {
200 int delta = rnd.nextInt(1000) + 1;
201 Integer before = em.createQuery(
202 "select u.magic from UserPT u where u.userid = :uid", Integer.class
203 ).setParameter("uid", uid).getSingleResult();
204 before = before != null ? before : 0;
rootf35409f2025-05-19 04:41:57 +0000205 System.out.println("Running AddMagic assert for user=" + uid + ", delta=" + delta);
206 Assertions.assertFalse(tracker.AddMagic(uid, delta));
207 em.clear();
rootf35409f2025-05-19 04:41:57 +0000208 Integer after = em.createQuery(
209 "select u.magic from UserPT u where u.userid = :uid", Integer.class
210 ).setParameter("uid", uid).getSingleResult();
211 System.out.println("Running magic-value assert for user=" + uid);
212 Assertions.assertEquals(before + delta, after.intValue());
rootf35409f2025-05-19 04:41:57 +0000213 System.out.println("Running rollback ReduceMagic assert for user=" + uid + ", delta=" + delta);
214 Assertions.assertFalse(tracker.ReduceMagic(uid, delta));
215 }))
216 .collect(Collectors.toList());
217 }
rootf35409f2025-05-19 04:41:57 +0000218 @TestFactory
219 Collection<DynamicTest> testReduceMagic() {
220 Random rnd = new Random();
221 return userIds.stream()
222 .map(uid -> DynamicTest.dynamicTest("ReduceMagic for user " + uid, () -> {
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 int max = before.intValue();
228 int delta = max > 0 ? rnd.nextInt(max) + 1 : 0;
229 if (delta == 0) return;
rootf35409f2025-05-19 04:41:57 +0000230 System.out.println("Running ReduceMagic assert for user=" + uid + ", delta=" + delta);
231 Assertions.assertFalse(tracker.ReduceMagic(uid, delta));
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 post-reduce-magic-value assert for user=" + uid);
236 Assertions.assertEquals(before - delta, after.intValue());
rootf35409f2025-05-19 04:41:57 +0000237 System.out.println("Running rollback AddMagic assert for user=" + uid + ", delta=" + delta);
238 Assertions.assertFalse(tracker.AddMagic(uid, delta));
239 }))
240 .collect(Collectors.toList());
241 }
rootf35409f2025-05-19 04:41:57 +0000242 @TestFactory
243 Collection<DynamicTest> testAddRecord() {
244 Random rnd = new Random();
245 // 取所有 seed_id 用于外键测试
246 List<String> seedIds = em.createQuery(
247 "select s.seedid from Seed s", String.class
248 ).getResultList();
249 // 若无可用 seedId 则跳过此组测试,避免 rnd.nextInt(0) 抛错
250 // if (seedIds.isEmpty()) {
251 // return Collections.emptyList();
252 // }
253 return IntStream.range(0, 10)
254 .mapToObj(i -> DynamicTest.dynamicTest("AddRecord test #" + i, () -> {
255 // 随机构造 TransRecord
256 String uploaderId = userIds.get(rnd.nextInt(userIds.size()));
257 String downloaderId = userIds.get(rnd.nextInt(userIds.size()));
258 String seedId = seedIds.get(rnd.nextInt(seedIds.size()));
259 String taskId = UUID.randomUUID().toString();
rootf35409f2025-05-19 04:41:57 +0000260 TransRecord rd = new TransRecord();
261 rd.taskid = taskId;
262 rd.uploaduserid = uploaderId;
263 rd.downloaduserid = downloaderId;
264 rd.seedid = seedId;
265 rd.upload = rnd.nextInt(10000);
266 rd.download = rnd.nextInt(10000);
267 rd.maxupload = rd.upload + rnd.nextInt(10000);
268 rd.maxdownload = rd.download + rnd.nextInt(10000);
rootf35409f2025-05-19 04:41:57 +0000269 // 调用待测方法
270 int ret = tracker.AddRecord(rd);
271 Assertions.assertTrue(ret > 0, "返回值应为新记录主键");
rootf35409f2025-05-19 04:41:57 +0000272 // 验证已插入
273 TransportId pk = new TransportId(taskId, uploaderId, downloaderId);
274 TransRecord fetched = em.find(TransRecord.class, pk);
275 Assertions.assertNotNull(fetched, "应查询到新增的 TransRecord");
rootf35409f2025-05-19 04:41:57 +0000276 // 清理:删除测试记录
277 EntityTransaction tx = em.getTransaction();
278 tx.begin();
279 em.remove(fetched);
280 tx.commit();
rootff0769a2025-05-18 17:24:41 +0000281 }))
282 .collect(Collectors.toList());
283 }
rootd4959a82025-05-27 07:07:37 +0000284 @TestFactory
285 Collection<DynamicTest> testSaveTorrent() {
286 List<String> seedIds = em.createQuery(
287 "select s.seedid from Seed s", String.class
288 ).getResultList();
289 return seedIds.stream()
290 .map(sid -> DynamicTest.dynamicTest("SaveTorrent for seed " + sid, () -> {
291 // 准备一个临时空文件
292 File temp = File.createTempFile(sid + "_test", ".torrent");
293 // 调用 SaveTorrent
294 int ret = tracker.SaveTorrent(sid, temp);
295 Assertions.assertEquals(0, ret, "SaveTorrent 应返回 0");
rootd4959a82025-05-27 07:07:37 +0000296 // 验证文件已按约定存储
297 File stored = new File(config.TORRENT_STORAGE_DIR,
298 sid + "_" + temp.getName());
299 Assertions.assertTrue(stored.exists(), "存储文件应存在");
rootd4959a82025-05-27 07:07:37 +0000300 // 验证数据库中 url 字段已更新
301 em.clear();
302 Seed seed = em.find(Seed.class, sid);
303 // 将 seed.url 转为 File 再取绝对路径进行比较
304 Assertions.assertEquals(
305 stored.getAbsolutePath(),
306 new File(seed.url).getAbsolutePath(),
307 "Seed.url 应更新为存储路径"
308 );
rootd4959a82025-05-27 07:07:37 +0000309 // 清理测试文件
310 stored.delete();
311 temp.delete();
312 }))
313 .collect(Collectors.toList());
314 }
rootd4959a82025-05-27 07:07:37 +0000315 @TestFactory
316 Collection<DynamicTest> testGetTTorent() {
317 // 拿到所有 seedid
318 List<String> seedIds = em.createQuery(
319 "select s.seedid from Seed s", String.class
320 ).getResultList();
321 return seedIds.stream()
322 .map(sid -> DynamicTest.dynamicTest("GetTTorent for seed " + sid, () -> {
323 // 准备一个临时空文件并 SaveTorrent
324 File temp = File.createTempFile(sid + "_test", ".torrent");
325 int saveRet = tracker.SaveTorrent(sid, temp);
326 Assertions.assertEquals(0, saveRet, "SaveTorrent 应返回 0");
rootd4959a82025-05-27 07:07:37 +0000327 // 刷新上下文并取回更新后的 seed 实体
328 em.clear();
329 Seed seed = em.find(Seed.class, sid);
330 Assertions.assertNotNull(seed.url, "Seed.url 应已被更新");
rootd4959a82025-05-27 07:07:37 +0000331 // 调用 GetTTorent 并断言路径一致
332 String uid = userIds.get(0), ip = "127.0.0.1";
Raveraae06122025-06-05 08:13:35 +0000333 File ret = tracker.GetTTorent(sid, uid);
rootd4959a82025-05-27 07:07:37 +0000334 File expected = new File(seed.url);
335 Assertions.assertNotNull(ret, "应返回文件对象");
336 Assertions.assertEquals(
337 expected.getAbsolutePath(),
338 ret.getAbsolutePath(),
339 "返回文件路径应与Seed.url一致"
340 );
rootd4959a82025-05-27 07:07:37 +0000341 // 清理:删掉本地文件,回滚 DB url 字段,删掉 temp
342 expected.delete();
343 EntityTransaction tx = em.getTransaction();
344 tx.begin();
345 seed.url = null;
346 em.merge(seed);
347 tx.commit();
348 temp.delete();
349 }))
350 .collect(Collectors.toList());
351 }
root33a7d952025-05-18 17:24:41 +0000352}