Python源码示例:responses.PUT

示例1
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 
示例2
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"} 
示例3
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"] 
示例4
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"] 
示例5
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"] 
示例6
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"] 
示例7
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 
示例8
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"}} 
示例9
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' 
示例10
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 
示例11
def test_relabel_node_403_status(patch1, patch2):
    """
    Test relabel node with 403 resp status
    """
    responses.add(
        responses.PUT,
        'http://promhost:80/api/v1.0/node-labels/n1',
        body='{"key1":"label1"}',
        status=403)

    prom_client = PromenadeClient()

    with pytest.raises(errors.ClientForbiddenError):
        prom_client.relabel_node('n1', {"key1": "label1"}) 
示例12
def test_relabel_node_401_status(patch1, patch2):
    """
    Test relabel node with 401 resp status
    """
    responses.add(
        responses.PUT,
        'http://promhost:80/api/v1.0/node-labels/n1',
        body='{"key1":"label1"}',
        status=401)

    prom_client = PromenadeClient()

    with pytest.raises(errors.ClientUnauthorizedError):
        prom_client.relabel_node('n1', {"key1": "label1"}) 
示例13
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() 
示例14
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() 
示例15
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() 
示例16
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) 
示例17
def __init__(self, registry):
        self.hostname = registry_hostname(registry)
        self.repos = {}
        self._add_pattern(responses.PUT, r'/v2/(.*)/manifests/([^/]+)',
                          self._put_manifest) 
示例18
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
        ) 
示例19
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 
示例20
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 
示例21
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 
示例22
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) 
示例23
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 
示例24
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 
示例25
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 
示例26
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 
示例27
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 
示例28
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 
示例29
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) 
示例30
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)