Skip to content

Commit ae9e1c1

Browse files
authored
Merge pull request #86 from dusktreader/dusktreader/add_response_comparison_operator
Dusktreader/add response comparison operator
2 parents 93b119f + 587d48a commit ae9e1c1

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

pytest_flask/plugin.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
:copyright: (c) by Vital Kudzelka
77
:license: MIT
88
"""
9+
import sys
10+
911
import pytest
1012

1113
from flask import json
@@ -29,6 +31,36 @@ def json(self):
2931
"""
3032
return json.loads(self.data)
3133

34+
def __eq__(self, other):
35+
if isinstance(other, int):
36+
return self.status_code == other
37+
# even though the Python 2-specific code works on Python 3, keep the two versions
38+
# separate so we can simplify the code once Python 2 support is dropped
39+
if sys.version_info[0] == 2:
40+
try:
41+
super_eq = super(JSONResponse, self).__eq__
42+
except AttributeError:
43+
return NotImplemented
44+
else:
45+
return super_eq(other)
46+
else:
47+
return super(JSONResponse, self).__eq__(other)
48+
49+
def __ne__(self, other):
50+
return not self == other
51+
52+
53+
def pytest_assertrepr_compare(op, left, right):
54+
if isinstance(left, JSONResponse) and op == '==' and isinstance(right, int):
55+
return [
56+
'Mismatch in status code for response: {} != {}'.format(
57+
left.status_code,
58+
right,
59+
),
60+
'Response status: {}'.format(left.status),
61+
]
62+
return None
63+
3264

3365
def _make_test_response_class(response_class):
3466
"""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+
assert client.get('fake-route', headers=accept_json) != '404'
40+
res = client.get(url_for('ping'), headers=accept_json)
41+
assert res == res
42+
43+
def test_mismatching_eq_comparison(self, client, accept_json):
44+
with pytest.raises(AssertionError, match=r'Mismatch in status code'):
45+
assert client.get('fake-route', headers=accept_json) == 200
46+
with pytest.raises(AssertionError, match=r'404 NOT FOUND'):
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)