當前位置: 首頁>>代碼示例>>Python>>正文


Python requests_mock.Adapter方法代碼示例

本文整理匯總了Python中requests_mock.Adapter方法的典型用法代碼示例。如果您正苦於以下問題:Python requests_mock.Adapter方法的具體用法?Python requests_mock.Adapter怎麽用?Python requests_mock.Adapter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在requests_mock的用法示例。


在下文中一共展示了requests_mock.Adapter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: prepare_test_env

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def prepare_test_env(self):
        if is_test_env is True:
            adapter = requests_mock.Adapter()

            imported_scenarios = __import__('tests._requests_scenarios.{}'.format(os.environ['VX_TEST_SCENARIO']), fromlist=[None])

            for scenario in imported_scenarios.scenarios:
                scenario['url'] = '{}/api/v2{}'.format(self.config['server'], scenario['url'])
                if 'headers' in scenario:
                    if 'api-limits' in scenario['headers']:
                        scenario['headers']['api-limits'] = json.dumps(scenario['headers']['api-limits'])

                    if 'submission-limits' in scenario['headers']:
                        scenario['headers']['submission-limits'] = json.dumps(scenario['headers']['submission-limits'])

                adapter.register_uri(**scenario)

            self.request_session.mount('mock', adapter) 
開發者ID:PayloadSecurity,項目名稱:VxAPI,代碼行數:20,代碼來源:vxapi.py

示例2: test_client_do_basic

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_client_do_basic():
    c = Client()
    c.set_base_url('mock://test/')

    adapter = requests_mock.Adapter()
    c.session.mount('mock', adapter)

    adapter.register_uri('GET', 'mock://test/', text='ok')
    with pytest.raises(Exception):
        res = c.do('GET', '/')

    adapter.register_uri('GET', 'mock://test/', text='{"key":"value"}')
    res = c.do('GET', '/')
    assert res['key'] == 'value'

    adapter.register_uri('GET', 'mock://test/', text='{}', status_code=400)
    res = c.do('GET', '/')  # no exception, because no error present

    adapter.register_uri('GET', 'mock://test/',
                         text='{"error_code":"code","error":"message"}',
                         status_code=400)
    with pytest.raises(APIError) as e:
        res = c.do('GET', '/')
    assert e.value.code == 'code'
    assert e.value.message == 'message' 
開發者ID:luno,項目名稱:luno-python,代碼行數:27,代碼來源:test_client.py

示例3: test_cancel_ordered_certificate

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_cancel_ordered_certificate(mock_pending_cert):
    import requests_mock
    from lemur.plugins.lemur_digicert.plugin import DigiCertIssuerPlugin

    mock_pending_cert.external_id = 1234
    subject = DigiCertIssuerPlugin()
    adapter = requests_mock.Adapter()
    adapter.register_uri(
        "PUT",
        "mock://www.digicert.com/services/v2/order/certificate/1234/status",
        status_code=204,
    )
    adapter.register_uri(
        "PUT",
        "mock://www.digicert.com/services/v2/order/certificate/111/status",
        status_code=404,
    )
    subject.session.mount("mock", adapter)
    data = {"note": "Test"}
    subject.cancel_ordered_certificate(mock_pending_cert, **data)

    # A non-existing order id, does not raise exception because if it doesn't exist, then it doesn't matter
    mock_pending_cert.external_id = 111
    subject.cancel_ordered_certificate(mock_pending_cert, **data) 
開發者ID:Netflix,項目名稱:lemur,代碼行數:26,代碼來源:test_digicert.py

示例4: __init__

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def __init__(self, org_name=None, email=None):
        self.email = email or "api@example.com"
        self.org_name = org_name or "Test Org"
        LOG.info("Initialize ResilientMock %s %s", self.email, self.org_name)

        self.adapter = requests_mock.Adapter()
        for endpoint, handler in self.registered_endpoints.items():
            # Register with regex since some endpoints embed the org_id in the path
            LOG.info("Registering %s %s to %s", endpoint.type,
                     endpoint.uri, str(handler))
            self.adapter.add_matcher(lambda request,
                                     method=endpoint.type,
                                     callback=handler,
                                     uri=endpoint.uri: self._custom_matcher(method,
                                                                   uri,
                                                                   lambda request: callback(self, request),
                                                                   request)) 
開發者ID:ibmresilient,項目名稱:resilient-python-api,代碼行數:19,代碼來源:resilient_rest_mock.py

