HTTPretty | Intercept HTTP requests at the Python socket level | Mock library
kandi X-RAY | HTTPretty Summary
Support
Quality
Security
License
Reuse
- Decorator for tests
- Disable socket
- Enable logging
- Restore the old socket
- Match URI info
- Checks if the given info object matches the URL
- Return the full URL
- Get the full domain name
- Close the file
- Flush the file
- Close the database
- Create a temporary file
- Generate a list of HTTP requests
- Decode bytes to UTF - 8
- Construct a response entry
- Register a new uri
- Wraps a websocket function
- Return a matcher that matches a given hostname
- Set kwargs to kwargs
- Parse the last requestline in sent_data
- Parse a request - line string
- The body of the request
- Parse the request body
- Context manager to enable streaming
- Test the read timeout
- Returns the version string
HTTPretty Key Features
HTTPretty Examples and Code Snippets
from PyBambooHR import PyBambooHR bamboo = PyBambooHR(subdomain='yoursub', api_key='yourapikeyhere') employees = bamboo.get_employee_directory()
from PyBambooHR import PyBambooHR bamboo = PyBambooHR(subdomain='yoursub', api_key='yourapikeyhere') # Jim's employee ID is 123 and we are not specifying fields so this will get all of them. jim = bamboo.get_employee(123) # Pam's employee ID is 222 and we are specifying fields so this will get only the ones we request. pam = bamboo.get_employee(222, ['city', 'workPhone', 'workEmail'])
from PyBambooHR import PyBambooHR bamboo = PyBambooHR(subdomain='yoursub', api_key='yourapikeyhere') # The firstName and lastName keys are required... employee = {'firstName': 'Test', 'lastName': 'Person'} result = bamboo.add_employee(employee) The result dict will contain id and location. "id" is the numerical BambooHR employee ID. Location is a link to that employee.
from PyBambooHR import PyBambooHR bamboo = PyBambooHR(subdomain='yoursub', api_key='yourapikeyhere') # His name was test person... employee = {'firstName': 'Another', 'lastName': 'Namenow'} # Use the ID and then the dict with the new information result = bamboo.update_employee(333, employee) result will be True or False depending on if it succeeded.
from PyBambooHR import PyBambooHR bamboo = PyBambooHR(subdomain='yoursub', api_key='yourapikeyhere') # Use the ID to request json information result = bamboo.request_company_report(1, format='json', filter_duplicates=True) # Now do stuff with your results (Will vary by report.) for employee in result['employees']: print(employee) # Use the ID and save a pdf: result = bamboo.request_company_report(1, format='pdf', output_file='/tmp/report.pdf', filter_duplicates=True)
from PyBambooHR import PyBambooHR bamboo = PyBambooHR(subdomain='yoursub', api_key='yourapikeyhere', only_current=False)
import myproject import pytest import aiohttpretty @pytest.mark.asyncio async def test_get_keys_foo(): good_response = {'dog': 'woof', 'duck': 'quack'} good_url = 'http://example.com/dict' aiohttpretty.register_json_uri('GET', good_url, body=good_response) bad_response = ['dog', 'duck'] bad_url = 'http://example.com/list' aiohttpretty.register_json_uri('GET', bad_url, body=bad_response) aiohttpretty.activate() # .get_keys_from_url() calls .keys() on response keys_from_good = await myproject.get_keys_from_url(good_url) assert keys_from_good == ['dog', 'duck'] with pytest.raises(exceptions.AttributeError) as exc: await myproject.get_keys_from_url(bad_url) # aiohttpretty will die screaming that this url hasn't been mocked # await myproject.get_keys_from_url('http://example.com/unhandled') aiohttpretty.deactivate()
import aiohttpretty def pytest_configure(config): config.addinivalue_line( 'markers', 'aiohttpretty: mark tests to activate aiohttpretty' ) def pytest_runtest_setup(item): marker = item.get_marker('aiohttpretty') if marker is not None: aiohttpretty.clear() aiohttpretty.activate() def pytest_runtest_teardown(item, nextitem): marker = item.get_marker('aiohttpretty') if marker is not None: aiohttpretty.deactivate()
Trending Discussions on HTTPretty
Trending Discussions on HTTPretty
QUESTION
I have a test which simulates a request from a remote server which does not exist:
@httpretty.activate
def test_no_such_host(self):
def no_such_host(request, uri, headers):
raise requests.ConnectionError()
httpretty.register_uri(
'GET',
EXAMPLE_WEBFINGER_URL,
status=200,
headers = {
'Content-Type': 'application/jrd+json',
},
body = no_such_host,
)
webfinger = get_webfinger(
EXAMPLE_USERNAME,
EXAMPLE_HOSTNAME,
)
self.assertEqual(
webfinger.url,
None,
)
get_webfinger
does in fact catch ConnectionError
. When it runs, the test passes-- but it also reports the ConnectionError
exception as coming from an httpretty thread:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/marnanel/alpha/lib/python3.6/site-packages/httpretty/core.py", line 781, in fill_filekind
status, headers, self.body = self.callable_body(self.request, self.info.full_url(), headers)
File "/home/marnanel/proj/kepi/kepi/sombrero_sendpub/tests/test_webfinger.py", line 183, in no_such_host
raise requests.ConnectionError()
requests.exceptions.ConnectionError
.
----------------------------------------------------------------------
Ran 1 test in 0.117s
OK
Destroying test database for alias 'default'...
There is no threading in the unit test or in the code being tested. This is one of many similar tests. The ones which don't involve exceptions all run perfectly.
How can I get it to stop printing the exception?
ANSWER
Answered 2020-Aug-01 at 15:33HTTPretty uses a thread to simulate socket timeouts but are not handling exceptions correctly, see issue #334. The latter proposes a method for handling exceptions, but that hasn't been picked up by the maintainers (yet).
However, the message you see is printed by the default threading.excepthook()
implementation. You can set your own hook; a no-op lambda would silence the errors:
threading.excepthook = lambda a: None
You could use a context manager to disable the hook temporarily:
import threading
from contextlib import contextmanager
@contextmanager
def suppress_thread_exceptions():
orig = threading.excepthook
threading.excepthook = lambda a: None
try:
yield
finally:
threading.excepthook = orig
then use the above in your tests:
with suppress_thread_exceptions():
# use HTTPretty
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install HTTPretty
You can use HTTPretty like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page