Python responses.PUT Examples

The following are 30 code examples of responses.PUT(). 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 responses , or try the search function .
Example #1
Source File: test_datasets.py    From mapbox-sdk-py with MIT License 6 votes vote down vote up
def test_update_feature():
    """Feature update works."""

    def request_callback(request):
        payload = json.loads(request.body.decode())
        assert payload == {'type': 'Feature'}
        return (200, {}, "")

    responses.add_callback(
        responses.PUT,
        'https://api.mapbox.com/datasets/v1/{0}/{1}/features/{2}?access_token={3}'.format(
            username, 'test', '1', access_token),
        match_querystring=True,
        callback=request_callback)

    response = Datasets(access_token=access_token).update_feature(
        'test', '1', {'type': 'Feature'})
    assert response.status_code == 200 
Example #2
Source File: test_channels.py    From python-twitch-client with MIT License 6 votes vote down vote up
def test_update():
    channel_id = example_channel["_id"]
    responses.add(
        responses.PUT,
        "{}channels/{}".format(BASE_URL, channel_id),
        body=json.dumps(example_channel),
        status=200,
        content_type="application/json",
    )

    client = TwitchClient("client id", "oauth token")
    status = "Spongebob Squarepants"
    channel = client.channels.update(channel_id, status=status)

    assert len(responses.calls) == 1
    expected_body = json.dumps({"channel": {"status": status}}).encode("utf-8")
    assert responses.calls[0].request.body == expected_body
    assert isinstance(channel, Channel)
    assert channel.id == channel_id
    assert channel.name == example_channel["name"] 
Example #3
Source File: test_collections.py    From python-twitch-client with MIT License 6 votes vote down vote up
def test_add_item():
    collection_id = "abcd"
    responses.add(
        responses.PUT,
        "{}collections/{}/items".format(BASE_URL, collection_id),
        body=json.dumps(example_item),
        status=200,
        content_type="application/json",
    )

    client = TwitchClient("client id", "oauth client")

    item = client.collections.add_item(collection_id, "1234", "video")

    assert len(responses.calls) == 1
    assert isinstance(item, Item)
    assert item.id == example_item["_id"]
    assert item.title == example_item["title"] 
Example #4
Source File: test_users.py    From python-twitch-client with MIT License 6 votes vote down vote up
def test_follow_channel():
    user_id = 1234
    channel_id = 12345
    responses.add(
        responses.PUT,
        "{}users/{}/follows/channels/{}".format(BASE_URL, user_id, channel_id),
        body=json.dumps(example_follow),
        status=200,
        content_type="application/json",
    )

    client = TwitchClient("client id", "oauth token")

    follow = client.users.follow_channel(user_id, channel_id)

    assert len(responses.calls) == 1
    assert isinstance(follow, Follow)
    assert follow.notifications == example_follow["notifications"]
    assert isinstance(follow.channel, Channel)
    assert follow.channel.id == example_channel["_id"]
    assert follow.channel.name == example_channel["name"] 
Example #5
Source File: test_users.py    From python-twitch-client with MIT License 6 votes vote down vote up
def test_block_user():
    user_id = 1234
    blocked_user_id = 12345
    responses.add(
        responses.PUT,
        "{}users/{}/blocks/{}".format(BASE_URL, user_id, blocked_user_id),
        body=json.dumps(example_block),
        status=200,
        content_type="application/json",
    )

    client = TwitchClient("client id", "oauth token")

    block = client.users.block_user(user_id, blocked_user_id)

    assert len(responses.calls) == 1
    assert isinstance(block, UserBlock)
    assert block.id == example_block["_id"]
    assert isinstance(block.user, User)
    assert block.user.id == example_user["_id"]
    assert block.user.name == example_user["name"] 
Example #6
Source File: test_enterprise_catalog.py    From edx-enterprise with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_update_enterprise_catalog():
    expected_response = {
        'catalog_uuid': TEST_ENTERPRISE_CATALOG_UUID,
        'enterprise_customer': TEST_ENTERPRISE_ID,
        'enterprise_customer_name': TEST_ENTERPRISE_NAME,
        'title': 'Test Catalog',
        'content_filter': {"content_type": "course"},
        'enabled_course_modes': ["verified"],
        'publish_audit_enrollment_urls': False,
    }
    responses.add(
        responses.PUT,
        _url("enterprise-catalogs/{catalog_uuid}/".format(catalog_uuid=TEST_ENTERPRISE_CATALOG_UUID)),
        json=expected_response,
    )
    client = enterprise_catalog.EnterpriseCatalogApiClient('staff-user-goes-here')
    actual_response = client.update_enterprise_catalog(
        TEST_ENTERPRISE_CATALOG_UUID,
        content_filter={"content_type": "course"}
    )
    assert actual_response == expected_response
    request = responses.calls[0][0]
    assert json.loads(request.body) == {'content_filter': {"content_type": "course"}} 
