Python httpretty.disable() Examples

The following are 30 code examples of httpretty.disable(). 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_conditions.py    From ecommerce with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_lms_resource_for_user_caching_none(self):
        """
        LMS resource should be properly cached when enrollments is None.
        """
        basket = BasketFactory(site=self.site, owner=UserFactory())
        resource_name = 'test_resource_name'
        mock_endpoint = mock.Mock()
        mock_endpoint.get.return_value = None

        return_value = self.condition._get_lms_resource_for_user(basket, resource_name, mock_endpoint)  # pylint: disable=protected-access

        self.assertEqual(return_value, [])
        self.assertEqual(mock_endpoint.get.call_count, 1, 'Endpoint should be called before caching.')

        mock_endpoint.reset_mock()

        return_value = self.condition._get_lms_resource_for_user(basket, resource_name, mock_endpoint)  # pylint: disable=protected-access

        self.assertEqual(return_value, [])
        self.assertEqual(mock_endpoint.get.call_count, 0, 'Endpoint should NOT be called after caching.') 
Example #2
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get(self):
        """ The context should contain a list of enterprise offers. """

        # These should be ignored since their associated Condition objects do NOT have an Enterprise Customer UUID.
        factories.ConditionalOfferFactory.create_batch(3)

        enterprise_offers = factories.EnterpriseOfferFactory.create_batch(4, partner=self.partner)

        for offer in enterprise_offers:
            self.mock_specific_enterprise_customer_api(offer.condition.enterprise_customer_uuid)

        response = self.assert_get_response_status(200)
        self.assertEqual(list(response.context['object_list']), enterprise_offers)

        # The page should load even if the Enterprise API is inaccessible
        httpretty.disable()
        response = self.assert_get_response_status(200)
        self.assertEqual(list(response.context['object_list']), enterprise_offers) 
Example #3
Source File: test_migrate_course.py    From ecommerce with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_course_name_missing(self):
        """Verify the Course Structure API is queried if the Commerce API doesn't return a course name."""
        # Mock the Commerce API so that it does not return a name
        body = {
            'name': None,
            'verification_deadline': EXPIRES_STRING,
        }
        httpretty.register_uri(httpretty.GET, self.commerce_api_url, body=json.dumps(body), content_type=JSON)

        # Mock the Course Structure API
        httpretty.register_uri(httpretty.GET, self.course_structure_url, body='{}', content_type=JSON)

        # Try migrating the course, which should fail.
        try:
            migrated_course = MigratedCourse(self.course_id, self.site.domain)
            migrated_course.load_from_lms()
        except Exception as ex:  # pylint: disable=broad-except
            self.assertEqual(six.text_type(ex),
                             'Aborting migration. No name is available for {}.'.format(self.course_id))

        # Verify the Course Structure API was called.
        last_request = httpretty.last_request()
        self.assertEqual(last_request.path, urlparse(self.course_structure_url).path) 
Example #4
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 #5
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get(self):
        """ The context should contain a list of program offers. """

        # These should be ignored since their associated Condition objects do NOT have a program UUID.
        factories.ConditionalOfferFactory.create_batch(3)

        program_offers = factories.ProgramOfferFactory.create_batch(4, partner=self.partner)

        for offer in program_offers:
            self.mock_program_detail_endpoint(offer.condition.program_uuid, self.site_configuration.discovery_api_url)

        response = self.assert_get_response_status(200)
        self.assertEqual(list(response.context['object_list']), program_offers)

        # The page should load even if the Programs API is inaccessible
        httpretty.disable()
        response = self.assert_get_response_status(200)
        self.assertEqual(list(response.context['object_list']), program_offers) 
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: 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 #8
Source File: test_gzip.py    From influxdb-client-python with MIT License 6 votes vote down vote up
def test_write_query_gzip(self):
        httpretty.disable()

        self.client = InfluxDBClient(self.host, token="my-token", org="my-org", debug=False,
                                     enable_gzip=True)
        self.api_client = self.client.api_client
        self.buckets_client = self.client.buckets_api()
        self.query_client = self.client.query_api()
        self.org = "my-org"
        self.my_organization = self.find_my_org()

        _bucket = self.create_test_bucket()

        self.client.write_api(write_options=SYNCHRONOUS) \
            .write(_bucket.name, self.org, "h2o_feet,location=coyote_creek water_level=111.0 1")

        _result = self.query_client.query(
            "from(bucket:\"{0}\") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()".format(_bucket.name),
            self.org)

        self.assertEqual(len(_result), 1)
        self.assertEqual(_result[0].records[0].get_measurement(), "h2o_feet")
        self.assertEqual(_result[0].records[0].get_value(), 111.0)
        self.assertEqual(_result[0].records[0].get_field(), "water_level") 
