Ejemplo n.º 1
0
def test_none_on_code_and_message_1(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=403, data=b"message")

    res = fake_request_with_none_on_code_and_message()

    assert httpx_mock.get_requests()
    assert res is None
Ejemplo n.º 2
0
def test_headers_matching(httpx_mock: HTTPXMock):
    httpx_mock.add_response(
        match_headers={"user-agent": f"python-httpx/{httpx.__version__}"})

    with httpx.Client() as client:
        response = client.get("http://test_url")
        assert response.content == b""
def test_oauth2_password_credentials_flow_token_is_expired_after_30_seconds_by_default(
        token_cache, httpx_mock: HTTPXMock):
    auth = httpx_auth.OAuth2ResourceOwnerPasswordCredentials(
        "http://provide_access_token",
        username="******",
        password="******")
    # Add a token that expires in 29 seconds, so should be considered as expired when issuing the request
    token_cache._add_token(
        key=
        "db2be9203dd2718c7285319dde1270056808482fbf7fffa6a9362d092d1cf799b393dd15140ea13e4d76d1603e56390a6222ff7063736a1b686d317706b2c001",
        token="2YotnFZFEjr1zCsicMWpAA",
        expiry=httpx_auth.oauth2_tokens._to_expiry(expires_in=29),
    )
    # Meaning a new one will be requested
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={
            "access_token": "2YotnFZFEjr1zCsicMWpAA",
            "token_type": "example",
            "expires_in": 3600,
            "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
            "example_parameter": "example_value",
        },
        match_content=
        b"grant_type=password&username=test_user&password=test_pwd",
    )
    assert (get_header(
        httpx_mock,
        auth).get("Authorization") == "Bearer 2YotnFZFEjr1zCsicMWpAA")
def test_oauth2_client_credentials_flow_token_is_expired_after_30_seconds_by_default(
        token_cache, httpx_mock: HTTPXMock):
    auth = httpx_auth.OAuth2ClientCredentials("http://provide_access_token",
                                              client_id="test_user",
                                              client_secret="test_pwd")
    # Add a token that expires in 29 seconds, so should be considered as expired when issuing the request
    token_cache._add_token(
        key=
        "a8a1c17ded24b3710524306819084310b08f97e151c79f4f1979202c541f3e8506c93176f7ee816bfcd2b2f6de9c5c3e16aaff220f1ad8f08d31ee086e8618da",
        token="2YotnFZFEjr1zCsicMWpAA",
        expiry=httpx_auth.oauth2_tokens._to_expiry(expires_in=29),
    )
    # Meaning a new one will be requested
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={
            "access_token": "2YotnFZFEjr1zCsicMWpAA",
            "token_type": "example",
            "expires_in": 3600,
            "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
            "example_parameter": "example_value",
        },
    )
    assert (get_header(
        httpx_mock,
        auth).get("Authorization") == "Bearer 2YotnFZFEjr1zCsicMWpAA")
Ejemplo n.º 5
0
def test_header_as_httpx_headers(httpx_mock: HTTPXMock):
    httpx_mock.add_response(headers=httpx.Headers({"set-cookie": "key=value"}))

    with httpx.Client() as client:
        response = client.get("http://test_url")

    assert dict(response.cookies) == {"key": "value"}
Ejemplo n.º 6
0
async def test_find_by_id_not_found(httpx_mock: HTTPXMock):
    expected = []
    httpx_mock.add_response(method="POST",
                            url=f"{SuggestClient.BASE_URL}findById/party",
                            json={"suggestions": expected})
    actual = await dadata.find_by_id(name="party", query="1234567890")
    assert actual == expected
Ejemplo n.º 7
0
async def test_clean(httpx_mock: HTTPXMock):
    expected = {"source": "Сережа", "result": "Сергей", "qc": 1}
    httpx_mock.add_response(method="POST",
                            url=f"{CleanClient.BASE_URL}clean/name",
                            json=[expected])
    actual = await dadata.clean(name="name", source="Сережа")
    assert actual == expected
Ejemplo n.º 8
0
def test_none_on_http_codes_2(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=401)

    with pytest.raises(httpx.HTTPStatusError):
        fake_request_with_400_decorator()

    assert httpx_mock.get_requests()
