summaryrefslogtreecommitdiff
path: root/tests/unit
diff options
context:
space:
mode:
authorGabriel Falcão <gabriel@nacaolivre.org>2018-11-04 23:34:43 +0100
committerGabriel Falcão <gabriel@nacaolivre.org>2018-11-04 23:34:43 +0100
commit067c4bda72a442e1771374f9d69a5a1c77c88de5 (patch)
tree907b5303ea0c77fbc64daa67e79920577c8edc2f /tests/unit
parent2314893ec5ab46513e91ab867d7b55a72968909e (diff)
downloadhttpretty-black.tar.gz
prettify code with blackblack
Diffstat (limited to 'tests/unit')
-rw-r--r--tests/unit/test_core.py470
-rw-r--r--tests/unit/test_httpretty.py320
-rw-r--r--tests/unit/test_main.py10
3 files changed, 441 insertions, 359 deletions
diff --git a/tests/unit/test_core.py b/tests/unit/test_core.py
index 450b021..0758b73 100644
--- a/tests/unit/test_core.py
+++ b/tests/unit/test_core.py
@@ -19,41 +19,47 @@ class SocketErrorStub(Exception):
def test_request_stubs_internals():
- ("HTTPrettyRequest is a BaseHTTPRequestHandler that replaces "
- "real socket file descriptors with in-memory ones")
+ (
+ "HTTPrettyRequest is a BaseHTTPRequestHandler that replaces "
+ "real socket file descriptors with in-memory ones"
+ )
# Given a valid HTTP request header string
- headers = "\r\n".join([
- 'POST /somewhere/?name=foo&age=bar HTTP/1.1',
- 'accept-encoding: identity',
- 'host: github.com',
- 'content-type: application/json',
- 'connection: close',
- 'user-agent: Python-urllib/2.7',
- ])
+ headers = "\r\n".join(
+ [
+ "POST /somewhere/?name=foo&age=bar HTTP/1.1",
+ "accept-encoding: identity",
+ "host: github.com",
+ "content-type: application/json",
+ "connection: close",
+ "user-agent: Python-urllib/2.7",
+ ]
+ )
# When I create a HTTPrettyRequest with an empty body
- request = HTTPrettyRequest(headers, body='')
+ request = HTTPrettyRequest(headers, body="")
# Then it should have parsed the headers
- dict(request.headers).should.equal({
- 'accept-encoding': 'identity',
- 'connection': 'close',
- 'content-type': 'application/json',
- 'host': 'github.com',
- 'user-agent': 'Python-urllib/2.7'
- })
+ dict(request.headers).should.equal(
+ {
+ "accept-encoding": "identity",
+ "connection": "close",
+ "content-type": "application/json",
+ "host": "github.com",
+ "user-agent": "Python-urllib/2.7",
+ }
+ )
# And the `rfile` should be a StringIO
- type_as_str = StringIO.__module__ + '.' + StringIO.__name__
+ type_as_str = StringIO.__module__ + "." + StringIO.__name__
- request.should.have.property('rfile').being.a(type_as_str)
+ request.should.have.property("rfile").being.a(type_as_str)
# And the `wfile` should be a StringIO
- request.should.have.property('wfile').being.a(type_as_str)
+ request.should.have.property("wfile").being.a(type_as_str)
# And the `method` should be available
- request.should.have.property('method').being.equal('POST')
+ request.should.have.property("method").being.equal("POST")
def test_request_parse_querystring():
@@ -61,88 +67,92 @@ def test_request_parse_querystring():
# Given a request string containing a unicode encoded querystring
- headers = "\r\n".join([
- 'POST /create?name=Gabriel+Falcão HTTP/1.1',
- 'Content-Type: multipart/form-data',
- ])
+ headers = "\r\n".join(
+ [
+ "POST /create?name=Gabriel+Falcão HTTP/1.1",
+ "Content-Type: multipart/form-data",
+ ]
+ )
# When I create a HTTPrettyRequest with an empty body
- request = HTTPrettyRequest(headers, body='')
+ request = HTTPrettyRequest(headers, body="")
# Then it should have a parsed querystring
- request.querystring.should.equal({'name': ['Gabriel Falcão']})
+ request.querystring.should.equal({"name": ["Gabriel Falcão"]})
def test_request_parse_body_when_it_is_application_json():
- ("HTTPrettyRequest#parse_request_body recognizes the "
- "content-type `application/json` and parses it")
+ (
+ "HTTPrettyRequest#parse_request_body recognizes the "
+ "content-type `application/json` and parses it"
+ )
# Given a request string containing a unicode encoded querystring
- headers = "\r\n".join([
- 'POST /create HTTP/1.1',
- 'Content-Type: application/json',
- ])
+ headers = "\r\n".join(["POST /create HTTP/1.1", "Content-Type: application/json"])
# And a valid json body
- body = json.dumps({'name': 'Gabriel Falcão'})
+ body = json.dumps({"name": "Gabriel Falcão"})
# When I create a HTTPrettyRequest with that data
request = HTTPrettyRequest(headers, body)
# Then it should have a parsed body
- request.parsed_body.should.equal({'name': 'Gabriel Falcão'})
+ request.parsed_body.should.equal({"name": "Gabriel Falcão"})
def test_request_parse_body_when_it_is_text_json():
- ("HTTPrettyRequest#parse_request_body recognizes the "
- "content-type `text/json` and parses it")
+ (
+ "HTTPrettyRequest#parse_request_body recognizes the "
+ "content-type `text/json` and parses it"
+ )
# Given a request string containing a unicode encoded querystring
- headers = "\r\n".join([
- 'POST /create HTTP/1.1',
- 'Content-Type: text/json',
- ])
+ headers = "\r\n".join(["POST /create HTTP/1.1", "Content-Type: text/json"])
# And a valid json body
- body = json.dumps({'name': 'Gabriel Falcão'})
+ body = json.dumps({"name": "Gabriel Falcão"})
# When I create a HTTPrettyRequest with that data
request = HTTPrettyRequest(headers, body)
# Then it should have a parsed body
- request.parsed_body.should.equal({'name': 'Gabriel Falcão'})
+ request.parsed_body.should.equal({"name": "Gabriel Falcão"})
def test_request_parse_body_when_it_is_urlencoded():
- ("HTTPrettyRequest#parse_request_body recognizes the "
- "content-type `application/x-www-form-urlencoded` and parses it")
+ (
+ "HTTPrettyRequest#parse_request_body recognizes the "
+ "content-type `application/x-www-form-urlencoded` and parses it"
+ )
# Given a request string containing a unicode encoded querystring
- headers = "\r\n".join([
- 'POST /create HTTP/1.1',
- 'Content-Type: application/x-www-form-urlencoded',
- ])
+ headers = "\r\n".join(
+ ["POST /create HTTP/1.1", "Content-Type: application/x-www-form-urlencoded"]
+ )
# And a valid urlencoded body
- body = "name=Gabriel+Falcão&age=25&projects=httpretty&projects=sure&projects=lettuce"
+ body = (
+ "name=Gabriel+Falcão&age=25&projects=httpretty&projects=sure&projects=lettuce"
+ )
# When I create a HTTPrettyRequest with that data
request = HTTPrettyRequest(headers, body)
# Then it should have a parsed body
- request.parsed_body.should.equal({
- 'name': ['Gabriel Falcão'],
- 'age': ["25"],
- 'projects': ["httpretty", "sure", "lettuce"]
- })
+ request.parsed_body.should.equal(
+ {
+ "name": ["Gabriel Falcão"],
+ "age": ["25"],
+ "projects": ["httpretty", "sure", "lettuce"],
+ }
+ )
def test_request_parse_body_when_unrecognized():
- ("HTTPrettyRequest#parse_request_body returns the value as "
- "is if the Content-Type is not recognized")
+ (
+ "HTTPrettyRequest#parse_request_body returns the value as "
+ "is if the Content-Type is not recognized"
+ )
# Given a request string containing a unicode encoded querystring
- headers = "\r\n".join([
- 'POST /create HTTP/1.1',
- 'Content-Type: whatever',
- ])
+ headers = "\r\n".join(["POST /create HTTP/1.1", "Content-Type: whatever"])
# And a valid urlencoded body
body = "foobar:\nlalala"
@@ -154,14 +164,10 @@ def test_request_parse_body_when_unrecognized():
def test_request_string_representation():
- ("HTTPrettyRequest should have a debug-friendly "
- "string representation")
+ ("HTTPrettyRequest should have a debug-friendly " "string representation")
# Given a request string containing a unicode encoded querystring
- headers = "\r\n".join([
- 'POST /create HTTP/1.1',
- 'Content-Type: JPEG-baby',
- ])
+ headers = "\r\n".join(["POST /create HTTP/1.1", "Content-Type: JPEG-baby"])
# And a valid urlencoded body
body = "foobar:\nlalala"
@@ -169,12 +175,16 @@ def test_request_string_representation():
request = HTTPrettyRequest(headers, body)
# Then its string representation should show the headers and the body
- str(request).should.equal('<HTTPrettyRequest("JPEG-baby", total_headers=1, body_length=14)>')
+ str(request).should.equal(
+ '<HTTPrettyRequest("JPEG-baby", total_headers=1, body_length=14)>'
+ )
def test_fake_ssl_socket_proxies_its_ow_socket():
- ("FakeSSLSocket is a simpel wrapper around its own socket, "
- "which was designed to be a HTTPretty fake socket")
+ (
+ "FakeSSLSocket is a simpel wrapper around its own socket, "
+ "which was designed to be a HTTPretty fake socket"
+ )
# Given a sentinel mock object
socket = Mock()
@@ -189,7 +199,7 @@ def test_fake_ssl_socket_proxies_its_ow_socket():
socket.send.assert_called_once_with("FOO")
-@patch('httpretty.core.datetime')
+@patch("httpretty.core.datetime")
def test_fakesock_socket_getpeercert(dt):
("fakesock.socket#getpeercert should return a hardcoded fake certificate")
# Background:
@@ -199,24 +209,27 @@ def test_fakesock_socket_getpeercert(dt):
socket = fakesock.socket()
# And that it's bound to some host
- socket._host = 'somewhere.com'
+ socket._host = "somewhere.com"
# When I retrieve the peer certificate
certificate = socket.getpeercert()
# Then it should return a hardcoded value
- certificate.should.equal({
- u'notAfter': 'Sep 29 04:20:00 GMT',
- u'subject': (
- ((u'organizationName', u'*.somewhere.com'),),
- ((u'organizationalUnitName', u'Domain Control Validated'),),
- ((u'commonName', u'*.somewhere.com'),)),
- u'subjectAltName': (
- (u'DNS', u'*.somewhere.com'),
- (u'DNS', u'somewhere.com'),
- (u'DNS', u'*')
- )
- })
+ certificate.should.equal(
+ {
+ "notAfter": "Sep 29 04:20:00 GMT",
+ "subject": (
+ (("organizationName", "*.somewhere.com"),),
+ (("organizationalUnitName", "Domain Control Validated"),),
+ (("commonName", "*.somewhere.com"),),
+ ),
+ "subjectAltName": (
+ ("DNS", "*.somewhere.com"),
+ ("DNS", "somewhere.com"),
+ ("DNS", "*"),
+ ),
+ }
+ )
def test_fakesock_socket_ssl():
@@ -234,31 +247,38 @@ def test_fakesock_socket_ssl():
result.should.equal(sentinel)
-@patch('httpretty.core.old_socket')
-@patch('httpretty.core.POTENTIAL_HTTP_PORTS')
+@patch("httpretty.core.old_socket")
+@patch("httpretty.core.POTENTIAL_HTTP_PORTS")
def test_fakesock_socket_connect_fallback(POTENTIAL_HTTP_PORTS, old_socket):
- ("fakesock.socket#connect should open a real connection if the "
- "given port is not a potential http port")
+ (
+ "fakesock.socket#connect should open a real connection if the "
+ "given port is not a potential http port"
+ )
# Background: the potential http ports are 80 and 443
- POTENTIAL_HTTP_PORTS.__contains__.side_effect = lambda other: int(other) in (80, 443)
+ POTENTIAL_HTTP_PORTS.__contains__.side_effect = lambda other: int(other) in (
+ 80,
+ 443,
+ )
# Given a fake socket instance
socket = fakesock.socket()
# When it is connected to a remote server in a port that isn't 80 nor 443
- socket.connect(('somewhere.com', 42))
+ socket.connect(("somewhere.com", 42))
# Then it should have open a real connection in the background
- old_socket.return_value.connect.assert_called_once_with(('somewhere.com', 42))
+ old_socket.return_value.connect.assert_called_once_with(("somewhere.com", 42))
# And _closed is set to False
socket._closed.should.be.false
-@patch('httpretty.core.old_socket')
+@patch("httpretty.core.old_socket")
def test_fakesock_socket_close(old_socket):
- ("fakesock.socket#close should close the actual socket in case "
- "it's not http and _closed is False")
+ (
+ "fakesock.socket#close should close the actual socket in case "
+ "it's not http and _closed is False"
+ )
# Given a fake socket instance that is synthetically open
socket = fakesock.socket()
socket._closed = False
@@ -274,22 +294,24 @@ def test_fakesock_socket_close(old_socket):
socket._closed.should.be.true
-@patch('httpretty.core.old_socket')
+@patch("httpretty.core.old_socket")
def test_fakesock_socket_makefile(old_socket):
- ("fakesock.socket#makefile should set the mode, "
- "bufsize and return its mocked file descriptor")
+ (
+ "fakesock.socket#makefile should set the mode, "
+ "bufsize and return its mocked file descriptor"
+ )
# Given a fake socket that has a mocked Entry associated with it
socket = fakesock.socket()
socket._entry = Mock()
# When I call makefile()
- fd = socket.makefile(mode='rw', bufsize=512)
+ fd = socket.makefile(mode="rw", bufsize=512)
# Then it should have returned the socket's own filedescriptor
expect(fd).to.equal(socket.fd)
# And the mode should have been set in the socket instance
- socket._mode.should.equal('rw')
+ socket._mode.should.equal("rw")
# And the bufsize should have been set in the socket instance
socket._bufsize.should.equal(512)
@@ -297,23 +319,27 @@ def test_fakesock_socket_makefile(old_socket):
socket._entry.fill_filekind.assert_called_once_with(fd)
-@patch('httpretty.core.old_socket')
+@patch("httpretty.core.old_socket")
def test_fakesock_socket_real_sendall(old_socket):
- ("fakesock.socket#real_sendall calls truesock#connect and bails "
- "out when not http")
+ (
+ "fakesock.socket#real_sendall calls truesock#connect and bails "
+ "out when not http"
+ )
# Background: the real socket will stop returning bytes after the
# first call
real_socket = old_socket.return_value
- real_socket.recv.side_effect = [b'response from server', b""]
+ real_socket.recv.side_effect = [b"response from server", b""]
# Given a fake socket
socket = fakesock.socket()
# When I call real_sendall with data, some args and kwargs
- socket.real_sendall(b"SOMEDATA", b'some extra args...', foo=b'bar')
+ socket.real_sendall(b"SOMEDATA", b"some extra args...", foo=b"bar")
# Then it should have called sendall in the real socket
- real_socket.sendall.assert_called_once_with(b"SOMEDATA", b'some extra args...', foo=b'bar')
+ real_socket.sendall.assert_called_once_with(
+ b"SOMEDATA", b"some extra args...", foo=b"bar"
+ )
# And setblocking was never called
real_socket.setblocking.called.should.be.false
@@ -322,38 +348,40 @@ def test_fakesock_socket_real_sendall(old_socket):
real_socket.recv.called.should.be.false
# And the buffer is empty
- socket.fd.read().should.equal(b'')
+ socket.fd.read().should.equal(b"")
# And connect was never called
real_socket.connect.called.should.be.false
-@patch('httpretty.core.old_socket')
+@patch("httpretty.core.old_socket")
def test_fakesock_socket_real_sendall_when_http(old_socket):
- ("fakesock.socket#real_sendall sends data and buffers "
- "the response in the file descriptor")
+ (
+ "fakesock.socket#real_sendall sends data and buffers "
+ "the response in the file descriptor"
+ )
# Background: the real socket will stop returning bytes after the
# first call
real_socket = old_socket.return_value
- real_socket.recv.side_effect = [b'response from server', b""]
+ real_socket.recv.side_effect = [b"response from server", b""]
# Given a fake socket
socket = fakesock.socket()
socket.is_http = True
# When I call real_sendall with data, some args and kwargs
- socket.real_sendall(b"SOMEDATA", b'some extra args...', foo=b'bar')
+ socket.real_sendall(b"SOMEDATA", b"some extra args...", foo=b"bar")
# Then it should have called sendall in the real socket
- real_socket.sendall.assert_called_once_with(b"SOMEDATA", b'some extra args...', foo=b'bar')
+ real_socket.sendall.assert_called_once_with(
+ b"SOMEDATA", b"some extra args...", foo=b"bar"
+ )
# And the socket was set to blocking
real_socket.setblocking.assert_called_once_with(1)
# And recv was called with the bufsize
- real_socket.recv.assert_has_calls([
- call(socket._bufsize)
- ])
+ real_socket.recv.assert_has_calls([call(socket._bufsize)])
# And the buffer should contain the data from the server
socket.fd.read().should.equal(b"response from server")
@@ -362,33 +390,33 @@ def test_fakesock_socket_real_sendall_when_http(old_socket):
real_socket.connect.called.should.be.true
-@patch('httpretty.core.old_socket')
-@patch('httpretty.core.socket')
+@patch("httpretty.core.old_socket")
+@patch("httpretty.core.socket")
def test_fakesock_socket_real_sendall_continue_eagain_when_http(socket, old_socket):
("fakesock.socket#real_sendall should continue if the socket error was EAGAIN")
socket.error = SocketErrorStub
# Background: the real socket will stop returning bytes after the
# first call
real_socket = old_socket.return_value
- real_socket.recv.side_effect = [SocketErrorStub(errno.EAGAIN), b'after error', b""]
+ real_socket.recv.side_effect = [SocketErrorStub(errno.EAGAIN), b"after error", b""]
# Given a fake socket
socket = fakesock.socket()
socket.is_http = True
# When I call real_sendall with data, some args and kwargs
- socket.real_sendall(b"SOMEDATA", b'some extra args...', foo=b'bar')
+ socket.real_sendall(b"SOMEDATA", b"some extra args...", foo=b"bar")
# Then it should have called sendall in the real socket
- real_socket.sendall.assert_called_once_with(b"SOMEDATA", b'some extra args...', foo=b'bar')
+ real_socket.sendall.assert_called_once_with(
+ b"SOMEDATA", b"some extra args...", foo=b"bar"
+ )
# And the socket was set to blocking
real_socket.setblocking.assert_called_once_with(1)
# And recv was called with the bufsize
- real_socket.recv.assert_has_calls([
- call(socket._bufsize)
- ])
+ real_socket.recv.assert_has_calls([call(socket._bufsize)])
# And the buffer should contain the data from the server
socket.fd.read().should.equal(b"after error")
@@ -397,25 +425,27 @@ def test_fakesock_socket_real_sendall_continue_eagain_when_http(socket, old_sock
real_socket.connect.called.should.be.true
-@patch('httpretty.core.old_socket')
-@patch('httpretty.core.socket')
+@patch("httpretty.core.old_socket")
+@patch("httpretty.core.socket")
def test_fakesock_socket_real_sendall_socket_error_when_http(socket, old_socket):
("fakesock.socket#real_sendall should continue if the socket error was EAGAIN")
socket.error = SocketErrorStub
# Background: the real socket will stop returning bytes after the
# first call
real_socket = old_socket.return_value
- real_socket.recv.side_effect = [SocketErrorStub(42), b'after error', ""]
+ real_socket.recv.side_effect = [SocketErrorStub(42), b"after error", ""]
# Given a fake socket
socket = fakesock.socket()
socket.is_http = True
# When I call real_sendall with data, some args and kwargs
- socket.real_sendall(b"SOMEDATA", b'some extra args...', foo=b'bar')
+ socket.real_sendall(b"SOMEDATA", b"some extra args...", foo=b"bar")
# Then it should have called sendall in the real socket
- real_socket.sendall.assert_called_once_with(b"SOMEDATA", b'some extra args...', foo=b'bar')
+ real_socket.sendall.assert_called_once_with(
+ b"SOMEDATA", b"some extra args...", foo=b"bar"
+ )
# And the socket was set to blocking
real_socket.setblocking.assert_called_once_with(1)
@@ -430,14 +460,16 @@ def test_fakesock_socket_real_sendall_socket_error_when_http(socket, old_socket)
real_socket.connect.called.should.be.true
-@patch('httpretty.core.old_socket')
-@patch('httpretty.core.POTENTIAL_HTTP_PORTS')
-def test_fakesock_socket_real_sendall_when_sending_data(POTENTIAL_HTTP_PORTS, old_socket):
+@patch("httpretty.core.old_socket")
+@patch("httpretty.core.POTENTIAL_HTTP_PORTS")
+def test_fakesock_socket_real_sendall_when_sending_data(
+ POTENTIAL_HTTP_PORTS, old_socket
+):
("fakesock.socket#real_sendall should connect before sending data")
# Background: the real socket will stop returning bytes after the
# first call
real_socket = old_socket.return_value
- real_socket.recv.side_effect = [b'response from foobar :)', b""]
+ real_socket.recv.side_effect = [b"response from foobar :)", b""]
# And the potential http port is 4000
POTENTIAL_HTTP_PORTS.__contains__.side_effect = lambda other: int(other) == 4000
@@ -447,107 +479,119 @@ def test_fakesock_socket_real_sendall_when_sending_data(POTENTIAL_HTTP_PORTS, ol
socket = fakesock.socket()
# When I call connect to a server in a port that is considered HTTP
- socket.connect(('foobar.com', 4000))
+ socket.connect(("foobar.com", 4000))
# And send some data
socket.real_sendall(b"SOMEDATA")
# Then connect should have been called
- real_socket.connect.assert_called_once_with(('foobar.com', 4000))
+ real_socket.connect.assert_called_once_with(("foobar.com", 4000))
# And the socket was set to blocking
real_socket.setblocking.assert_called_once_with(1)
# And recv was called with the bufsize
- real_socket.recv.assert_has_calls([
- call(socket._bufsize)
- ])
+ real_socket.recv.assert_has_calls([call(socket._bufsize)])
# And the buffer should contain the data from the server
socket.fd.read().should.equal(b"response from foobar :)")
-@patch('httpretty.core.old_socket')
-@patch('httpretty.core.httpretty')
-@patch('httpretty.core.POTENTIAL_HTTP_PORTS')
-def test_fakesock_socket_sendall_with_valid_requestline(POTENTIAL_HTTP_PORTS, httpretty, old_socket):
- ("fakesock.socket#sendall should create an entry if it's given a valid request line")
- matcher = Mock(name='matcher')
- info = Mock(name='info')
+@patch("httpretty.core.old_socket")
+@patch("httpretty.core.httpretty")
+@patch("httpretty.core.POTENTIAL_HTTP_PORTS")
+def test_fakesock_socket_sendall_with_valid_requestline(
+ POTENTIAL_HTTP_PORTS, httpretty, old_socket
+):
+ (
+ "fakesock.socket#sendall should create an entry if it's given a valid request line"
+ )
+ matcher = Mock(name="matcher")
+ info = Mock(name="info")
httpretty.match_uriinfo.return_value = (matcher, info)
- httpretty.register_uri(httpretty.GET, 'http://foo.com/foobar')
+ httpretty.register_uri(httpretty.GET, "http://foo.com/foobar")
# Background:
# using a subclass of socket that mocks out real_sendall
class MySocket(fakesock.socket):
def real_sendall(self, data, *args, **kw):
- raise AssertionError('should never call this...')
+ raise AssertionError("should never call this...")
# Given an instance of that socket
socket = MySocket()
# And that is is considered http
- socket.connect(('foo.com', 80))
+ socket.connect(("foo.com", 80))
# When I try to send data
socket.sendall(b"GET /foobar HTTP/1.1\r\nContent-Type: application/json\r\n\r\n")
-@patch('httpretty.core.old_socket')
-@patch('httpretty.core.httpretty')
-@patch('httpretty.core.POTENTIAL_HTTP_PORTS')
-def test_fakesock_socket_sendall_with_valid_requestline_2(POTENTIAL_HTTP_PORTS, httpretty, old_socket):
- ("fakesock.socket#sendall should create an entry if it's given a valid request line")
- matcher = Mock(name='matcher')
- info = Mock(name='info')
+@patch("httpretty.core.old_socket")
+@patch("httpretty.core.httpretty")
+@patch("httpretty.core.POTENTIAL_HTTP_PORTS")
+def test_fakesock_socket_sendall_with_valid_requestline_2(
+ POTENTIAL_HTTP_PORTS, httpretty, old_socket
+):
+ (
+ "fakesock.socket#sendall should create an entry if it's given a valid request line"
+ )
+ matcher = Mock(name="matcher")
+ info = Mock(name="info")
httpretty.match_uriinfo.return_value = (matcher, info)
- httpretty.register_uri(httpretty.GET, 'http://foo.com/foobar')
+ httpretty.register_uri(httpretty.GET, "http://foo.com/foobar")
# Background:
# using a subclass of socket that mocks out real_sendall
class MySocket(fakesock.socket):
def real_sendall(self, data, *args, **kw):
- raise AssertionError('should never call this...')
+ raise AssertionError("should never call this...")
# Given an instance of that socket
socket = MySocket()
# And that is is considered http
- socket.connect(('foo.com', 80))
+ socket.connect(("foo.com", 80))
# When I try to send data
socket.sendall(b"GET /foobar HTTP/1.1\r\nContent-Type: application/json\r\n\r\n")
-@patch('httpretty.core.old_socket')
-@patch('httpretty.core.POTENTIAL_HTTP_PORTS')
-def test_fakesock_socket_sendall_with_body_data_no_entry(POTENTIAL_HTTP_PORTS, old_socket):
- ("fakesock.socket#sendall should call real_sendall when not parsing headers and there is no entry")
+@patch("httpretty.core.old_socket")
+@patch("httpretty.core.POTENTIAL_HTTP_PORTS")
+def test_fakesock_socket_sendall_with_body_data_no_entry(
+ POTENTIAL_HTTP_PORTS, old_socket
+):
+ (
+ "fakesock.socket#sendall should call real_sendall when not parsing headers and there is no entry"
+ )
# Background:
# Using a subclass of socket that mocks out real_sendall
class MySocket(fakesock.socket):
def real_sendall(self, data):
- data.should.equal(b'BLABLABLABLA')
- return 'cool'
+ data.should.equal(b"BLABLABLABLA")
+ return "cool"
# Given an instance of that socket
socket = MySocket()
socket._entry = None
# And that is is considered http
- socket.connect(('foo.com', 80))
+ socket.connect(("foo.com", 80))
# When I try to send data
result = socket.sendall(b"BLABLABLABLA")
# Then the result should be the return value from real_sendall
- result.should.equal('cool')
+ result.should.equal("cool")
-@patch('httpretty.core.old_socket')
-@patch('httpretty.core.POTENTIAL_HTTP_PORTS')
-def test_fakesock_socket_sendall_with_body_data_with_entry(POTENTIAL_HTTP_PORTS, old_socket):
+@patch("httpretty.core.old_socket")
+@patch("httpretty.core.POTENTIAL_HTTP_PORTS")
+def test_fakesock_socket_sendall_with_body_data_with_entry(
+ POTENTIAL_HTTP_PORTS, old_socket
+):
("fakesock.socket#sendall should call real_sendall when there is no entry")
# Background:
# Using a subclass of socket that mocks out real_sendall
@@ -561,96 +605,110 @@ def test_fakesock_socket_sendall_with_body_data_with_entry(POTENTIAL_HTTP_PORTS,
socket = MySocket()
# And that is is considered http
- socket.connect(('foo.com', 80))
+ socket.connect(("foo.com", 80))
# When I try to send data
socket.sendall(b"BLABLABLABLA")
# Then it should have called real_sendall
- data_sent.should.equal([b'BLABLABLABLA'])
+ data_sent.should.equal([b"BLABLABLABLA"])
-@patch('httpretty.core.httpretty.match_uriinfo')
-@patch('httpretty.core.old_socket')
-@patch('httpretty.core.POTENTIAL_HTTP_PORTS')
-def test_fakesock_socket_sendall_with_body_data_with_chunked_entry(POTENTIAL_HTTP_PORTS, old_socket, match_uriinfo):
+@patch("httpretty.core.httpretty.match_uriinfo")
+@patch("httpretty.core.old_socket")
+@patch("httpretty.core.POTENTIAL_HTTP_PORTS")
+def test_fakesock_socket_sendall_with_body_data_with_chunked_entry(
+ POTENTIAL_HTTP_PORTS, old_socket, match_uriinfo
+):
("fakesock.socket#sendall should call real_sendall when not ")
# Background:
# Using a subclass of socket that mocks out real_sendall
class MySocket(fakesock.socket):
def real_sendall(self, data):
- raise AssertionError('should have never been called')
+ raise AssertionError("should have never been called")
- matcher = Mock(name='matcher')
- info = Mock(name='info')
+ matcher = Mock(name="matcher")
+ info = Mock(name="info")
httpretty.match_uriinfo.return_value = (matcher, info)
# Using a mocked entry
entry = Mock()
- entry.method = 'GET'
- entry.info.path = '/foo'
+ entry.method = "GET"
+ entry.info.path = "/foo"
- entry.request.headers = {
- 'transfer-encoding': 'chunked',
- }
- entry.request.body = b''
+ entry.request.headers = {"transfer-encoding": "chunked"}
+ entry.request.body = b""
# Given an instance of that socket
socket = MySocket()
socket._entry = entry
# And that is is considered http
- socket.connect(('foo.com', 80))
+ socket.connect(("foo.com", 80))
# When I try to send data
socket.sendall(b"BLABLABLABLA")
# Then the entry should have that body
- httpretty.last_request.body.should.equal(b'BLABLABLABLA')
+ httpretty.last_request.body.should.equal(b"BLABLABLABLA")
def test_URIMatcher_respects_querystring():
("URIMatcher response querystring")
- matcher = URIMatcher('http://www.foo.com/?query=true', None)
- info = URIInfo.from_uri('http://www.foo.com/', None)
+ matcher = URIMatcher("http://www.foo.com/?query=true", None)
+ info = URIInfo.from_uri("http://www.foo.com/", None)
assert matcher.matches(info)
- matcher = URIMatcher('http://www.foo.com/?query=true', None, match_querystring=True)
- info = URIInfo.from_uri('http://www.foo.com/', None)
+ matcher = URIMatcher("http://www.foo.com/?query=true", None, match_querystring=True)
+ info = URIInfo.from_uri("http://www.foo.com/", None)
assert not matcher.matches(info)
- matcher = URIMatcher('http://www.foo.com/?query=true', None, match_querystring=True)
- info = URIInfo.from_uri('http://www.foo.com/?query=true', None)
+ matcher = URIMatcher("http://www.foo.com/?query=true", None, match_querystring=True)
+ info = URIInfo.from_uri("http://www.foo.com/?query=true", None)
assert matcher.matches(info)
- matcher = URIMatcher('http://www.foo.com/?query=true&unquery=false', None, match_querystring=True)
- info = URIInfo.from_uri('http://www.foo.com/?unquery=false&query=true', None)
+ matcher = URIMatcher(
+ "http://www.foo.com/?query=true&unquery=false", None, match_querystring=True
+ )
+ info = URIInfo.from_uri("http://www.foo.com/?unquery=false&query=true", None)
assert matcher.matches(info)
- matcher = URIMatcher('http://www.foo.com/?unquery=false&query=true', None, match_querystring=True)
- info = URIInfo.from_uri('http://www.foo.com/?query=true&unquery=false', None)
+ matcher = URIMatcher(
+ "http://www.foo.com/?unquery=false&query=true", None, match_querystring=True
+ )
+ info = URIInfo.from_uri("http://www.foo.com/?query=true&unquery=false", None)
assert matcher.matches(info)
def test_URIMatcher_equality_respects_querystring():
("URIMatcher equality check should check querystring")
- matcher_a = URIMatcher('http://www.foo.com/?query=true', None)
- matcher_b = URIMatcher('http://www.foo.com/?query=false', None)
+ matcher_a = URIMatcher("http://www.foo.com/?query=true", None)
+ matcher_b = URIMatcher("http://www.foo.com/?query=false", None)
assert matcher_a == matcher_b
- matcher_a = URIMatcher('http://www.foo.com/?query=true', None)
- matcher_b = URIMatcher('http://www.foo.com/', None)
+ matcher_a = URIMatcher("http://www.foo.com/?query=true", None)
+ matcher_b = URIMatcher("http://www.foo.com/", None)
assert matcher_a == matcher_b
- matcher_a = URIMatcher('http://www.foo.com/?query=true', None, match_querystring=True)
- matcher_b = URIMatcher('http://www.foo.com/?query=false', None, match_querystring=True)
+ matcher_a = URIMatcher(
+ "http://www.foo.com/?query=true", None, match_querystring=True
+ )
+ matcher_b = URIMatcher(
+ "http://www.foo.com/?query=false", None, match_querystring=True
+ )
assert not matcher_a == matcher_b
- matcher_a = URIMatcher('http://www.foo.com/?query=true', None, match_querystring=True)
- matcher_b = URIMatcher('http://www.foo.com/', None, match_querystring=True)
+ matcher_a = URIMatcher(
+ "http://www.foo.com/?query=true", None, match_querystring=True
+ )
+ matcher_b = URIMatcher("http://www.foo.com/", None, match_querystring=True)
assert not matcher_a == matcher_b
- matcher_a = URIMatcher('http://www.foo.com/?query=true&unquery=false', None, match_querystring=True)
- matcher_b = URIMatcher('http://www.foo.com/?unquery=false&query=true', None, match_querystring=True)
+ matcher_a = URIMatcher(
+ "http://www.foo.com/?query=true&unquery=false", None, match_querystring=True
+ )
+ matcher_b = URIMatcher(
+ "http://www.foo.com/?unquery=false&query=true", None, match_querystring=True
+ )
assert matcher_a == matcher_b
diff --git a/tests/unit/test_httpretty.py b/tests/unit/test_httpretty.py
index 3ae4f4f..f072b31 100644
--- a/tests/unit/test_httpretty.py
+++ b/tests/unit/test_httpretty.py
@@ -50,38 +50,40 @@ Content-Type: %(content_type)s
def test_httpretty_should_raise_proper_exception_on_inconsistent_length():
- ("HTTPretty should raise proper exception on inconsistent Content-Length / "
- "registered response body")
+ (
+ "HTTPretty should raise proper exception on inconsistent Content-Length / "
+ "registered response body"
+ )
HTTPretty.register_uri.when.called_with(
HTTPretty.GET,
"http://github.com/gabrielfalcao",
body="that's me!",
- adding_headers={
- 'Content-Length': '999'
- }
+ adding_headers={"Content-Length": "999"},
).should.have.raised(
HTTPrettyError,
'HTTPretty got inconsistent parameters. The header Content-Length you registered expects size "999" '
- 'but the body you registered for that has actually length "10".'
+ 'but the body you registered for that has actually length "10".',
)
def test_httpretty_should_raise_on_socket_send_when_uri_registered():
- ("HTTPretty should raise a RuntimeError when the fakesocket is "
- "used in an invalid usage.")
+ (
+ "HTTPretty should raise a RuntimeError when the fakesocket is "
+ "used in an invalid usage."
+ )
import socket
+
HTTPretty.enable()
- HTTPretty.register_uri(HTTPretty.GET,
- 'http://127.0.0.1:5000')
+ HTTPretty.register_uri(HTTPretty.GET, "http://127.0.0.1:5000")
expect(core.POTENTIAL_HTTP_PORTS).to.be.equal(set([80, 5000]))
expect(core.POTENTIAL_HTTPS_PORTS).to.be.equal(set([443]))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.connect(('127.0.0.1', 5000))
- expect(sock.send).when.called_with(b'whatever').to.throw(RuntimeError)
+ sock.connect(("127.0.0.1", 5000))
+ expect(sock.send).when.called_with(b"whatever").to.throw(RuntimeError)
sock.close()
# restore the previous value
@@ -91,17 +93,20 @@ def test_httpretty_should_raise_on_socket_send_when_uri_registered():
def test_httpretty_should_not_raise_on_socket_send_when_uri_not_registered():
- ("HTTPretty should not raise a RuntimeError when the fakesocket "
- "is used in an invalid usage.")
+ (
+ "HTTPretty should not raise a RuntimeError when the fakesocket "
+ "is used in an invalid usage."
+ )
import socket
+
HTTPretty.enable()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
sock.setblocking(0)
- expect(sock.sendto).when.called_with(b'whatever',
- ('127.0.0.1', 53)
- ).should_not.throw(RuntimeError)
+ expect(sock.sendto).when.called_with(
+ b"whatever", ("127.0.0.1", 53)
+ ).should_not.throw(RuntimeError)
sock.close()
HTTPretty.reset()
@@ -109,7 +114,7 @@ def test_httpretty_should_not_raise_on_socket_send_when_uri_not_registered():
def test_does_not_have_last_request_by_default():
- 'HTTPretty.last_request is a dummy object by default'
+ "HTTPretty.last_request is a dummy object by default"
HTTPretty.reset()
expect(HTTPretty.last_request.headers).to.be.empty
@@ -119,93 +124,95 @@ def test_does_not_have_last_request_by_default():
def test_status_codes():
"HTTPretty supports N status codes"
- expect(STATUSES).to.equal({
- 100: "Continue",
- 101: "Switching Protocols",
- 102: "Processing",
- 200: "OK",
- 201: "Created",
- 202: "Accepted",
- 203: "Non-Authoritative Information",
- 204: "No Content",
- 205: "Reset Content",
- 206: "Partial Content",
- 207: "Multi-Status",
- 208: "Already Reported",
- 226: "IM Used",
- 300: "Multiple Choices",
- 301: "Moved Permanently",
- 302: "Found",
- 303: "See Other",
- 304: "Not Modified",
- 305: "Use Proxy",
- 306: "Switch Proxy",
- 307: "Temporary Redirect",
- 308: "Permanent Redirect",
- 400: "Bad Request",
- 401: "Unauthorized",
- 402: "Payment Required",
- 403: "Forbidden",
- 404: "Not Found",
- 405: "Method Not Allowed",
- 406: "Not Acceptable",
- 407: "Proxy Authentication Required",
- 408: "Request a Timeout",
- 409: "Conflict",
- 410: "Gone",
- 411: "Length Required",
- 412: "Precondition Failed",
- 413: "Request Entity Too Large",
- 414: "Request-URI Too Long",
- 415: "Unsupported Media Type",
- 416: "Requested Range Not Satisfiable",
- 417: "Expectation Failed",
- 418: "I'm a teapot",
- 420: "Enhance Your Calm",
- 422: "Unprocessable Entity",
- 423: "Locked",
- 424: "Failed Dependency",
- 425: "Unordered Collection",
- 426: "Upgrade Required",
- 428: "Precondition Required",
- 429: "Too Many Requests",
- 431: "Request Header Fields Too Large",
- 444: "No Response",
- 449: "Retry With",
- 450: "Blocked by Windows Parental Controls",
- 451: "Unavailable For Legal Reasons",
- 494: "Request Header Too Large",
- 495: "Cert Error",
- 496: "No Cert",
- 497: "HTTP to HTTPS",
- 499: "Client Closed Request",
- 500: "Internal Server Error",
- 501: "Not Implemented",
- 502: "Bad Gateway",
- 503: "Service Unavailable",
- 504: "Gateway Timeout",
- 505: "HTTP Version Not Supported",
- 506: "Variant Also Negotiates",
- 507: "Insufficient Storage",
- 508: "Loop Detected",
- 509: "Bandwidth Limit Exceeded",
- 510: "Not Extended",
- 511: "Network Authentication Required",
- 598: "Network read timeout error",
- 599: "Network connect timeout error",
- })
+ expect(STATUSES).to.equal(
+ {
+ 100: "Continue",
+ 101: "Switching Protocols",
+ 102: "Processing",
+ 200: "OK",
+ 201: "Created",
+ 202: "Accepted",
+ 203: "Non-Authoritative Information",
+ 204: "No Content",
+ 205: "Reset Content",
+ 206: "Partial Content",
+ 207: "Multi-Status",
+ 208: "Already Reported",
+ 226: "IM Used",
+ 300: "Multiple Choices",
+ 301: "Moved Permanently",
+ 302: "Found",
+ 303: "See Other",
+ 304: "Not Modified",
+ 305: "Use Proxy",
+ 306: "Switch Proxy",
+ 307: "Temporary Redirect",
+ 308: "Permanent Redirect",
+ 400: "Bad Request",
+ 401: "Unauthorized",
+ 402: "Payment Required",
+ 403: "Forbidden",
+ 404: "Not Found",
+ 405: "Method Not Allowed",
+ 406: "Not Acceptable",
+ 407: "Proxy Authentication Required",
+ 408: "Request a Timeout",
+ 409: "Conflict",
+ 410: "Gone",
+ 411: "Length Required",
+ 412: "Precondition Failed",
+ 413: "Request Entity Too Large",
+ 414: "Request-URI Too Long",
+ 415: "Unsupported Media Type",
+ 416: "Requested Range Not Satisfiable",
+ 417: "Expectation Failed",
+ 418: "I'm a teapot",
+ 420: "Enhance Your Calm",
+ 422: "Unprocessable Entity",
+ 423: "Locked",
+ 424: "Failed Dependency",
+ 425: "Unordered Collection",
+ 426: "Upgrade Required",
+ 428: "Precondition Required",
+ 429: "Too Many Requests",
+ 431: "Request Header Fields Too Large",
+ 444: "No Response",
+ 449: "Retry With",
+ 450: "Blocked by Windows Parental Controls",
+ 451: "Unavailable For Legal Reasons",
+ 494: "Request Header Too Large",
+ 495: "Cert Error",
+ 496: "No Cert",
+ 497: "HTTP to HTTPS",
+ 499: "Client Closed Request",
+ 500: "Internal Server Error",
+ 501: "Not Implemented",
+ 502: "Bad Gateway",
+ 503: "Service Unavailable",
+ 504: "Gateway Timeout",
+ 505: "HTTP Version Not Supported",
+ 506: "Variant Also Negotiates",
+ 507: "Insufficient Storage",
+ 508: "Loop Detected",
+ 509: "Bandwidth Limit Exceeded",
+ 510: "Not Extended",
+ 511: "Network Authentication Required",
+ 598: "Network read timeout error",
+ 599: "Network connect timeout error",
+ }
+ )
def test_uri_info_full_url():
uri_info = URIInfo(
- username='johhny',
- password='password',
- hostname=b'google.com',
+ username="johhny",
+ password="password",
+ hostname=b"google.com",
port=80,
- path=b'/',
- query=b'foo=bar&baz=test',
- fragment='',
- scheme='',
+ path=b"/",
+ query=b"foo=bar&baz=test",
+ fragment="",
+ scheme="",
)
expect(uri_info.full_url()).to.equal(
@@ -222,24 +229,24 @@ def test_uri_info_eq_ignores_case():
hostname matching.
"""
uri_info_uppercase = URIInfo(
- username='johhny',
- password='password',
- hostname=b'GOOGLE.COM',
+ username="johhny",
+ password="password",
+ hostname=b"GOOGLE.COM",
port=80,
- path=b'/',
- query=b'foo=bar&baz=test',
- fragment='',
- scheme='',
+ path=b"/",
+ query=b"foo=bar&baz=test",
+ fragment="",
+ scheme="",
)
uri_info_lowercase = URIInfo(
- username='johhny',
- password='password',
- hostname=b'google.com',
+ username="johhny",
+ password="password",
+ hostname=b"google.com",
port=80,
- path=b'/',
- query=b'foo=bar&baz=test',
- fragment='',
- scheme='',
+ path=b"/",
+ query=b"foo=bar&baz=test",
+ fragment="",
+ scheme="",
)
expect(uri_info_uppercase).to.equal(uri_info_lowercase)
@@ -256,43 +263,48 @@ def test_global_boolean_enabled():
def test_py3kobject_implements_valid__repr__based_on__str__():
class MyObject(BaseClass):
def __str__(self):
- return 'hi'
+ return "hi"
myobj = MyObject()
- expect(repr(myobj)).to.be.equal('hi')
+ expect(repr(myobj)).to.be.equal("hi")
def test_Entry_class_normalizes_headers():
- entry = Entry(HTTPretty.GET, 'http://example.com', 'example',
- host='example.com', cache_control='no-cache', x_forward_for='proxy')
+ entry = Entry(
+ HTTPretty.GET,
+ "http://example.com",
+ "example",
+ host="example.com",
+ cache_control="no-cache",
+ x_forward_for="proxy",
+ )
- entry.adding_headers.should.equal({
- 'Host': 'example.com',
- 'Cache-Control': 'no-cache',
- 'X-Forward-For': 'proxy'
- })
+ entry.adding_headers.should.equal(
+ {"Host": "example.com", "Cache-Control": "no-cache", "X-Forward-For": "proxy"}
+ )
def test_Entry_class_counts_multibyte_characters_in_bytes():
- entry = Entry(HTTPretty.GET, 'http://example.com', 'こんにちは')
+ entry = Entry(HTTPretty.GET, "http://example.com", "こんにちは")
buf = FakeSockFile()
entry.fill_filekind(buf)
response = buf.read()
- expect(b'content-length: 15\n').to.be.within(response)
+ expect(b"content-length: 15\n").to.be.within(response)
def test_Entry_class_counts_dynamic():
- result = (200, {}, 'こんにちは'.encode('utf-8'))
- entry = Entry(HTTPretty.GET, 'http://example.com', lambda *args: result)
- entry.info = URIInfo.from_uri('http://example.com', entry)
+ result = (200, {}, "こんにちは".encode("utf-8"))
+ entry = Entry(HTTPretty.GET, "http://example.com", lambda *args: result)
+ entry.info = URIInfo.from_uri("http://example.com", entry)
buf = FakeSockFile()
entry.fill_filekind(buf)
response = buf.getvalue()
- expect(b'content-length: 15\n').to.be.within(response)
+ expect(b"content-length: 15\n").to.be.within(response)
def test_fake_socket_passes_through_setblocking():
import socket
+
HTTPretty.enable()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
@@ -302,6 +314,7 @@ def test_fake_socket_passes_through_setblocking():
def test_fake_socket_passes_through_fileno():
import socket
+
with httpretty.enabled():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
@@ -311,15 +324,19 @@ def test_fake_socket_passes_through_fileno():
def test_fake_socket_passes_through_getsockopt():
import socket
+
HTTPretty.enable()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
- expect(s.getsockopt).called_with(socket.SOL_SOCKET, 1).should_not.throw(AttributeError)
+ expect(s.getsockopt).called_with(socket.SOL_SOCKET, 1).should_not.throw(
+ AttributeError
+ )
s.truesock.getsockopt.assert_called_with(socket.SOL_SOCKET, 1)
def test_fake_socket_passes_through_bind():
import socket
+
HTTPretty.enable()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
@@ -329,6 +346,7 @@ def test_fake_socket_passes_through_bind():
def test_fake_socket_passes_through_connect_ex():
import socket
+
HTTPretty.enable()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
@@ -338,6 +356,7 @@ def test_fake_socket_passes_through_connect_ex():
def test_fake_socket_passes_through_listen():
import socket
+
HTTPretty.enable()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
@@ -347,6 +366,7 @@ def test_fake_socket_passes_through_listen():
def test_fake_socket_passes_through_getpeername():
import socket
+
HTTPretty.enable()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
@@ -356,6 +376,7 @@ def test_fake_socket_passes_through_getpeername():
def test_fake_socket_passes_through_getsockname():
import socket
+
HTTPretty.enable()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
@@ -365,6 +386,7 @@ def test_fake_socket_passes_through_getsockname():
def test_fake_socket_passes_through_gettimeout():
import socket
+
HTTPretty.enable()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
@@ -374,6 +396,7 @@ def test_fake_socket_passes_through_gettimeout():
def test_fake_socket_passes_through_shutdown():
import socket
+
HTTPretty.enable()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.truesock = MagicMock()
@@ -383,11 +406,12 @@ def test_fake_socket_passes_through_shutdown():
def test_unix_socket():
import socket
+
HTTPretty.enable()
# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- server_address = './not-exist-socket'
+ server_address = "./not-exist-socket"
try:
sock.connect(server_address)
except socket.error:
@@ -397,32 +421,32 @@ def test_unix_socket():
def test_HTTPrettyRequest_json_body():
""" A content-type of application/json should parse a valid json body """
- header = TEST_HEADER % {'content_type': 'application/json'}
- test_dict = {'hello': 'world'}
+ header = TEST_HEADER % {"content_type": "application/json"}
+ test_dict = {"hello": "world"}
request = HTTPrettyRequest(header, json.dumps(test_dict))
expect(request.parsed_body).to.equal(test_dict)
def test_HTTPrettyRequest_invalid_json_body():
""" A content-type of application/json with an invalid json body should return the content unaltered """
- header = TEST_HEADER % {'content_type': 'application/json'}
- invalid_json = u"{'hello', 'world','thisstringdoesntstops}"
+ header = TEST_HEADER % {"content_type": "application/json"}
+ invalid_json = "{'hello', 'world','thisstringdoesntstops}"
request = HTTPrettyRequest(header, invalid_json)
expect(request.parsed_body).to.equal(invalid_json)
def test_HTTPrettyRequest_queryparam():
""" A content-type of x-www-form-urlencoded with a valid queryparam body should return parsed content """
- header = TEST_HEADER % {'content_type': 'application/x-www-form-urlencoded'}
- valid_queryparam = u"hello=world&this=isavalidquerystring"
- valid_results = {'hello': ['world'], 'this': ['isavalidquerystring']}
+ header = TEST_HEADER % {"content_type": "application/x-www-form-urlencoded"}
+ valid_queryparam = "hello=world&this=isavalidquerystring"
+ valid_results = {"hello": ["world"], "this": ["isavalidquerystring"]}
request = HTTPrettyRequest(header, valid_queryparam)
expect(request.parsed_body).to.equal(valid_results)
def test_HTTPrettyRequest_arbitrarypost():
""" A non-handled content type request's post body should return the content unaltered """
- header = TEST_HEADER % {'content_type': 'thisis/notarealcontenttype'}
+ header = TEST_HEADER % {"content_type": "thisis/notarealcontenttype"}
gibberish_body = "1234567890!@#$%^&*()"
request = HTTPrettyRequest(header, gibberish_body)
expect(request.parsed_body).to.equal(gibberish_body)
@@ -435,8 +459,9 @@ def test_socktype_bad_python_version_regression():
https://bugs.python.org/issue20386
"""
import socket
+
someObject = object()
- with patch('socket.SocketType', someObject):
+ with patch("socket.SocketType", someObject):
HTTPretty.enable()
expect(socket.SocketType).to.equal(someObject)
HTTPretty.disable()
@@ -444,7 +469,8 @@ def test_socktype_bad_python_version_regression():
def test_socktype_good_python_version():
import socket
- with patch('socket.SocketType', socket.socket):
+
+ with patch("socket.SocketType", socket.socket):
HTTPretty.enable()
expect(socket.SocketType).to.equal(socket.socket)
HTTPretty.disable()
@@ -454,21 +480,17 @@ def test_httpretty_should_allow_registering_regex_hostnames():
"HTTPretty should allow registering regexes with requests"
HTTPretty.register_uri(
- HTTPretty.GET,
- re.compile(r'^http://\w+\.foo\.com/baz$'),
- body="yay",
+ HTTPretty.GET, re.compile(r"^http://\w+\.foo\.com/baz$"), body="yay"
)
- assert HTTPretty.match_http_address('www.foo.com', 80)
+ assert HTTPretty.match_http_address("www.foo.com", 80)
def test_httpretty_should_allow_registering_regex_hostnames_ssl():
"HTTPretty should allow registering regexes with requests (ssl version)"
HTTPretty.register_uri(
- HTTPretty.GET,
- re.compile(r'^https://\w+\.foo\.com/baz$'),
- body="yay",
+ HTTPretty.GET, re.compile(r"^https://\w+\.foo\.com/baz$"), body="yay"
)
- assert HTTPretty.match_https_hostname('www.foo.com')
+ assert HTTPretty.match_https_hostname("www.foo.com")
diff --git a/tests/unit/test_main.py b/tests/unit/test_main.py
index 6ce49d8..1c36f9e 100644
--- a/tests/unit/test_main.py
+++ b/tests/unit/test_main.py
@@ -6,7 +6,7 @@ import httpretty
from httpretty.core import HTTPrettyRequest
-@patch('httpretty.httpretty')
+@patch("httpretty.httpretty")
def test_last_request(original):
("httpretty.last_request() should return httpretty.core.last_request")
@@ -14,9 +14,11 @@ def test_last_request(original):
def test_has_request():
- ("httpretty.has_request() correctly detects "
- "whether or not a request has been made")
+ (
+ "httpretty.has_request() correctly detects "
+ "whether or not a request has been made"
+ )
httpretty.reset()
httpretty.has_request().should.be.false
- with patch('httpretty.httpretty.last_request', return_value=HTTPrettyRequest('')):
+ with patch("httpretty.httpretty.last_request", return_value=HTTPrettyRequest("")):
httpretty.has_request().should.be.true