示例5: test_invalid_protocol

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_invalid_protocol():
    device_name = "test_device"
    mock_url = "not-http-or-tcp://mock-qpu-compiler"

    config = PyquilConfig(TEST_CONFIG_PATHS)
    session = get_session(config=config)
    mock_adapter = requests_mock.Adapter()
    session.mount("", mock_adapter)
    device = Device(
        name="not_actually_device_name", raw={"device_name": device_name, "isa": DUMMY_ISA_DICT}
    )

    with pytest.raises(UserMessageError):
        QPUCompiler(
            quilc_endpoint=session.config.quilc_url,
            qpu_compiler_endpoint=mock_url,
            device=device,
            session=session,
        ) 
開發者ID:rigetti,項目名稱:pyquil,代碼行數:21,代碼來源:test_compiler.py

示例6: test_forest_session_request_authenticated_with_user_token

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_forest_session_request_authenticated_with_user_token():
    config = PyquilConfig(TEST_CONFIG_PATHS)
    config.config_parsers["QCS_CONFIG"].set(
        "Rigetti Forest", "qmi_auth_token_path", api_fixture_path("qmi_auth_token_invalid.json")
    )
    config.config_parsers["QCS_CONFIG"].set(
        "Rigetti Forest", "user_auth_token_path", api_fixture_path("user_auth_token_valid.json")
    )
    config.config_parsers["QCS_CONFIG"].set("Rigetti Forest", "url", "mock://forest")
    config._parse_auth_tokens()

    session = ForestSession(config=config)
    mock_adapter = requests_mock.Adapter()
    session.mount("mock", mock_adapter)

    url = "%s/devices" % config.forest_url
    headers = {
        # access token from ./data/user_auth_token_valid.json.
        "Authorization": "Bearer secret"
    }
    mock_adapter.register_uri("GET", url, status_code=200, json=[{"id": 0}], headers=headers)

    devices = session.get(url).json()
    assert len(devices) == 1
    assert devices[0]["id"] == 0 
開發者ID:rigetti,項目名稱:pyquil,代碼行數:27,代碼來源:test_base_connection.py

示例7: test_forest_session_request_authenticated_with_qmi_auth

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_forest_session_request_authenticated_with_qmi_auth():
    config = PyquilConfig(TEST_CONFIG_PATHS)
    config.config_parsers["QCS_CONFIG"].set(
        "Rigetti Forest", "qmi_auth_token_path", api_fixture_path("qmi_auth_token_valid.json")
    )
    config.config_parsers["QCS_CONFIG"].set(
        "Rigetti Forest", "user_auth_token_path", api_fixture_path("user_auth_token_invalid.json")
    )
    config.config_parsers["QCS_CONFIG"].set("Rigetti Forest", "url", "mock://forest")
    config._parse_auth_tokens()

    session = ForestSession(config=config)
    mock_adapter = requests_mock.Adapter()
    session.mount("mock", mock_adapter)

    url = "%s/devices" % config.forest_url
    headers = {
        # access token from ./data/qmi_auth_token_valid.json.
        "X-QMI-AUTH-TOKEN": "secret"
    }
    mock_adapter.register_uri("GET", url, status_code=200, json=[{"id": 0}], headers=headers)

    devices = session.get(url).json()
    assert len(devices) == 1
    assert devices[0]["id"] == 0 
開發者ID:rigetti,項目名稱:pyquil,代碼行數:27,代碼來源:test_base_connection.py

示例8: sm_adap

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def sm_adap(monkeypatch):
    from pyrh.models import SessionManager

    sample_user = {
        "username": "user@example.com",
        "password": "some password",
    }

    monkeypatch.setattr("pyrh.urls.OAUTH", MOCK_URL)
    monkeypatch.setattr("pyrh.urls.OAUTH_REVOKE", MOCK_URL)
    monkeypatch.setattr("pyrh.urls.build_challenge", lambda x: MOCK_URL)

    session_manager = SessionManager(**sample_user)
    adapter = requests_mock.Adapter()
    session_manager.session.mount("mock", adapter)

    return session_manager, adapter 
開發者ID:robinhood-unofficial,項目名稱:pyrh,代碼行數:19,代碼來源:test_sessionmanager.py

