Skip to content

Commit d48ab4d

Browse files
dusktreaderTucker Beck
authored andcommitted
Added comparison operator for status codes
Provided a convenience for quickly checking the status code of a response. Now, comparing a result to an integer will compare the status code against that integer If the comparison fails, a useful failure message is provided that also shows the full status string from the response Furthermore, the object being compared against could be a string. It just has to be a type that *can* be converted to an integer Also added some tests to ensure good behavior such as using the default comparator if the code comparison doesn't work (by virtue of raising an exception -- usually caused by failure to convert right-hand-side to an int.
1 parent 6ad0ae5 commit d48ab4d

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

pytest_flask/plugin.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,29 @@ def json(self):
2929
"""
3030
return json.loads(self.data)
3131

32+
def __eq__(self, other):
33+
try:
34+
status_code = int(other)
35+
return self.status_code == status_code
36+
except:
37+
return super(JSONResponse, self).__eq__(other)
38+
39+
40+
def pytest_assertrepr_compare(op, left, right):
41+
if isinstance(left, JSONResponse) and op == '==':
42+
try:
43+
right = int(right)
44+
return [
45+
'Mismatch in status code for response: {} != {}'.format(
46+
left.status_code,
47+
right,
48+
),
49+
'Response status: {}'.format(left.status),
50+
]
51+
except:
52+
pass
53+
return None
54+
3255

3356
def _make_test_response_class(response_class):
3457
"""Extends the response class with special attribute to test JSON

tests/test_fixtures.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,19 @@ def test_json_response(self, client, accept_json):
3333
res = client.get(url_for('ping'), headers=accept_json)
3434
assert res.json == {'ping': 'pong'}
3535

36+
def test_json_response_compare_to_status_code(self, client, accept_json):
37+
assert client.get(url_for('ping'), headers=accept_json) == 200
38+
assert client.get('fake-route', headers=accept_json) == 404
39+
res = client.get(url_for('ping'), headers=accept_json)
40+
assert res == res
41+
42+
@pytest.mark.xfail(
43+
strict=True,
44+
reason='Assertion comparing result to non-matching int should fail',
45+
)
46+
def test_mismatching_eq_comparison(self, client, accept_json):
47+
assert client.get('fake-route', headers=accept_json) == 200
48+
3649
def test_dont_rewrite_existing_implementation(self, app, accept_json):
3750
class MyResponse(app.response_class):
3851
@property

0 commit comments

Comments
 (0)