-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraper_test.go
107 lines (97 loc) · 2.46 KB
/
scraper_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package zenrows_test
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"testing"
"time"
"github.com/renatoaraujo/go-zenrows"
mocks "github.com/renatoaraujo/go-zenrows/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestScrape(t *testing.T) {
tests := []struct {
name string
timeoutDuration time.Duration
url string
httpClientSetup func(client *mocks.HttpClient)
result string
expectError bool
}{
{
name: "Success scraping data from website",
url: "http://example.com",
httpClientSetup: func(s *mocks.HttpClient) {
s.On("Do", mock.Anything).
Once().
Return(&http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("some content"))),
}, nil)
},
result: "some content",
expectError: false,
},
{
name: "Failed to make the request",
url: "http://example.com",
httpClientSetup: func(s *mocks.HttpClient) {
s.On("Do", mock.Anything).
Once().
Return(nil, errors.New("failed to make the request"))
},
expectError: true,
},
{
name: "Failed with context timeout",
url: "http://example.com",
timeoutDuration: 1 * time.Second,
httpClientSetup: func(s *mocks.HttpClient) {
s.On("Do", mock.Anything).Return(func(req *http.Request) (*http.Response, error) {
select {
case <-req.Context().Done():
return nil, req.Context().Err()
case <-time.After(2 * time.Second):
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("some content"))),
}, nil
}
}).Once()
},
expectError: true,
},
{
name: "Failed to scrape with valid url",
url: "invalid",
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
httpClientMock := mocks.NewHttpClient(t)
if tt.httpClientSetup != nil {
tt.httpClientSetup(httpClientMock)
}
ctx := context.Background()
if tt.timeoutDuration != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, tt.timeoutDuration)
defer cancel()
}
client := zenrows.NewClient(httpClientMock).
WithApiKey("key")
content, err := client.Scrape(ctx, tt.url)
if tt.expectError {
require.Error(t, err)
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.result, content)
})
}
}