Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added expected_data parameter to register_uri #97

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions httpretty/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
# OTHER DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals

from urlparse import parse_qsl
import re
import inspect
import socket
Expand Down Expand Up @@ -277,6 +278,13 @@ def sendall(self, data, *args, **kw):

for matcher, value in httpretty._entries.items():
if matcher.matches(info):
if matcher.expected_data is not None:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code got a little cluttered here, the indentation got too deep. Maybe lines 281 to 287 could be moved into a function or method and simply be called if matcher.matches(info) ?

body_dict = dict(parse_qsl(request.body))
if body_dict != matcher.expected_data:
raise ValueError("Body Post didn't match, expected %s, got %s" % (
matcher.expected_data,
body_dict
))
entries = value
break

Expand Down Expand Up @@ -601,12 +609,13 @@ class URIMatcher(object):
regex = None
info = None

def __init__(self, uri, entries):
def __init__(self, uri, expected_data, entries):
if type(uri).__name__ == 'SRE_Pattern':
self.regex = uri
else:
self.info = URIInfo.from_uri(uri, entries)

self.expected_data = expected_data
self.entries = entries

#hash of current_entry pointers, per method.
Expand Down Expand Up @@ -683,6 +692,7 @@ def register_uri(cls, method, uri, body='HTTPretty :)',
adding_headers=None,
forcing_headers=None,
status=200,
expected_data=None,
responses=None, **headers):

uri_is_string = isinstance(uri, basestring)
Expand All @@ -705,7 +715,7 @@ def register_uri(cls, method, uri, body='HTTPretty :)',
cls.Response(method=method, uri=uri, **headers),
]

matcher = URIMatcher(uri, entries_for_this_uri)
matcher = URIMatcher(uri, expected_data, entries_for_this_uri)
if matcher in cls._entries:
matcher.entries.extend(cls._entries[matcher])
del cls._entries[matcher]
Expand Down
31 changes: 31 additions & 0 deletions tests/functional/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,3 +626,34 @@ def test_lack_of_trailing_slash():
HTTPretty.register_uri(HTTPretty.GET, url, body='')
response = requests.get(url)
response.status_code.should.equal(200)


@httprettified
def test_httpretty_should_check_post_payload():
"HTTPretty should allow checking POST data payload"

HTTPretty.register_uri(
HTTPretty.POST,
"https://api.imaginary.com/v1/sweet/",
expected_data={'name': "Lollipop"},
body='{"id": 12, "status": "Created"}',
)

response = requests.post(
"https://api.imaginary.com/v1/sweet/",
{"name": "Lollipop"}
)

expect(HTTPretty.last_request.method).to.equal('POST')
expect(HTTPretty.last_request.method).to.equal('POST')
expect(HTTPretty.last_request.body).to.equal(b'name=Lollipop')
expect(response.json()).to.equal({"id": 12, "status": "Created"})

try:
response = requests.post(
"https://api.imaginary.com/v1/sweet/",
{"wrong": "data"}
)
raise Exception("Payload checked didn't work")
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could have used:

requests.post.when.called_with("https://api.imaginary.com/v1/sweet/", {"wrong": "data"}).should.throw(ValueError)

http://falcao.it/sure/reference.html#callable-when-called_with-arg1--kwarg1-2--should-throw-exception-

except ValueError:
pass
45 changes: 45 additions & 0 deletions tests/functional/test_urllib2.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from __future__ import unicode_literals

try:
from urllib import urlencode
from urllib.request import urlopen
import urllib.request as urllib2
except ImportError:
Expand Down Expand Up @@ -335,3 +336,47 @@ def test_httpretty_should_allow_registering_regexes():
fd.close()

expect(got).to.equal(b"Found brand")


@httprettified
def test_httpretty_should_check_post_payload():
"HTTPretty should allow checking POST data payload"

HTTPretty.register_uri(
HTTPretty.POST,
"https://api.imaginary.com/v1/sweet/",
expected_data={'name': "Lollipop"},
body='{"id": 12, "status": "Created"}',
)

request = urllib2.Request(
"https://api.imaginary.com/v1/sweet/",
urlencode({"name": "Lollipop"}),
{
'content-type': 'text/json',
},
)
fd = urllib2.urlopen(request)
got = fd.read()
fd.close()

expect(HTTPretty.last_request.method).to.equal('POST')
expect(HTTPretty.last_request.method).to.equal('POST')
expect(HTTPretty.last_request.body).to.equal(b'name=Lollipop')
expect(got).to.equal(b'{"id": 12, "status": "Created"}')

request = urllib2.Request(
"https://api.imaginary.com/v1/sweet/",
urlencode({"wrong": "data"}),
{
'content-type': 'text/json',
},
)

try:
fd = urllib2.urlopen(request)
got = fd.read()
fd.close()
raise Exception("Payload checked didn't work")
except ValueError:
pass