Ejemplo n.º 9
0
def test_none_on_404_1(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=404)

    res = fake_request_with_none_on_404_deco()

    assert httpx_mock.get_requests()
    assert res is None
Ejemplo n.º 10
0
def test_raise_known_save_errors_1(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=400, data=b"URL_ALREADY_EXISTS")

    with pytest.raises(UrlAlreadyExistsError):
        fake_request_with_raise_known_save_errors()

    assert httpx_mock.get_requests()
Ejemplo n.º 11
0
def test_raise_known_save_errors_2(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=400, data=b"Feeds are required")

    with pytest.raises(FeedsRequiredError):
        fake_request_with_raise_known_save_errors()

    assert httpx_mock.get_requests()
Ejemplo n.º 12
0
def test_none_on_400_ALREADY_ARCHIVED_2(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=401, data=b"ALREADY_ARCHIVED")

    with pytest.raises(httpx.HTTPStatusError):
        fake_request_with_none_on_400_ALREADY_ARCHIVED()

    assert httpx_mock.get_requests()
Ejemplo n.º 13
0
def test_none_on_400_ALREADY_ARCHIVED_1(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=400, data=b"ALREADY_ARCHIVED")

    res = fake_request_with_none_on_400_ALREADY_ARCHIVED()

    assert httpx_mock.get_requests()
    assert res is None
Ejemplo n.º 14
0
def test_none_on_code_and_message_3(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=403, data=b"pas le mot dedans")

    with pytest.raises(httpx.HTTPStatusError):
        fake_request_with_none_on_code_and_message()

    assert httpx_mock.get_requests()
def test_oauth2_authorization_code_flow_uses_provided_client(
        token_cache, httpx_mock: HTTPXMock, browser_mock: BrowserMock):
    client = httpx.Client(headers={"x-test": "Test value"})
    auth = httpx_auth.OAuth2AuthorizationCode("http://provide_code",
                                              "http://provide_access_token",
                                              client=client)
    tab = browser_mock.add_response(
        opened_url=
        "http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
        reply_url=
        "http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de",
    )
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={
            "access_token": "2YotnFZFEjr1zCsicMWpAA",
            "token_type": "example",
            "expires_in": 3600,
            "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
            "example_parameter": "example_value",
        },
        match_content=
        b"grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F&response_type=code&code=SplxlOBeZQQYbYS6WxSbIA",
        match_headers={"x-test": "Test value"},
    )
    httpx_mock.add_response(
        match_headers={"Authorization": "Bearer 2YotnFZFEjr1zCsicMWpAA"})
    # Send a request to this dummy URL with authentication
    httpx.get("http://authorized_only", auth=auth)
    tab.assert_success(
        "You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab."
    )
def test_empty_token_is_invalid(token_cache, httpx_mock: HTTPXMock,
                                browser_mock: BrowserMock):
    auth = httpx_auth.OAuth2AuthorizationCode("http://provide_code",
                                              "http://provide_access_token")
    tab = browser_mock.add_response(
        opened_url=
        "http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
        reply_url=
        "http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de",
    )
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={
            "access_token": "",
            "token_type": "example",
            "expires_in": 3600,
            "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
            "example_parameter": "example_value",
        },
    )
    with pytest.raises(httpx_auth.GrantNotProvided) as exception_info:
        httpx.get("http://authorized_only", auth=auth)
    assert (
        str(exception_info.value) ==
        "access_token not provided within {'access_token': '', 'token_type': 'example', 'expires_in': 3600, 'refresh_token': 'tGzv3JOkF0XG5Qx2TlKWIA', 'example_parameter': 'example_value'}."
    )
    tab.assert_success(
        "You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab."
    )
Ejemplo n.º 17
0
async def test_find_by_id(httpx_mock: HTTPXMock):
    expected = [{"value": "ООО МОТОРИКА", "data": {"inn": "7719402047"}}]
    httpx_mock.add_response(method="POST",
                            url=f"{SuggestClient.BASE_URL}findById/party",
                            json={"suggestions": expected})
    actual = await dadata.find_by_id(name="party", query="7719402047")
    assert actual == expected
