How to use the responses.add_callback function in responses

To help you get started, we’ve selected a few responses examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vintasoftware / tapioca-wrapper / tests / test_tapioca.py View on Github external
def test_token_expired_automatically_refresh_authentication(self):
        self.first_call = True

        def request_callback(request):
            if self.first_call:
                self.first_call = False
                return (401, {'content_type': 'application/json'}, json.dumps({"error": "Token expired"}))
            else:
                self.first_call = None
                return (201, {'content_type': 'application/json'}, '')

        responses.add_callback(
            responses.POST, self.wrapper.test().data,
            callback=request_callback,
            content_type='application/json',
        )

        response = self.wrapper.test().post()

        # refresh_authentication method should be able to update api_params
        self.assertEqual(response._api_params['token'], 'new_token')
github MediaMath / t1-python / tests / test_t1_base_classes.py View on Github external
def test_no_key_fails(self):
        def login_callback(_):
            with open('tests/fixtures/xml/login_no_key.xml') as f:
                body = f.read()
            return 403, {}, body

        mock_credentials = {
            'username': 'user',
            'password': 'pass',
        }
        responses.add_callback(responses.POST, 'https://api.mediamath.com/api/v2.0/login',
                               content_type='text/xml',
                               callback=login_callback)

        with self.assertRaises(errors.T1Error) as cm:
            T1(auth_method='cookie',
               json=True,
               api_base=API_BASE,
               **mock_credentials)

        exc = cm.exception
        self.assertEqual(b'<h1>Developer Inactive</h1>', exc.message)
github olipratt / swagger-conformance / tests / test_custom_types.py View on Github external
def _run_test_colour_type(self, value_factory):
        """Test just to show how tests using multiple requests work."""

        def _get_request_callback(_):
            # Respond with the previously received body value.
            raw_val = json.loads(responses.calls[-1].request.body)["hexcolour"]
            int_val = int(raw_val.lstrip('#'), 16)
            return 200, {}, json.dumps({'intcolour': int_val})

        responses.add(responses.POST, SCHEMA_URL_BASE + '/example',
                      json={'id': 1}, content_type=CONTENT_TYPE_JSON)
        responses.add(responses.PUT, SCHEMA_URL_BASE + '/example/1/hexcolour',
                      content_type=CONTENT_TYPE_JSON, status=204)

        responses.add_callback(responses.GET,
                               SCHEMA_URL_BASE + '/example/1/intcolour',
                               callback=_get_request_callback,
                               content_type=CONTENT_TYPE_JSON)

        client = swaggerconformance.client.Client(COLOUR_TYPE_SCHEMA_PATH)
        post_operation = client.api.endpoints["/example"]["post"]
        put_operation = \
            client.api.endpoints["/example/{int_id}/hexcolour"]["put"]
        put_strategy = put_operation.parameters_strategy(value_factory)
        get_operation = \
            client.api.endpoints["/example/{int_id}/intcolour"]["get"]
        get_strategy = get_operation.parameters_strategy(value_factory)

        @hypothesis.settings(
            max_examples=50,
            suppress_health_check=[hypothesis.HealthCheck.too_slow])
github containerbuildsystem / atomic-reactor / tests / test_util.py View on Github external
else:
            headers = {}
        return (200, headers, '')

    if registry.startswith('http'):
        url = registry + path
    else:
        # In the insecure case, we should try the https URL, and when that produces
        # an error, fall back to http
        if insecure:
            https_url = 'https://' + registry + path
            responses.add(responses.GET, https_url, body=ConnectionError())
            url = 'http://' + registry + path
        else:
            url = 'https://' + registry + path
    responses.add_callback(responses.GET, url, callback=request_callback)

    expected_versions = versions
    if versions is None:
        # Test default versions value
        expected_versions = ('v1', 'v2')

    expected_result = dict(
        (version, '{}-digest'.format(version))
        for version in expected_versions)
    if versions and 'v2_list' in versions:
        expected_result['v2_list'] = True

    # Only capture errors, since we want to be sure none are reported
    with caplog.at_level(logging.ERROR, logger='atomic_reactor'):
        if expected_versions:
            actual_digests = get_manifest_digests(**kwargs)
github offu / WeRoBot / tests / test_client.py View on Github external
def test_send_voice_message(self):
        responses.add_callback(
            responses.POST, self.URL, callback=self.voice_callback
        )

        r = self.client.send_voice_message("test_id", "test_media_id")
        assert r == {"errcode": 0, "errmsg": "ok"}
github offu / WeRoBot / tests / test_client.py View on Github external
def test_delete_menu(self):
        responses.add_callback(
            responses.GET,
            self.DELETE_URL,
            callback=self.callback_without_check
        )
        r = self.client.delete_menu()
        assert r == {"errcode": 0, "errmsg": "ok"}
github getsentry / sentry / tests / sentry / integrations / jira / test_integration.py View on Github external
body=SAMPLE_GET_ISSUE_RESPONSE,
            content_type="json",
            match_querystring=False,
        )

        def responder(request):
            body = json.loads(request.body)
            assert body["fields"]["labels"] == ["fuzzy", "bunnies"]
            assert body["fields"]["customfield_10200"] == {"value": "sad"}
            assert body["fields"]["customfield_10300"] == [
                {"value": "Feature 1"},
                {"value": "Feature 2"},
            ]
            return (200, {"content-type": "application/json"}, '{"key":"APP-123"}')

        responses.add_callback(
            responses.POST,
            "https://example.atlassian.net/rest/api/2/issue",
            callback=responder,
            match_querystring=False,
        )

        result = installation.create_issue(
            {
                "title": "example summary",
                "description": "example bug report",
                "issuetype": "1",
                "project": "10000",
                "customfield_10200": "sad",
                "customfield_10300": ["Feature 1", "Feature 2"],
                "labels": "fuzzy , ,  bunnies",
            }
github Datatamer / tamr-client / tests / unit / test_attribute.py View on Github external
)
        attr_specs = [inner_spec.with_name(str(i)) for i in range(4)]
        outer_spec = (
            AttributeTypeSpec.new().with_base_type("RECORD").with_attributes(attr_specs)
        )
        spec = (
            AttributeSpec.new()
            .with_name("attr")
            .with_is_nullable(False)
            .with_type(outer_spec)
        )

        snoop_dict = {}
        rel_path = "projects/1/attributes"
        base_path = "http://localhost:9100/api/versioned/v1"
        responses.add_callback(
            responses.POST,
            f"{base_path}/{rel_path}",
            partial(create_callback, snoop=snoop_dict),
        )

        collection = AttributeCollection(self.tamr, rel_path)
        collection.create(spec.to_dict())

        self.assertEqual(snoop_dict["payload"], spec_json)
github offu / WeRoBot / tests / test_client.py View on Github external
def test_upload_news(self):
        responses.add_callback(
            responses.POST, self.UP_NEWS_URL, callback=self.up_news_callback
        )
        r = self.client.upload_news(self.articles)
        assert r == {'errcode': 0, 'errmsg': 'ok'}
github Fueled / django-push-notifications / tests / test_register_device.py View on Github external
def test_register_device_manager(self):
        """
        Test if register_device() on the manager works as expected
        """
        responses.add_callback(
            responses.POST, ZEROPUSH_REGISTER_URL,
            callback=request_register_callback,
            content_type='application/json',
        )

        user = TestUserFactory.create()
        device = PushDevice.objects.register_push_device(
            user, self._create_token())

        assert device is not None
        assert device.user.pk == user.pk