Python httpretty.activate() Examples

The following are 10 code examples of httpretty.activate(). 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: helpers.py    From coinbase-python with Apache License 2.0 6 votes vote down vote up
def mock_response(method, uri, data, errors=None, warnings=None, pagination=None):
    def wrapper(fn):
        @six.wraps(fn)
        @hp.activate
        def inner(*args, **kwargs):
            body = {'data': data}
            if errors is not None:
                body['errors'] = errors
            if warnings is not None:
                body['warnings'] = warnings
            if pagination is not None:
                body['pagination'] = pagination
            hp.reset()
            hp.register_uri(method, re.compile('.*' + uri + '$'), json.dumps(body))
            return fn(*args, **kwargs)
        return inner
    return wrapper 
Example #2
Source File: __init__.py    From edx-analytics-dashboard with GNU Affero General Public License v3.0 6 votes vote down vote up
def mock_course_api(self, url, body=None, **kwargs):
        """
        Registers an HTTP mock for the specified course API path. The mock returns the specified data.

        The calling test function MUST activate httpretty.

        Arguments
            url     --  URL to be mocked
            body    --  Data returned by the mocked API
            kwargs  --  Additional arguments passed to httpretty.register_uri()
        """

        # Avoid developer confusion when httpretty is not active and fail the test now.
        if not httpretty.is_enabled():
            self.fail('httpretty is not enabled. The mock will not be used!')

        body = body or {}
        default_kwargs = {
            'body': kwargs.get('body', json.dumps(body)),
            'content_type': 'application/json'
        }
        default_kwargs.update(kwargs)

        httpretty.register_uri(httpretty.GET, url, **default_kwargs)
        logger.debug('Mocking Course API URL: %s', url) 
Example #3
Source File: ime_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_activate_ime_engine(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/ime/activate'),
        )
        engine = 'com.android.inputmethod.latin/.LatinIME'
        assert isinstance(driver.activate_ime_engine(engine), WebDriver)

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['engine'] == 'com.android.inputmethod.latin/.LatinIME' 
Example #4
Source File: test_task_identities.py    From grimoirelab-sirmordred with GNU General Public License v3.0 5 votes vote down vote up
def off_test_load_orgs(self):
        """ Test loading of orgs in SH """
        setup_http_server()

        config = Config(CONF_FILE)
        task = TaskIdentitiesLoad(config)
        task.execute()
        # Check the number of orgs loaded
        norgs = len(api.registry(self.sh_db))
        self.assertEqual(norgs, 20)

    # @httpretty.activate
    # TODO: remote loading 
Example #5
Source File: bluegreen_test.py    From tsuru-bluegreen with MIT License 5 votes vote down vote up
def test_remove_cname_return_true_when_can_remove(self):
    httpretty.register_uri(httpretty.DELETE, 'http://tsuruhost.com/apps/xpto/cname',
                           data='cname=cname1&cname=cname2',
                           status=200)

    self.assertTrue(self.bg.remove_cname('xpto', self.cnames))

    @httpretty.activate
    def test_remove_cname_return_false_when_cant_remove(self):
      httpretty.register_uri(httpretty.DELETE, 'http://tsuruhost.com/apps/xpto/cname',
                             data='cname=cname1&cname=cname2',
                             status=500)

      self.assertFalse(self.bg.remove_cname('xpto', self.cnames))

    @httpretty.activate
    def test_set_cname_return_true_when_can_set(self):
      httpretty.register_uri(httpretty.POST, 'http://tsuruhost.com/apps/xpto/cname',
                             data='cname=cname1&cname=cname2',
                             status=200)

      self.assertTrue(self.bg.set_cname('xpto', self.cnames))

    @httpretty.activate
    def test_set_cname_return_false_when_cant_set(self):
      httpretty.register_uri(httpretty.POST, 'http://tsuruhost.com/apps/xpto/cname',
                             data='cname=cname1&cname=cname2',
                             status=500)

      self.assertFalse(self.bg.set_cname('xpto', self.cnames)) 
Example #6
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_inactive_user_email_domain_restricted_coupon_redemption(self):
        """
        Verify that a user must activate their account before being allowed
        to redeem an email domain-restricted coupon.
        """
        self.mock_account_api(self.request, self.user.username, data={'is_active': False})
        self.mock_access_token_response()
        email_domain = self.user.email.split('@')[1]
        self.create_coupon(catalog=self.catalog, code=COUPON_CODE, benefit_value=5, email_domains=email_domain)

        response = self.client.get(self.redeem_url_with_params())
        self.assert_redirected_to_email_confirmation(response) 
Example #7
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 #8
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 #9
Source File: test_user.py    From polyaxon-client with MIT License 5 votes vote down vote up
def test_activate_user(self):
        httpretty.register_uri(
            httpretty.POST,
            BaseApiHandler.build_url(
                self.api_config.base_url,
                '/users',
                'activate',
                'test-username'
            ),
            content_type='application/json',
            status=200)

        response = self.api_handler.activate_user('test-username')
        assert response.status_code == 200 
Example #10
Source File: test_chalice.py    From pylti with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def test_access_to_oauth_resource_post_grade_fail(self):
        """
        Check post_grade functionality fails on invalid response.
        """
        # pylint: disable=maybe-no-member
        uri = (u'https://example.edu/courses/MITx/ODL_ENG/2014_T1/xblock/'
               u'i4x:;_;_MITx;_ODL_ENG;_lti;'
               u'_94173d3e79d145fd8ec2e83f15836ac8/handler_noauth'
               u'/grade_handler')

        def request_callback(request, cburi, headers):
            # pylint: disable=unused-argument
            """
            Mock error response callback.
            """
            return 200, headers, "wrong_response"

        httpretty.register_uri(httpretty.POST, uri, body=request_callback)

        consumers = self.consumers
        url = 'https://localhost/post_grade/1.0?'
        new_url = self.generate_launch_request(consumers, url)
        ret = self.localGateway.handle_request(method='GET',
                                               path=new_url,
                                               headers={
                                                  'host': 'localhost',
                                                  'x-forwarded-proto': 'https'
                                               },
                                               body='')
        self.assertTrue(self.has_exception())
        self.assertEqual(ret['body'], "error")

    # DELETED: Not implemented. Sounds like an EdX edge case
    # @httpretty.activate
    # def test_access_to_oauth_resource_post_grade_fix_url(self):
    #     """
    #     Make sure URL remap works for edX vagrant stack.
    #     """
    #     # pylint: disable=maybe-no-member
    #     uri = 'https://localhost:8000/dev_stack'

    #     httpretty.register_uri(httpretty.POST, uri,
    #                            body=self.request_callback)

    #     url = 'https://localhost/initial?'
    #     new_url = self.generate_launch_request(
    #         self.consumers, url, lit_outcome_service_url=uri
    #     )
    #     ret = self.app.get(new_url)
    #     self.assertFalse(self.has_exception())

    #     ret = self.app.get("/post_grade/1.0")
    #     self.assertFalse(self.has_exception())
    #     self.assertEqual(ret.data.decode('utf-8'), "grade=True")

    #     ret = self.app.get("/post_grade/2.0")
    #     self.assertFalse(self.has_exception())
    #     self.assertEqual(ret.data.decode('utf-8'), "grade=False")