def test_with_invalid_grant_request_invalid_request_error(
        token_cache, httpx_mock: HTTPXMock, browser_mock: BrowserMock):
    auth = httpx_auth.OAuth2AuthorizationCode("http://provide_code",
                                              "http://provide_access_token")
    tab = browser_mock.add_response(
        opened_url=
        "http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
        reply_url=
        "http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de",
    )
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={"error": "invalid_request"},
        status_code=400,
    )
    with pytest.raises(httpx_auth.InvalidGrantRequest) as exception_info:
        httpx.get("http://authorized_only", auth=auth)
    assert (
        str(exception_info.value) ==
        "invalid_request: The request is missing a required parameter, includes an "
        "unsupported parameter value (other than grant type), repeats a parameter, "
        "includes multiple credentials, utilizes more than one mechanism for "
        "authenticating the client, or is otherwise malformed.")
    tab.assert_success(
        "You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab."
    )
Ejemplo n.º 19
0
async def test_get_balance(httpx_mock: HTTPXMock):
    response = {"balance": 9922.30}
    httpx_mock.add_response(method="GET",
                            url=f"{ProfileClient.BASE_URL}profile/balance",
                            json=response)
    actual = await dadata.get_balance()
    assert actual == 9922.30
def test_with_invalid_grant_request_invalid_request_error_and_error_description_and_uri_and_other_fields(
        token_cache, httpx_mock: HTTPXMock, browser_mock: BrowserMock):
    auth = httpx_auth.OAuth2AuthorizationCode("http://provide_code",
                                              "http://provide_access_token")
    tab = browser_mock.add_response(
        opened_url=
        "http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
        reply_url=
        "http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de",
    )
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={
            "error": "invalid_request",
            "error_description": "desc of the error",
            "error_uri": "http://test_url",
            "other": "other info",
        },
        status_code=400,
    )
    with pytest.raises(httpx_auth.InvalidGrantRequest) as exception_info:
        httpx.get("http://authorized_only", auth=auth)
    assert (
        str(exception_info.value) ==
        "invalid_request: desc of the error\nMore information can be found on http://test_url\nAdditional information: {'other': 'other info'}"
    )
    tab.assert_success(
        "You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab."
    )
Ejemplo n.º 21
0
def test_browser_error(token_cache, httpx_mock: HTTPXMock, monkeypatch):
    import httpx_auth.oauth2_authentication_responses_server

    auth = httpx_auth.OAuth2Implicit("http://provide_token", timeout=0.1)

    class FakeBrowser:
        def open(self, url, new):
            import webbrowser

            raise webbrowser.Error("Failure")

    monkeypatch.setattr(
        httpx_auth.oauth2_authentication_responses_server.webbrowser,
        "get",
        lambda *args: FakeBrowser(),
    )

    httpx_mock.add_response(
        method="GET",
        url=
        "http://provide_token?response_type=token&state=42a85b271b7a652ca3cc4c398cfd3f01b9ad36bf9c945ba823b023e8f8b95c4638576a0e3dcc96838b838bec33ec6c0ee2609d62ed82480b3b8114ca494c0521&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
    )
    with pytest.raises(httpx_auth.TimeoutOccurred) as exception_info:
        httpx.get("http://authorized_only", auth=auth)
    assert (str(exception_info.value) ==
            "User authentication was not received within 0.1 seconds.")
def test_with_invalid_grant_request_invalid_client_error(
        token_cache, httpx_mock: HTTPXMock, browser_mock: BrowserMock):
    auth = httpx_auth.OAuth2AuthorizationCode("http://provide_code",
                                              "http://provide_access_token")
    tab = browser_mock.add_response(
        opened_url=
        "http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
        reply_url=
        "http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de",
    )
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={"error": "invalid_client"},
        status_code=400,
    )
    with pytest.raises(httpx_auth.InvalidGrantRequest) as exception_info:
        httpx.get("http://authorized_only", auth=auth)
    assert (
        str(exception_info.value) ==
        "invalid_client: Client authentication failed (e.g., unknown client, no "
        "client authentication included, or unsupported authentication method).  The "
        "authorization server MAY return an HTTP 401 (Unauthorized) status code to "
        "indicate which HTTP authentication schemes are supported.  If the client "
        'attempted to authenticate via the "Authorization" request header field, the '
        "authorization server MUST respond with an HTTP 401 (Unauthorized) status "
        'code and include the "WWW-Authenticate" response header field matching the '
        "authentication scheme used by the client.")
    tab.assert_success(
        "You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab."
    )