示例9: test_post

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_post(mock_login, sm):
    import json

    from requests.exceptions import HTTPError

    adapter = requests_mock.Adapter()
    sm.session.mount("mock", adapter)
    mock_url = "mock://test.com"
    expected = [
        {"text": '{"error": "login error"}', "status_code": 401},
        {"text": '{"test": "321"}', "status_code": 200},
        {"text": '{"error": "resource not found"}', "status_code": 404},
    ]
    adapter.register_uri("POST", mock_url, expected)

    resp1 = sm.post(mock_url)

    with pytest.raises(HTTPError) as e:
        sm.post(mock_url)

    assert resp1 == json.loads(expected[1]["text"])
    assert mock_login.call_count == 1
    assert "404 Client Error" in str(e.value) 
開發者ID:robinhood-unofficial,項目名稱:pyrh,代碼行數:25,代碼來源:test_sessionmanager.py

示例10: test_get_all

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_get_all():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter)

    setup_mock(adapter, "GET", "bike_counts_page_1.json", 200, query="$offset=0")
    setup_mock(adapter, "GET", "bike_counts_page_2.json", 200, query="$offset=1000")
    response = client.get_all(DATASET_IDENTIFIER)

    assert inspect.isgenerator(response)
    data = list(response)
    assert len(data) == 1001
    assert data[0]["date"] == "2016-09-21T15:45:00.000"
    assert data[-1]["date"] == "2016-10-02T01:45:00.000"

    client.close() 
開發者ID:xmunoz,項目名稱:sodapy,代碼行數:20,代碼來源:test_socrata.py

示例11: test_get_unicode

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_get_unicode():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter)

    response_data = "get_songs_unicode.txt"
    setup_mock(adapter, "GET", response_data, 200)

    response = client.get(DATASET_IDENTIFIER)

    assert isinstance(response, list)
    assert len(response) == 10

    client.close() 
開發者ID:xmunoz,項目名稱:sodapy,代碼行數:18,代碼來源:test_socrata.py

示例12: test_get_metadata_and_attachments

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_get_metadata_and_attachments():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter)

    response_data = "get_song_metadata.txt"
    setup_old_api_mock(adapter, "GET", response_data, 200)
    response = client.get_metadata(DATASET_IDENTIFIER)

    assert isinstance(response, dict)
    assert "newBackend" in response
    assert "attachments" in response["metadata"]

    response = client.download_attachments(DATASET_IDENTIFIER)

    assert isinstance(response, list)
    assert len(response) == 0

    client.close() 
開發者ID:xmunoz,項目名稱:sodapy,代碼行數:23,代碼來源:test_socrata.py

示例13: test_upsert_exception

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_upsert_exception():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter)

    response_data = "403_response_json.txt"
    setup_mock(adapter, "POST", response_data, 403, reason="Forbidden")

    data = [
        {
            "theme": "Surfing",
            "artist": "Wavves",
            "title": "King of the Beach",
            "year": "2010",
        }
    ]
    try:
        client.upsert(DATASET_IDENTIFIER, data)
    except Exception as e:
        assert isinstance(e, requests.exceptions.HTTPError)
    else:
        raise AssertionError("No exception raised for bad request.") 
開發者ID:xmunoz,項目名稱:sodapy,代碼行數:26,代碼來源:test_socrata.py

示例14: test_delete

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_delete():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(
        DOMAIN,
        APPTOKEN,
        username=USERNAME,
        password=PASSWORD,
        session_adapter=mock_adapter,
    )

    uri = "{}{}{}/{}.json".format(PREFIX, DOMAIN, OLD_API_PATH, DATASET_IDENTIFIER)
    adapter.register_uri("DELETE", uri, status_code=200)
    response = client.delete(DATASET_IDENTIFIER)
    assert response.status_code == 200

    try:
        client.delete("foobar")
    except Exception as e:
        assert isinstance(e, requests_mock.exceptions.NoMockAddress)
    finally:
        client.close() 
開發者ID:xmunoz,項目名稱:sodapy,代碼行數:26,代碼來源:test_socrata.py

示例15: test_publish

# 需要導入模塊: import requests_mock [as 別名]
# 或者: from requests_mock import Adapter [as 別名]
def test_publish():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(
        DOMAIN,
        APPTOKEN,
        username=USERNAME,
        password=PASSWORD,
        session_adapter=mock_adapter,
    )

    response_data = "create_foobar.txt"
    setup_publish_mock(adapter, "POST", response_data, 200)

    response = client.publish(DATASET_IDENTIFIER)
    assert isinstance(response, dict)
    assert len(response.get("id")) == 9
    client.close() 
開發者ID:xmunoz,項目名稱:sodapy,代碼行數:22,代碼來源:test_socrata.py


注:本文中的requests_mock.Adapter方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。