|
17 | 17 | package validator |
18 | 18 |
|
19 | 19 | import ( |
| 20 | + "net/http" |
| 21 | + "net/http/httptest" |
20 | 22 | "net/url" |
21 | 23 | "testing" |
22 | 24 |
|
23 | 25 | "github.com/stretchr/testify/require" |
24 | 26 | ) |
25 | 27 |
|
26 | | -func TestURLLivenessCheck(t *testing.T) { |
27 | | - negativeTests := []string{ |
28 | | - "https://dcl-test.org", |
29 | | - "https://httpbin.org/status/404", |
30 | | - "https://httpbin.org/status/500", |
31 | | - } |
32 | | - positiveTests := []string{ |
33 | | - "http://github.com/", // Redirects to https://github.com/ |
34 | | - "https://httpbin.org/status/401", // Private repo |
35 | | - "https://httpbin.org/status/403", // Unavailable for some reason |
| 28 | +func TestIsLiveURL(t *testing.T) { |
| 29 | + tests := []struct { |
| 30 | + name string |
| 31 | + statusCode int |
| 32 | + want bool |
| 33 | + }{ |
| 34 | + {"200 OK", http.StatusOK, true}, |
| 35 | + {"301 redirect", http.StatusMovedPermanently, true}, |
| 36 | + {"401 unauthorized", http.StatusUnauthorized, true}, |
| 37 | + {"403 forbidden", http.StatusForbidden, true}, |
| 38 | + {"451 unavailable for legal reasons", http.StatusUnavailableForLegalReasons, true}, |
| 39 | + {"404 not found", http.StatusNotFound, false}, |
| 40 | + {"500 internal server error", http.StatusInternalServerError, false}, |
| 41 | + {"502 bad gateway", http.StatusBadGateway, false}, |
36 | 42 | } |
37 | 43 |
|
38 | | - for _, testUrl := range negativeTests { |
39 | | - u, err := url.ParseRequestURI(testUrl) |
40 | | - require.NoError(t, err) |
| 44 | + for _, tt := range tests { |
| 45 | + t.Run(tt.name, func(t *testing.T) { |
| 46 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 47 | + require.Equal(t, http.MethodHead, r.Method) |
| 48 | + require.NotEmpty(t, r.Header.Get("User-Agent")) |
| 49 | + w.WriteHeader(tt.statusCode) |
| 50 | + })) |
| 51 | + defer srv.Close() |
| 52 | + |
| 53 | + u, err := url.ParseRequestURI(srv.URL) |
| 54 | + require.NoError(t, err) |
41 | 55 |
|
42 | | - require.False(t, _isLiveURL(u)) |
| 56 | + require.Equal(t, tt.want, isLiveURL(u)) |
| 57 | + }) |
43 | 58 | } |
| 59 | +} |
44 | 60 |
|
45 | | - for _, testUrl := range positiveTests { |
46 | | - u, err := url.ParseRequestURI(testUrl) |
47 | | - require.NoError(t, err) |
| 61 | +func TestIsLiveURLUnreachable(t *testing.T) { |
| 62 | + u, err := url.ParseRequestURI("http://192.0.2.1:1") |
| 63 | + require.NoError(t, err) |
48 | 64 |
|
49 | | - require.True(t, _isLiveURL(u)) |
50 | | - } |
| 65 | + require.False(t, isLiveURL(u)) |
51 | 66 | } |
0 commit comments