Ejemplo n.º 23
0
def test_get_forks(httpx_mock: HTTPXMock, fake_get_forks_response):
    api = API(username="******", token="definitelynotatoken")

    httpx_mock.add_response(url=api.url,
                            json=fake_get_forks_response,
                            status_code=200)

    data = api.get_forks()

    assert data == [
        {
            "name": "nox",
            "diskUsage": 5125,
            "createdAt": "2021-07-01T11:43:36Z",
            "pushedAt": "2022-01-08T11:00:44Z",
            "parent": {
                "nameWithOwner": "theacodes/nox"
            },
        },
        {
            "name": "python-launcher",
            "diskUsage": 824,
            "createdAt": "2021-10-25T18:33:11Z",
            "pushedAt": "2021-11-09T07:47:23Z",
            "parent": {
                "nameWithOwner": "brettcannon/python-launcher"
            },
        },
    ]
def test_with_invalid_grant_request_invalid_grant_error(
        token_cache, httpx_mock: HTTPXMock, browser_mock: BrowserMock):
    auth = httpx_auth.OAuth2AuthorizationCode("http://provide_code",
                                              "http://provide_access_token")
    tab = browser_mock.add_response(
        opened_url=
        "http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
        reply_url=
        "http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de",
    )
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={"error": "invalid_grant"},
        status_code=400,
    )
    with pytest.raises(httpx_auth.InvalidGrantRequest) as exception_info:
        httpx.get("http://authorized_only", auth=auth)
    assert (
        str(exception_info.value) ==
        "invalid_grant: The provided authorization grant (e.g., authorization code, "
        "resource owner credentials) or refresh token is invalid, expired, revoked, "
        "does not match the redirection URI used in the authorization request, or was "
        "issued to another client.")
    tab.assert_success(
        "You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab."
    )
Ejemplo n.º 25
0
def test_multipart_body(httpx_mock: HTTPXMock):
    httpx_mock.add_response(
        url="http://test_url",
        files={"file1": "content of file 1"},
        boundary=b"2256d3a36d2a61a1eba35a22bee5c74a",
    )
    httpx_mock.add_response(
        url="http://test_url",
        data={"key1": "value1"},
        files={"file1": "content of file 1"},
        boundary=b"2256d3a36d2a61a1eba35a22bee5c74a",
    )

    with httpx.Client() as client:
        response = client.get("http://test_url")
        assert (
            response.text ==
            '--2256d3a36d2a61a1eba35a22bee5c74a\r\nContent-Disposition: form-data; name="file1"; filename="upload"\r\nContent-Type: application/octet-stream\r\n\r\ncontent of file 1\r\n--2256d3a36d2a61a1eba35a22bee5c74a--\r\n'
        )

        response = client.get("http://test_url")
        assert (response.text == """--2256d3a36d2a61a1eba35a22bee5c74a\r
Content-Disposition: form-data; name="key1"\r
\r
value1\r
--2256d3a36d2a61a1eba35a22bee5c74a\r
Content-Disposition: form-data; name="file1"; filename="upload"\r
Content-Type: application/octet-stream\r
\r
content of file 1\r
--2256d3a36d2a61a1eba35a22bee5c74a--\r
""")
def test_with_invalid_grant_request_invalid_scope_error(
        token_cache, httpx_mock: HTTPXMock, browser_mock: BrowserMock):
    auth = httpx_auth.OAuth2AuthorizationCode("http://provide_code",
                                              "http://provide_access_token")
    tab = browser_mock.add_response(
        opened_url=
        "http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
        reply_url=
        "http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de",
    )
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={"error": "invalid_scope"},
        status_code=400,
    )
    with pytest.raises(httpx_auth.InvalidGrantRequest) as exception_info:
        httpx.get("http://authorized_only", auth=auth)
    assert (
        str(exception_info.value) ==
        "invalid_scope: The requested scope is invalid, unknown, malformed, or "
        "exceeds the scope granted by the resource owner.")
    tab.assert_success(
        "You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab."
    )
