e2e_edge_cases_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. package testutil
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "testing"
  7. "time"
  8. "wails-app/internal/dao"
  9. "wails-app/internal/global"
  10. "wails-app/internal/model/common/response"
  11. dt_svc "wails-app/internal/modules/digital-ticket/service"
  12. )
  13. // TestVehicleReEntry 同一车辆重复入场应被拦截
  14. func TestVehicleReEntry(t *testing.T) {
  15. env := InitTestEnv(t)
  16. createVehicle(t, env, "JingR00001", "RFID_REENTRY", 1)
  17. entryResp, entryBody := env.DoPost("/vehicle/entry", map[string]interface{}{
  18. "plate_number": "JingR00001", "rfid_tag": "RFID_REENTRY",
  19. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  20. })
  21. AssertResponse(t, entryResp, entryBody, http.StatusOK, response.SUCCESS)
  22. _, entryBody2 := env.DoPost("/vehicle/entry", map[string]interface{}{
  23. "plate_number": "JingR00001", "rfid_tag": "RFID_REENTRY",
  24. "parking_lot_id": 1, "parking_space_id": 2, "entry_image": "test2.jpg",
  25. })
  26. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  27. json.Unmarshal(entryBody2, &result)
  28. if result.Code == response.SUCCESS {
  29. t.Fatalf("BUG: Vehicle re-entry was NOT blocked! code=%d msg=%s", result.Code, result.Msg)
  30. }
  31. fmt.Println("PASS: Re-entry attempt correctly rejected")
  32. }
  33. // TestExitWithoutEntry 未入场车辆尝试出场应返回错误
  34. func TestExitWithoutEntry(t *testing.T) {
  35. env := InitTestEnv(t)
  36. _, exitPreviewBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  37. "plate_number": "JingZ99999", "rfid_tag": "RFID_NOENTRY",
  38. })
  39. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  40. json.Unmarshal(exitPreviewBody, &result)
  41. if result.Code == response.SUCCESS {
  42. t.Fatalf("BUG: Exit preview succeeded for non-entered vehicle!")
  43. }
  44. fmt.Println("PASS: Exit without entry correctly rejected")
  45. }
  46. // TestPaymentInsufficientAmount 支付金额不足时的行为
  47. func TestPaymentInsufficientAmount(t *testing.T) {
  48. env := InitTestEnv(t)
  49. createVehicle(t, env, "JingP00001", "RFID_PAY", 1)
  50. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  51. "plate_number": "JingP00001", "rfid_tag": "RFID_PAY",
  52. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  53. })
  54. entryTime := time.Now().Add(-3 * time.Hour)
  55. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingP00001").Update("entry_time", entryTime)
  56. _, exitConfirmBody := env.DoPost("/vehicle/exit/confirm", map[string]interface{}{
  57. "plate_number": "JingP00001", "rfid_tag": "RFID_PAY",
  58. "payment_method": "cash", "paid_amount": 0.0,
  59. })
  60. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  61. json.Unmarshal(exitConfirmBody, &result)
  62. fmt.Printf("INFO: Insufficient payment response: code=%d msg=%s\n", result.Code, result.Msg)
  63. }
  64. // TestVIPExpired 过期 VIP 应恢复普通计费
  65. func TestVIPExpired(t *testing.T) {
  66. env := InitTestEnv(t)
  67. ownerResp, ownerBody := env.DoPost("/owner/create", map[string]interface{}{
  68. "owner_name": "VIP Expired Test", "owner_surname": "VIP",
  69. "owner_phone": "13900000001", "is_vip": true,
  70. "vip_expire_time": time.Now().Add(-24*time.Hour).Format(time.RFC3339),
  71. })
  72. AssertResponse(t, ownerResp, ownerBody, http.StatusOK, response.SUCCESS)
  73. var owner dao.Owner
  74. env.DB.Where("owner_phone = ?", "13900000001").First(&owner)
  75. createVehicleWithOwner(t, env, "JingV00001", "RFID_VIP_EXP", owner.ID)
  76. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  77. "plate_number": "JingV00001", "rfid_tag": "RFID_VIP_EXP",
  78. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  79. })
  80. entryTime := time.Now().Add(-3 * time.Hour)
  81. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingV00001").Update("entry_time", entryTime)
  82. exitResp, exitBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  83. "plate_number": "JingV00001", "rfid_tag": "RFID_VIP_EXP",
  84. })
  85. AssertResponse(t, exitResp, exitBody, http.StatusOK, response.SUCCESS)
  86. var result struct {
  87. Data struct {
  88. Fee float64 `json:"fee"`
  89. } `json:"data"`
  90. }
  91. json.Unmarshal(exitBody, &result)
  92. if result.Data.Fee == 0 {
  93. t.Fatalf("BUG: Expired VIP still getting free parking! Fee should be > 0")
  94. }
  95. fmt.Printf("PASS: Expired VIP charged correctly, fee=%.2f\n", result.Data.Fee)
  96. }
  97. // TestFreeDuration 免费时长内不应收费
  98. func TestFreeDuration(t *testing.T) {
  99. env := InitTestEnv(t)
  100. createVehicle(t, env, "JingF00001", "RFID_FREE", 1)
  101. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  102. "plate_number": "JingF00001", "rfid_tag": "RFID_FREE",
  103. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  104. })
  105. entryTime := time.Now().Add(-10 * time.Minute)
  106. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingF00001").Update("entry_time", entryTime)
  107. exitResp, exitBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  108. "plate_number": "JingF00001", "rfid_tag": "RFID_FREE",
  109. })
  110. AssertResponse(t, exitResp, exitBody, http.StatusOK, response.SUCCESS)
  111. var preview struct { Fee float64 `json:"fee"` }
  112. json.Unmarshal(exitBody, &preview)
  113. if preview.Fee != 0 {
  114. t.Fatalf("BUG: Vehicle within free duration should have zero fee, got %.2f", preview.Fee)
  115. }
  116. fmt.Println("PASS: Free duration correctly applied")
  117. }
  118. // TestDailyCap 超过每日封顶费用应封顶
  119. func TestDailyCap(t *testing.T) {
  120. env := InitTestEnv(t)
  121. createVehicle(t, env, "JingD00001", "RFID_CAP", 1)
  122. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  123. "plate_number": "JingD00001", "rfid_tag": "RFID_CAP",
  124. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  125. })
  126. entryTime := time.Now().Add(-24 * time.Hour)
  127. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingD00001").Update("entry_time", entryTime)
  128. exitResp, exitBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  129. "plate_number": "JingD00001", "rfid_tag": "RFID_CAP",
  130. })
  131. AssertResponse(t, exitResp, exitBody, http.StatusOK, response.SUCCESS)
  132. var preview struct { Fee float64 `json:"fee"` }
  133. json.Unmarshal(exitBody, &preview)
  134. if preview.Fee > 50.0 {
  135. t.Fatalf("BUG: Fee exceeds daily cap! Expected <= 50, got %.2f", preview.Fee)
  136. }
  137. fmt.Printf("PASS: Daily cap applied correctly, fee=%.2f\n", preview.Fee)
  138. }
  139. // TestNoFeeConfig 无收费配置时默认计费
  140. func TestNoFeeConfig(t *testing.T) {
  141. env := InitTestEnv(t)
  142. var normalType dao.VehicleType
  143. env.DB.Where("is_system = ? AND name != ?", true, "临时车").First(&normalType)
  144. if normalType.ID == 0 {
  145. normalType = dao.VehicleType{Name: "特殊车", Remarks: "无收费配置"}
  146. env.DB.Create(&normalType)
  147. }
  148. env.DB.Where("vehicle_type_id = ?", normalType.ID).Delete(&dao.FeeConfig{})
  149. createVehicleWithOwner(t, env, "JingN00001", "RFID_NOFEE", normalType.ID)
  150. _, _ = env.DoPost("/vehicle/entry", map[string]interface{}{
  151. "plate_number": "JingN00001", "rfid_tag": "RFID_NOFEE",
  152. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  153. })
  154. entryTime := time.Now().Add(-1 * time.Hour)
  155. global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", "JingN00001").Update("entry_time", entryTime)
  156. exitResp, exitBody := env.DoPost("/vehicle/exit/preview", map[string]interface{}{
  157. "plate_number": "JingN00001", "rfid_tag": "RFID_NOFEE",
  158. })
  159. AssertResponse(t, exitResp, exitBody, http.StatusOK, response.SUCCESS)
  160. var result struct {
  161. Data struct {
  162. Fee float64 `json:"fee"`
  163. } `json:"data"`
  164. }
  165. json.Unmarshal(exitBody, &result)
  166. if result.Data.Fee <= 0 {
  167. t.Fatalf("BUG: No fee config should use default rate, got fee=%.2f", result.Data.Fee)
  168. }
  169. fmt.Printf("PASS: Default fee applied correctly, fee=%.2f\n", result.Data.Fee)
  170. }
  171. // TestShortlistByPlateOrRFID 黑白名单按车牌/RFID查询
  172. func TestShortlistByPlateOrRFID(t *testing.T) {
  173. env := InitTestEnv(t)
  174. createVehicle(t, env, "JingS00001", "RFID_FILTER", 1)
  175. var vehicle dao.Vehicle
  176. env.DB.Where("plate_number = ?", "JingS00001").First(&vehicle)
  177. _, _ = env.DoPost("/shortlist/createShortlist", dao.Shortlist{
  178. ListType: "黑名单", VehicleId: int(vehicle.ID), ExpirationTime: nil,
  179. })
  180. resp1, body1 := env.DoPost("/shortlist/queryShortlistList", map[string]interface{}{
  181. "page": 1, "pageSize": 10, "list_type": "", "plate_number": "JingS00001",
  182. })
  183. AssertResponse(t, resp1, body1, http.StatusOK, response.SUCCESS)
  184. list1 := ParsePageList(body1)
  185. if len(list1) < 1 { t.Fatalf("Expected at least 1 shortlist record by plate number") }
  186. fmt.Printf("PASS: Shortlist query by plate number returned %d records\n", len(list1))
  187. resp2, body2 := env.DoPost("/shortlist/queryShortlistList", map[string]interface{}{
  188. "page": 1, "pageSize": 10, "list_type": "", "rfid_tag": "RFID_FILTER",
  189. })
  190. AssertResponse(t, resp2, body2, http.StatusOK, response.SUCCESS)
  191. list2 := ParsePageList(body2)
  192. if len(list2) < 1 { t.Fatalf("Expected at least 1 shortlist record by RFID") }
  193. fmt.Printf("PASS: Shortlist query by RFID returned %d records\n", len(list2))
  194. }
  195. // TestShortlistUpdate 黑白名单更新
  196. func TestShortlistUpdate(t *testing.T) {
  197. env := InitTestEnv(t)
  198. createVehicle(t, env, "JingU00001", "RFID_UPDATE", 1)
  199. var vehicle dao.Vehicle
  200. env.DB.Where("plate_number = ?", "JingU00001").First(&vehicle)
  201. _, _ = env.DoPost("/shortlist/createShortlist", dao.Shortlist{
  202. ListType: "白名单", VehicleId: int(vehicle.ID), ExpirationTime: nil,
  203. })
  204. queryResp, queryBody := env.DoGet("/shortlist/queryAllShortlists", nil)
  205. AssertResponse(t, queryResp, queryBody, http.StatusOK, response.SUCCESS)
  206. var result struct { Data []map[string]interface{} `json:"data"` }
  207. json.Unmarshal(queryBody, &result)
  208. if len(result.Data) == 0 { t.Fatalf("No shortlist found") }
  209. idVal, ok := result.Data[0]["ID"]; if !ok { idVal = result.Data[0]["id"] }
  210. id := int(idVal.(float64))
  211. updateResp, updateBody := env.DoPut("/shortlist/updateShortlist", map[string]interface{}{
  212. "ID": id, "list_type": "黑名单", "vehicle_id": vehicle.ID,
  213. "expiration_time": time.Now().Add(30*24*time.Hour).Format(time.RFC3339),
  214. })
  215. AssertResponse(t, updateResp, updateBody, http.StatusOK, response.SUCCESS)
  216. updatedResp, updatedBody := env.DoGet("/shortlist/queryAllShortlists", nil)
  217. AssertResponse(t, updatedResp, updatedBody, http.StatusOK, response.SUCCESS)
  218. fmt.Println("PASS: Shortlist update successful")
  219. }
  220. // TestShortlistDelete 黑白名单删除
  221. func TestShortlistDelete(t *testing.T) {
  222. env := InitTestEnv(t)
  223. createVehicle(t, env, "JingDel001", "RFID_DELETE", 1)
  224. var vehicle dao.Vehicle
  225. env.DB.Where("plate_number = ?", "JingDel001").First(&vehicle)
  226. _, _ = env.DoPost("/shortlist/createShortlist", dao.Shortlist{
  227. ListType: "黑名单", VehicleId: int(vehicle.ID), ExpirationTime: nil,
  228. })
  229. queryResp, queryBody := env.DoGet("/shortlist/queryAllShortlists", nil)
  230. AssertResponse(t, queryResp, queryBody, http.StatusOK, response.SUCCESS)
  231. var result struct { Data []map[string]interface{} `json:"data"` }
  232. json.Unmarshal(queryBody, &result)
  233. if len(result.Data) == 0 { t.Fatalf("No shortlist found") }
  234. idVal, ok := result.Data[0]["ID"]; if !ok { idVal = result.Data[0]["id"] }
  235. id := int(idVal.(float64))
  236. deleteResp, deleteBody := env.DoDelete(fmt.Sprintf("/shortlist/deleteShortlist?id=%d", id))
  237. AssertResponse(t, deleteResp, deleteBody, http.StatusOK, response.SUCCESS)
  238. fmt.Println("PASS: Shortlist delete successful")
  239. }
  240. // TestOwnerVehicleRelationship 车主关联车辆查询
  241. func TestOwnerVehicleRelationship(t *testing.T) {
  242. env := InitTestEnv(t)
  243. ownerResp, ownerBody := env.DoPost("/owner/create", map[string]interface{}{
  244. "owner_name": "Rel Test Owner", "owner_surname": "REL",
  245. "owner_phone": "13911111111", "is_vip": false, "vip_expire_time": nil,
  246. })
  247. AssertResponse(t, ownerResp, ownerBody, http.StatusOK, response.SUCCESS)
  248. var owner dao.Owner
  249. env.DB.Where("owner_phone = ?", "13911111111").First(&owner)
  250. createVehicleWithOwner(t, env, "JingO00001", "RFID_OWNER", owner.ID)
  251. ownerListResp, ownerListBody := env.DoGet("/owner/list", map[string]string{"page": "1", "page_size": "10"})
  252. AssertResponse(t, ownerListResp, ownerListBody, http.StatusOK, response.SUCCESS)
  253. list := ParsePageList(ownerListBody)
  254. found := false
  255. for _, item := range list {
  256. m, ok := item.(map[string]interface{})
  257. if !ok { continue }
  258. if m["owner_phone"] == "13911111111" { found = true; break }
  259. }
  260. if !found { t.Fatalf("Owner not found in list") }
  261. fmt.Println("PASS: Owner-vehicle relationship verified")
  262. }
  263. // TestParkingLotCapacity 停车场容量检查
  264. func TestParkingLotCapacity(t *testing.T) {
  265. env := InitTestEnv(t)
  266. lotResp, lotBody := env.DoPost("/parking/lot/create", map[string]interface{}{
  267. "lot_code": "TEST_EMPTY", "lot_name": "Empty Lot",
  268. "capacity": 0, "description": "Zero capacity test",
  269. })
  270. AssertResponse(t, lotResp, lotBody, http.StatusOK, response.SUCCESS)
  271. createVehicle(t, env, "JingC00001", "RFID_FULL", 1)
  272. _, entryBody := env.DoPost("/vehicle/entry", map[string]interface{}{
  273. "plate_number": "JingC00001", "rfid_tag": "RFID_FULL",
  274. "parking_lot_id": 1, "parking_space_id": 1, "entry_image": "test.jpg",
  275. })
  276. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  277. json.Unmarshal(entryBody, &result)
  278. fmt.Printf("INFO: Entry into zero-capacity lot: code=%d msg=%s\n", result.Code, result.Msg)
  279. }
  280. // TestBoothCRUD 岗亭CRUD
  281. func TestBoothCRUD(t *testing.T) {
  282. env := InitTestEnv(t)
  283. boothResp, boothBody := env.DoPost("/parking/booth/create", map[string]interface{}{
  284. "booth_code": "BT001", "booth_name": "Test Booth",
  285. "parking_lot_id": 1, "description": "Automated test booth",
  286. })
  287. AssertResponse(t, boothResp, boothBody, http.StatusOK, response.SUCCESS)
  288. listResp, listBody := env.DoGet("/parking/booth/list", map[string]string{"page": "1", "page_size": "10"})
  289. AssertResponse(t, listResp, listBody, http.StatusOK, response.SUCCESS)
  290. list := ParsePageList(listBody)
  291. if len(list) < 1 { t.Fatalf("Booth list is empty") }
  292. fmt.Printf("PASS: Booth CRUD successful, total %d booths\n", len(list))
  293. }
  294. // TestChannelCRUD 通道CRUD
  295. func TestChannelCRUD(t *testing.T) {
  296. env := InitTestEnv(t)
  297. channelResp, channelBody := env.DoPost("/parking/channel/create", map[string]interface{}{
  298. "channel_code": "CH-IN-TEST", "channel_name": "Test Entrance",
  299. "direction": "in", "parking_lot_id": 1, "booth_id": 1,
  300. "allow_temporary": true, "description": "Automated test channel",
  301. })
  302. AssertResponse(t, channelResp, channelBody, http.StatusOK, response.SUCCESS)
  303. listResp, listBody := env.DoGet("/parking/channel/list", map[string]string{"page": "1", "page_size": "10"})
  304. AssertResponse(t, listResp, listBody, http.StatusOK, response.SUCCESS)
  305. list := ParsePageList(listBody)
  306. if len(list) < 1 { t.Fatalf("Channel list is empty") }
  307. fmt.Printf("PASS: Channel CRUD successful, total %d channels\n", len(list))
  308. }
  309. // TestDeviceCRUD 设备CRUD
  310. func TestDeviceCRUD(t *testing.T) {
  311. env := InitTestEnv(t)
  312. deviceResp, deviceBody := env.DoPost("/parking/device/create", map[string]interface{}{
  313. "device_code": "DEV001", "device_name": "Test Device",
  314. "device_type": "TCP", "connect_type": "tcp", "ip_address": "127.0.0.1",
  315. "port": 9000, "is_active": true, "parking_lot_id": 1, "channel_id": 1,
  316. "description": "Automated test device",
  317. })
  318. AssertResponse(t, deviceResp, deviceBody, http.StatusOK, response.SUCCESS)
  319. listResp, listBody := env.DoGet("/parking/device/list", map[string]string{"page": "1", "page_size": "10"})
  320. AssertResponse(t, listResp, listBody, http.StatusOK, response.SUCCESS)
  321. list := ParsePageList(listBody)
  322. if len(list) < 1 { t.Fatalf("Device list is empty") }
  323. fmt.Printf("PASS: Device CRUD successful, total %d devices\n", len(list))
  324. }
  325. // TestVehicleTypeCRUD 自定义车辆类型CRUD
  326. func TestVehicleTypeCRUD(t *testing.T) {
  327. env := InitTestEnv(t)
  328. typeResp, typeBody := env.DoPost("/vehicle/type/create", map[string]interface{}{
  329. "name": "新能源车", "remarks": "测试新能源车辆类型", "is_system": false,
  330. })
  331. AssertResponse(t, typeResp, typeBody, http.StatusOK, response.SUCCESS)
  332. listResp, listBody := env.DoGet("/vehicle/type/all", nil)
  333. AssertResponse(t, listResp, listBody, http.StatusOK, response.SUCCESS)
  334. list := ParseDataList(listBody)
  335. if len(list) < 1 { t.Fatalf("Vehicle type list is empty") }
  336. fmt.Printf("PASS: Vehicle type CRUD successful, total %d types\n", len(list))
  337. }
  338. // ===================== Helper functions =====================
  339. // TestVehicleUpdate 车辆信息更新
  340. func TestVehicleUpdate(t *testing.T) {
  341. env := InitTestEnv(t)
  342. createVehicle(t, env, "JingUPD001", "RFID_UPDATE_TEST", 1)
  343. var v dao.Vehicle
  344. env.DB.Where("plate_number = ?", "JingUPD001").First(&v)
  345. resp, body := env.DoPut("/vehicle/update", map[string]interface{}{
  346. "ID": v.ID, "plate_number": "JingUPD001", "vehicle_type_id": 1,
  347. "vehicle_brand": "UpdatedBrand",
  348. "vehicle_color": "Blue", "rfid_tag": "RFID_UPDATE_TEST",
  349. })
  350. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  351. fmt.Println("PASS: Vehicle update successful")
  352. }
  353. // TestVehicleDelete 车辆删除
  354. func TestVehicleDelete(t *testing.T) {
  355. env := InitTestEnv(t)
  356. createVehicle(t, env, "JingDEL001", "RFID_DELETE_TEST", 1)
  357. var v dao.Vehicle
  358. env.DB.Where("plate_number = ?", "JingDEL001").First(&v)
  359. resp, body := env.DoDelete(fmt.Sprintf("/vehicle/delete?id=%d", v.ID))
  360. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  361. fmt.Println("PASS: Vehicle delete successful")
  362. }
  363. // TestVehicleList 车辆分页列表
  364. func TestVehicleList(t *testing.T) {
  365. env := InitTestEnv(t)
  366. createVehicle(t, env, "JingLST001", "RFID_LIST_TEST", 1)
  367. resp, body := env.DoGet("/vehicle/list", map[string]string{"page": "1", "page_size": "10"})
  368. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  369. list := ParsePageList(body)
  370. if len(list) < 1 { t.Fatalf("Vehicle list is empty") }
  371. fmt.Printf("PASS: Vehicle list returned %d records\n", len(list))
  372. }
  373. // TestOwnerUpdate 业主信息更新
  374. func TestOwnerUpdate(t *testing.T) {
  375. env := InitTestEnv(t)
  376. ownerResp, ownerBody := env.DoPost("/owner/create", map[string]interface{}{
  377. "owner_name": "Update Test", "owner_surname": "Upd",
  378. "owner_phone": "13900000999", "is_vip": false,
  379. })
  380. AssertResponse(t, ownerResp, ownerBody, http.StatusOK, response.SUCCESS)
  381. var o dao.Owner
  382. env.DB.Where("owner_phone = ?", "13900000999").First(&o)
  383. updResp, updBody := env.DoPut("/owner/update", map[string]interface{}{
  384. "ID": o.ID, "owner_name": "Updated Name", "owner_surname": "Upd2",
  385. "owner_phone": "13900000999", "is_vip": true,
  386. })
  387. AssertResponse(t, updResp, updBody, http.StatusOK, response.SUCCESS)
  388. fmt.Println("PASS: Owner update successful")
  389. }
  390. // TestOwnerGetByPhone 按手机号查询业主
  391. func TestOwnerGetByPhone(t *testing.T) {
  392. env := InitTestEnv(t)
  393. _, _ = env.DoPost("/owner/create", map[string]interface{}{
  394. "owner_name": "Phone Query", "owner_surname": "Ph",
  395. "owner_phone": "13900000888", "is_vip": false,
  396. })
  397. resp, body := env.DoGet("/owner/get-by-phone", map[string]string{"phone": "13900000888"})
  398. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  399. fmt.Println("PASS: Owner query by phone successful")
  400. }
  401. // TestFeeConfigCreate 收费配置创建
  402. func TestFeeConfigCreate(t *testing.T) {
  403. env := InitTestEnv(t)
  404. // 创建一个新的车辆类型并为其创建收费配置
  405. typeResp, typeBody := env.DoPost("/vehicle/type/create", map[string]interface{}{
  406. "name": "FeeConfigTest", "remarks": "Fee config test type", "is_system": false,
  407. })
  408. AssertResponse(t, typeResp, typeBody, http.StatusOK, response.SUCCESS)
  409. var vt2 dao.VehicleType
  410. env.DB.Where("name = ?", "FeeConfigTest").First(&vt2)
  411. resp, body := env.DoPost("/vehicle/fee-config/create", map[string]interface{}{
  412. "vehicle_type_id": vt2.ID, "start_time": 0, "start_fee": 0,
  413. "unit_time": 60, "unit_fee": 10, "daily_max_fee": 80,
  414. })
  415. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  416. fmt.Println("PASS: Fee config create successful")
  417. }
  418. // TestParkingLotUpdate 停车场信息更新
  419. func TestParkingLotUpdate(t *testing.T) {
  420. env := InitTestEnv(t)
  421. var lot dao.ParkingLot
  422. env.DB.Where("lot_code = ?", "TEST001").First(&lot)
  423. resp, body := env.DoPut("/parking/lot/update", map[string]interface{}{
  424. "ID": lot.ID, "lot_code": "TEST001", "lot_name": "Updated Lot",
  425. "capacity": 200, "description": "Updated desc",
  426. })
  427. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  428. fmt.Println("PASS: Parking lot update successful")
  429. }
  430. // ===================== 月租车管理模块测试 =====================
  431. // TestMonthlyCardCreate 办理月卡
  432. func TestMonthlyCardCreate(t *testing.T) {
  433. env := InitTestEnv(t)
  434. createVehicle(t, env, "JingMC001", "RFID_MC001", 1)
  435. var v dao.Vehicle
  436. env.DB.Where("plate_number = ?", "JingMC001").First(&v)
  437. resp, body := env.DoPost("/monthly-card/create", map[string]interface{}{
  438. "vehicle_id": v.ID, "card_type": "month", "fee": 300.0, "remark": "test month card",
  439. })
  440. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  441. var card dao.MonthlyCard
  442. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  443. if card.ID == 0 { t.Fatalf("Monthly card not created in DB") }
  444. if card.PaymentStatus != "paid" { t.Fatalf("Expected paid, got %s", card.PaymentStatus) }
  445. // Verify shortlist (whitelist) was created
  446. var sl dao.Shortlist
  447. env.DB.Where("vehicle_id = ? AND list_type = ?", v.ID, "白名单").First(&sl)
  448. if sl.ID == 0 { t.Fatalf("Shortlist not created") }
  449. fmt.Println("PASS: Monthly card created successfully")
  450. }
  451. // TestMonthlyCardRenew 月卡续费
  452. func TestMonthlyCardRenew(t *testing.T) {
  453. env := InitTestEnv(t)
  454. createVehicle(t, env, "JingMC002", "RFID_MC002", 1)
  455. var v dao.Vehicle
  456. env.DB.Where("plate_number = ?", "JingMC002").First(&v)
  457. _, _ = env.DoPost("/monthly-card/create", map[string]interface{}{
  458. "vehicle_id": v.ID, "card_type": "month", "fee": 300.0,
  459. })
  460. var card dao.MonthlyCard
  461. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  462. origEnd := card.EndDate
  463. resp, body := env.DoPost("/monthly-card/renew", map[string]interface{}{
  464. "card_id": card.ID, "card_type": "month", "fee": 300.0,
  465. })
  466. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  467. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  468. expectedEnd := origEnd.AddDate(0, 0, 30)
  469. if !card.EndDate.Equal(expectedEnd) && !card.EndDate.After(expectedEnd.Add(-time.Hour*23)) {
  470. t.Fatalf("EndDate not extended correctly: orig=%v, new=%v", origEnd, card.EndDate)
  471. }
  472. fmt.Println("PASS: Monthly card renewed successfully")
  473. }
  474. // TestMonthlyCardRefund 月卡退卡
  475. func TestMonthlyCardRefund(t *testing.T) {
  476. env := InitTestEnv(t)
  477. createVehicle(t, env, "JingMC003", "RFID_MC003", 1)
  478. var v dao.Vehicle
  479. env.DB.Where("plate_number = ?", "JingMC003").First(&v)
  480. _, _ = env.DoPost("/monthly-card/create", map[string]interface{}{
  481. "vehicle_id": v.ID, "card_type": "month", "fee": 300.0,
  482. })
  483. var card dao.MonthlyCard
  484. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  485. resp, body := env.DoDelete(fmt.Sprintf("/monthly-card/refund?id=%d", card.ID))
  486. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  487. env.DB.First(&card, card.ID)
  488. if card.PaymentStatus != "refunded" { t.Fatalf("Expected refunded, got %s", card.PaymentStatus) }
  489. var count int64
  490. env.DB.Model(&dao.Shortlist{}).Where("vehicle_id = ? AND list_type = ?", v.ID, "白名单").Count(&count)
  491. if count != 0 { t.Fatalf("Shortlist should be removed after refund, found %d", count) }
  492. fmt.Println("PASS: Monthly card refunded successfully")
  493. }
  494. // TestMonthlyCardList 月卡列表查询
  495. func TestMonthlyCardList(t *testing.T) {
  496. env := InitTestEnv(t)
  497. createVehicle(t, env, "JingMC004", "RFID_MC004", 1)
  498. var v dao.Vehicle
  499. env.DB.Where("plate_number = ?", "JingMC004").First(&v)
  500. _, _ = env.DoPost("/monthly-card/create", map[string]interface{}{
  501. "vehicle_id": v.ID, "card_type": "quarter", "fee": 800.0,
  502. })
  503. resp, body := env.DoGet("/monthly-card/list", map[string]string{"page": "1", "page_size": "10"})
  504. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  505. list := ParsePageList(body)
  506. if len(list) < 1 { t.Fatalf("Monthly card list is empty") }
  507. resp, body2 := env.DoGet("/monthly-card/list", map[string]string{
  508. "page": "1", "page_size": "10", "card_type": "quarter",
  509. })
  510. AssertResponse(t, resp, body2, http.StatusOK, response.SUCCESS)
  511. list2 := ParsePageList(body2)
  512. if len(list2) < 1 { t.Fatalf("Filtered list by card_type is empty") }
  513. fmt.Printf("PASS: Monthly card list returned %d records\\n", len(list))
  514. }
  515. // TestMonthlyCardDuplicate 重复办卡拦截
  516. func TestMonthlyCardDuplicate(t *testing.T) {
  517. env := InitTestEnv(t)
  518. createVehicle(t, env, "JingMC005", "RFID_MC005", 1)
  519. var v dao.Vehicle
  520. env.DB.Where("plate_number = ?", "JingMC005").First(&v)
  521. _, _ = env.DoPost("/monthly-card/create", map[string]interface{}{
  522. "vehicle_id": v.ID, "card_type": "month", "fee": 300.0,
  523. })
  524. _, body2 := env.DoPost("/monthly-card/create", map[string]interface{}{
  525. "vehicle_id": v.ID, "card_type": "year", "fee": 3000.0,
  526. })
  527. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  528. json.Unmarshal(body2, &result)
  529. if result.Code == response.SUCCESS {
  530. t.Fatalf("BUG: Duplicate monthly card creation was NOT blocked!")
  531. }
  532. fmt.Printf("PASS: Duplicate card creation correctly rejected: %s\\n", result.Msg)
  533. }
  534. // TestMonthlyCardNonexistentRefund 不存在的月卡退卡
  535. func TestMonthlyCardNonexistentRefund(t *testing.T) {
  536. env := InitTestEnv(t)
  537. _, body := env.DoDelete("/monthly-card/refund?id=99999")
  538. // Should fail with error code
  539. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  540. json.Unmarshal(body, &result)
  541. if result.Code == response.SUCCESS {
  542. t.Fatalf("BUG: Refunding non-existent card was NOT blocked!")
  543. }
  544. // HTTP status may vary, just check code != 0
  545. fmt.Printf("PASS: Non-existent card refund correctly rejected: code=%d msg=%s\\n", result.Code, result.Msg)
  546. }
  547. // TestMonthlyCardDifferentTypes 不同套餐类型
  548. func TestMonthlyCardDifferentTypes(t *testing.T) {
  549. env := InitTestEnv(t)
  550. createVehicle(t, env, "JingMC006", "RFID_MC006", 1)
  551. var v dao.Vehicle
  552. env.DB.Where("plate_number = ?", "JingMC006").First(&v)
  553. resp, body := env.DoPost("/monthly-card/create", map[string]interface{}{
  554. "vehicle_id": v.ID, "card_type": "year", "fee": 3000.0,
  555. })
  556. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  557. var card dao.MonthlyCard
  558. env.DB.Where("vehicle_id = ?", v.ID).First(&card)
  559. duration := card.EndDate.Sub(card.StartDate).Hours() / 24
  560. if duration < 360 || duration > 370 {
  561. t.Fatalf("Year card should be ~365 days, got %.0f days", duration)
  562. }
  563. fmt.Printf("PASS: Year card duration = %.0f days\\n", duration)
  564. }
  565. // ===================== 数字票模块测试 =====================
  566. func createTicket(t *testing.T, env *TestEnv, plate, trigger string) (string, uint) {
  567. t.Helper()
  568. createVehicle(t, env, plate, "RFID_"+plate, 1)
  569. var v dao.Vehicle
  570. env.DB.Where("plate_number = ?", plate).First(&v)
  571. rec := dao.VehicleRecord{PlateNumber: plate, RFIDTag: "RFID_" + plate, EntryTime: time.Now(), ParkingLotID: 1}
  572. env.DB.Create(&rec)
  573. var svc = new(dt_svc.TicketService)
  574. ticket, err := svc.Create(plate, trigger, rec.ID)
  575. if err != nil {
  576. t.Fatalf("Failed to create ticket: %v", err)
  577. }
  578. return ticket.TicketNo, ticket.ID
  579. }
  580. // TestDigitalTicketDetail DT01: 查询数字票详情
  581. func TestDigitalTicketDetail(t *testing.T) {
  582. env := InitTestEnv(t)
  583. ticketNo, _ := createTicket(t, env, "DT001", "manual")
  584. resp, body := env.DoGet("/digital-ticket/"+ticketNo, nil)
  585. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  586. data := ParseDataMap(body)
  587. if data["state"] != "pending_payment" {
  588. t.Fatalf("Expected state=pending_payment, got %v", data["state"])
  589. }
  590. if data["ticket_no"] != ticketNo {
  591. t.Fatalf("TicketNo mismatch")
  592. }
  593. if data["trigger_mode"] != "manual" {
  594. t.Fatalf("TriggerMode mismatch")
  595. }
  596. fmt.Println("PASS: Digital ticket detail query successful")
  597. }
  598. // TestDigitalTicketPay DT02: 支付数字票
  599. // BUG: paid_amount 字段在 digital_ticket 表中不存在,PayTicket API 会报 SQL 错误
  600. // 预期: 该测试应失败,暴露后端缺陷
  601. func TestDigitalTicketPay(t *testing.T) {
  602. env := InitTestEnv(t)
  603. ticketNo, _ := createTicket(t, env, "DT002", "plate_recognition")
  604. resp, body := env.DoPost("/digital-ticket/"+ticketNo+"/pay", map[string]interface{}{
  605. "payment_method": "cash", "payment_order_no": "PO002", "paid_amount": 20.0,
  606. })
  607. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  608. fmt.Println("PASS: Pay API works correctly")
  609. }
  610. // TestDigitalTicketExit DT03: 离场验证
  611. func TestDigitalTicketExit(t *testing.T) {
  612. env := InitTestEnv(t)
  613. ticketNo, _ := createTicket(t, env, "DT003", "rfid")
  614. // 支付
  615. _, _ = env.DoPost("/digital-ticket/"+ticketNo+"/pay", map[string]interface{}{
  616. "payment_method": "cash", "payment_order_no": "PO003", "paid_amount": 15.0,
  617. })
  618. // 支付成功后离场
  619. resp, body := env.DoPost("/digital-ticket/"+ticketNo+"/exit", nil)
  620. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  621. fmt.Println("PASS: Pay → Exit flow works correctly")
  622. }
  623. // TestDigitalTicketList DT04: 数字票列表
  624. func TestDigitalTicketList(t *testing.T) {
  625. env := InitTestEnv(t)
  626. createTicket(t, env, "DT004", "manual")
  627. resp, body := env.DoGet("/digital-ticket/list", map[string]string{"page": "1", "page_size": "10"})
  628. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  629. list := ParsePageList(body)
  630. if len(list) < 1 {
  631. t.Fatalf("Ticket list is empty")
  632. }
  633. fmt.Printf("PASS: Digital ticket list returned %d records\n", len(list))
  634. }
  635. // TestDigitalTicketFullFlow DT05: 完整流程
  636. // BUG: Pay API 因 paid_amount 缺失而失败,完整流程无法通过 pay API 完成
  637. // 测试验证: exit API 本身在状态正确时可正常工作
  638. func TestDigitalTicketFullFlow(t *testing.T) {
  639. env := InitTestEnv(t)
  640. ticketNo, _ := createTicket(t, env, "DT005", "manual")
  641. // Pay
  642. resp1, body1 := env.DoPost("/digital-ticket/"+ticketNo+"/pay", map[string]interface{}{
  643. "payment_method": "cash", "payment_order_no": "PO005", "paid_amount": 25.0,
  644. })
  645. AssertResponse(t, resp1, body1, http.StatusOK, response.SUCCESS)
  646. // Exit
  647. resp2, body2 := env.DoPost("/digital-ticket/"+ticketNo+"/exit", nil)
  648. AssertResponse(t, resp2, body2, http.StatusOK, response.SUCCESS)
  649. // Verify state
  650. _, getBody := env.DoGet("/digital-ticket/"+ticketNo, nil)
  651. data := ParseDataMap(getBody)
  652. if data["state"] != "exited" {
  653. t.Fatalf("Expected exited, got state=%v", data["state"])
  654. }
  655. fmt.Println("PASS: Full flow (pay → exit) works correctly")
  656. }
  657. // TestDigitalTicketInvalidExit DT06: 未支付直接离场被拒
  658. func TestDigitalTicketInvalidExit(t *testing.T) {
  659. env := InitTestEnv(t)
  660. ticketNo, _ := createTicket(t, env, "DT006", "manual")
  661. _, body := env.DoPost("/digital-ticket/"+ticketNo+"/exit", nil)
  662. var result struct{ Code int `json:"code"`; Msg string `json:"msg"` }
  663. json.Unmarshal(body, &result)
  664. if result.Code == response.SUCCESS {
  665. t.Fatalf("BUG: Exit without payment was NOT blocked!")
  666. }
  667. fmt.Printf("PASS: Exit without payment correctly rejected: %s\n", result.Msg)
  668. }
  669. // TestDigitalTicketNonexistent DT08: 不存在的票号
  670. func TestDigitalTicketNonexistent(t *testing.T) {
  671. env := InitTestEnv(t)
  672. _, body := env.DoGet("/digital-ticket/FAKE", nil)
  673. var result struct{ Code int `json:"code"`; Msg string `json:"msg"` }
  674. json.Unmarshal(body, &result)
  675. if result.Code == response.SUCCESS {
  676. t.Fatalf("BUG: Non-existent ticket returned success!")
  677. }
  678. fmt.Printf("PASS: Non-existent ticket correctly rejected: %s\n", result.Msg)
  679. }
  680. // TestDigitalTicketListFilter DT09+10: 列表过滤
  681. func TestDigitalTicketListFilter(t *testing.T) {
  682. env := InitTestEnv(t)
  683. createTicket(t, env, "DTFILTER", "manual")
  684. resp, body := env.DoGet("/digital-ticket/list", map[string]string{
  685. "page": "1", "page_size": "10", "plate_number": "DTFILTER",
  686. })
  687. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  688. list := ParsePageList(body)
  689. if len(list) < 1 {
  690. t.Fatalf("Filter by plate returned empty")
  691. }
  692. fmt.Printf("PASS: Ticket list filter returned %d records\n", len(list))
  693. }
  694. // TestDigitalTicketEmptyList DT13: 空列表
  695. func TestDigitalTicketListPagination(t *testing.T) {
  696. env := InitTestEnv(t)
  697. createTicket(t, env, "DTPAGE", "manual")
  698. resp, body := env.DoGet("/digital-ticket/list", map[string]string{"page": "1", "page_size": "5"})
  699. AssertResponse(t, resp, body, http.StatusOK, response.SUCCESS)
  700. list := ParsePageList(body)
  701. if len(list) < 1 {
  702. t.Fatalf("Paginated list is empty")
  703. }
  704. fmt.Printf("PASS: Ticket list pagination returned %d records\n", len(list))
  705. }
  706. func createVehicleWithOwner(t *testing.T, env *TestEnv, plateNumber, rfidTag string, ownerID uint) {
  707. t.Helper()
  708. _, body := env.DoPost("/vehicle/create", map[string]interface{}{
  709. "plate_number": plateNumber, "vehicle_type_id": 1,
  710. "vehicle_brand": "TestBrand", "vehicle_color": "TestColor",
  711. "rfid_tag": rfidTag, "owner_id": ownerID,
  712. })
  713. var result struct { Code int `json:"code"`; Msg string `json:"msg"` }
  714. json.Unmarshal(body, &result)
  715. if result.Code != response.SUCCESS {
  716. t.Fatalf("Failed to create vehicle with owner: %s", result.Msg)
  717. }
  718. }