Example #9
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 #10
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(EnterpriseOfferUpdateViewTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #11
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(UserTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #12
Source File: test_api.py    From youtube-transcript-api with MIT License 5 votes vote down vote up
def tearDown(self):
        httpretty.disable() 
Example #13
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_user_verification_status_cache(self):
        """ Verify the user verification status values are cached. """
        user = self.create_user()
        self.mock_verification_status_api(self.site, user)
        self.assertTrue(user.is_verified(self.site))

        httpretty.disable()
        self.assertTrue(user.is_verified(self.site)) 
Example #14
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_enterprise_api_client(self):
        """
        Verify the property "enterprise_api_client" returns a Slumber-based
        REST API client for enterprise service API.
        """
        token = self.mock_access_token_response()
        client = self.site.siteconfiguration.enterprise_api_client
        client_store = client._store  # pylint: disable=protected-access
        client_auth = client_store['session'].auth

        self.assertEqual(client_store['base_url'], ENTERPRISE_API_URL)
        self.assertIsInstance(client_auth, SuppliedJwtAuth)
        self.assertEqual(client_auth.token, token) 
Example #15
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_discovery_api_client(self):
        """ Verify the property returns a Discovery API client. """
        token = self.mock_access_token_response()
        client = self.site_configuration.discovery_api_client
        client_store = client._store  # pylint: disable=protected-access
        client_auth = client_store['session'].auth

        self.assertEqual(client_store['base_url'], self.site_configuration.discovery_api_url)
        self.assertIsInstance(client_auth, SuppliedJwtAuth)
        self.assertEqual(client_auth.token, token) 
Example #16
Source File: test_gzip.py    From influxdb-client-python with MIT License 5 votes vote down vote up
def tearDown(self) -> None:
        self.client.__del__()
        httpretty.disable() 
Example #17
Source File: test_QueryApiDataFrame.py    From influxdb-client-python with MIT License 5 votes vote down vote up
def tearDown(self) -> None:
        self.client.__del__()
        httpretty.disable() 
Example #18
Source File: test_WriteApiBatching.py    From influxdb-client-python with MIT License 5 votes vote down vote up
def tearDown(self) -> None:
        self._write_client.__del__()
        httpretty.disable() 
Example #19
Source File: helper.py    From tinify-python with MIT License 5 votes vote down vote up
def tearDown(self):
        httpretty.disable()
        httpretty.reset()

        tinify.key = None
        tinify.app_identifier = None
        tinify.proxy = None
        tinify.compression_count 
Example #20
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_access_token(self):
        """ Verify the property retrieves, and caches, an access token from the OAuth 2.0 provider. """
        token = self.mock_access_token_response()
        self.assertEqual(self.site.siteconfiguration.access_token, token)
        self.assertTrue(httpretty.has_request())

        # Verify the value is cached
        httpretty.disable()
        self.assertEqual(self.site.siteconfiguration.access_token, token) 
Example #21
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get(self):
        """ The context should contain the enterprise offer. """
        response = self.assert_get_response_status(200)
        self.assertEqual(response.context['object'], self.enterprise_offer)

        # The page should load even if the Enterprise API is inaccessible
        httpretty.disable()
        response = self.assert_get_response_status(200)
        self.assertEqual(response.context['object'], self.enterprise_offer) 
Example #22
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_applicable_lines(self):
        """ Assert that basket lines matching the range's discovery query are selected. """
        basket = factories.BasketFactory(site=self.site, owner=self.user)
        entitlement_product = self.create_entitlement_product()
        course, seat = self.create_course_and_seat()
        no_certificate_product = factories.ProductFactory(stockrecords__price_currency='USD')

        basket.add_product(entitlement_product)
        basket.add_product(seat)
        applicable_lines = [(line.product.stockrecords.first().price_excl_tax, line) for line in basket.all_lines()]
        basket.add_product(no_certificate_product)

        self.mock_access_token_response()

        # Verify that the method raises an exception when it fails to reach the Discovery Service
        with self.assertRaises(Exception):
            self.benefit.get_applicable_lines(self.offer, basket)

        self.mock_catalog_query_contains_endpoint(
            course_run_ids=[], course_uuids=[entitlement_product.attr.UUID, course.id], absent_ids=[],
            query=self.benefit.range.catalog_query, discovery_api_url=self.site_configuration.discovery_api_url
        )

        self.assertEqual(self.benefit.get_applicable_lines(self.offer, basket), applicable_lines)

        # Verify that the API return value is cached
        httpretty.disable()
        self.assertEqual(self.benefit.get_applicable_lines(self.offer, basket), applicable_lines) 
Example #23
Source File: test_models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_range_condition_satisfied(self):
        """
        Verify that a basket satisfies a condition only when all of its products are in its range's catalog queryset.
        """
        valid_user_email = 'valid@{domain}'.format(domain=self.valid_sub_domain)
        basket = factories.BasketFactory(site=self.site, owner=UserFactory(email=valid_user_email))
        product = self.create_entitlement_product()
        another_product = self.create_entitlement_product()

        _range = factories.RangeFactory()
        _range.course_seat_types = ','.join(Range.ALLOWED_SEAT_TYPES)
        _range.catalog_query = 'uuid:{course_uuid}'.format(course_uuid=product.attr.UUID)
        benefit = factories.BenefitFactory(range=_range)
        offer = factories.ConditionalOfferFactory(benefit=benefit)
        self.mock_access_token_response()
        self.mock_catalog_query_contains_endpoint(
            course_run_ids=[], course_uuids=[product.attr.UUID], absent_ids=[another_product.attr.UUID],
            query=benefit.range.catalog_query, discovery_api_url=self.site_configuration.discovery_api_url
        )

        basket.add_product(product)
        self.assertTrue(offer.is_condition_satisfied(basket))

        basket.add_product(another_product)
        self.assertFalse(offer.is_condition_satisfied(basket))

        # Verify that API return values are cached
        httpretty.disable()
        self.assertFalse(offer.is_condition_satisfied(basket)) 
Example #24
Source File: test_api.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(ProgramsApiClientTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #25
Source File: test_migrate_course.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(MigratedCourseTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #26
Source File: test_utils.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_program_not_found(self):  # pylint: disable=unused-argument
        """
        The method should log not found errors for program data
        """
        self.mock_program_detail_endpoint(self.program_uuid, self.discovery_api_url, empty=True)
        with mock.patch.object(ProgramsApiClient, 'get_program', side_effect=HttpNotFoundError):
            with LogCapture(LOGGER_NAME) as logger:
                response = get_program(self.program_uuid, self.site.siteconfiguration)
                self.assertIsNone(response)
                msg = 'No program data found for {}'.format(self.program_uuid)
                logger.check((LOGGER_NAME, 'DEBUG', msg)) 
Example #27
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(ProgramOfferListViewTests, self).tearDown()
        httpretty.disable()
        httpretty.reset() 
Example #28
Source File: test_utils.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_program(self):
        """
        The method should return data from the Discovery Service API.
        Data should be cached for subsequent calls.
        """
        data = self.mock_program_detail_endpoint(self.program_uuid, self.discovery_api_url)
        self.assertEqual(get_program(self.program_uuid, self.site.siteconfiguration), data)

        # The program data should be cached
        httpretty.disable()
        self.assertEqual(get_program(self.program_uuid, self.site.siteconfiguration), data) 
Example #29
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get(self):
        """ The context should contain the program offer. """
        response = self.assert_get_response_status(200)
        self.assertEqual(response.context['object'], self.program_offer)

        # The page should load even if the Programs API is inaccessible
        httpretty.disable()
        response = self.assert_get_response_status(200)
        self.assertEqual(response.context['object'], self.program_offer) 
Example #30
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        super(ProgramOfferUpdateViewTests, self).tearDown()
        httpretty.disable()
        httpretty.reset()