HTTPretty | Intercept HTTP requests at the Python socket level | Mock library

 by   gabrielfalcao Python Version: 1.1.4 License: MIT

kandi X-RAY | HTTPretty Summary

HTTPretty is a Python library typically used in Testing, Mock applications. HTTPretty has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can download it from GitHub.
Intercept HTTP requests at the Python socket level. Fakes the whole socket module
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        HTTPretty has a medium active ecosystem.
                        summary
                        It has 2022 star(s) with 264 fork(s). There are 43 watchers for this library.
                        summary
                        It had no major release in the last 6 months.
                        summary
                        There are 95 open issues and 142 have been closed. On average issues are closed in 660 days. There are 13 open pull requests and 0 closed requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of HTTPretty is 1.1.4
                        HTTPretty Support
                          Best in #Mock
                            Average in #Mock
                            HTTPretty Support
                              Best in #Mock
                                Average in #Mock

                                  kandi-Quality Quality

                                    summary
                                    HTTPretty has 0 bugs and 0 code smells.
                                    HTTPretty Quality
                                      Best in #Mock
                                        Average in #Mock
                                        HTTPretty Quality
                                          Best in #Mock
                                            Average in #Mock

                                              kandi-Security Security

                                                summary
                                                HTTPretty has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                HTTPretty code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                HTTPretty Security
                                                  Best in #Mock
                                                    Average in #Mock
                                                    HTTPretty Security
                                                      Best in #Mock
                                                        Average in #Mock

                                                          kandi-License License

                                                            summary
                                                            HTTPretty is licensed under the MIT License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            HTTPretty License
                                                              Best in #Mock
                                                                Average in #Mock
                                                                HTTPretty License
                                                                  Best in #Mock
                                                                    Average in #Mock

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        HTTPretty releases are not available. You will need to build from source code and install.
                                                                        summary
                                                                        Build file is available. You can build the component from source.
                                                                        summary
                                                                        HTTPretty saves you 1709 person hours of effort in developing the same functionality from scratch.
                                                                        summary
                                                                        It has 4244 lines of code, 356 functions and 46 files.
                                                                        summary
                                                                        It has medium code complexity. Code complexity directly impacts maintainability of the code.
                                                                        HTTPretty Reuse
                                                                          Best in #Mock
                                                                            Average in #Mock
                                                                            HTTPretty Reuse
                                                                              Best in #Mock
                                                                                Average in #Mock
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi has reviewed HTTPretty and discovered the below as its top functions. This is intended to give you an instant insight into HTTPretty implemented functionality, and help decide if they suit your requirements.
                                                                                  • 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
                                                                                  Get all kandi verified functions for this library.
                                                                                  Get all kandi verified functions for this library.

                                                                                  HTTPretty Key Features

                                                                                  Intercept HTTP requests at the Python socket level. Fakes the whole socket module

                                                                                  HTTPretty Examples and Code Snippets

                                                                                  PyBambooHR
                                                                                  Pythondot imgLines of Code : 56dot imgLicense : Permissive (MIT)
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      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)
                                                                                  aiohttpretty,Synopsis
                                                                                  Pythondot imgLines of Code : 29dot imgno licencesLicense : No License
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      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()
                                                                                  aiohttpretty,Other,pytest marker
                                                                                  Pythondot imgLines of Code : 18dot imgno licencesLicense : No License
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      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()
                                                                                  Community Discussions

                                                                                  Trending Discussions on HTTPretty

                                                                                  How can I get httpretty to stop printing exceptions during testing?
                                                                                  chevron right

                                                                                  QUESTION

                                                                                  How can I get httpretty to stop printing exceptions during testing?
                                                                                  Asked 2020-Aug-01 at 15:33

                                                                                  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:33

                                                                                  HTTPretty 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
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/63206653

                                                                                  Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                  Vulnerabilities

                                                                                  No vulnerabilities reported

                                                                                  Install HTTPretty

                                                                                  You can download it from GitHub.
                                                                                  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

                                                                                  For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
                                                                                  Find more information at:
                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit
                                                                                  CLONE
                                                                                • HTTPS

                                                                                  https://github.com/gabrielfalcao/HTTPretty.git

                                                                                • CLI

                                                                                  gh repo clone gabrielfalcao/HTTPretty

                                                                                • sshUrl

                                                                                  git@github.com:gabrielfalcao/HTTPretty.git

                                                                                • Share this Page

                                                                                  share link

                                                                                  Explore Related Topics

                                                                                  Reuse Pre-built Kits with HTTPretty

                                                                                  Consider Popular Mock Libraries

                                                                                  faker.js

                                                                                  by Marak

                                                                                  Faker

                                                                                  by fzaninotto

                                                                                  Mock

                                                                                  by nuysoft

                                                                                  faker

                                                                                  by joke2k

                                                                                  nock

                                                                                  by nock

                                                                                  Try Top Libraries by gabrielfalcao

                                                                                  lettuce

                                                                                  by gabrielfalcaoPython

                                                                                  sure

                                                                                  by gabrielfalcaoPython

                                                                                  flask-react-bootstrap

                                                                                  by gabrielfalcaoJavaScript

                                                                                  unclebob

                                                                                  by gabrielfalcaoPython

                                                                                  jquery-yql

                                                                                  by gabrielfalcaoJavaScript

                                                                                  Compare Mock Libraries with Highest Support

                                                                                  faker

                                                                                  by joke2k

                                                                                  Faker

                                                                                  by fzaninotto

                                                                                  wiremock

                                                                                  by tomakehurst

                                                                                  faker

                                                                                  by faker-ruby

                                                                                  powermock

                                                                                  by powermock

                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit