|
| 1 | +package check |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "testing" |
| 7 | +) |
| 8 | + |
| 9 | +func TestPortCheck_Pass(t *testing.T) { |
| 10 | + c := &PortCheck{Service: "PostgreSQL", Port: "5432", dialer: func(_ string) error { |
| 11 | + return nil |
| 12 | + }} |
| 13 | + result := c.Run(context.Background()) |
| 14 | + if result.Status != StatusPass { |
| 15 | + t.Errorf("expected pass, got %v: %s", result.Status, result.Message) |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +func TestPortCheck_Fail(t *testing.T) { |
| 20 | + c := &PortCheck{Service: "PostgreSQL", Port: "5432", dialer: func(_ string) error { |
| 21 | + return errors.New("connection refused") |
| 22 | + }} |
| 23 | + result := c.Run(context.Background()) |
| 24 | + if result.Status != StatusFail { |
| 25 | + t.Errorf("expected fail, got %v", result.Status) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +func TestPortCheck_MessageContainsPort(t *testing.T) { |
| 30 | + c := &PortCheck{Service: "Redis", Port: "6379", dialer: func(_ string) error { |
| 31 | + return errors.New("connection refused") |
| 32 | + }} |
| 33 | + result := c.Run(context.Background()) |
| 34 | + if result.Message != "nothing listening on port 6379" { |
| 35 | + t.Errorf("unexpected message: %s", result.Message) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +func TestPortFromURL_StandardURL(t *testing.T) { |
| 40 | + cases := []struct { |
| 41 | + url string |
| 42 | + defaultPort string |
| 43 | + expectedPort string |
| 44 | + }{ |
| 45 | + {"postgres://user:pass@localhost:5555/db", "5432", "5555"}, |
| 46 | + {"redis://localhost:6380", "6379", "6380"}, |
| 47 | + {"mongodb://localhost:27018", "27017", "27018"}, |
| 48 | + {"", "5432", "5432"}, |
| 49 | + {"postgres://localhost/db", "5432", "5432"}, // no port in URL → default |
| 50 | + } |
| 51 | + for _, tc := range cases { |
| 52 | + got := portFromURL(tc.url, tc.defaultPort) |
| 53 | + if got != tc.expectedPort { |
| 54 | + t.Errorf("portFromURL(%q, %q) = %q, want %q", tc.url, tc.defaultPort, got, tc.expectedPort) |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +func TestPortFromURL_MySQLDSN(t *testing.T) { |
| 60 | + got := portFromURL("user:pass@tcp(localhost:3307)/db", "3306") |
| 61 | + if got != "3307" { |
| 62 | + t.Errorf("expected 3307, got %s", got) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +func TestPortFromURL_MySQLDSN_Default(t *testing.T) { |
| 67 | + got := portFromURL("user:pass@tcp(localhost:3306)/db", "3306") |
| 68 | + if got != "3306" { |
| 69 | + t.Errorf("expected 3306, got %s", got) |
| 70 | + } |
| 71 | +} |
0 commit comments