-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_docs.py
executable file
·70 lines (53 loc) · 1.75 KB
/
test_docs.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
#!/usr/bin/env python
"""
probably shouldn't be doing this, but rolling my own
super basic doctest helps keep docstrings and readme clean.
it's quite fragile, but i'm ok with that.
"""
import re
import requests # noqa
import requests_mock
def test_docs(requests_mock):
# requests_mock makes sure only this url gets hit.
url = 'https://api.example.com/cool/path'
requests_mock.get(url, text='ok')
requests_mock.post(url, text='ok')
with open('README.md') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if ' = ' in line or line.startswith('from '):
print('>>> ' + line)
exec(line)
continue
if not line.startswith('api'):
continue
if not line.endswith(')'):
print('>>> ' + line)
exec(line)
continue
print('>>> resp = ' + line)
resp = eval(line)
assert resp.text == 'ok'
# the below is kinda complicated, and not strictly necessary
# since the logic is tested elsewhere, but eh, i wrote it
# so here it remains.
request_kw = re.search(r'(\w+)=(\{.*\})', line)
if not request_kw:
continue
kw, val = request_kw.groups()
print("#", kw, val)
val = eval(val)
if kw == 'json':
json = eval('resp.request.json()')
assert json == val
elif kw == 'headers':
headers = eval('resp.request.headers')
intersection = {}
for k, v in val.items():
if headers[k] == v:
intersection[k] = v
assert intersection == val
if __name__ == '__main__':
with requests_mock.Mocker() as m:
test_docs(m)