-
Notifications
You must be signed in to change notification settings - Fork 512
/
test_utils.py
336 lines (237 loc) · 8.25 KB
/
test_utils.py
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import io
import json
import os
from functools import partial
import mock
import pytest
from fake_useragent import errors, settings, utils
from fake_useragent.utils import urlopen_has_ssl_context
from tests.utils import _request, find_unused_port, assets
try: # Python 2 # pragma: no cover
from urllib2 import Request
except ImportError: # Python 3 # pragma: no cover
from urllib.request import Request
def test_utils_get():
assert utils.get('http://google.com') is not None
if urlopen_has_ssl_context:
with pytest.raises(errors.FakeUserAgentError):
utils.get('https://expired.badssl.com/')
assert utils.get(
'https://expired.badssl.com/',
verify_ssl=False,
) is not None
def test_utils_get_retries():
def __retried_request(*args, **kwargs): # noqa
__retried_request.attempt += 1
if __retried_request.attempt < settings.HTTP_RETRIES:
return Request('http://0.0.0.0:{port}'.format(
port=find_unused_port(),
))
return Request(*args, **kwargs)
__retried_request.attempt = 0
with mock.patch(
'fake_useragent.utils.Request',
side_effect=__retried_request,
):
assert utils.get('http://google.com') is not None
assert __retried_request.attempt == 2
def test_utils_get_cache_server():
body = utils.get(settings.CACHE_SERVER).decode('utf-8')
data = json.loads(body)
expected = {
'randomize': mock.ANY,
'browsers': {
'chrome': mock.ANY,
'firefox': mock.ANY,
'opera': mock.ANY,
'safari': mock.ANY,
'internetexplorer': mock.ANY,
},
}
assert expected == data
def test_utils_get_browsers():
browsers = utils.get_browsers()
assert len(browsers) == 5
expected = [
'Firefox',
'Opera',
'Chrome',
'Internet Explorer',
'Safari',
]
browser_names = [browser[0] for browser in browsers]
assert set(expected) == set(browser_names)
total = 100
for _, percentage in browsers:
total -= float(percentage)
assert round(total, 0) <= 2
if urlopen_has_ssl_context:
with mock.patch(
'fake_useragent.utils.Request',
side_effect=partial(
_request,
response_url='https://expired.badssl.com/',
),
):
with pytest.raises(errors.FakeUserAgentError):
utils.get_browsers()
def test_utils_get_browser_versions():
browser_names = [browser[0] for browser in utils.get_browsers()]
for browser in browser_names:
count = len(utils.get_browser_versions(browser))
assert count == settings.BROWSERS_COUNT_LIMIT
if urlopen_has_ssl_context:
with mock.patch(
'fake_useragent.utils.Request',
side_effect=partial(
_request,
response_url='https://expired.badssl.com/',
),
):
with pytest.raises(errors.FakeUserAgentError):
utils.get_browser_versions(browser)
def test_utils_get_browser_versions_no_browser_versions():
browser_names = [browser[0] for browser in utils.get_browsers()]
for browser in browser_names:
with mock.patch('fake_useragent.utils.urlopen') as mocked:
path = os.path.join(assets, 'no_browser_versions.html')
with io.open(path, mode='rb') as fp:
m = mock.Mock()
m.read = fp.read
mocked.return_value = m
with pytest.raises(errors.FakeUserAgentError) as ctx:
utils.get_browser_versions(browser)
assert ctx.value.args[0].startswith('No browsers version')
def test_utils_load(path):
_load = utils.load
with mock.patch(
'fake_useragent.utils.load',
side_effect=_load,
) as mocked:
data = utils.load(use_cache_server=False)
mocked.assert_called()
expected = {
'randomize': mock.ANY,
'browsers': {
'chrome': mock.ANY,
'firefox': mock.ANY,
'opera': mock.ANY,
'safari': mock.ANY,
'internetexplorer': mock.ANY,
},
}
assert expected == data
def test_utils_write(path):
data = {'foo': 'bar'}
utils.write(path, data)
with io.open(path, mode='rt', encoding='utf-8') as fp:
expected = json.loads(fp.read())
assert expected == data
def test_utils_read(path):
data = {'foo': 'bar'}
with io.open(path, mode='wt', encoding='utf-8') as fp:
dumped = json.dumps(data)
if not isinstance(dumped, utils.text): # Python 2
dumped = dumped.decode('utf-8')
fp.write(dumped)
expected = utils.read(path)
assert expected == data
def test_utils_exist(path):
assert not os.path.isfile(path)
assert not utils.exist(path)
with io.open(path, mode='wb') as fp:
fp.write(b'\n')
assert os.path.isfile(path)
assert utils.exist(path)
def test_utils_rm(path):
assert not os.path.isfile(path)
with io.open(path, mode='wb') as fp:
fp.write(b'\n')
assert os.path.isfile(path)
utils.rm(path)
assert not os.path.isfile(path)
def test_utils_update(path):
utils.update(path, use_cache_server=False)
mtime = os.path.getmtime(path)
_load = utils.load
with mock.patch(
'fake_useragent.utils.load',
side_effect=_load,
) as mocked:
utils.update(path, use_cache_server=False)
mocked.assert_called()
assert os.path.getmtime(path) != mtime
def test_utils_load_cached(path):
_load = utils.load
with mock.patch(
'fake_useragent.utils.load',
side_effect=_load,
) as mocked:
data = utils.load_cached(path, use_cache_server=False)
mocked.assert_called()
expected = {
'randomize': mock.ANY,
'browsers': {
'chrome': mock.ANY,
'firefox': mock.ANY,
'opera': mock.ANY,
'safari': mock.ANY,
'internetexplorer': mock.ANY,
},
}
assert expected == data
expected = data
with mock.patch('fake_useragent.utils.load') as mocked:
data = utils.load_cached(path, use_cache_server=False)
mocked.assert_not_called()
assert expected == data
def test_utils_load_no_use_cache_server(path):
denied_urls = [
'https://www.w3schools.com/browsers/browsers_stats.asp',
'http://useragentstring.com/pages/useragentstring.php',
]
with mock.patch(
'fake_useragent.utils.Request',
side_effect=partial(_request, denied_urls=denied_urls),
):
with pytest.raises(errors.FakeUserAgentError):
utils.load(use_cache_server=False)
with pytest.raises(errors.FakeUserAgentError):
utils.load_cached(path, use_cache_server=False)
with pytest.raises(errors.FakeUserAgentError):
utils.update(path, use_cache_server=False)
def test_utils_load_use_cache_server(path):
denied_urls = [
'https://www.w3schools.com/browsers/browsers_stats.asp',
'http://useragentstring.com/pages/useragentstring.php',
]
with mock.patch(
'fake_useragent.utils.Request',
side_effect=partial(_request, denied_urls=denied_urls),
):
data = utils.load(use_cache_server=True)
expected = {
'randomize': mock.ANY,
'browsers': {
'chrome': mock.ANY,
'firefox': mock.ANY,
'opera': mock.ANY,
'safari': mock.ANY,
'internetexplorer': mock.ANY,
},
}
assert expected == data
def test_utils_load_use_cache_server_down(path):
denied_urls = [
'https://www.w3schools.com/browsers/browsers_stats.asp',
'http://useragentstring.com/pages/useragentstring.php',
settings.CACHE_SERVER,
]
with mock.patch(
'fake_useragent.utils.Request',
side_effect=partial(_request, denied_urls=denied_urls),
):
with pytest.raises(errors.FakeUserAgentError):
utils.load(use_cache_server=True)