同步提交
Change-Id: Ia8b140cefb8bc70d12a20685b91e8c0b93315db5
diff --git a/src/test/java/databasetest/database2Test.java b/src/test/java/databasetest/database2Test.java
new file mode 100644
index 0000000..196db26
--- /dev/null
+++ b/src/test/java/databasetest/database2Test.java
@@ -0,0 +1,864 @@
+// package databasetest;
+
+// import database.Database2;
+// import entity.*;
+// import org.junit.jupiter.api.*;
+
+// import javax.persistence.*;
+// import java.util.*;
+// import java.util.stream.Collectors;
+
+// public class database2Test {
+// private static EntityManagerFactory emf;
+// private static EntityManager em;
+// private static Database2 db;
+
+// @BeforeAll
+// static void setup() throws Exception {
+// // 强制加载 MySQL 驱动
+// Class.forName("com.mysql.cj.jdbc.Driver");
+// entity.config cfg = new entity.config();
+// Map<String, Object> props = new HashMap<>();
+// String jdbcUrl = String.format(
+// "jdbc:mysql://%s/%s?useSSL=false&serverTimezone=UTC",
+// cfg.SqlURL, cfg.TestDatabase);
+// props.put("javax.persistence.jdbc.url", jdbcUrl);
+// props.put("javax.persistence.jdbc.user", cfg.SqlUsername);
+// props.put("javax.persistence.jdbc.password", cfg.SqlPassword);
+// props.put("javax.persistence.jdbc.driver", "com.mysql.cj.jdbc.Driver");
+// emf = Persistence.createEntityManagerFactory("myPersistenceUnit", props);
+// em = emf.createEntityManager();
+// // 修改此处:传入配置好的EntityManagerFactory给Database2
+// db = new Database2(emf);
+// }
+
+// @AfterAll
+// static void teardown() {
+// if (em != null && em.isOpen())
+// em.close();
+// if (emf != null && emf.isOpen())
+// emf.close();
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testAddBegSeed() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String begId = "test_beg_" + UUID.randomUUID().toString();
+
+// BegInfo beg = new BegInfo();
+// beg.begid = begId;
+// beg.begnumbers = 1;
+// beg.magic = 100;
+// beg.endtime = new Date();
+// beg.hasseed = false;
+
+// return List.of(
+// DynamicTest.dynamicTest("AddBegSeed success", () -> {
+// int ret = db.AddBegSeed(beg);
+// Assertions.assertEquals(0, ret, "AddBegSeed应返回0");
+// BegInfo inserted = em.find(BegInfo.class, begId);
+// Assertions.assertNotNull(inserted, "求种信息应已插入");
+// Assertions.assertFalse(inserted.hasseed, "新求种默认未完成");
+// }),
+
+// DynamicTest.dynamicTest("AddBegSeed duplicate", () -> {
+// int ret = db.AddBegSeed(beg);
+// Assertions.assertEquals(1, ret, "重复插入应返回1");
+// }),
+
+// DynamicTest.dynamicTest("AddBegSeed invalid param", () -> {
+// Assertions.assertEquals(2, db.AddBegSeed(null));
+// BegInfo invalidBeg = new BegInfo();
+// invalidBeg.begid = "";
+// Assertions.assertEquals(2, db.AddBegSeed(invalidBeg));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testUpdateBegSeed() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String begId = "test_beg_update_" + UUID.randomUUID().toString();
+
+// // 先插入一条求种记录
+// BegInfo beg = new BegInfo();
+// beg.begid = begId;
+// beg.begnumbers = 1;
+// beg.magic = 100;
+// beg.endtime = new Date();
+// db.AddBegSeed(beg);
+
+// return List.of(
+// DynamicTest.dynamicTest("UpdateBegSeed success", () -> {
+// BegInfo update = new BegInfo();
+// update.begid = begId;
+// update.begnumbers = 2;
+// update.magic = 200;
+
+// int ret = db.UpdateBegSeed(update);
+// Assertions.assertEquals(0, ret, "UpdateBegSeed应返回0");
+
+// BegInfo updated = em.find(BegInfo.class, begId);
+// Assertions.assertEquals(200, updated.magic, "魔力值应已更新");
+// Assertions.assertEquals(2, updated.begnumbers, "求种人数应已更新");
+// }),
+
+// DynamicTest.dynamicTest("UpdateBegSeed not exist", () -> {
+// BegInfo notExist = new BegInfo();
+// notExist.begid = "not_exist_beg";
+// notExist.begnumbers = 1;
+// int ret = db.UpdateBegSeed(notExist);
+// Assertions.assertEquals(1, ret, "不存在的求种应返回1");
+// }),
+
+// DynamicTest.dynamicTest("UpdateBegSeed invalid param", () -> {
+// Assertions.assertEquals(2, db.UpdateBegSeed(null));
+// BegInfo invalid = new BegInfo();
+// invalid.begid = "";
+// Assertions.assertEquals(2, db.UpdateBegSeed(invalid));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testDeleteBegSeed() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String begId = "test_beg_delete_" + UUID.randomUUID().toString();
+
+// // 先插入一条求种记录
+// BegInfo beg = new BegInfo();
+// beg.begid = begId;
+// beg.begnumbers = 1;
+// beg.magic = 100;
+// beg.endtime = new Date();
+// beg.hasseed = false;
+// db.AddBegSeed(beg);
+
+// return List.of(
+// DynamicTest.dynamicTest("DeleteBegSeed success", () -> {
+// int ret = db.DeleteBegSeed(begId);
+// Assertions.assertEquals(0, ret, "DeleteBegSeed应返回0");
+// BegInfo deleted = em.find(BegInfo.class, begId);
+// Assertions.assertNull(deleted, "求种信息应已删除");
+// }),
+
+// DynamicTest.dynamicTest("DeleteBegSeed not exist", () -> {
+// int ret = db.DeleteBegSeed("not_exist_beg");
+// Assertions.assertEquals(1, ret, "不存在的求种应返回1");
+// }),
+
+// DynamicTest.dynamicTest("DeleteBegSeed invalid param", () -> {
+// Assertions.assertEquals(2, db.DeleteBegSeed(null));
+// Assertions.assertEquals(2, db.DeleteBegSeed(""));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testVoteSeed() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String uid = userIds.get(0);
+// String begId = "test_beg_vote_" + UUID.randomUUID().toString();
+// String seedId = "test_seed_" + UUID.randomUUID().toString();
+
+// // 插入求种记录
+// BegInfo beg = new BegInfo();
+// beg.begid = begId;
+// beg.begnumbers = 1;
+// beg.magic = 100;
+// beg.endtime = new Date();
+// beg.hasseed = false;
+// db.AddBegSeed(beg);
+
+// // 插入种子记录
+// Seed seed = new Seed();
+// seed.seedid = seedId;
+// seed.seeduserid = uid;
+// seed.title = "测试种子";
+// em.getTransaction().begin();
+// em.persist(seed);
+// em.getTransaction().commit();
+
+// // 提交种子
+// db.SubmitSeed(begId, seed);
+
+// return List.of(
+// DynamicTest.dynamicTest("VoteSeed success", () -> {
+// int ret = db.VoteSeed(begId, seedId, uid);
+// Assertions.assertEquals(0, ret, "VoteSeed应返回0");
+// }),
+
+// DynamicTest.dynamicTest("VoteSeed duplicate", () -> {
+// int ret = db.VoteSeed(begId, seedId, uid);
+// Assertions.assertEquals(1, ret, "重复投票应返回1");
+// }),
+
+// DynamicTest.dynamicTest("VoteSeed invalid param", () -> {
+// Assertions.assertEquals(2, db.VoteSeed(null, seedId, uid));
+// Assertions.assertEquals(2, db.VoteSeed(begId, null, uid));
+// Assertions.assertEquals(2, db.VoteSeed(begId, seedId, null));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testSubmitSeed() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String uid = userIds.get(0);
+// String begId = "test_beg_submit_" + UUID.randomUUID().toString();
+// String seedId = "test_seed_submit_" + UUID.randomUUID().toString();
+
+// // 插入求种记录
+// BegInfo beg = new BegInfo();
+// beg.begid = begId;
+// beg.begnumbers = 1;
+// beg.magic = 100;
+// beg.endtime = new Date();
+// beg.hasseed = false;
+// db.AddBegSeed(beg);
+
+// Seed seed = new Seed();
+// seed.seedid = seedId;
+// seed.seeduserid = uid;
+// seed.title = "测试种子";
+
+// return List.of(
+// DynamicTest.dynamicTest("SubmitSeed success", () -> {
+// int ret = db.SubmitSeed(begId, seed);
+// Assertions.assertEquals(0, ret, "SubmitSeed应返回0");
+// }),
+
+// DynamicTest.dynamicTest("SubmitSeed duplicate", () -> {
+// int ret = db.SubmitSeed(begId, seed);
+// Assertions.assertEquals(1, ret, "重复提交应返回1");
+// }),
+
+// DynamicTest.dynamicTest("SubmitSeed invalid param", () -> {
+// Assertions.assertEquals(2, db.SubmitSeed(null, seed));
+// Assertions.assertEquals(2, db.SubmitSeed(begId, null));
+// }));
+// }
+
+// @Test
+// void testSettleBeg() {
+// // 准备测试数据
+// String uid = em.createQuery("select u.userid from User u", String.class)
+// .setMaxResults(1)
+// .getSingleResult();
+
+// String begId = "test_beg_settle_" + UUID.randomUUID().toString();
+// String seedId = "test_seed_settle_" + UUID.randomUUID().toString();
+
+// // 创建求种记录(已过期)
+// BegInfo beg = new BegInfo();
+// beg.begid = begId;
+// beg.begnumbers = 1;
+// beg.magic = 100;
+// Calendar cal = Calendar.getInstance();
+// cal.add(Calendar.DAY_OF_MONTH, -15); // 15天前
+// beg.endtime = cal.getTime();
+// beg.hasseed = false;
+// db.AddBegSeed(beg);
+
+// // 创建种子并提交
+// Seed seed = new Seed();
+// seed.seedid = seedId;
+// seed.seeduserid = uid;
+// seed.title = "测试种子";
+// db.SubmitSeed(begId, seed);
+
+// // 投票
+// db.VoteSeed(begId, seedId, uid);
+
+// // 执行结算
+// db.SettleBeg();
+
+// // 验证结算结果
+// BegInfo settled = em.find(BegInfo.class, begId);
+// Assertions.assertTrue(settled.hasseed, "求种应已完成");
+
+// UserPT userPT = em.find(UserPT.class, uid);
+// Assertions.assertTrue(userPT.magic >= 100, "用户应获得魔力值奖励");
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testAddPost() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+// String uid = userIds.get(0);
+// String postid = "test_post_" + UUID.randomUUID();
+// Post post = new Post();
+// post.postid = postid;
+// post.postuserid = uid;
+// post.posttitle = "单元测试帖子";
+// post.postcontent = "内容";
+// post.posttime = new Date();
+
+// return List.of(
+// DynamicTest.dynamicTest("AddPost success", () -> {
+// int ret = db.AddPost(post);
+// Assertions.assertEquals(0, ret, "AddPost 应返回0");
+// Post inserted = em.find(Post.class, postid);
+// Assertions.assertNotNull(inserted, "帖子应已插入");
+// }),
+// DynamicTest.dynamicTest("AddPost duplicate", () -> {
+// int ret = db.AddPost(post);
+// Assertions.assertEquals(1, ret, "重复插入应返回1");
+// }),
+// DynamicTest.dynamicTest("AddPost user not exist", () -> {
+// Post p2 = new Post();
+// p2.postid = "test_post_" + UUID.randomUUID();
+// p2.postuserid = "not_exist_user";
+// p2.posttitle = "无效用户";
+// p2.postcontent = "内容";
+// p2.posttime = new Date();
+// int ret = db.AddPost(p2);
+// Assertions.assertEquals(2, ret, "用户不存在应返回2");
+// }),
+// DynamicTest.dynamicTest("AddPost invalid param", () -> {
+// Assertions.assertEquals(2, db.AddPost(null));
+// Post p3 = new Post();
+// p3.postid = null;
+// p3.postuserid = uid;
+// Assertions.assertEquals(2, db.AddPost(p3));
+// Post p4 = new Post();
+// p4.postid = "";
+// p4.postuserid = uid;
+// Assertions.assertEquals(2, db.AddPost(p4));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testUpdatePost() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+// String uid = userIds.get(0);
+// String postid = "test_post_update_" + UUID.randomUUID();
+// Post post = new Post();
+// post.postid = postid;
+// post.postuserid = uid;
+// post.posttitle = "原始标题";
+// post.postcontent = "原始内容";
+// post.posttime = new Date();
+// db.AddPost(post);
+
+// return List.of(
+// DynamicTest.dynamicTest("UpdatePost success", () -> {
+// Post update = new Post();
+// update.postid = postid;
+// update.postuserid = uid; // 实际实现会忽略此字段
+// update.posttitle = "新标题";
+// update.postcontent = "新内容";
+// update.posttime = post.posttime;
+// int ret = db.UpdatePost(update);
+// Assertions.assertEquals(0, ret, "UpdatePost 应返回0");
+// Post updated = em.find(Post.class, postid);
+// Assertions.assertEquals("新标题", updated.posttitle);
+// Assertions.assertEquals("新内容", updated.postcontent);
+// }),
+// DynamicTest.dynamicTest("UpdatePost not exist", () -> {
+// Post notExist = new Post();
+// notExist.postid = "not_exist_post";
+// notExist.postuserid = uid;
+// notExist.posttitle = "xxx";
+// notExist.postcontent = "xxx";
+// int ret = db.UpdatePost(notExist);
+// Assertions.assertEquals(1, ret, "不存在的帖子应返回1");
+// }),
+// DynamicTest.dynamicTest("UpdatePost invalid param", () -> {
+// Assertions.assertEquals(2, db.UpdatePost(null));
+// Post p2 = new Post();
+// p2.postid = null;
+// Assertions.assertEquals(2, db.UpdatePost(p2));
+// Post p3 = new Post();
+// p3.postid = "";
+// Assertions.assertEquals(2, db.UpdatePost(p3));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testDeletePost() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+// String uid = userIds.get(0);
+// String postid = "test_post_delete_" + UUID.randomUUID();
+// Post post = new Post();
+// post.postid = postid;
+// post.postuserid = uid;
+// post.posttitle = "待删除帖子";
+// post.postcontent = "内容";
+// post.posttime = new Date();
+// db.AddPost(post);
+
+// return List.of(
+// DynamicTest.dynamicTest("DeletePost success", () -> {
+// int ret = db.DeletePost(postid);
+// Assertions.assertEquals(0, ret, "DeletePost 应返回0");
+// Post deleted = em.find(Post.class, postid);
+// Assertions.assertNull(deleted, "帖子应已删除");
+// }),
+// DynamicTest.dynamicTest("DeletePost not exist", () -> {
+// int ret = db.DeletePost("not_exist_post");
+// Assertions.assertEquals(1, ret, "不存在的帖子应返回1");
+// }),
+// DynamicTest.dynamicTest("DeletePost invalid param", () -> {
+// Assertions.assertEquals(2, db.DeletePost(null));
+// Assertions.assertEquals(2, db.DeletePost(""));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testAddComment() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// List<String> postIds = em.createQuery("select p.postid from Post p",
+// String.class).getResultList();
+// if (userIds.isEmpty() || postIds.isEmpty()) {
+// return Collections.emptyList();
+// }
+// String comment = "单元测试评论";
+// return userIds.stream().flatMap(uid -> postIds.stream()
+// .map(pid -> DynamicTest.dynamicTest("AddComment for user=" + uid + ", post="
+// + pid, () -> {
+// int ret = db.AddComment(pid, uid, comment);
+// Assertions.assertEquals(0, ret, "AddComment 应返回0");
+// // 验证评论已插入
+// List<PostReply> replies = em.createQuery(
+// "SELECT r FROM PostReply r WHERE r.postid = :pid AND r.authorid = :uid AND
+// r.content = :c",
+// PostReply.class)
+// .setParameter("pid", pid)
+// .setParameter("uid", uid)
+// .setParameter("c", comment)
+// .getResultList();
+// Assertions.assertFalse(replies.isEmpty(), "评论应已插入");
+// }))).collect(Collectors.toList());
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testDeleteComment() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// List<String> postIds = em.createQuery("select p.postid from Post p",
+// String.class).getResultList();
+// if (userIds.isEmpty() || postIds.isEmpty()) {
+// return Collections.emptyList();
+// }
+// String comment = "待删除评论";
+// List<DynamicTest> tests = new ArrayList<>();
+// for (String uid : userIds) {
+// for (String pid : postIds) {
+// // 插入评论
+// db.AddComment(pid, uid, comment);
+// // 查询评论id
+// List<PostReply> replies = em.createQuery(
+// "SELECT r FROM PostReply r WHERE r.postid = :pid AND r.authorid = :uid AND
+// r.content = :c",
+// PostReply.class)
+// .setParameter("pid", pid)
+// .setParameter("uid", uid)
+// .setParameter("c", comment)
+// .getResultList();
+// if (replies.isEmpty())
+// continue;
+// PostReply reply = replies.get(0);
+// String replyid = reply.replyid;
+
+// tests.add(DynamicTest.dynamicTest("DeleteComment for post=" + pid + ",
+// replyid=" + replyid, () -> {
+// int ret = db.DeleteComment(pid, replyid);
+// Assertions.assertEquals(0, ret, "DeleteComment 应返回0");
+// PostReply deleted = em.find(PostReply.class, replyid);
+// Assertions.assertNull(deleted, "评论应已删除");
+// }));
+// }
+// }
+// return tests;
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testExchangeMagicToUpload() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String uid = userIds.get(0);
+// final UserPT testUserPT;
+
+// // 确保用户有足够的魔力值用于测试
+// EntityTransaction tx = em.getTransaction();
+// tx.begin();
+// UserPT tempUserPT = em.find(UserPT.class, uid);
+// if (tempUserPT == null) {
+// tempUserPT = new UserPT();
+// tempUserPT.userid = uid;
+// tempUserPT.magic = 1000;
+// tempUserPT.upload = 1000;
+// tempUserPT.download = 1000;
+// em.persist(tempUserPT);
+// } else {
+// tempUserPT.magic = 1000;
+// em.merge(tempUserPT);
+// }
+// testUserPT = tempUserPT;
+// tx.commit();
+
+// return List.of(
+// DynamicTest.dynamicTest("ExchangeMagicToUpload success", () -> {
+// int magic = 100;
+// long beforeUpload = testUserPT.upload;
+// int beforeMagic = testUserPT.magic;
+
+// boolean ret = db.ExchangeMagicToUpload(uid, magic);
+// Assertions.assertTrue(ret, "兑换上传量应成功");
+
+// em.clear();
+// UserPT after = em.find(UserPT.class, uid);
+// Assertions.assertEquals(beforeMagic - magic, after.magic, "魔力值应减少");
+// Assertions.assertEquals(beforeUpload + magic, after.upload, "上传量应增加");
+// }),
+
+// DynamicTest.dynamicTest("ExchangeMagicToUpload insufficient magic", () -> {
+// boolean ret = db.ExchangeMagicToUpload(uid, 2000);
+// Assertions.assertFalse(ret, "魔力值不足时应返回false");
+// }),
+
+// DynamicTest.dynamicTest("ExchangeMagicToUpload invalid params", () -> {
+// Assertions.assertFalse(db.ExchangeMagicToUpload(null, 100));
+// Assertions.assertFalse(db.ExchangeMagicToUpload("", 100));
+// Assertions.assertFalse(db.ExchangeMagicToUpload(uid, 0));
+// Assertions.assertFalse(db.ExchangeMagicToUpload(uid, -1));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testExchangeMagicToDownload() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String uid = userIds.get(0);
+// final UserPT testUserPT;
+
+// // 确保用户有足够的魔力值和下载量用于测试
+// EntityTransaction tx = em.getTransaction();
+// tx.begin();
+// UserPT tempUserPT = em.find(UserPT.class, uid);
+// if (tempUserPT == null) {
+// tempUserPT = new UserPT();
+// tempUserPT.userid = uid;
+// tempUserPT.magic = 1000;
+// tempUserPT.upload = 1000;
+// tempUserPT.download = 1000;
+// em.persist(tempUserPT);
+// } else {
+// tempUserPT.magic = 1000;
+// em.merge(tempUserPT);
+// }
+// testUserPT = tempUserPT;
+// tx.commit();
+
+// return List.of(
+// DynamicTest.dynamicTest("ExchangeMagicToDownload success", () -> {
+// int magic = 100;
+// long beforeDownload = testUserPT.download;
+// int beforeMagic = testUserPT.magic;
+
+// boolean ret = db.ExchangeMagicToDownload(uid, magic);
+// Assertions.assertTrue(ret, "兑换下载量应成功");
+
+// em.clear();
+// UserPT after = em.find(UserPT.class, uid);
+// Assertions.assertEquals(beforeMagic - magic, after.magic, "魔力值应减少");
+// Assertions.assertEquals(beforeDownload - magic, after.download, "下载量应减少");
+// }),
+
+// DynamicTest.dynamicTest("ExchangeMagicToDownload insufficient magic", () -> {
+// boolean ret = db.ExchangeMagicToDownload(uid, 2000);
+// Assertions.assertFalse(ret, "魔力值不足时应返回false");
+// }),
+
+// DynamicTest.dynamicTest("ExchangeMagicToDownload invalid params", () -> {
+// Assertions.assertFalse(db.ExchangeMagicToDownload(null, 100));
+// Assertions.assertFalse(db.ExchangeMagicToDownload("", 100));
+// Assertions.assertFalse(db.ExchangeMagicToDownload(uid, 0));
+// Assertions.assertFalse(db.ExchangeMagicToDownload(uid, -1));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testExchangeMagicToVip() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String uid = userIds.get(0);
+// final UserPT testUserPT;
+
+// // 确保用户有足够的魔力值用于测试
+// EntityTransaction tx = em.getTransaction();
+// tx.begin();
+// UserPT tempUserPT = em.find(UserPT.class, uid);
+// if (tempUserPT == null) {
+// tempUserPT = new UserPT();
+// tempUserPT.userid = uid;
+// tempUserPT.magic = 1000;
+// tempUserPT.upload = 1000;
+// tempUserPT.download = 1000;
+// em.persist(tempUserPT);
+// } else {
+// tempUserPT.magic = 1000;
+// em.merge(tempUserPT);
+// }
+// testUserPT = tempUserPT;
+// tx.commit();
+
+// return List.of(
+// DynamicTest.dynamicTest("ExchangeMagicToVip success", () -> {
+// int magic = 100;
+// int beforeVip = testUserPT.viptime;
+// int beforeMagic = testUserPT.magic;
+
+// boolean ret = db.ExchangeMagicToVip(uid, magic);
+// Assertions.assertTrue(ret, "兑换VIP次数应成功");
+
+// em.clear();
+// UserPT after = em.find(UserPT.class, uid);
+// Assertions.assertEquals(beforeMagic - magic, after.magic, "魔力值应减少");
+// Assertions.assertEquals(beforeVip + magic, after.viptime, "VIP次数应增加");
+// }),
+
+// DynamicTest.dynamicTest("ExchangeMagicToVip insufficient magic", () -> {
+// boolean ret = db.ExchangeMagicToVip(uid, 2000);
+// Assertions.assertFalse(ret, "魔力值不足时应返回false");
+// }),
+
+// DynamicTest.dynamicTest("ExchangeMagicToVip invalid params", () -> {
+// Assertions.assertFalse(db.ExchangeMagicToVip(null, 100));
+// Assertions.assertFalse(db.ExchangeMagicToVip("", 100));
+// Assertions.assertFalse(db.ExchangeMagicToVip(uid, 0));
+// Assertions.assertFalse(db.ExchangeMagicToVip(uid, -1));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testUploadTransmitProfile() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String uid = userIds.get(0);
+// String profileId = "test_profile_" + UUID.randomUUID();
+// Profile profile = new Profile();
+// profile.profileurl = profileId;
+// profile.userid = uid;
+// profile.magictogive = "100";
+// profile.uploadtogive = "1000";
+// profile.downloadtogive = "500";
+
+// return List.of(
+// DynamicTest.dynamicTest("UploadTransmitProfile success", () -> {
+// boolean ret = db.UploadTransmitProfile(profile);
+// Assertions.assertTrue(ret, "上传迁移信息应成功");
+
+// Profile inserted = em.find(Profile.class, profileId);
+// Assertions.assertNotNull(inserted, "迁移信息应已插入");
+// Assertions.assertFalse(inserted.exampass, "新迁移信息默认未审核");
+// Assertions.assertEquals("0", inserted.magicgived, "已发放魔力值应为0");
+// Assertions.assertEquals("0", inserted.uploadgived, "已发放上传量应为0");
+// }),
+
+// DynamicTest.dynamicTest("UploadTransmitProfile duplicate", () -> {
+// boolean ret = db.UploadTransmitProfile(profile);
+// Assertions.assertFalse(ret, "重复上传应返回false");
+// }),
+
+// DynamicTest.dynamicTest("UploadTransmitProfile invalid params", () -> {
+// Assertions.assertFalse(db.UploadTransmitProfile(null));
+// Profile invalidProfile = new Profile();
+// Assertions.assertFalse(db.UploadTransmitProfile(invalidProfile));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testGetTransmitProfile() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String uid = userIds.get(0);
+// String profileId = "test_profile_get_" + UUID.randomUUID();
+// Profile profile = new Profile();
+// profile.profileurl = profileId;
+// profile.userid = uid;
+// profile.magictogive = "100";
+// profile.uploadtogive = "1000";
+// profile.exampass = false;
+
+// // 先插入测试数据
+// EntityTransaction tx = em.getTransaction();
+// tx.begin();
+// em.persist(profile);
+// tx.commit();
+
+// return List.of(
+// DynamicTest.dynamicTest("GetTransmitProfile success", () -> {
+// Profile ret = db.GetTransmitProfile(profileId);
+// Assertions.assertNotNull(ret, "应成功获取迁移信息");
+// Assertions.assertEquals(uid, ret.userid, "用户ID应匹配");
+// Assertions.assertEquals("100", ret.magictogive, "待发放魔力值应匹配");
+// Assertions.assertEquals("1000", ret.uploadtogive, "待发放上传量应匹配");
+// }),
+
+// DynamicTest.dynamicTest("GetTransmitProfile not exist", () -> {
+// Profile ret = db.GetTransmitProfile("not_exist_profile");
+// Assertions.assertNull(ret, "不存在的迁移信息应返回null");
+// }),
+
+// DynamicTest.dynamicTest("GetTransmitProfile invalid params", () -> {
+// Assertions.assertNull(db.GetTransmitProfile(null));
+// Assertions.assertNull(db.GetTransmitProfile(""));
+// }));
+// }
+
+// @TestFactory
+// Collection<DynamicTest> testExamTransmitProfile() {
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class).getResultList();
+// if (userIds.isEmpty())
+// return Collections.emptyList();
+
+// String uid = userIds.get(0);
+// String profileId = "test_profile_exam_" + UUID.randomUUID();
+// Profile profile = new Profile();
+// profile.profileurl = profileId;
+// profile.userid = uid;
+// profile.magictogive = "100";
+// profile.uploadtogive = "1000";
+// profile.exampass = false;
+
+// // 先插入测试数据
+// EntityTransaction tx = em.getTransaction();
+// tx.begin();
+// em.persist(profile);
+// UserPT userPT = em.find(UserPT.class, uid);
+// if (userPT == null) {
+// userPT = new UserPT();
+// userPT.userid = uid;
+// userPT.magic = 0;
+// userPT.upload = 0;
+// em.persist(userPT);
+// }
+// tx.commit();
+
+// return List.of(
+// DynamicTest.dynamicTest("ExamTransmitProfile approve", () -> {
+// boolean ret = db.ExamTransmitProfile(profileId, true);
+// Assertions.assertTrue(ret, "审核通过应成功");
+
+// em.clear();
+// Profile examined = em.find(Profile.class, profileId);
+// Assertions.assertTrue(examined.exampass, "迁移信息应已审核通过");
+// Assertions.assertEquals("100", examined.magicgived, "应记录已发放魔力值");
+// Assertions.assertEquals("1000", examined.uploadgived, "应记录已发放上传量");
+
+// UserPT afterPT = em.find(UserPT.class, uid);
+// Assertions.assertEquals(100, afterPT.magic, "用户魔力值应增加");
+// Assertions.assertEquals(1000, afterPT.upload, "用户上传量应增加");
+// }),
+
+// DynamicTest.dynamicTest("ExamTransmitProfile reject", () -> {
+// String rejectId = "test_profile_reject_" + UUID.randomUUID();
+// Profile rejectProfile = new Profile();
+// rejectProfile.profileurl = rejectId;
+// rejectProfile.userid = uid;
+// rejectProfile.magictogive = "100";
+// rejectProfile.uploadtogive = "1000";
+// rejectProfile.exampass = false;
+
+// tx.begin();
+// em.persist(rejectProfile);
+// tx.commit();
+
+// boolean ret = db.ExamTransmitProfile(rejectId, false);
+// Assertions.assertTrue(ret, "审核拒绝应成功");
+
+// em.clear();
+// Profile examined = em.find(Profile.class, rejectId);
+// Assertions.assertFalse(examined.exampass, "迁移信息应已审核拒绝");
+// Assertions.assertEquals("0", examined.magicgived, "不应发放魔力值");
+// Assertions.assertEquals("0", examined.uploadgived, "不应发放上传量");
+// }),
+
+// DynamicTest.dynamicTest("ExamTransmitProfile invalid params", () -> {
+// Assertions.assertFalse(db.ExamTransmitProfile(null, true));
+// Assertions.assertFalse(db.ExamTransmitProfile("", true));
+// Assertions.assertFalse(db.ExamTransmitProfile("not_exist_profile", true));
+// }));
+// }
+
+// @Test
+// void testGetTransmitProfileList() {
+// // 清空已有数据
+// em.getTransaction().begin();
+// em.createQuery("DELETE FROM Profile").executeUpdate();
+// em.getTransaction().commit();
+
+// // 插入测试数据
+// List<String> userIds = em.createQuery("select u.userid from User u",
+// String.class)
+// .setMaxResults(3)
+// .getResultList();
+// if (userIds.isEmpty()) {
+// return;
+// }
+
+// EntityTransaction tx = em.getTransaction();
+// tx.begin();
+// for (int i = 0; i < userIds.size(); i++) {
+// Profile profile = new Profile();
+// profile.profileurl = "test_profile_list_" + i;
+// profile.userid = userIds.get(i);
+// profile.magictogive = String.valueOf(100 * (i + 1));
+// profile.uploadtogive = String.valueOf(1000 * (i + 1));
+// profile.exampass = false;
+// em.persist(profile);
+// }
+// tx.commit();
+
+// // 测试获取列表
+// Profile[] profiles = db.GetTransmitProfileList();
+// Assertions.assertEquals(userIds.size(), profiles.length, "应返回所有迁移申请");
+// Arrays.stream(profiles)
+// .forEach(p ->
+// Assertions.assertTrue(p.profileurl.startsWith("test_profile_list_"),
+// "应为测试数据"));
+// }
+// }
diff --git a/src/test/java/trackertest/TrackerTest.java b/src/test/java/trackertest/TrackerTest.java
index 104f017..8f45a4a 100644
--- a/src/test/java/trackertest/TrackerTest.java
+++ b/src/test/java/trackertest/TrackerTest.java
@@ -1,5 +1,4 @@
package trackertest;
-
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
@@ -9,31 +8,26 @@
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
-
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
-
import entity.Seed;
import entity.TransRecord;
import entity.TransportId;
import entity.config;
import tracker.Tracker;
-
public class TrackerTest {
private static EntityManagerFactory emf;
private static EntityManager em;
private static List<String> userIds;
private static Map<String, Long> originalUploads;
private static Tracker tracker;
-
@BeforeAll
static void setup() throws Exception {
// 强制加载 MySQL 驱动,否则无法建立连接
@@ -54,7 +48,6 @@
userIds = em.createQuery(
"select u.userid from UserPT u", String.class
).getResultList();
-
// 保存初始 upload 值
originalUploads = new HashMap<>();
for (String uid : userIds) {
@@ -66,7 +59,6 @@
}
tracker = new Tracker(emf);
}
-
@AfterAll
static void teardown() {
// 清理:删除测试过程中保存的所有 torrent 文件
@@ -81,11 +73,9 @@
}
}
}
-
if (em != null && em.isOpen()) em.close();
if (emf != null && emf.isOpen()) emf.close();
}
-
@TestFactory
Collection<DynamicTest> testAddUpLoad() {
Random rnd = new Random();
@@ -99,7 +89,6 @@
Assertions.assertFalse(tracker.AddUpLoad(uid, delta),
"AddUpLoad should return false on successful operation");
System.out.println("AddUpLoad assert passed for user=" + uid);
-
// Clear the persistence context to ensure fresh data is fetched
em.clear();
@@ -108,7 +97,6 @@
"select u.upload from UserPT u where u.userid = :uid", Long.class
).setParameter("uid", uid)
.getSingleResult();
-
// upload 值断言前打印
System.out.println("Running upload-value assert for user=" + uid);
Assertions.assertEquals(before + delta, after,
@@ -123,7 +111,6 @@
}))
.collect(Collectors.toList());
}
-
@TestFactory
Collection<DynamicTest> testReduceUpLoad() {
Random rnd = new Random();
@@ -133,22 +120,18 @@
int max = (int)Math.min(before, 1000);
int delta = max > 0 ? rnd.nextInt(max) + 1 : 0;
if (delta == 0) return; // 无可减量时跳过
-
// ReduceUpLoad 前打印
System.out.println("Running ReduceUpLoad assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.ReduceUpLoad(uid, delta));
System.out.println("ReduceUpLoad assert passed for user=" + uid);
-
Long after = em.createQuery(
"select u.upload from UserPT u where u.userid = :uid", Long.class
).setParameter("uid", uid)
.getSingleResult();
-
// 减少后值断言前打印
System.out.println("Running post-reduce-value assert for user=" + uid);
Assertions.assertEquals(before - delta, after);
System.out.println("Post-reduce-value assert passed for user=" + uid);
-
// 回滚 AddUpLoad 前打印
System.out.println("Running rollback AddUpLoad assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.AddUpLoad(uid, delta));
@@ -156,7 +139,6 @@
}))
.collect(Collectors.toList());
}
-
@TestFactory
Collection<DynamicTest> testAddDownload() {
Random rnd = new Random();
@@ -167,26 +149,22 @@
"select u.download from UserPT u where u.userid = :uid", Long.class
).setParameter("uid", uid).getSingleResult();
before = before != null ? before : 0L;
-
System.out.println("Running AddDownload assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.AddDownload(uid, delta),
"AddDownload should return false on successful operation");
em.clear();
-
Long after = em.createQuery(
"select u.download from UserPT u where u.userid = :uid", Long.class
).setParameter("uid", uid).getSingleResult();
System.out.println("Running download-value assert for user=" + uid);
Assertions.assertEquals(before + delta, after,
"Download value should be increased by " + delta);
-
System.out.println("Running rollback ReduceDownload assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.ReduceDownload(uid, delta),
"Rollback ReduceDownload should return false");
}))
.collect(Collectors.toList());
}
-
@TestFactory
Collection<DynamicTest> testReduceDownload() {
Random rnd = new Random();
@@ -199,7 +177,6 @@
int max = before.intValue();
int delta = max > 0 ? rnd.nextInt(max) + 1 : 0;
if (delta == 0) return;
-
System.out.println("Running ReduceDownload assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.ReduceDownload(uid, delta));
Long after = em.createQuery(
@@ -207,13 +184,11 @@
).setParameter("uid", uid).getSingleResult();
System.out.println("Running post-reduce-download-value assert for user=" + uid);
Assertions.assertEquals(before - delta, after);
-
System.out.println("Running rollback AddDownload assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.AddDownload(uid, delta));
}))
.collect(Collectors.toList());
}
-
@TestFactory
Collection<DynamicTest> testAddMagic() {
Random rnd = new Random();
@@ -224,23 +199,19 @@
"select u.magic from UserPT u where u.userid = :uid", Integer.class
).setParameter("uid", uid).getSingleResult();
before = before != null ? before : 0;
-
System.out.println("Running AddMagic assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.AddMagic(uid, delta));
em.clear();
-
Integer after = em.createQuery(
"select u.magic from UserPT u where u.userid = :uid", Integer.class
).setParameter("uid", uid).getSingleResult();
System.out.println("Running magic-value assert for user=" + uid);
Assertions.assertEquals(before + delta, after.intValue());
-
System.out.println("Running rollback ReduceMagic assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.ReduceMagic(uid, delta));
}))
.collect(Collectors.toList());
}
-
@TestFactory
Collection<DynamicTest> testReduceMagic() {
Random rnd = new Random();
@@ -253,7 +224,6 @@
int max = before.intValue();
int delta = max > 0 ? rnd.nextInt(max) + 1 : 0;
if (delta == 0) return;
-
System.out.println("Running ReduceMagic assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.ReduceMagic(uid, delta));
Integer after = em.createQuery(
@@ -261,13 +231,11 @@
).setParameter("uid", uid).getSingleResult();
System.out.println("Running post-reduce-magic-value assert for user=" + uid);
Assertions.assertEquals(before - delta, after.intValue());
-
System.out.println("Running rollback AddMagic assert for user=" + uid + ", delta=" + delta);
Assertions.assertFalse(tracker.AddMagic(uid, delta));
}))
.collect(Collectors.toList());
}
-
@TestFactory
Collection<DynamicTest> testAddRecord() {
Random rnd = new Random();
@@ -286,7 +254,6 @@
String downloaderId = userIds.get(rnd.nextInt(userIds.size()));
String seedId = seedIds.get(rnd.nextInt(seedIds.size()));
String taskId = UUID.randomUUID().toString();
-
TransRecord rd = new TransRecord();
rd.taskid = taskId;
rd.uploaduserid = uploaderId;
@@ -296,16 +263,13 @@
rd.download = rnd.nextInt(10000);
rd.maxupload = rd.upload + rnd.nextInt(10000);
rd.maxdownload = rd.download + rnd.nextInt(10000);
-
// 调用待测方法
int ret = tracker.AddRecord(rd);
Assertions.assertTrue(ret > 0, "返回值应为新记录主键");
-
// 验证已插入
TransportId pk = new TransportId(taskId, uploaderId, downloaderId);
TransRecord fetched = em.find(TransRecord.class, pk);
Assertions.assertNotNull(fetched, "应查询到新增的 TransRecord");
-
// 清理:删除测试记录
EntityTransaction tx = em.getTransaction();
tx.begin();
@@ -314,7 +278,6 @@
}))
.collect(Collectors.toList());
}
-
@TestFactory
Collection<DynamicTest> testSaveTorrent() {
List<String> seedIds = em.createQuery(
@@ -327,12 +290,10 @@
// 调用 SaveTorrent
int ret = tracker.SaveTorrent(sid, temp);
Assertions.assertEquals(0, ret, "SaveTorrent 应返回 0");
-
// 验证文件已按约定存储
File stored = new File(config.TORRENT_STORAGE_DIR,
sid + "_" + temp.getName());
Assertions.assertTrue(stored.exists(), "存储文件应存在");
-
// 验证数据库中 url 字段已更新
em.clear();
Seed seed = em.find(Seed.class, sid);
@@ -342,14 +303,12 @@
new File(seed.url).getAbsolutePath(),
"Seed.url 应更新为存储路径"
);
-
// 清理测试文件
stored.delete();
temp.delete();
}))
.collect(Collectors.toList());
}
-
@TestFactory
Collection<DynamicTest> testGetTTorent() {
// 拿到所有 seedid
@@ -362,12 +321,10 @@
File temp = File.createTempFile(sid + "_test", ".torrent");
int saveRet = tracker.SaveTorrent(sid, temp);
Assertions.assertEquals(0, saveRet, "SaveTorrent 应返回 0");
-
// 刷新上下文并取回更新后的 seed 实体
em.clear();
Seed seed = em.find(Seed.class, sid);
Assertions.assertNotNull(seed.url, "Seed.url 应已被更新");
-
// 调用 GetTTorent 并断言路径一致
String uid = userIds.get(0), ip = "127.0.0.1";
File ret = tracker.GetTTorent(sid, uid, ip);
@@ -378,7 +335,6 @@
ret.getAbsolutePath(),
"返回文件路径应与Seed.url一致"
);
-
// 清理:删掉本地文件,回滚 DB url 字段,删掉 temp
expected.delete();
EntityTransaction tx = em.getTransaction();
@@ -390,4 +346,4 @@
}))
.collect(Collectors.toList());
}
-}
+}
\ No newline at end of file