Package: pook
Versatile, expressive and hackable utility library for HTTP traffic mocking
and expectations made easy inPython. Heavily inspired bygock.To get started, read thedocumentation,how it works,FAQorexamples.FeaturesSimple, expressive and fluent API.Provides both Pythonic and chainable DSL API styles.Full-featured HTTP response definitions and expectations.Matches any HTTP protocol primitive (URL, method, query params, headers, body…).Full regular expressions capable mock expectations matching.Supports most popular HTTP clients via interceptor adapters.Configurable volatile, persistent or TTL limited mocks.Works with unittest and pytest.First-class JSON & XML support matching and responses.Supports JSON Schema body matching.Works in both runtime and testing environments.Can be used as decorator and/or via context managers.Supports real networking mode with optional traffic filtering.Map/filter mocks easily for generic or custom mock expectations.Custom user-defined mock matcher functions.Simulated raised error exceptions.Network delay simulation (only available foraiohttp).Pluggable and hackable API.Customizable HTTP traffic mock interceptor engine.Supports third-party mocking engines, such asmocket.Fits good for painless test doubles.Does not support WebSocket traffic mocking.Works with +3.8 (including PyPy).Dependency-less: just 3 small dependencies for JSONSchema, XML tree comparison, and URL parsing.Supported HTTP clientspookcan work with multiple mock engines, however it provides a
built-in one by default, which currently supports traffic mocking in
the following HTTP clients:✔urllib3v1+✔requestsv2+✔aiohttpv3+✔urllib/http.client✔httpxMore HTTP clients can be supported progressively.Note: only recent HTTP client package versions were tested.InstallationUsingpippackage manager (requires pip 1.8+):pipinstall--upgradepookOr install the latest sources from Github:pipinstall-egit+git://github.com/h2non/pook.git#egg=pookGetting startedSee ReadTheDocs documentation:APISeeannotated API referencedocumention.ExamplesSeeexamplesdocumentation for full featured code and use case examples.Basic mocking:importpookimportrequests@pook.ondeftest_my_api():mock=pook.get('http://twitter.com/api/1/foobar',reply=404,response_json={'error':'not found'})resp=requests.get('http://twitter.com/api/1/foobar')assertresp.status_code==404assertresp.json()=={"error":"not found"}assertmock.calls==1Using the chainable API DSL:importpookimportrequests@pook.ondeftest_my_api():mock=(pook.get('http://twitter.com/api/1/foobar').reply(404).json({'error':'not found'}))resp=requests.get('http://twitter.com/api/1/foobar')assertresp.json()=={"error":"not found"}assertmock.calls==1Using the decorator:importpookimportrequests@pook.get('http://httpbin.org/status/500',reply=204)@pook.get('http://httpbin.org/status/400',reply=200)deffetch(url):returnrequests.get(url)res=fetch('http://httpbin.org/status/400')print('#1 status:',res.status_code)res=fetch('http://httpbin.org/status/500')print('#2 status:',res.status_code)Simpleunittestintegration:importpookimportunittestimportrequestsclassTestUnitTestEngine(unittest.TestCase):@pook.ondeftest_request(self):pook.get('server.com/foo').reply(204)res=requests.get('http://server.com/foo')self.assertEqual(res.status_code,204)deftest_request_with_context_manager(self):withpook.use():pook.get('server.com/bar',reply=204)res=requests.get('http://server.com/bar')self.assertEqual(res.status_code,204)Using the context manager for isolated HTTP traffic interception blocks:importpookimportrequests# Enable HTTP traffic interceptorwithpook.use():pook.get('http://httpbin.org/status/500',reply=204)res=requests.get('http://httpbin.org/status/500')print('#1 status:',res.status_code)# Interception-free HTTP trafficres=requests.get('http://httpbin.org/status/200')print('#2 status:',res.status_code)Example usingmocketPython library as underlying mock engine:importpookimportrequestsfrommocket.plugins.pook_mock_engineimportMocketEngine# Use mocket library as underlying mock enginepook.set_mock_engine(MocketEngine)# Explicitly enable pook HTTP mocking (optional)pook.on()# Target server URL to mock outurl='http://twitter.com/api/1/foobar'# Define your mockmock=pook.get(url,reply=404,times=2,headers={'content-type':'application/json'},response_json={'error':'foo'})# Run first HTTP requestrequests.get(url)assertmock.calls==1# Run second HTTP requestres=requests.get(url)assertmock.calls==2# Assert response dataassertres.status_code==404assertres.json()=={'error':'foo'}# Explicitly disable pook (optional)pook.off()Example using Hy language (Lisp dialect for Python):(import[pook])(import[requests])(defnrequest[url&optional[status404]](doto(.mockpookurl)(.replystatus))(let[res(.getrequestsurl)](.resstatus_code)))(defnrun[](with[(.usepook)](print"Status:"(request"http://server.com/foo":status204))));;Runtestprogram(defmain[&args](run))DevelopmentClone the repository:gitclonegit@github.com:h2non/pook.gitUse [hatch](https://hatch.pypa.io/) to configure the environment by running the test suite:hatchruntestInstall the pre-commit hook:hatchrunlint:installLint the code:hatchrunlint:runRun tests on all supported Python versions and implementations (this requires your host operating system to have each implementation available):hatchruntest:testTo run tests only for a specific version, affix the version designation to the environment name (the left side of the:):hatchruntest.pypy3.10:testGenerate documentation:hatchrundocs:buildLicenseMIT - Tomas Aparicio