-
Notifications
You must be signed in to change notification settings - Fork 157
/
test_api.py
83 lines (73 loc) · 2.7 KB
/
test_api.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
from requests import get, post, put, delete, HTTPError
def test_api():
"""
An automated version of the manual testing I've been doing,
testing the lifecycle of an inserted document.
"""
student_root = "http://localhost:8000/students/"
initial_doc = {
"course": "Test Course",
"email": "[email protected]",
"gpa": "3.0",
"name": "Jane Doe",
}
try:
# Insert a student
response = post(student_root, json=initial_doc)
response.raise_for_status()
doc = response.json()
inserted_id = doc["id"]
print(f"Inserted document with id: {inserted_id}")
print(
"If the test fails in the middle you may want to manually remove the document."
)
assert doc["course"] == "Test Course"
assert doc["email"] == "[email protected]"
assert doc["gpa"] == 3.0
assert doc["name"] == "Jane Doe"
# List students and ensure it's present
response = get(student_root)
response.raise_for_status()
student_ids = {s["id"] for s in response.json()["students"]}
assert inserted_id in student_ids
# Get individual student doc
response = get(student_root + inserted_id)
response.raise_for_status()
doc = response.json()
assert doc["id"] == inserted_id
assert doc["course"] == "Test Course"
assert doc["email"] == "[email protected]"
assert doc["gpa"] == 3.0
assert doc["name"] == "Jane Doe"
# Update the student doc
response = put(
student_root + inserted_id,
json={
"email": "[email protected]",
},
)
response.raise_for_status()
doc = response.json()
assert doc["id"] == inserted_id
assert doc["course"] == "Test Course"
assert doc["email"] == "[email protected]"
assert doc["gpa"] == 3.0
assert doc["name"] == "Jane Doe"
# Get the student doc and check for change
response = get(student_root + inserted_id)
response.raise_for_status()
doc = response.json()
assert doc["id"] == inserted_id
assert doc["course"] == "Test Course"
assert doc["email"] == "[email protected]"
assert doc["gpa"] == 3.0
assert doc["name"] == "Jane Doe"
# Delete the doc
response = delete(student_root + inserted_id)
response.raise_for_status()
# Get the doc and ensure it's been deleted
response = get(student_root + inserted_id)
assert response.status_code == 404
except HTTPError as he:
print(he.response.json())
raise