Example #7
Source File: test_tags.py    From upcloud-python-api with MIT License 6 votes vote down vote up
def test_edit_tag(self, manager):

        Mock.mock_get('tag/TheTestTag')
        tag = manager.get_tag('TheTestTag')

        responses.add_callback(
            responses.PUT,
            Mock.base_url + '/tag/TheTestTag',
            content_type='application/json',
            callback=tag_post_callback
        )

        tag.name = 'AnotherTestTag'
        assert tag._api_name == 'TheTestTag'

        tag.save()

        assert tag.name == 'AnotherTestTag'
        assert tag._api_name == 'AnotherTestTag' 
Example #8
Source File: test_connect.py    From pykiteconnect with MIT License 6 votes vote down vote up
def test_modify_gtt(kiteconnect):
    """Test modify gtt order."""
    responses.add(
        responses.PUT,
        "{0}{1}".format(kiteconnect.root, kiteconnect._routes["gtt.modify"].format(trigger_id=123)),
        body=utils.get_response("gtt.modify"),
        content_type="application/json"
    )
    gtts = kiteconnect.modify_gtt(
        trigger_id=123,
        trigger_type=kiteconnect.GTT_TYPE_SINGLE,
        tradingsymbol="INFY",
        exchange="NSE",
        trigger_values=[1],
        last_price=800,
        orders=[{
            "transaction_type": kiteconnect.TRANSACTION_TYPE_BUY,
            "quantity": 1,
            "order_type": kiteconnect.ORDER_TYPE_LIMIT,
            "product": kiteconnect.PRODUCT_CNC,
            "price": 1,
        }]
    )
    assert gtts["trigger_id"] == 123 
Example #9
Source File: test_k8sdriver_promenade_client.py    From drydock with Apache License 2.0 6 votes vote down vote up
def test_put(patch1, patch2):
    """
    Test put functionality
    """
    responses.add(
        responses.PUT,
        'http://promhost:80/api/v1.0/node-label/n1',
        body='{"key1":"label1"}',
        status=200)

    prom_session = PromenadeSession()
    result = prom_session.put(
        'v1.0/node-label/n1', body='{"key1":"label1"}', timeout=(60, 60))

    assert PROM_HOST == prom_session.host
    assert result.status_code == 200 
Example #10
Source File: test_k8sdriver_promenade_client.py    From drydock with Apache License 2.0 6 votes vote down vote up
def test_relabel_node(patch1, patch2):
    """
    Test relabel node call from Promenade
    Client
    """
    responses.add(
        responses.PUT,
        'http://promhost:80/api/v1.0/node-labels/n1',
        body='{"key1":"label1"}',
        status=200)

    prom_client = PromenadeClient()

    result = prom_client.relabel_node('n1', {"key1": "label1"})

    assert result == {"key1": "label1"} 
Example #11
Source File: test_swaggerconformance.py    From swagger-conformance with MIT License 5 votes vote down vote up
def test_full_put(self):
        """A PUT request containing all different parameter types."""
        # Handle all the basic endpoints.
        respond_to_get('/example')
        respond_to_delete('/example', status=204)
        respond_to_put(r'/example/-?\d+', status=204)

        # Now just kick off the validation process.
        swaggerconformance.api_conformance_test(FULL_PUT_SCHEMA_PATH,
                                                cont_on_err=False) 
Example #12
Source File: test_swaggerconformance.py    From swagger-conformance with MIT License 5 votes vote down vote up
def respond_to_put(path, response_json=None, status=200,
                   content_type=CONTENT_TYPE_JSON):
    """Respond to a PUT request to the provided path."""
    _respond_to_method(responses.PUT, path, response_json, status,
                       content_type) 
Example #13
Source File: test_swaggerconformance.py    From swagger-conformance with MIT License 5 votes vote down vote up
def test_all_constraints(self):
        """A PUT request containing all parameter constraint combinations."""
        # Handle all the basic endpoints.
        respond_to_get('/schema')
        respond_to_put(r'/example/-?\d+', status=204)

        # Now just kick off the validation process.
        swaggerconformance.api_conformance_test(ALL_CONSTRAINTS_SCHEMA_PATH,
                                                cont_on_err=False) 
