locations.integration.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. import { describe, it, expect, beforeEach } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import {
  4. IntegrationTestDatabase,
  5. setupIntegrationDatabaseHooks,
  6. TestDataFactory
  7. } from '~/utils/server/integration-test-db';
  8. import { IntegrationTestAssertions } from '~/utils/server/integration-test-utils';
  9. import { adminLocationsRoutesExport } from '@d8d/server/api';
  10. import { AuthService } from '@d8d/server/modules/auth/auth.service';
  11. import { UserService } from '@d8d/server/modules/users/user.service';
  12. // 设置集成测试钩子
  13. setupIntegrationDatabaseHooks()
  14. describe('地点管理API集成测试', () => {
  15. let client: ReturnType<typeof testClient<typeof adminLocationsRoutesExport>>['api']['v1']['admin'];
  16. let testToken: string;
  17. beforeEach(async () => {
  18. // 创建测试客户端
  19. client = testClient(adminLocationsRoutesExport).api.v1.admin;
  20. // 创建测试用户并生成token
  21. const dataSource = await IntegrationTestDatabase.getDataSource();
  22. const userService = new UserService(dataSource);
  23. const authService = new AuthService(userService);
  24. // 确保admin用户存在
  25. const user = await authService.ensureAdminExists();
  26. // 生成admin用户的token
  27. testToken = authService.generateToken(user);
  28. });
  29. describe('地点创建测试', () => {
  30. it('应该成功创建地点', async () => {
  31. const dataSource = await IntegrationTestDatabase.getDataSource();
  32. const testProvince = await TestDataFactory.createTestArea(dataSource, { level: 1 });
  33. const testCity = await TestDataFactory.createTestArea(dataSource, { level: 2, parentId: testProvince.id });
  34. const testDistrict = await TestDataFactory.createTestArea(dataSource, { level: 3, parentId: testCity.id });
  35. const locationData = {
  36. name: '测试地点',
  37. provinceId: testProvince.id,
  38. cityId: testCity.id,
  39. districtId: testDistrict.id,
  40. address: '测试详细地址',
  41. latitude: 39.9042,
  42. longitude: 116.4074
  43. };
  44. const response = await client.locations.$post({
  45. json: locationData,
  46. },
  47. {
  48. headers: {
  49. 'Authorization': `Bearer ${testToken}`
  50. }
  51. });
  52. // 断言响应
  53. expect(response.status).toBe(201);
  54. if (response.status === 201) {
  55. const responseData = await response.json();
  56. expect(responseData).toHaveProperty('id');
  57. expect(responseData.name).toBe(locationData.name);
  58. expect(responseData.address).toBe(locationData.address);
  59. expect(responseData.isDisabled).toBe(0); // 默认启用
  60. // 断言数据库中存在地点
  61. await IntegrationTestAssertions.expectLocationToExist(responseData.id);
  62. }
  63. });
  64. it('应该拒绝创建无效省市区的地点', async () => {
  65. const locationData = {
  66. name: '测试无效地点',
  67. provinceId: 999999,
  68. cityId: 999999,
  69. districtId: 999999,
  70. address: '测试详细地址',
  71. latitude: 39.9042,
  72. longitude: 116.4074
  73. };
  74. const response = await client.locations.$post({
  75. json: locationData,
  76. },
  77. {
  78. headers: {
  79. 'Authorization': `Bearer ${testToken}`
  80. }
  81. });
  82. // 应该返回验证错误
  83. expect([400, 500]).toContain(response.status);
  84. });
  85. });
  86. describe('地点读取测试', () => {
  87. it('应该成功获取地点列表', async () => {
  88. const dataSource = await IntegrationTestDatabase.getDataSource();
  89. if (!dataSource) throw new Error('Database not initialized');
  90. // 创建几个测试地点
  91. await TestDataFactory.createTestLocation(dataSource, { name: '地点1' });
  92. await TestDataFactory.createTestLocation(dataSource, { name: '地点2' });
  93. const response = await client.locations.$get({
  94. query: {}
  95. },
  96. {
  97. headers: {
  98. 'Authorization': `Bearer ${testToken}`
  99. }
  100. });
  101. if (response.status !== 200) {
  102. const errorData = await response.json();
  103. console.debug('获取地点列表失败:', errorData);
  104. }
  105. expect(response.status).toBe(200);
  106. if (response.status === 200) {
  107. const responseData = await response.json();
  108. expect(Array.isArray(responseData.data)).toBe(true);
  109. expect(responseData.data.length).toBeGreaterThanOrEqual(2);
  110. }
  111. });
  112. it('应该成功获取单个地点详情', async () => {
  113. const dataSource = await IntegrationTestDatabase.getDataSource();
  114. if (!dataSource) throw new Error('Database not initialized');
  115. const testLocation = await TestDataFactory.createTestLocation(dataSource, {
  116. name: '测试地点详情'
  117. });
  118. const response = await client.locations[':id'].$get({
  119. param: { id: testLocation.id }
  120. },
  121. {
  122. headers: {
  123. 'Authorization': `Bearer ${testToken}`
  124. }
  125. });
  126. expect(response.status).toBe(200);
  127. if (response.status === 200) {
  128. const responseData = await response.json();
  129. expect(responseData.id).toBe(testLocation.id);
  130. expect(responseData.name).toBe(testLocation.name);
  131. expect(responseData.address).toBe(testLocation.address);
  132. }
  133. });
  134. it('应该返回404当地点不存在时', async () => {
  135. const response = await client.locations[':id'].$get({
  136. param: { id: 999999 }
  137. },
  138. {
  139. headers: {
  140. 'Authorization': `Bearer ${testToken}`
  141. }
  142. });
  143. expect(response.status).toBe(404);
  144. if (response.status === 404) {
  145. const responseData = await response.json();
  146. expect(responseData.message).toContain('资源不存在');
  147. }
  148. });
  149. });
  150. describe('地点更新测试', () => {
  151. it('应该成功更新地点信息', async () => {
  152. const dataSource = await IntegrationTestDatabase.getDataSource();
  153. if (!dataSource) throw new Error('Database not initialized');
  154. const testLocation = await TestDataFactory.createTestLocation(dataSource, {
  155. name: '测试地点更新'
  156. });
  157. const updateData = {
  158. name: '更新后的地点名称',
  159. address: '更新后的详细地址'
  160. };
  161. const response = await client.locations[':id'].$put({
  162. param: { id: testLocation.id },
  163. json: updateData
  164. },
  165. {
  166. headers: {
  167. 'Authorization': `Bearer ${testToken}`
  168. }
  169. });
  170. expect(response.status).toBe(200);
  171. if (response.status === 200) {
  172. const responseData = await response.json();
  173. expect(responseData.name).toBe(updateData.name);
  174. expect(responseData.address).toBe(updateData.address);
  175. }
  176. // 验证数据库中的更新
  177. const getResponse = await client.locations[':id'].$get({
  178. param: { id: testLocation.id }
  179. },
  180. {
  181. headers: {
  182. 'Authorization': `Bearer ${testToken}`
  183. }
  184. });
  185. if (getResponse.status === 200) {
  186. expect(getResponse.status).toBe(200);
  187. const getResponseData = await getResponse.json();
  188. expect(getResponseData.name).toBe(updateData.name);
  189. }
  190. });
  191. it('应该成功启用/禁用地地点', async () => {
  192. const dataSource = await IntegrationTestDatabase.getDataSource();
  193. if (!dataSource) throw new Error('Database not initialized');
  194. const testLocation = await TestDataFactory.createTestLocation(dataSource, {
  195. name: '测试状态切换',
  196. isDisabled: 0 // 启用状态
  197. });
  198. // 禁用地地点
  199. const disableResponse = await client.locations[':id'].$put({
  200. param: { id: testLocation.id },
  201. json: { isDisabled: 1 } // 禁用
  202. },
  203. {
  204. headers: {
  205. 'Authorization': `Bearer ${testToken}`
  206. }
  207. });
  208. expect(disableResponse.status).toBe(200);
  209. if (disableResponse.status === 200) {
  210. const disableData = await disableResponse.json();
  211. expect(disableData.isDisabled).toBe(1);
  212. }
  213. // 重新启用地点
  214. const enableResponse = await client.locations[':id'].$put({
  215. param: { id: testLocation.id },
  216. json: { isDisabled: 0 } // 启用
  217. },
  218. {
  219. headers: {
  220. 'Authorization': `Bearer ${testToken}`
  221. }
  222. });
  223. expect(enableResponse.status).toBe(200);
  224. if (enableResponse.status === 200) {
  225. const enableData = await enableResponse.json();
  226. expect(enableData.isDisabled).toBe(0);
  227. }
  228. });
  229. it('应该返回404当更新不存在的地点时', async () => {
  230. const updateData = {
  231. name: '更新后的名称'
  232. };
  233. const response = await client.locations[':id'].$put({
  234. param: { id: 999999 },
  235. json: updateData
  236. },
  237. {
  238. headers: {
  239. 'Authorization': `Bearer ${testToken}`
  240. }
  241. });
  242. expect(response.status).toBe(404);
  243. if (response.status === 404) {
  244. const responseData = await response.json();
  245. expect(responseData.message).toContain('资源不存在');
  246. }
  247. });
  248. });
  249. describe('地点删除测试', () => {
  250. it('应该成功删除地点', async () => {
  251. const dataSource = await IntegrationTestDatabase.getDataSource();
  252. if (!dataSource) throw new Error('Database not initialized');
  253. const testLocation = await TestDataFactory.createTestLocation(dataSource, {
  254. name: '测试地点删除'
  255. });
  256. const response = await client.locations[':id'].$delete({
  257. param: { id: testLocation.id }
  258. },
  259. {
  260. headers: {
  261. 'Authorization': `Bearer ${testToken}`
  262. }
  263. });
  264. IntegrationTestAssertions.expectStatus(response, 204);
  265. // 验证地点已从数据库中删除
  266. await IntegrationTestAssertions.expectLocationNotToExist(testLocation.id);
  267. // 验证再次获取地点返回404
  268. const getResponse = await client.locations[':id'].$get({
  269. param: { id: testLocation.id }
  270. },
  271. {
  272. headers: {
  273. 'Authorization': `Bearer ${testToken}`
  274. }
  275. });
  276. IntegrationTestAssertions.expectStatus(getResponse, 404);
  277. });
  278. it('应该返回404当删除不存在的地点时', async () => {
  279. const response = await client.locations[':id'].$delete({
  280. param: { id: 999999 }
  281. },
  282. {
  283. headers: {
  284. 'Authorization': `Bearer ${testToken}`
  285. }
  286. });
  287. IntegrationTestAssertions.expectStatus(response, 404);
  288. if (response.status === 404) {
  289. const responseData = await response.json();
  290. expect(responseData.message).toContain('资源不存在');
  291. }
  292. });
  293. });
  294. describe('地点搜索测试', () => {
  295. it('应该能够按地点名称搜索地点', async () => {
  296. const dataSource = await IntegrationTestDatabase.getDataSource();
  297. if (!dataSource) throw new Error('Database not initialized');
  298. await TestDataFactory.createTestLocation(dataSource, { name: '搜索地点1', address: '测试地址1' });
  299. await TestDataFactory.createTestLocation(dataSource, { name: '搜索地点2', address: '测试地址2' });
  300. await TestDataFactory.createTestLocation(dataSource, { name: '其他地点', address: '其他地址' });
  301. const response = await client.locations.$get({
  302. query: { keyword: '搜索地点' }
  303. },
  304. {
  305. headers: {
  306. 'Authorization': `Bearer ${testToken}`
  307. }
  308. });
  309. IntegrationTestAssertions.expectStatus(response, 200);
  310. if (response.status === 200) {
  311. const responseData = await response.json();
  312. expect(Array.isArray(responseData.data)).toBe(true);
  313. expect(responseData.data.length).toBe(2);
  314. // 验证搜索结果包含正确的地点
  315. const names = responseData.data.map((location) => location.name);
  316. expect(names).toContain('搜索地点1');
  317. expect(names).toContain('搜索地点2');
  318. expect(names).not.toContain('其他地点');
  319. }
  320. });
  321. it('应该能够按地点地址搜索地点', async () => {
  322. const dataSource = await IntegrationTestDatabase.getDataSource();
  323. if (!dataSource) throw new Error('Database not initialized');
  324. await TestDataFactory.createTestLocation(dataSource, { name: '地点1', address: '测试地址搜索1' });
  325. await TestDataFactory.createTestLocation(dataSource, { name: '地点2', address: '测试地址搜索2' });
  326. const response = await client.locations.$get({
  327. query: { keyword: '测试地址' }
  328. },
  329. {
  330. headers: {
  331. 'Authorization': `Bearer ${testToken}`
  332. }
  333. });
  334. IntegrationTestAssertions.expectStatus(response, 200);
  335. if (response.status === 200) {
  336. const responseData = await response.json();
  337. expect(responseData.data.length).toBe(2);
  338. const addresses = responseData.data.map((location) => location.address);
  339. expect(addresses).toContain('测试地址搜索1');
  340. expect(addresses).toContain('测试地址搜索2');
  341. }
  342. });
  343. it('应该能够按省市区筛选地点', async () => {
  344. const dataSource = await IntegrationTestDatabase.getDataSource();
  345. if (!dataSource) throw new Error('Database not initialized');
  346. const testProvince = await TestDataFactory.createTestArea(dataSource, { level: 1, name: '测试省份' });
  347. const testCity = await TestDataFactory.createTestArea(dataSource, { level: 2, name: '测试城市', parentId: testProvince.id });
  348. await TestDataFactory.createTestLocation(dataSource, {
  349. name: '地点1',
  350. provinceId: testProvince.id,
  351. cityId: testCity.id
  352. });
  353. await TestDataFactory.createTestLocation(dataSource, {
  354. name: '地点2',
  355. provinceId: testProvince.id,
  356. cityId: testCity.id
  357. });
  358. const response = await client.locations.$get({
  359. query: { filters: JSON.stringify({ provinceId: testProvince.id }) }
  360. },
  361. {
  362. headers: {
  363. 'Authorization': `Bearer ${testToken}`
  364. }
  365. });
  366. IntegrationTestAssertions.expectStatus(response, 200);
  367. if (response.status === 200) {
  368. const responseData = await response.json();
  369. expect(responseData.data.length).toBe(2);
  370. const names = responseData.data.map((location) => location.name);
  371. expect(names).toContain('地点1');
  372. expect(names).toContain('地点2');
  373. }
  374. });
  375. });
  376. describe('地点关联关系测试', () => {
  377. it('应该能够获取地点的完整省市区信息', async () => {
  378. const dataSource = await IntegrationTestDatabase.getDataSource();
  379. if (!dataSource) throw new Error('Database not initialized');
  380. const testLocation = await TestDataFactory.createTestLocation(dataSource, {
  381. name: '测试关联关系'
  382. });
  383. const response = await client.locations[':id'].$get({
  384. param: { id: testLocation.id }
  385. },
  386. {
  387. headers: {
  388. 'Authorization': `Bearer ${testToken}`
  389. }
  390. });
  391. expect(response.status).toBe(200);
  392. if (response.status === 200) {
  393. const responseData = await response.json();
  394. expect(responseData).toHaveProperty('province');
  395. expect(responseData).toHaveProperty('city');
  396. expect(responseData).toHaveProperty('district');
  397. // 验证省市区信息存在
  398. expect(responseData.province).toBeDefined();
  399. expect(responseData.city).toBeDefined();
  400. expect(responseData.district).toBeDefined();
  401. }
  402. });
  403. });
  404. describe('性能测试', () => {
  405. it('地点列表查询响应时间应小于200ms', async () => {
  406. const dataSource = await IntegrationTestDatabase.getDataSource();
  407. if (!dataSource) throw new Error('Database not initialized');
  408. // 创建一些测试数据
  409. for (let i = 0; i < 10; i++) {
  410. await TestDataFactory.createTestLocation(dataSource, {
  411. name: `性能测试地点_${i}`,
  412. address: `性能测试地址_${i}`
  413. });
  414. }
  415. const startTime = Date.now();
  416. const response = await client.locations.$get({
  417. query: {}
  418. },
  419. {
  420. headers: {
  421. 'Authorization': `Bearer ${testToken}`
  422. }
  423. });
  424. const endTime = Date.now();
  425. const responseTime = endTime - startTime;
  426. IntegrationTestAssertions.expectStatus(response, 200);
  427. expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
  428. });
  429. });
  430. });