Ejemplo n.º 27
0
def get_header(httpx_mock: HTTPXMock, auth: httpx.Auth) -> dict:
    # Mock a dummy response
    httpx_mock.add_response()
    # Send a request to this dummy URL with authentication
    response = httpx.get("http://authorized_only", auth=auth)
    # Return headers received on this dummy URL
    return response.request.headers
def test_response_type_can_be_provided_in_url(token_cache,
                                              httpx_mock: HTTPXMock,
                                              browser_mock: BrowserMock):
    auth = httpx_auth.OAuth2AuthorizationCode(
        "http://provide_code?response_type=my_code",
        "http://provide_access_token",
        response_type="not_used",
    )
    tab = browser_mock.add_response(
        opened_url=
        "http://provide_code?response_type=my_code&state=49b67a19e70f692c3fc09dd124e5782b41a86f4f4931e1cc938ccbb466eecf1b730edb9eb01e42005de77ce3dd5a016418f8e780f30c4477d71102fe03e39e62&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
        reply_url=
        "http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=49b67a19e70f692c3fc09dd124e5782b41a86f4f4931e1cc938ccbb466eecf1b730edb9eb01e42005de77ce3dd5a016418f8e780f30c4477d71102fe03e39e62",
    )
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={
            "access_token": "2YotnFZFEjr1zCsicMWpAA",
            "token_type": "example",
            "expires_in": 3600,
            "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
            "example_parameter": "example_value",
        },
        match_content=
        b"grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F&code=SplxlOBeZQQYbYS6WxSbIA",
    )
    # Mock a dummy response
    httpx_mock.add_response(
        match_headers={"Authorization": "Bearer 2YotnFZFEjr1zCsicMWpAA"})
    # Send a request to this dummy URL with authentication
    httpx.get("http://authorized_only", auth=auth)
    tab.assert_success(
        "You are now authenticated on 49b67a19e70f692c3fc09dd124e5782b41a86f4f4931e1cc938ccbb466eecf1b730edb9eb01e42005de77ce3dd5a016418f8e780f30c4477d71102fe03e39e62. You may close this tab."
    )
def test_oauth2_password_credentials_flow_uses_provided_client(
        token_cache, httpx_mock: HTTPXMock):
    client = httpx.Client(headers={"x-test": "Test value"})
    auth = httpx_auth.OAuth2ResourceOwnerPasswordCredentials(
        "http://provide_access_token",
        username="******",
        password="******",
        client=client,
    )
    httpx_mock.add_response(
        method="POST",
        url="http://provide_access_token",
        json={
            "access_token": "2YotnFZFEjr1zCsicMWpAA",
            "token_type": "example",
            "expires_in": 3600,
            "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
            "example_parameter": "example_value",
        },
        match_content=
        b"grant_type=password&username=test_user&password=test_pwd",
        match_headers={"x-test": "Test value"},
    )
    assert (get_header(
        httpx_mock,
        auth).get("Authorization") == "Bearer 2YotnFZFEjr1zCsicMWpAA")
Ejemplo n.º 30
0
async def test_neo4j_http_driver_run_cypher_fail(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="http://localhost:7474",
                            method="GET",
                            status_code=200)
    driver = Neo4jHTTPDriver(host='localhost',
                             port='7474',
                             auth=('neo4j', 'somepass'))
    test_response = {"errors": "some_error"}
    query = "some test cypher"

    httpx_mock.add_response(url=driver._full_transaction_path,
                            method='POST',
                            json=test_response,
                            match_content=json.dumps({
                                "statements": [{
                                    "statement": f"{query}"
                                }]
                            }).encode('utf-8'),
                            status_code=500)
    try:
        response = await driver.run(query)
    except:
        assert True
    response = await driver.run(query, return_errors=True)
    assert response == test_response
    # test sync runner
    try:
        response = driver.run_sync(query)
    except:
        assert True