API Reference

register_uri

classmethodhttpretty.register_uri(method,uri,body='{"message":"HTTPretty:)"}',adding_headers=None,forcing_headers=None,status=200,responses=None,match_querystring=False,priority=0,**headers)[source]
importhttprettydefrequest_callback(request,uri,response_headers):content_type=request.headers.get('Content-Type')assertrequest.body=='{"nothing": "here"}','unexpected body:{}'.format(request.body)assertcontent_type=='application/json','expected application/json but received Content-Type:{}'.format(content_type)return[200,response_headers,json.dumps({"hello":"world"})]httpretty.register_uri(HTTPretty.POST,"https://httpretty.example.com/api",body=request_callback)withhttpretty.enabled():requests.post('https://httpretty.example.com/api',data='{"nothing": "here"}',headers={'Content-Type':'application/json'})asserthttpretty.latest_requests[-1].url=='https://httpbin.org/ip'
Parameters
  • method – one ofhttpretty.GET,httpretty.PUT,httpretty.POST,httpretty.DELETE,httpretty.HEAD,httpretty.PATCH,httpretty.OPTIONS,httpretty.CONNECT

  • uri – a string or regex pattern (e.g.:“https://httpbin.org/ip”)

  • body – a string, defaults to{"message":"HTTPretty:)"}

  • adding_headers – dict - headers to be added to the response

  • forcing_headers – dict - headers to be forcefully set in the response

  • status – an integer, defaults to200

  • responses – a list of entries, ideally each created withResponse()

  • priority – an integer, useful for setting higher priority over previously registered urls. defaults to zero

  • match_querystring – bool - whether to take the querystring into account when matching an URL

  • headers – headers to be added to the response

Warning

When using a port in the request, add a trailing slash if no path is provided otherwise Httpretty will not catch the request. Ex:httpretty.register_uri(httpretty.GET,'http://fakeuri.com:8080/',body='{"hello":"world"}')

enable

classmethodhttpretty.enable(allow_net_connect=True,verbose=False)[source]

Enables HTTPretty.

Parameters
  • allow_net_connect – boolean to determine if unmatched requests are forwarded to a real network connection OR throwhttpretty.errors.UnmockedError.

  • verbose – boolean to set HTTPretty’s logging level to DEBUG

importre,jsonimporthttprettyhttpretty.enable(allow_net_connect=True,verbose=True)httpretty.register_uri(httpretty.GET,re.compile(r'http://.*'),body=json.dumps({'man':'in','the':'middle'}))response=requests.get('https://foo.bar/foo/bar')response.json().should.equal({"man":"in","the":"middle",})

Warning

after calling this method the originalsocket is replaced withhttpretty.core.fakesock. Make sure to calldisable() after done with your tests or use thehttpretty.enabled as decorator orcontext-manager

disable

classmethodhttpretty.disable()[source]

Disables HTTPretty entirely, putting the originalsocketmodule back in its place.

importre,jsonimporthttprettyhttpretty.enable()# request passes through fake socketresponse=requests.get('https://httpbin.org')httpretty.disable()# request uses real python socket moduleresponse=requests.get('https://httpbin.org')

Note

This method does not callhttpretty.core.reset() automatically.

is_enabled

classmethodhttpretty.is_enabled()[source]

Check if HTTPretty is enabled

Returns

bool

importhttprettyhttpretty.enable()asserthttpretty.is_enabled()==Truehttpretty.disable()asserthttpretty.is_enabled()==False

last_request

httpretty.last_request()[source]
Returns

the lastHTTPrettyRequest

latest_requests

httpretty.latest_requests()[source]

returns the history of made requests

activate

httpretty.activate

alias ofhttpretty.core.httprettified

httprettified

httpretty.core.httprettified(test=None,allow_net_connect=True,verbose=False)[source]

decorator for test functions

Tip

Also available under the aliashttpretty.activate()

Parameters

test – a callable

example usage withnosetests

importsurefromhttprettyimporthttprettified@httprettifieddeftest_using_nosetests():httpretty.register_uri(httpretty.GET,'https://httpbin.org/ip')response=requests.get('https://httpbin.org/ip')response.json().should.equal({"message":"HTTPretty :)"})

example usage withunittest module

importunittestfromsureimportexpectfromhttprettyimporthttprettified@httprettifiedclassTestWithPyUnit(unittest.TestCase):deftest_httpbin(self):httpretty.register_uri(httpretty.GET,'https://httpbin.org/ip')response=requests.get('https://httpbin.org/ip')expect(response.json()).to.equal({"message":"HTTPretty :)"})

enabled

httpretty.enabled

alias ofhttpretty.core.httprettized

httprettized

classhttpretty.core.httprettized(allow_net_connect=True,verbose=False)[source]

context-manager for enabling HTTPretty.

Tip

Also available under the aliashttpretty.enabled()

importjsonimporthttprettyhttpretty.register_uri(httpretty.GET,'https://httpbin.org/ip',body=json.dumps({'origin':'42.42.42.42'}))withhttpretty.enabled():response=requests.get('https://httpbin.org/ip')asserthttpretty.latest_requests[-1].url=='https://httpbin.org/ip'assertresponse.json()=={'origin':'42.42.42.42'}

HTTPrettyRequest

classhttpretty.core.HTTPrettyRequest(headers,body='',sock=None,path_encoding='iso-8859-1')[source]

Represents a HTTP request. It takes a valid multi-line,\r\n separated string with HTTP headers and parse them out usingthe internalparse_request method.

It also replaces therfile andwfile attributes withio.BytesIOinstances so that we guarantee that it won’t make any I/O, neitherfor writing nor reading.

It has some convenience attributes:

headers -> a mimetype object that can be cast into a dictionary,contains all the request headers

protocol -> the protocol of this host, inferred from the portof the underlying fake TCP socket.

host -> the hostname of this request.

url -> the full url of this request.

path -> the path of the request.

method -> the HTTP method used in this request.

querystring -> a dictionary containing lists with theattributes. Please notice that if you need a single value from aquery string you will need to get it manually like:

body -> the request body as a string.

parsed_body -> the request body parsed byparse_request_body.

>>>request.querystring{'name': ['Gabriel Falcao']}>>>printrequest.querystring['name'][0]
propertymethod

the HTTP method used in this request

parse_querystring(qs)[source]

parses an UTF-8 encoded query string into a dict of string lists

Parameters

qs – a querystring

Returns

a dict of lists

parse_request_body(body)[source]

Attempt to parse the post based on the content-type passed.Return the regular body if not

Parameters

body – string

Returns

a python object such as dict or list in case the deserialization suceeded. Else returns the given parambody

propertyprotocol

the protocol used in this request

querystring

a dictionary containing parsed request body or None ifHTTPrettyRequest doesn’t know how to parse it. It currentlysupports parsing body data that was sent under thecontent`-type`headersvalues:``application/json orapplication/x-www-form-urlencoded

propertyurl

the full url of this recorded request

HTTPrettyRequestEmpty

classhttpretty.core.HTTPrettyRequestEmpty[source]

Represents an emptyHTTPrettyRequestwhere all its properties are somehow empty orNone

FakeSockFile

classhttpretty.core.FakeSockFile[source]

Fake socket file descriptor. Under the hood all data is written ina temporary file, giving it a real file descriptor number.

FakeSSLSocket

classhttpretty.core.FakeSSLSocket(sock,*args,**kw)[source]

Shorthand forfakesock

URIInfo

classhttpretty.URIInfo(username='',password='',hostname='',port=80,path='/',query='',fragment='',scheme='',last_request=None)[source]

Internal representation ofURIs

Tip

all arguments are optional

Parameters
  • username

  • password

  • hostname

  • port

  • path

  • query

  • fragment

  • scheme

  • last_request

classmethodfrom_uri(uri,entry)[source]
Parameters
  • uri – string

  • entry – an instance ofEntry

full_url(use_querystring=True)[source]
Parameters

use_querystring – bool

Returns

a string with the full url with the format{scheme}://{credentials}{domain}{path}{query}

get_full_domain()[source]
Returns

a string in the form{domain}:{port} or just the domain if the port is 80 or 443

URIMatcher

classhttpretty.URIMatcher(uri,entries,match_querystring=False,priority=0)[source]
get_next_entry(method,info,request)[source]

Cycle through available responses, but only once.Any subsequent requests will receive the last response

Entry

classhttpretty.Entry(method,uri,body,adding_headers=None,forcing_headers=None,status=200,streaming=False,**headers)[source]

Created byregister_uri() andstored in memory as internal representation of a HTTPrequest/response definition.

Parameters
  • method (str) – One ofhttpretty.GET,httpretty.PUT,httpretty.POST,httpretty.DELETE,httpretty.HEAD,httpretty.PATCH,httpretty.OPTIONS,httpretty.CONNECT.

  • uri (str|re.Pattern) – The URL to match

  • adding_headers (dict) – Extra headers to be added to the response

  • forcing_headers (dict) – Overwrite response headers.

  • status (int) – The status code for the response, defaults to200.

  • streaming (bool) – Whether should stream the response into chunks via generator.

  • headers – Headers to inject in the faked response.

Returns

containing the request-matching metadata.

Return type

httpretty.Entry

Warning

When using theforcing_headers option make sure to add the headerContent-Length to match at most the total body length, otherwise some HTTP clients can hang indefinitely.

fill_filekind(fk)[source]

writes HTTP Response data to a file descriptor

Parm fk

a file-like object

Warning

side-effect: this method moves the cursor of the given file object to zero

normalize_headers(headers)[source]

Normalize keys in header names so thatCOntent-tyPe becomescontent-type

Parameters

headers – dict

Returns

dict

validate()[source]

validates the body size with the value of theContent-Lengthheader

Modules

Core

classhttpretty.core.EmptyRequestHeaders[source]

A dict subclass used as internal representation of empty requestheaders

classhttpretty.core.Entry(method,uri,body,adding_headers=None,forcing_headers=None,status=200,streaming=False,**headers)[source]

Created byregister_uri() andstored in memory as internal representation of a HTTPrequest/response definition.

Parameters
  • method (str) – One ofhttpretty.GET,httpretty.PUT,httpretty.POST,httpretty.DELETE,httpretty.HEAD,httpretty.PATCH,httpretty.OPTIONS,httpretty.CONNECT.

  • uri (str|re.Pattern) – The URL to match

  • adding_headers (dict) – Extra headers to be added to the response

  • forcing_headers (dict) – Overwrite response headers.

  • status (int) – The status code for the response, defaults to200.

  • streaming (bool) – Whether should stream the response into chunks via generator.

  • headers – Headers to inject in the faked response.

Returns

containing the request-matching metadata.

Return type

httpretty.Entry

Warning

When using theforcing_headers option make sure to add the headerContent-Length to match at most the total body length, otherwise some HTTP clients can hang indefinitely.

fill_filekind(fk)[source]

writes HTTP Response data to a file descriptor

Parm fk

a file-like object

Warning

side-effect: this method moves the cursor of the given file object to zero

normalize_headers(headers)[source]

Normalize keys in header names so thatCOntent-tyPe becomescontent-type

Parameters

headers – dict

Returns

dict

validate()[source]

validates the body size with the value of theContent-Lengthheader

classhttpretty.core.FakeSSLSocket(sock,*args,**kw)[source]

Shorthand forfakesock

classhttpretty.core.FakeSockFile[source]

Fake socket file descriptor. Under the hood all data is written ina temporary file, giving it a real file descriptor number.

classhttpretty.core.HTTPrettyRequest(headers,body='',sock=None,path_encoding='iso-8859-1')[source]

Represents a HTTP request. It takes a valid multi-line,\r\n separated string with HTTP headers and parse them out usingthe internalparse_request method.

It also replaces therfile andwfile attributes withio.BytesIOinstances so that we guarantee that it won’t make any I/O, neitherfor writing nor reading.

It has some convenience attributes:

headers -> a mimetype object that can be cast into a dictionary,contains all the request headers

protocol -> the protocol of this host, inferred from the portof the underlying fake TCP socket.

host -> the hostname of this request.

url -> the full url of this request.

path -> the path of the request.

method -> the HTTP method used in this request.

querystring -> a dictionary containing lists with theattributes. Please notice that if you need a single value from aquery string you will need to get it manually like:

body -> the request body as a string.

parsed_body -> the request body parsed byparse_request_body.

>>>request.querystring{'name': ['Gabriel Falcao']}>>>printrequest.querystring['name'][0]
propertymethod

the HTTP method used in this request

parse_querystring(qs)[source]

parses an UTF-8 encoded query string into a dict of string lists

Parameters

qs – a querystring

Returns

a dict of lists

parse_request_body(body)[source]

Attempt to parse the post based on the content-type passed.Return the regular body if not

Parameters

body – string

Returns

a python object such as dict or list in case the deserialization suceeded. Else returns the given parambody

propertyprotocol

the protocol used in this request

querystring

a dictionary containing parsed request body or None ifHTTPrettyRequest doesn’t know how to parse it. It currentlysupports parsing body data that was sent under thecontent`-type`headersvalues:``application/json orapplication/x-www-form-urlencoded

propertyurl

the full url of this recorded request

classhttpretty.core.HTTPrettyRequestEmpty[source]

Represents an emptyHTTPrettyRequestwhere all its properties are somehow empty orNone

classhttpretty.core.URIInfo(username='',password='',hostname='',port=80,path='/',query='',fragment='',scheme='',last_request=None)[source]

Internal representation ofURIs

Tip

all arguments are optional

Parameters
  • username

  • password

  • hostname

  • port

  • path

  • query

  • fragment

  • scheme

  • last_request

classmethodfrom_uri(uri,entry)[source]
Parameters
  • uri – string

  • entry – an instance ofEntry

full_url(use_querystring=True)[source]
Parameters

use_querystring – bool

Returns

a string with the full url with the format{scheme}://{credentials}{domain}{path}{query}

get_full_domain()[source]
Returns

a string in the form{domain}:{port} or just the domain if the port is 80 or 443

httpretty.core.create_fake_connection(address,timeout=<objectobject>,source_address=None)[source]

drop-in replacement forsocket.create_connection()

httpretty.core.fake_getaddrinfo(host,port,family=None,socktype=None,proto=None,flags=None)[source]

drop-in replacement forsocket.getaddrinfo()

httpretty.core.fake_gethostbyname(host)[source]

drop-in replacement forsocket.gethostbyname()

httpretty.core.fake_gethostname()[source]

drop-in replacement forsocket.gethostname()

httpretty.core.fake_wrap_socket(orig_wrap_socket_fn,*args,**kw)[source]

drop-in replacement for py:func:ssl.wrap_socket

classhttpretty.core.fakesock[source]

fakesocket

classsocket(family=AddressFamily.AF_INET,type=SocketKind.SOCK_STREAM,proto=0,fileno=None)[source]

drop-in replacement forsocket.socket

makefile(mode='r',bufsize=-1)[source]

Returns this fake socket’s own tempfile buffer.

If there is an entry associated with the socket, the filedescriptor gets filled in with the entry data before beingreturned.

real_sendall(data,*args,**kw)[source]

Sends data to the remote server. This method is calledwhen HTTPretty identifies that someone is trying to sendnon-http data.

The received bytes are written in this socket’s tempfilebuffer so that HTTPretty can return it accordingly whennecessary.

httpretty.core.get_default_thread_timeout()[source]

sets the default thread timeout for HTTPretty threads

Returns

int

httpretty.core.httprettified(test=None,allow_net_connect=True,verbose=False)[source]

decorator for test functions

Tip

Also available under the aliashttpretty.activate()

Parameters

test – a callable

example usage withnosetests

importsurefromhttprettyimporthttprettified@httprettifieddeftest_using_nosetests():httpretty.register_uri(httpretty.GET,'https://httpbin.org/ip')response=requests.get('https://httpbin.org/ip')response.json().should.equal({"message":"HTTPretty :)"})

example usage withunittest module

importunittestfromsureimportexpectfromhttprettyimporthttprettified@httprettifiedclassTestWithPyUnit(unittest.TestCase):deftest_httpbin(self):httpretty.register_uri(httpretty.GET,'https://httpbin.org/ip')response=requests.get('https://httpbin.org/ip')expect(response.json()).to.equal({"message":"HTTPretty :)"})
classhttpretty.core.httprettized(allow_net_connect=True,verbose=False)[source]

context-manager for enabling HTTPretty.

Tip

Also available under the aliashttpretty.enabled()

importjsonimporthttprettyhttpretty.register_uri(httpretty.GET,'https://httpbin.org/ip',body=json.dumps({'origin':'42.42.42.42'}))withhttpretty.enabled():response=requests.get('https://httpbin.org/ip')asserthttpretty.latest_requests[-1].url=='https://httpbin.org/ip'assertresponse.json()=={'origin':'42.42.42.42'}
classhttpretty.core.httpretty[source]

manages HTTPretty’s internal request/response registry and request matching.

classmethodResponse(body,method=None,uri=None,adding_headers=None,forcing_headers=None,status=200,streaming=False,**kw)[source]

Shortcut to create anEntry that takesthe body as first positional argument.

See also

the parameters of this function match those oftheEntry constructor.

Parameters
  • body (str) – The body to return as response..

  • method (str) – One ofhttpretty.GET,httpretty.PUT,httpretty.POST,httpretty.DELETE,httpretty.HEAD,httpretty.PATCH,httpretty.OPTIONS,httpretty.CONNECT.

  • uri (str|re.Pattern) – The URL to match

  • adding_headers (dict) – Extra headers to be added to the response

  • forcing_headers (dict) – Overwriteany response headers, even “Content-Length”.

  • status (int) – The status code for the response, defaults to200.

  • streaming (bool) – Whether should stream the response into chunks via generator.

  • kwargs – Keyword-arguments are forwarded toEntry

Returns

containing the request-matching metadata.

Return type

httpretty.Entry

classmethoddisable()[source]

Disables HTTPretty entirely, putting the originalsocketmodule back in its place.

importre,jsonimporthttprettyhttpretty.enable()# request passes through fake socketresponse=requests.get('https://httpbin.org')httpretty.disable()# request uses real python socket moduleresponse=requests.get('https://httpbin.org')

Note

This method does not callhttpretty.core.reset() automatically.

classmethodenable(allow_net_connect=True,verbose=False)[source]

Enables HTTPretty.

Parameters
  • allow_net_connect – boolean to determine if unmatched requests are forwarded to a real network connection OR throwhttpretty.errors.UnmockedError.

  • verbose – boolean to set HTTPretty’s logging level to DEBUG

importre,jsonimporthttprettyhttpretty.enable(allow_net_connect=True,verbose=True)httpretty.register_uri(httpretty.GET,re.compile(r'http://.*'),body=json.dumps({'man':'in','the':'middle'}))response=requests.get('https://foo.bar/foo/bar')response.json().should.equal({"man":"in","the":"middle",})

Warning

after calling this method the originalsocket is replaced withhttpretty.core.fakesock. Make sure to calldisable() after done with your tests or use thehttpretty.enabled as decorator orcontext-manager

classmethodhistorify_request(headers,body='',sock=None,append=True)[source]

appends request to a list for later retrieval

importhttprettyhttpretty.register_uri(httpretty.GET,'https://httpbin.org/ip',body='')withhttpretty.enabled():requests.get('https://httpbin.org/ip')asserthttpretty.latest_requests[-1].url=='https://httpbin.org/ip'
classmethodis_enabled()[source]

Check if HTTPretty is enabled

Returns

bool

importhttprettyhttpretty.enable()asserthttpretty.is_enabled()==Truehttpretty.disable()asserthttpretty.is_enabled()==False
classmethodmatch_http_address(hostname,port)[source]
Parameters
  • hostname – a string

  • port – an integer

Returns

anURLMatcher orNone

classmethodmatch_https_hostname(hostname)[source]
Parameters

hostname – a string

Returns

anURLMatcher orNone

classmethodmatch_uriinfo(info)[source]
Parameters

info – anURIInfo

Returns

a 2-item tuple: (URLMatcher,URIInfo) or(None,[])

classmethodplayback(filename,allow_net_connect=True,verbose=False)[source]
importioimportjsonimportrequestsimporthttprettywithhttpretty.record('/tmp/ip.json'):data=requests.get('https://httpbin.org/ip').json()withio.open('/tmp/ip.json')asfd:assertdata==json.load(fd)
Parameters

filename – a string

Returns

acontext-manager

classmethodrecord(filename,indentation=4,encoding='utf-8',verbose=False,allow_net_connect=True,pool_manager_params=None)[source]
importioimportjsonimportrequestsimporthttprettywithhttpretty.record('/tmp/ip.json'):data=requests.get('https://httpbin.org/ip').json()withio.open('/tmp/ip.json')asfd:assertdata==json.load(fd)
Parameters
  • filename – a string

  • indentation – an integer, defaults to4

  • encoding – a string, defaults to“utf-8”

Returns

acontext-manager

classmethodregister_uri(method,uri,body='{"message":"HTTPretty:)"}',adding_headers=None,forcing_headers=None,status=200,responses=None,match_querystring=False,priority=0,**headers)[source]
importhttprettydefrequest_callback(request,uri,response_headers):content_type=request.headers.get('Content-Type')assertrequest.body=='{"nothing": "here"}','unexpected body:{}'.format(request.body)assertcontent_type=='application/json','expected application/json but received Content-Type:{}'.format(content_type)return[200,response_headers,json.dumps({"hello":"world"})]httpretty.register_uri(HTTPretty.POST,"https://httpretty.example.com/api",body=request_callback)withhttpretty.enabled():requests.post('https://httpretty.example.com/api',data='{"nothing": "here"}',headers={'Content-Type':'application/json'})asserthttpretty.latest_requests[-1].url=='https://httpbin.org/ip'
Parameters
  • method – one ofhttpretty.GET,httpretty.PUT,httpretty.POST,httpretty.DELETE,httpretty.HEAD,httpretty.PATCH,httpretty.OPTIONS,httpretty.CONNECT

  • uri – a string or regex pattern (e.g.:“https://httpbin.org/ip”)

  • body – a string, defaults to{"message":"HTTPretty:)"}

  • adding_headers – dict - headers to be added to the response

  • forcing_headers – dict - headers to be forcefully set in the response

  • status – an integer, defaults to200

  • responses – a list of entries, ideally each created withResponse()

  • priority – an integer, useful for setting higher priority over previously registered urls. defaults to zero

  • match_querystring – bool - whether to take the querystring into account when matching an URL

  • headers – headers to be added to the response

Warning

When using a port in the request, add a trailing slash if no path is provided otherwise Httpretty will not catch the request. Ex:httpretty.register_uri(httpretty.GET,'http://fakeuri.com:8080/',body='{"hello":"world"}')

classmethodreset()[source]

resets the internal state of HTTPretty, unregistering all URLs

httpretty.core.set_default_thread_timeout(timeout)[source]

sets the default thread timeout for HTTPretty threads

Parameters

timeout – int

httpretty.core.url_fix(s,charset=None)[source]

escapes special characters

Http

httpretty.http.last_requestline(sent_data)[source]

Find the last line in sent_data that can be parsed with parse_requestline

httpretty.http.parse_requestline(s)[source]

http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5

>>>parse_requestline('GET / HTTP/1.0')('GET', '/', '1.0')>>>parse_requestline('post /testurl htTP/1.1')('POST', '/testurl', '1.1')>>>parse_requestline('Im not a RequestLine')Traceback (most recent call last):...ValueError:Not a Request-Line

Utils

Exceptions

exceptionhttpretty.errors.HTTPrettyError[source]
exceptionhttpretty.errors.UnmockedError(message='Failedtohandlenetworkrequest',request=None,address=None)[source]