client_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package service
  2. import (
  3. "encoding/json"
  4. "testing"
  5. "github.com/mhsanaei/3x-ui/v3/database/model"
  6. "github.com/mhsanaei/3x-ui/v3/xray"
  7. )
  8. func TestClientWithAttachmentsMarshalJSONIncludesExtras(t *testing.T) {
  9. c := ClientWithAttachments{
  10. ClientRecord: model.ClientRecord{Id: 1, Email: "[email protected]"},
  11. InboundIds: []int{3, 5},
  12. Traffic: &xray.ClientTraffic{Email: "[email protected]", Up: 1024, Down: 4096, Enable: true},
  13. }
  14. out, err := json.Marshal(c)
  15. if err != nil {
  16. t.Fatalf("Marshal failed: %v", err)
  17. }
  18. var parsed map[string]any
  19. if err := json.Unmarshal(out, &parsed); err != nil {
  20. t.Fatalf("output is not valid JSON: %v", err)
  21. }
  22. if parsed["email"] != "[email protected]" {
  23. t.Errorf("expected ClientRecord fields to survive, got %v", parsed)
  24. }
  25. ids, ok := parsed["inboundIds"].([]any)
  26. if !ok {
  27. t.Fatalf("expected inboundIds to be present as an array, got %T (%s)", parsed["inboundIds"], out)
  28. }
  29. if len(ids) != 2 {
  30. t.Errorf("expected 2 inbound ids, got %d", len(ids))
  31. }
  32. if _, ok := parsed["traffic"].(map[string]any); !ok {
  33. t.Errorf("expected traffic to be present as an object, got %T", parsed["traffic"])
  34. }
  35. }
  36. func TestClientWithAttachmentsMarshalJSONOmitsAbsentTraffic(t *testing.T) {
  37. c := ClientWithAttachments{
  38. ClientRecord: model.ClientRecord{Id: 1, Email: "[email protected]"},
  39. InboundIds: nil,
  40. }
  41. out, err := json.Marshal(c)
  42. if err != nil {
  43. t.Fatalf("Marshal failed: %v", err)
  44. }
  45. var parsed map[string]any
  46. if err := json.Unmarshal(out, &parsed); err != nil {
  47. t.Fatalf("output is not valid JSON: %v", err)
  48. }
  49. if _, present := parsed["traffic"]; present {
  50. t.Errorf("expected traffic to be omitted when nil, got %v", parsed["traffic"])
  51. }
  52. if _, present := parsed["inboundIds"]; !present {
  53. t.Errorf("expected inboundIds key to always be present, got %s", out)
  54. }
  55. }