Python httpretty.enable() Examples

The following are 30 code examples of httpretty.enable(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module httpretty , or try the search function .
Example #1
Source File: test_config.py    From zipa with Apache License 2.0 6 votes vote down vote up
def test_config_zipa():
    t.config.host = 'random'
    t.config.prefix = 'prefix'
    t.config.append_slash = True
    t.config.secure = False
    t.config.headers = {
        'x-custom-header': 'custom-value'
    }

    assert t.config['host'] == 'random'
    assert t.config['prefix'] == 'prefix'
    assert t.config['append_slash']
    assert t.config['headers']['x-custom-header'] == 'custom-value'

    httpretty.enable()
    httpretty.register_uri(httpretty.GET, 'http://randomprefix/a/', status=200,
                           content_type='application/json', body=u'{"name": "a"}')

    assert t.a().name == 'a'
    assert httpretty.last_request().headers['x-custom-header'] == 'custom-value' 
Example #2
Source File: test_WriteApiBatching.py    From influxdb-client-python with MIT License 6 votes vote down vote up
def setUp(self) -> None:
        # https://github.com/gabrielfalcao/HTTPretty/issues/368
        import warnings
        warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*")
        warnings.filterwarnings("ignore", category=PendingDeprecationWarning, message="isAlive*")

        httpretty.enable()
        httpretty.reset()

        conf = influxdb_client.configuration.Configuration()
        conf.host = "http://localhost"
        conf.debug = False

        self.influxdb_client = InfluxDBClient(url=conf.host, token="my-token")

        self.write_options = WriteOptions(batch_size=2, flush_interval=5_000, retry_interval=3_000)
        self._write_client = WriteApi(influxdb_client=self.influxdb_client, write_options=self.write_options) 
Example #3
Source File: conftest.py    From tortilla with MIT License 6 votes vote down vote up
def endpoints():
    httpretty.enable()
    with open(os.path.join(TESTS_DIR, 'endpoints.json')) as resource:
        test_data = json.load(resource)

    endpoints = test_data['endpoints']

    for endpoint, options in endpoints.items():
        if isinstance(options.get('body'), (dict, list, tuple)):
            body = json.dumps(options.get('body'))
        else:
            body = options.get('body')

        httpretty.register_uri(method=options.get('method', 'GET'),
                               status=options.get('status', 200),
                               uri=API_URL + endpoint,
                               body=body)
    yield endpoints
    httpretty.disable() 
Example #4
Source File: test_backends.py    From django-oidc-rp with MIT License 6 votes vote down vote up
def setup(self):
        httpretty.enable()

        self.key = RSAKey(kid='testkey').load(os.path.join(FIXTURE_ROOT, 'testkey.pem'))
        def jwks(_request, _uri, headers):  # noqa: E306
            ks = KEYS()
            ks.add(self.key.serialize())
            return 200, headers, ks.dump_jwks()
        httpretty.register_uri(
            httpretty.GET, oidc_rp_settings.PROVIDER_JWKS_ENDPOINT, status=200, body=jwks)
        httpretty.register_uri(
            httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT,
            body=json.dumps({
                'id_token': self.generate_jws(), 'access_token': 'accesstoken',
                'refresh_token': 'refreshtoken', }),
            content_type='text/json')
        httpretty.register_uri(
            httpretty.GET, oidc_rp_settings.PROVIDER_USERINFO_ENDPOINT,
            body=json.dumps({'sub': '1234', 'email': 'test@example.com', }),
            content_type='text/json')

        yield

        httpretty.disable() 
Example #5
Source File: test_middleware.py    From django-oidc-rp with MIT License 6 votes vote down vote up
def setup(self):
        httpretty.enable()

        self.key = RSAKey(kid='testkey').load(os.path.join(FIXTURE_ROOT, 'testkey.pem'))
        def jwks(_request, _uri, headers):  # noqa: E306
            ks = KEYS()
            ks.add(self.key.serialize())
            return 200, headers, ks.dump_jwks()
        httpretty.register_uri(
            httpretty.GET, oidc_rp_settings.PROVIDER_JWKS_ENDPOINT, status=200, body=jwks)
        httpretty.register_uri(
            httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT,
            body=json.dumps({
                'id_token': self.generate_jws(), 'access_token': 'accesstoken',
                'refresh_token': 'refreshtoken', }),
            content_type='text/json')
        httpretty.register_uri(
            httpretty.GET, oidc_rp_settings.PROVIDER_USERINFO_ENDPOINT,
            body=json.dumps({'sub': '1234', 'email': 'test@example.com', }),
            content_type='text/json')

        yield

        httpretty.disable() 
Example #6
Source File: test_authentication.py    From django-oidc-rp with MIT License 6 votes vote down vote up
def setup(self):
        httpretty.enable()

        self.key = RSAKey(kid='testkey').load(os.path.join(FIXTURE_ROOT, 'testkey.pem'))
        def jwks(_request, _uri, headers):  # noqa: E306
            ks = KEYS()
            ks.add(self.key.serialize())
            return 200, headers, ks.dump_jwks()
        httpretty.register_uri(
            httpretty.GET, oidc_rp_settings.PROVIDER_JWKS_ENDPOINT, status=200, body=jwks)
        httpretty.register_uri(
            httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT,
            body=json.dumps({
                'id_token': self.generate_jws(), 'access_token': 'accesstoken',
                'refresh_token': 'refreshtoken', }),
            content_type='text/json')
        httpretty.register_uri(
            httpretty.GET, oidc_rp_settings.PROVIDER_USERINFO_ENDPOINT,
            body=json.dumps({'sub': '1234', 'email': 'test@example.com', }),
            content_type='text/json')

        yield

        httpretty.disable() 
Example #7
Source File: crawl.py    From girlfriend with MIT License 6 votes vote down vote up
def setUp(self):
        httpretty.enable()
        httpretty.register_uri(
            httpretty.GET, "http://test.gf/users",
            body=ujson.dumps([
                sam_profile,
                jack_profile,
            ]),
            content_type="application/json"
        )
        httpretty.register_uri(
            httpretty.GET, "http://test.gf/blog/sam",
            body=ujson.dumps(sams_articles),
            content_type="application/json"
        )
        httpretty.register_uri(
            httpretty.GET, "http://test.gf/blog/jack",
            body=ujson.dumps(jacks_articles),
            content_type="application/json"
        ) 
Example #8
Source File: factory_source_tests.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Initialize the configuration
        """

        Cache.last_updated[APIURL] = {'__oldest': '2016-12-18T11:49:37Z'}
        httpretty.reset()
        httpretty.enable(allow_net_connect=False)

        oscrc = os.path.join(FIXTURES, 'oscrc')
        osc.core.conf.get_config(override_conffile=oscrc,
                                 override_no_keyring=True,
                                 override_no_gnome_keyring=True)
        #osc.conf.config['debug'] = 1
        #osc.conf.config['http_debug'] = 1

        logging.basicConfig()
        self.logger = logging.getLogger(__file__)
        self.logger.setLevel(logging.DEBUG)

        self.checker = FactorySourceChecker(apiurl = APIURL,
                user = 'factory-source',
                logger = self.logger)
        self.checker.override_allow = False # Test setup cannot handle. 
Example #9
Source File: maintenance_tests.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Initialize the configuration
        """

        httpretty.reset()
        httpretty.enable()

        oscrc = os.path.join(FIXTURES, 'oscrc')
        osc.core.conf.get_config(override_conffile=oscrc,
                                 override_no_keyring=True,
                                 override_no_gnome_keyring=True)
        #osc.conf.config['debug'] = 1

        logging.basicConfig()
        self.logger = logging.getLogger(__file__)
        self.logger.setLevel(logging.DEBUG)

        self.checker = MaintenanceChecker(apiurl = APIURL,
                user = 'maintbot',
                logger = self.logger)
        self.checker.override_allow = False # Test setup cannot handle. 
Example #10
Source File: site.py    From anime-downloader with The Unlicense 6 votes vote down vote up
def configure_httpretty(sitedir):
    httpretty.enable()
    dir = Path(f"tests/test_sites/data/test_{sitedir}/")
    data_file = dir / 'data.json'

    data = None
    with open(data_file) as f:
        data = json.load(f)

    for obj in data:
        method = httpretty.POST
        if obj['method'] == 'GET':
            method = httpretty.GET
        with open(dir / obj['file']) as f:
            httpretty.register_uri(
                method,
                obj['url'],
                f.read(),
            ) 
Example #11
Source File: test_course_list.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def mock_api_call(self, method, url, status_code=200, body='', **kwargs):
        """Register the given URL, and send data as a JSON string."""
        if isinstance(body, dict):
            body = json.dumps(body)

        log.debug('register_uri(%s, %s, %s, %s, %s)', method, url, body, status_code, kwargs)
        httpretty.enable()
        httpretty.register_uri(
            method, url, body=body, status=status_code, **kwargs
        ) 
Example #12
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(ProgramOfferUpdateViewTests, self).setUp()
        self.program_offer = factories.ProgramOfferFactory(partner=self.partner)
        self.path = reverse('programs:offers:edit', kwargs={'pk': self.program_offer.pk})

        # NOTE: We activate httpretty here so that we don't have to decorate every test method.
        httpretty.enable()
        self.mock_program_detail_endpoint(
            self.program_offer.condition.program_uuid, self.site_configuration.discovery_api_url
        ) 
Example #13
Source File: test_course_blocks.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes vote down vote up
def mock_api_call(self, method, url, status_code=200, body='', **kwargs):
        """Register the given URL, and send data as a JSON string."""
        if isinstance(body, dict):
            body = json.dumps(body)

        log.debug('register_uri(%s, %s, %s, %s, %s)', method, url, body, status_code, kwargs)
        httpretty.enable()
        httpretty.register_uri(
            method, url, body=body, status=status_code, **kwargs
        ) 
Example #14
Source File: test_api.py    From youtube-transcript-api with MIT License 5 votes vote down vote up
def setUp(self):
        httpretty.enable()
        httpretty.register_uri(
            httpretty.GET,
            'https://www.youtube.com/watch',
            body=load_asset('youtube.html.static')
        )
        httpretty.register_uri(
            httpretty.GET,
            'https://www.youtube.com/api/timedtext',
            body=load_asset('transcript.xml.static')
        ) 
Example #15
Source File: test_requests_integration.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super().setUp()
        RequestsInstrumentor().instrument()
        httpretty.enable()
        httpretty.register_uri(
            httpretty.GET, self.URL, body="Hello!",
        ) 
Example #16
Source File: test_client.py    From presto-python-client with Apache License 2.0 5 votes vote down vote up
def test_request_timeout():
    timeout = 0.1
    http_scheme = "http"
    host = "coordinator"
    port = 8080
    url = http_scheme + "://" + host + ":" + str(port) + constants.URL_STATEMENT_PATH

    def long_call(request, uri, headers):
        time.sleep(timeout * 2)
        return (200, headers, "delayed success")

    httpretty.enable()
    for method in [httpretty.POST, httpretty.GET]:
        httpretty.register_uri(method, url, body=long_call)

    # timeout without retry
    for request_timeout in [timeout, (timeout, timeout)]:
        req = PrestoRequest(
            host=host,
            port=port,
            user="test",
            http_scheme=http_scheme,
            max_attempts=1,
            request_timeout=request_timeout,
        )

        with pytest.raises(requests.exceptions.Timeout):
            req.get(url)

        with pytest.raises(requests.exceptions.Timeout):
            req.post("select 1")

    httpretty.disable()
    httpretty.reset() 
Example #17
Source File: csv.py    From girlfriend with MIT License 5 votes vote down vote up
def setUp(self):
        with open("test.csv", "w") as f:
            f.write(CSV_CONTENT)

        httpretty.enable()

        httpretty.register_uri(
            httpretty.GET,
            "http://test.gf/csv",
            body=CSV_CONTENT,
            content_type="text/plain"
        ) 
Example #18
Source File: json.py    From girlfriend with MIT License 5 votes vote down vote up
def setUp(self):
        self.records = [
            {"id": 1, "name": "Sam", "gender": 1},
            {"id": 2, "name": "Jack", "gender": 1},
            {"id": 3, "name": "Betty", "gender": 0},
        ]
        httpretty.enable() 
Example #19
Source File: test_publishers.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(LMSPublisherTests, self).setUp()

        httpretty.enable()
        self.mock_access_token_response()

        self.course = CourseFactory(
            verification_deadline=timezone.now() + datetime.timedelta(days=7),
            partner=self.partner
        )
        self.course.create_or_update_seat('honor', False, 0)
        self.course.create_or_update_seat('verified', True, 50)
        self.publisher = LMSPublisher()
        self.error_message = 'Failed to publish commerce data for {course_id} to LMS.'.format(course_id=self.course.id) 
Example #20
Source File: test_api.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(ProgramsApiClientTests, self).setUp()

        httpretty.enable()
        self.mock_access_token_response()
        self.client = ProgramsApiClient(self.site.siteconfiguration.discovery_api_client, self.site.domain) 
Example #21
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(ProgramOfferListViewTests, self).setUp()

        httpretty.enable()
        self.mock_access_token_response() 
Example #22
Source File: test_utilities.py    From python-devicecloud with Mozilla Public License 2.0 5 votes vote down vote up
def setUp(self):
        httpretty.enable()
        # setup Device Cloud ping response
        self.prepare_response("GET", "/ws/DeviceCore?size=1", "", status=200)
        self.dc = DeviceCloud('user', 'pass') 
Example #23
Source File: test_migrate_course.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(MigratedCourseTests, self).setUp()
        toggle_switch('publish_course_modes_to_lms', True)
        httpretty.enable()
        self.mock_access_token_response() 
Example #24
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(EnterpriseOfferUpdateViewTests, self).setUp()
        self.enterprise_offer = factories.EnterpriseOfferFactory(partner=self.partner)
        self.path = reverse('enterprise:offers:edit', kwargs={'pk': self.enterprise_offer.pk})

        # NOTE: We activate httpretty here so that we don't have to decorate every test method.
        httpretty.enable()
        self.mock_specific_enterprise_customer_api(self.enterprise_offer.condition.enterprise_customer_uuid) 
Example #25
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(UserTests, self).setUp()

        httpretty.enable()
        self.mock_access_token_response() 
Example #26
Source File: test_gzip.py    From influxdb-client-python with MIT License 5 votes vote down vote up
def setUp(self) -> None:
        super(GzipSupportTest, self).setUp()
        # https://github.com/gabrielfalcao/HTTPretty/issues/368
        import warnings
        warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*")
        warnings.filterwarnings("ignore", category=PendingDeprecationWarning, message="isAlive*")

        httpretty.enable()
        httpretty.reset() 
Example #27
Source File: test_QueryApiDataFrame.py    From influxdb-client-python with MIT License 5 votes vote down vote up
def setUp(self) -> None:
        super(QueryDataFrameApi, self).setUp()
        # https://github.com/gabrielfalcao/HTTPretty/issues/368
        import warnings
        warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*")
        warnings.filterwarnings("ignore", category=PendingDeprecationWarning, message="isAlive*")

        httpretty.enable()
        httpretty.reset() 
Example #28
Source File: helper.py    From tinify-python with MIT License 5 votes vote down vote up
def setUp(self):
        httpretty.enable()
        httpretty.HTTPretty.allow_net_connect = False 
Example #29
Source File: test_module.py    From edx-analytics-data-api-client with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(ModulesTests, self).setUp()
        httpretty.enable()

        self.course_id = 'edX/TestX/TestCourse'
        self.module_id = 'i4x://TestCourse/block1/module2/abcd1234'

        self.module = self.client.modules(self.course_id, self.module_id) 
Example #30
Source File: tests.py    From python-opencage-geocoder with MIT License 5 votes vote down vote up
def setUp(self):
        httpretty.enable()

        self.geocoder = OpenCageGeocode('abcde')