Example #14
Source File: test_patch.py    From code-review with Mozilla Public License 2.0 5 votes vote down vote up
def test_publication(
    monkeypatch, mock_taskcluster_config, mock_repositories, mock_task
):
    """
    Check a patch publication through Taskcluster services
    """

    # Setup local config as running in a real Taskcluster task with proxy
    monkeypatch.setenv("TASK_ID", "fakeTaskId")
    monkeypatch.setenv("RUN_ID", "0")
    monkeypatch.setenv("TASKCLUSTER_PROXY_URL", "http://proxy")
    settings.setup("test", [], mock_repositories)

    # Mock the storage response
    responses.add(
        responses.PUT,
        "http://storage.test/public/patch/mock-analyzer-test-improvement.diff",
        json={},
        headers={"ETag": "test123"},
    )

    patch = ImprovementPatch(
        mock_task(DefaultTask, "mock-analyzer"), "test-improvement", "This is good code"
    )
    assert patch.url is None

    patch.publish()
    assert (
        patch.url
        == "https://firefox-ci-tc.services.mozilla.com/api/queue/v1/task/fakeTaskId/runs/0/artifacts/public/patch/mock-analyzer-test-improvement.diff"
    )

    # Check the mock has been called
    assert [c.request.url for c in responses.calls] == [
        "http://storage.test/public/patch/mock-analyzer-test-improvement.diff"
    ] 
Example #15
Source File: test_communities.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_add_timed_out_user():
    community_id = "abcd"
    user_id = 12345
    responses.add(
        responses.PUT,
        "{}communities/{}/timeouts/{}".format(BASE_URL, community_id, user_id),
        status=204,
        content_type="application/json",
    )

    client = TwitchClient("client id", "oauth token")

    client.communities.add_timed_out_user(community_id, user_id, 5)

    assert len(responses.calls) == 1 
Example #16
Source File: test_communities.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_add_moderator():
    community_id = "abcd"
    user_id = 12345
    responses.add(
        responses.PUT,
        "{}communities/{}/moderators/{}".format(BASE_URL, community_id, user_id),
        status=204,
        content_type="application/json",
    )

    client = TwitchClient("client id", "oauth token")

    client.communities.add_moderator(community_id, user_id)

    assert len(responses.calls) == 1 
Example #17
Source File: test_communities.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_update():
    community_id = "abcd"
    responses.add(
        responses.PUT,
        "{}communities/{}".format(BASE_URL, community_id),
        body=json.dumps(example_community),
        status=204,
        content_type="application/json",
    )

    client = TwitchClient("client id")

    client.communities.update(community_id)

    assert len(responses.calls) == 1 
Example #18
Source File: test_channels.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_set_community():
    channel_id = example_channel["_id"]
    community_id = example_community["_id"]
    responses.add(
        responses.PUT,
        "{}channels/{}/community/{}".format(BASE_URL, channel_id, community_id),
        status=204,
        content_type="application/json",
    )

    client = TwitchClient("client id")

    client.channels.set_community(channel_id, community_id)

    assert len(responses.calls) == 1 
Example #19
Source File: test_collections.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_move_item():
    collection_id = "abcd"
    collection_item_id = "1234"
    responses.add(
        responses.PUT,
        "{}collections/{}/items/{}".format(BASE_URL, collection_id, collection_item_id),
        status=204,
        content_type="application/json",
    )

    client = TwitchClient("client id", "oauth client")

    client.collections.move_item(collection_id, collection_item_id, 3)

    assert len(responses.calls) == 1 
Example #20
Source File: test_collections.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_update():
    collection_id = "abcd"
    responses.add(
        responses.PUT,
        "{}collections/{}".format(BASE_URL, collection_id),
        status=204,
        content_type="application/json",
    )

    client = TwitchClient("client id", "oauth client")

    client.collections.update(collection_id, "this is title")

    assert len(responses.calls) == 1 
Example #21
Source File: test_base.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_request_put_raises_exception_if_not_200_response(status):
    responses.add(
        responses.PUT, BASE_URL, status=status, content_type="application/json"
    )

    api = TwitchAPI(client_id="client")

    with pytest.raises(exceptions.HTTPError):
        api._request_put("", dummy_data) 
Example #22
Source File: test_base.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_request_put_does_not_raise_exception_if_successful_and_returns_json():
    responses.add(
        responses.PUT,
        BASE_URL,
        body=json.dumps(dummy_data),
        status=200,
        content_type="application/json",
    )

    api = TwitchAPI(client_id="client")
    response = api._request_put("", dummy_data)
    assert response == dummy_data 
Example #23
Source File: test_base.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_request_put_sends_headers_with_the_request():
    responses.add(responses.PUT, BASE_URL, status=204, content_type="application/json")

    api = TwitchAPI(client_id="client")
    api._request_put("", dummy_data)

    assert "Client-ID" in responses.calls[0].request.headers
    assert "Accept" in responses.calls[0].request.headers 
Example #24
Source File: test_base.py    From python-twitch-client with MIT License 5 votes vote down vote up
def test_request_put_returns_dictionary_if_successful():
    responses.add(
        responses.PUT,
        BASE_URL,
        body=json.dumps(dummy_data),
        status=200,
        content_type="application/json",
    )

    api = TwitchAPI(client_id="client")
    response = api._request_put("", dummy_data)

    assert isinstance(response, dict)
    assert response == dummy_data 
