client_test.go 1.7 KB

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