|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+package files_test
|
|
|
2
|
+
|
|
|
3
|
+import (
|
|
|
4
|
+ "context"
|
|
|
5
|
+ "io"
|
|
|
6
|
+ "net/http"
|
|
|
7
|
+ "net/http/httptest"
|
|
|
8
|
+ "strings"
|
|
|
9
|
+ "testing"
|
|
|
10
|
+
|
|
|
11
|
+ "github.com/9seconds/mtg/v2/ipblocklist/files"
|
|
|
12
|
+ "github.com/stretchr/testify/suite"
|
|
|
13
|
+)
|
|
|
14
|
+
|
|
|
15
|
+type HTTPTestSuite struct {
|
|
|
16
|
+ suite.Suite
|
|
|
17
|
+
|
|
|
18
|
+ httpClient *http.Client
|
|
|
19
|
+ httpServer *httptest.Server
|
|
|
20
|
+ ctx context.Context
|
|
|
21
|
+ ctxCancel context.CancelFunc
|
|
|
22
|
+}
|
|
|
23
|
+
|
|
|
24
|
+func (suite *HTTPTestSuite) makeFile(path string) (files.File, error) {
|
|
|
25
|
+ return files.NewHTTP(suite.httpClient, suite.httpServer.URL+"/"+path)
|
|
|
26
|
+}
|
|
|
27
|
+
|
|
|
28
|
+func (suite *HTTPTestSuite) SetupSuite() {
|
|
|
29
|
+ mux := http.NewServeMux()
|
|
|
30
|
+
|
|
|
31
|
+ mux.Handle("/", http.FileServer(http.Dir("testdata")))
|
|
|
32
|
+
|
|
|
33
|
+ suite.httpServer = httptest.NewServer(mux)
|
|
|
34
|
+ suite.httpClient = suite.httpServer.Client()
|
|
|
35
|
+}
|
|
|
36
|
+
|
|
|
37
|
+func (suite *HTTPTestSuite) SetupTest() {
|
|
|
38
|
+ suite.ctx, suite.ctxCancel = context.WithCancel(context.Background())
|
|
|
39
|
+}
|
|
|
40
|
+
|
|
|
41
|
+func (suite *HTTPTestSuite) TearDownTest() {
|
|
|
42
|
+ suite.ctxCancel()
|
|
|
43
|
+ suite.httpServer.CloseClientConnections()
|
|
|
44
|
+}
|
|
|
45
|
+
|
|
|
46
|
+func (suite *HTTPTestSuite) TearDownSuite() {
|
|
|
47
|
+ suite.httpServer.Close()
|
|
|
48
|
+}
|
|
|
49
|
+
|
|
|
50
|
+func (suite *HTTPTestSuite) TestBadURL() {
|
|
|
51
|
+ _, err := files.NewHTTP(suite.httpClient, "sdfsdf")
|
|
|
52
|
+ suite.Error(err)
|
|
|
53
|
+}
|
|
|
54
|
+
|
|
|
55
|
+func (suite *HTTPTestSuite) TestBadSchema() {
|
|
|
56
|
+ _, err := files.NewHTTP(suite.httpClient, "gopher://lala")
|
|
|
57
|
+ suite.Error(err)
|
|
|
58
|
+}
|
|
|
59
|
+
|
|
|
60
|
+func (suite *HTTPTestSuite) TestNilHTTPClient() {
|
|
|
61
|
+ _, err := files.NewHTTP(nil, "")
|
|
|
62
|
+ suite.Error(err)
|
|
|
63
|
+}
|
|
|
64
|
+
|
|
|
65
|
+func (suite *HTTPTestSuite) TestAbsentFile() {
|
|
|
66
|
+ file, err := suite.makeFile("absent")
|
|
|
67
|
+ suite.NoError(err)
|
|
|
68
|
+
|
|
|
69
|
+ _, err = file.Open(suite.ctx)
|
|
|
70
|
+ suite.Error(err)
|
|
|
71
|
+}
|
|
|
72
|
+
|
|
|
73
|
+func (suite *HTTPTestSuite) TestOk() {
|
|
|
74
|
+ file, err := suite.makeFile("readable")
|
|
|
75
|
+ suite.NoError(err)
|
|
|
76
|
+
|
|
|
77
|
+ readCloser, err := file.Open(suite.ctx)
|
|
|
78
|
+ suite.NoError(err)
|
|
|
79
|
+
|
|
|
80
|
+ defer readCloser.Close()
|
|
|
81
|
+
|
|
|
82
|
+ data, err := io.ReadAll(readCloser)
|
|
|
83
|
+ suite.NoError(err)
|
|
|
84
|
+ suite.Equal("Hooray!", strings.TrimSpace(string(data)))
|
|
|
85
|
+}
|
|
|
86
|
+
|
|
|
87
|
+func TestHTTP(t *testing.T) {
|
|
|
88
|
+ t.Parallel()
|
|
|
89
|
+ suite.Run(t, &HTTPTestSuite{})
|
|
|
90
|
+}
|