Example #25
Source File: mixins.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def mock_node_edit(self, status):
        responses.add(
            responses.PUT,
            '{root}/node.json/{node_id}'.format(root=self.api_root, node_id=self.node_id),
            body=json.dumps({}),
            content_type='application/json',
            status=status
        ) 
Example #26
Source File: test_push_floating_tags.py    From atomic-reactor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, registry):
        self.hostname = registry_hostname(registry)
        self.repos = {}
        self._add_pattern(responses.PUT, r'/v2/(.*)/manifests/([^/]+)',
                          self._put_manifest) 
Example #27
Source File: test_group_manifests.py    From atomic-reactor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, registry):
        self.hostname = registry_hostname(registry)
        self.repos = {}
        self._add_pattern(responses.GET, r'/v2/(.*)/manifests/([^/]+)',
                          self._get_manifest)
        self._add_pattern(responses.HEAD, r'/v2/(.*)/manifests/([^/]+)',
                          self._get_manifest)
        self._add_pattern(responses.PUT, r'/v2/(.*)/manifests/([^/]+)',
                          self._put_manifest)
        self._add_pattern(responses.GET, r'/v2/(.*)/blobs/([^/]+)',
                          self._get_blob)
        self._add_pattern(responses.HEAD, r'/v2/(.*)/blobs/([^/]+)',
                          self._get_blob)
        self._add_pattern(responses.POST, r'/v2/(.*)/blobs/uploads/\?mount=([^&]+)&from=(.+)',
                          self._mount_blob) 
Example #28
Source File: test_datasets.py    From mapbox-cli-py with MIT License 5 votes vote down vote up
def test_cli_dataset_put_feature_stdin():
    dataset = "dataset-2"
    id = "abc"

    feature = """
        {{
          "type":"Feature",
          "id":"{0}",
          "properties":{{}},
          "geometry":{{"type":"Point","coordinates":[0,0]}}
        }}""".format(id)

    feature = "".join(feature.split())

    responses.add(
        responses.PUT,
        'https://api.mapbox.com/datasets/v1/{0}/{1}/features/{2}?access_token={3}'.format(username, dataset, id, access_token),
        match_querystring=True,
        status=200, body=feature,
        content_type='application/json'
    )

    runner = CliRunner()
    result = runner.invoke(
        main_group,
        ['--access-token', access_token,
         'datasets',
         'put-feature', dataset, id],
        input=feature)

    assert result.exit_code == 0
    assert result.output.strip() == feature.strip() 
Example #29
Source File: test_datasets.py    From mapbox-cli-py with MIT License 5 votes vote down vote up
def test_cli_dataset_put_feature_fromfile(tmpdir):
    tmpfile = str(tmpdir.join('test.put-feature.json'))
    dataset = "dataset-2"
    id = "abc"

    feature = """
        {{
          "type":"Feature",
          "id":"{0}",
          "properties":{{}},
          "geometry":{{"type":"Point","coordinates":[0,0]}}
        }}""".format(id)

    feature = "".join(feature.split())

    f = open(tmpfile, 'w')
    f.write(feature)
    f.close()

    responses.add(
        responses.PUT,
        'https://api.mapbox.com/datasets/v1/{0}/{1}/features/{2}?access_token={3}'.format(username, dataset, id, access_token),
        match_querystring=True,
        status=200, body=feature,
        content_type='application/json'
    )

    runner = CliRunner()
    result = runner.invoke(
        main_group,
        ['--access-token', access_token,
         'datasets',
         'put-feature', dataset, id,
         '--input', tmpfile])

    assert result.exit_code == 0
    assert result.output.strip() == feature.strip() 
Example #30
Source File: test_datasets.py    From mapbox-cli-py with MIT License 5 votes vote down vote up
def test_cli_dataset_put_feature_inline():
    dataset = "dataset-2"
    id = "abc"

    feature = """
        {{
          "type":"Feature",
          "id":"{0}",
          "properties":{{}},
          "geometry":{{"type":"Point","coordinates":[0,0]}}
        }}""".format(id)

    feature = "".join(feature.split())

    responses.add(
        responses.PUT,
        'https://api.mapbox.com/datasets/v1/{0}/{1}/features/{2}?access_token={3}'.format(username, dataset, id, access_token),
        match_querystring=True,
        status=200, body=feature,
        content_type='application/json'
    )

    runner = CliRunner()
    result = runner.invoke(
        main_group,
        ['--access-token', access_token,
         'datasets',
         'put-feature', dataset, id, feature])

    assert result.exit_code == 0
    assert result.output.strip() == feature.strip()