Exemplo n.º 1
0
def test_method_and_url_matching_and_headers_and_content_not_matching(
    httpx_mock: HTTPXMock,
):
    httpx_mock.add_response(
        url="http://test_url",
        method="POST",
        match_headers={
            "user-agent": f"python-httpx/{httpx.__version__}",
            "host": "test_url2",
        },
        match_content=b"This is the body2",
    )

    with httpx.Client() as client:
        with pytest.raises(httpx.TimeoutException) as exception_info:
            client.post("http://test_url", data=b"This is the body")
        assert (
            str(exception_info.value)
            == f"""No response can be found for POST request on http://test_url with {{'host': 'test_url', 'user-agent': 'python-httpx/{httpx.__version__}'}} headers and b'This is the body' body amongst:
Match POST requests on http://test_url with {{'user-agent': 'python-httpx/{httpx.__version__}', 'host': 'test_url2'}} headers and b'This is the body2' body"""
        )

    # Clean up responses to avoid assertion failure
    httpx_mock.reset(assert_all_responses_were_requested=False)
Exemplo n.º 2
0
def test_requests_json_body(httpx_mock: HTTPXMock):
    httpx_mock.add_response(
        url="http://test_url", method="GET", json=["list content 1", "list content 2"]
    )
    httpx_mock.add_response(
        url="http://test_url",
        method="POST",
        json={"key 1": "value 1", "key 2": "value 2"},
    )
    httpx_mock.add_response(url="http://test_url", method="PUT", json="string value")

    with httpx.Client() as client:
        response = client.post("http://test_url")
        assert response.json() == {"key 1": "value 1", "key 2": "value 2"}

        response = client.get("http://test_url")
        assert response.json() == ["list content 1", "list content 2"]

        response = client.put("http://test_url")
        assert response.json() == "string value"
Exemplo n.º 3
0
def add_response_file(httpx_mock: HTTPXMock, jsonfile_path: str):
    testdata = json.loads(_open_file(jsonfile_path))
    httpx_mock.add_response(json=testdata)
Exemplo n.º 4
0
def test_request_refund_ok_response(client: Client, httpx_mock: HTTPXMock):
    url = client.context + REFUND_PATH
    httpx_mock.add_response(url=url, method="POST", status_code=httpx.codes.OK)
    result = client.request_refund(trans_ref=get_random_string(),
                                   phone="22991617451")
    assert result.state == OPERATION_CONFIRMED
Exemplo n.º 5
0
def test_content_matching(httpx_mock: HTTPXMock):
    httpx_mock.add_response(match_content=b"This is the body")

    with httpx.Client() as client:
        response = client.post("http://test_url", content=b"This is the body")
        assert response.read() == b""
Exemplo n.º 6
0
def test_with_many_responses_urls_instances(httpx_mock: HTTPXMock):
    httpx_mock.add_response(
        url=httpx.URL("http://test_url", params={"param1": "test"}),
        method="GET",
        data=b"test content 1",
    )
    httpx_mock.add_response(
        url=httpx.URL("http://test_url", params={"param2": "test"}),
        method="POST",
        data=b"test content 2",
    )
    httpx_mock.add_response(
        url=httpx.URL("http://test_url", params={"param3": "test"}),
        method="PUT",
        data=b"test content 3",
    )
    httpx_mock.add_response(
        url=httpx.URL("http://test_url", params={"param4": "test"}),
        method="DELETE",
        data=b"test content 4",
    )
    httpx_mock.add_response(
        url=httpx.URL("http://test_url", params={"param5": "test"}),
        method="PATCH",
        data=b"test content 5",
    )
    httpx_mock.add_response(
        url=httpx.URL("http://test_url", params={"param6": "test"}),
        method="HEAD",
        data=b"test content 6",
    )

    with httpx.Client() as client:
        response = client.post("http://test_url?param2=test")
        assert response.content == b"test content 2"

        response = client.get("http://test_url?param1=test")
        assert response.content == b"test content 1"

        response = client.put("http://test_url?param3=test")
        assert response.content == b"test content 3"

        response = client.head("http://test_url?param6=test")
        assert response.content == b"test content 6"

        response = client.patch("http://test_url?param5=test")
        assert response.content == b"test content 5"

        response = client.delete("http://test_url?param4=test")
        assert response.content == b"test content 4"
Exemplo n.º 7
0
def test_with_many_responses_methods(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="http://test_url",
                            method="GET",
                            data=b"test content 1")
    httpx_mock.add_response(url="http://test_url",
                            method="POST",
                            data=b"test content 2")
    httpx_mock.add_response(url="http://test_url",
                            method="PUT",
                            data=b"test content 3")
    httpx_mock.add_response(url="http://test_url",
                            method="DELETE",
                            data=b"test content 4")
    httpx_mock.add_response(url="http://test_url",
                            method="PATCH",
                            data=b"test content 5")
    httpx_mock.add_response(url="http://test_url",
                            method="HEAD",
                            data=b"test content 6")

    with httpx.Client() as client:
        response = client.post("http://test_url")
        assert response.content == b"test content 2"

        response = client.get("http://test_url")
        assert response.content == b"test content 1"

        response = client.put("http://test_url")
        assert response.content == b"test content 3"

        response = client.head("http://test_url")
        assert response.content == b"test content 6"

        response = client.patch("http://test_url")
        assert response.content == b"test content 5"

        response = client.delete("http://test_url")
        assert response.content == b"test content 4"
Exemplo n.º 8
0
def test_response_with_string_body(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="http://test_url", data="test content")

    with httpx.Client() as client:
        response = client.get("http://test_url")
        assert response.content == b"test content"
Exemplo n.º 9
0
async def test_request_failed(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=504)
    with pytest.raises(httpx.HTTPError):
        await dadata.clean(name="name", source="Сережа")
Exemplo n.º 10
0
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 = dadata.clean(name="name", source="Сережа")
    assert actual == expected
Exemplo n.º 11
0
def httpx_session(httpx_mock: HTTPXMock):

    # Override reset since we don't care if not all mocked routes are called
    def reset_override(*args):
        pass

    httpx_mock.reset = reset_override

    # Load a minimal channel response to mock a Mirth server
    responses_path = Path(__file__).resolve().parent.joinpath("responses")
    with open(responses_path.joinpath("channels.xml"), "r") as f:
        channels_response: str = f.read()
    with open(responses_path.joinpath("channelStatistics.xml"), "r") as f:
        channel_statistics_response: str = f.read()
    with open(responses_path.joinpath("channelGroups.xml"), "r") as f:
        channel_groups_response: str = f.read()
    with open(responses_path.joinpath("messageResponse.xml"), "r") as f:
        message_999_response: str = f.read()

    httpx_mock.add_response(url=re.compile(r"mock:\/\/mirth.url\/channels"),
                            data=channels_response)
    httpx_mock.add_response(
        url=re.compile(r"mock:\/\/mirth.url\/channels\/statistics"),
        data=channel_statistics_response,
    )
    httpx_mock.add_response(
        url=re.compile(r"mock:\/\/mirth.url\/channelgroups"),
        data=channel_groups_response,
    )

    httpx_mock.add_response(
        method="POST",
        data="<long>999</long>",
        url=re.compile(r"mock:\/\/mirth.url\/channels\/.*\/messages"),
    )

    httpx_mock.add_response(
        method="GET",
        data=message_999_response,
        url=re.compile(r"mock:\/\/mirth.url\/channels\/.*\/messages\/999"),
    )

    httpx_mock.add_response(
        status_code=204,
        url=re.compile(r"mock:\/\/mirth.url\/channels\/.*\/messages"))
Exemplo n.º 12
0
 def test_pair_device(self, plcnet_api: PlcNetApi, httpx_mock: HTTPXMock):
     """Test pairing a device synchronously."""
     pair_device = PairDeviceStart()
     httpx_mock.add_response(content=pair_device.SerializeToString())
     assert plcnet_api.pair_device()
Exemplo n.º 13
0
 def test_identify_device_stop(self, plcnet_api: PlcNetApi,
                               httpx_mock: HTTPXMock):
     """Test stopping identifying a device synchronously."""
     identify_device = IdentifyDeviceResponse()
     httpx_mock.add_response(content=identify_device.SerializeToString())
     assert plcnet_api.identify_device_stop()
Exemplo n.º 14
0
def test_none_on_http_codes_1(httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=400)
    res = fake_request_with_400_decorator()

    assert httpx_mock.get_requests()
    assert res is None
Exemplo n.º 15
0
async def test_discovery_collecting(httpx_mock: HTTPXMock):
    httpx_mock.add_response(
        url='https://dev.url/api/v1/health/prometheus/service_discovery/',
        json=[{
            'targets': ['dev.fashion:80'],
            'labels': {
                '__metrics_path__': '/api/v1/health/prometheus/',
                'service': 'django',
            }
        }],
    )
    httpx_mock.add_response(
        url='https://prod.url/api/v1/health/prometheus/service_discovery/',
        json=[{
            'targets': ['prod.fashion:80'],
            'labels': {
                '__metrics_path__': '/api/v1/health/prometheus/',
                'service': 'django',
            }
        }],
    )
    httpx_mock.add_response(
        url='https://without.label/api/v1/health/prometheus/service_discovery/',
        json=[{
            'targets': ['without.fashion:80'],
            'labels': {
                '__metrics_path__': '/api/v1/health/prometheus/',
                'service': 'django',
            }
        }],
    )

    await discovery_collecting()

    dev_disc = json.load(
        open(
            'results/https_dev_url_api_v1_health_prometheus_service_discovery.json'
        ))
    prod_disc = json.load(
        open(
            'results/https_prod_url_api_v1_health_prometheus_service_discovery.json'
        ))
    wl_disc = json.load(
        open(
            'results/https_without_label_api_v1_health_prometheus_service_discovery.json'
        ))

    assert len(dev_disc) == 1
    assert len(prod_disc) == 1
    assert len(wl_disc) == 1
    assert dev_disc[0]['labels'] == {
        '__metrics_path__': '/api/v1/health/prometheus/',
        'service': 'django',
        'group': 'dev',
        'some_label': 'some_value',
    }
    assert prod_disc[0]['labels'] == {
        '__metrics_path__': '/api/v1/health/prometheus/',
        'service': 'django',
        'group': 'prod',
    }
    assert wl_disc[0]['labels'] == {
        '__metrics_path__': '/api/v1/health/prometheus/',
        'service': 'django',
    }
Exemplo n.º 16
0
def test_send_email_if_unavailable(httpx_mock: HTTPXMock):
    httpx_mock.add_response(data="품절".encode())
    with mock.patch("watchtower.smoketigers.main.mailer") as mock_mailer:
        main()
        mock_mailer.send_email.assert_not_called()
Exemplo n.º 17
0
def test_get_page_with_ok(tid, httpx_mock: HTTPXMock, leopold_in_stock):
    mock_page = leopold_in_stock.read()
    httpx_mock.add_response(data=mock_page)
    page = get_page(tid)
    assert page == mock_page
Exemplo n.º 18
0
def test_get_repos(httpx_mock: HTTPXMock, fake_get_repos_response):
    api = API(username="******", token="definitelynotatoken")

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

    data = api.get_repos()

    assert data == [
        {
            "name": "advent_of_code_2020",
            "description": "Retroactively doing AOC2020 in Go.",
            "createdAt": "2022-01-05T16:54:03Z",
            "pushedAt": "2022-01-09T06:55:32Z",
            "diskUsage": 45,
        },
        {
            "name": "advent_of_code_2021",
            "description": "My code for AOC 2021",
            "createdAt": "2021-11-30T12:01:22Z",
            "pushedAt": "2021-12-19T15:10:07Z",
            "diskUsage": 151,
        },
        {
            "name": "aircraft_crashes",
            "description": "Analysis of aircraft crash data.",
            "createdAt": "2021-01-02T19:34:15Z",
            "pushedAt": "2021-01-20T10:35:57Z",
            "diskUsage": 2062,
        },
        {
            "name": "cookie_pypackage",
            "description":
            "My own version of the Cookiecutter pypackage template",
            "createdAt": "2020-07-04T10:05:36Z",
            "pushedAt": "2021-12-03T08:45:49Z",
            "diskUsage": 734,
        },
        {
            "name": "cv",
            "description": "Repo for my CV, built with JSON Resume.",
            "createdAt": "2021-10-30T15:11:49Z",
            "pushedAt": "2022-01-10T19:50:24Z",
            "diskUsage": 145,
        },
        {
            "name": "eu_energy_analysis",
            "description": "Analysis of the EU Open Power System Data.",
            "createdAt": "2020-12-13T10:50:35Z",
            "pushedAt": "2020-12-24T11:12:34Z",
            "diskUsage": 1834,
        },
        {
            "name": "FollowTheProcess",
            "description": 'My "About Me" Repo',
            "createdAt": "2020-07-14T16:06:52Z",
            "pushedAt": "2022-01-10T20:05:47Z",
            "diskUsage": 14640,
        },
        {
            "name": "followtheprocess.github.io",
            "description": "Repo for my GitHub pages site.",
            "createdAt": "2021-02-19T20:16:05Z",
            "pushedAt": "2021-11-18T19:04:06Z",
            "diskUsage": 10753,
        },
    ]
Exemplo n.º 19
0
def test_get_page_with_bad_request(tid, httpx_mock: HTTPXMock):
    httpx_mock.add_response(status_code=BAD_REQUEST)
    with pytest.raises(HTTPStatusError):
        get_page(tid)
Exemplo n.º 20
0
def test_response_streaming(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="http://test_url", data=[b"part 1", b"part 2"])

    with httpx.Client() as client:
        with client.stream(method="GET", url="http://test_url") as response:
            assert list(response.iter_raw()) == [b"part 1", b"part 2"]
Exemplo n.º 21
0
def test_neo4j_http_driver_ping_success(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'))
Exemplo n.º 22
0
def test_with_many_responses_status_codes(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="http://test_url",
                            method="GET",
                            data=b"test content 1",
                            status_code=200)
    httpx_mock.add_response(url="http://test_url",
                            method="POST",
                            data=b"test content 2",
                            status_code=201)
    httpx_mock.add_response(url="http://test_url",
                            method="PUT",
                            data=b"test content 3",
                            status_code=202)
    httpx_mock.add_response(url="http://test_url",
                            method="DELETE",
                            data=b"test content 4",
                            status_code=303)
    httpx_mock.add_response(url="http://test_url",
                            method="PATCH",
                            data=b"test content 5",
                            status_code=404)
    httpx_mock.add_response(url="http://test_url",
                            method="HEAD",
                            data=b"test content 6",
                            status_code=500)

    with httpx.Client() as client:
        response = client.post("http://test_url")
        assert response.content == b"test content 2"
        assert response.status_code == 201

        response = client.get("http://test_url")
        assert response.content == b"test content 1"
        assert response.status_code == 200

        response = client.put("http://test_url")
        assert response.content == b"test content 3"
        assert response.status_code == 202

        response = client.head("http://test_url")
        assert response.content == b"test content 6"
        assert response.status_code == 500

        response = client.patch("http://test_url")
        assert response.content == b"test content 5"
        assert response.status_code == 404

        response = client.delete("http://test_url")
        assert response.content == b"test content 4"
        assert response.status_code == 303
Exemplo n.º 23
0
def test_is_available(tid, httpx_mock: HTTPXMock, leopold_in_stock):
    httpx_mock.add_response(data=leopold_in_stock.read())
    assert is_available(tid) is True
Exemplo n.º 24
0
def test_requests_retrieval(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="http://test_url",
                            method="GET",
                            data=b"test content 1")
    httpx_mock.add_response(url="http://test_url",
                            method="POST",
                            data=b"test content 2")
    httpx_mock.add_response(url="http://test_url",
                            method="PUT",
                            data=b"test content 3")
    httpx_mock.add_response(url="http://test_url",
                            method="DELETE",
                            data=b"test content 4")
    httpx_mock.add_response(url="http://test_url",
                            method="PATCH",
                            data=b"test content 5")
    httpx_mock.add_response(url="http://test_url",
                            method="HEAD",
                            data=b"test content 6")

    with httpx.Client() as client:
        client.post("http://test_url", content=b"sent content 2")
        client.get("http://test_url", headers={"X-TEST": "test header 1"})
        client.put("http://test_url", content=b"sent content 3")
        client.head("http://test_url")
        client.patch("http://test_url", content=b"sent content 5")
        client.delete("http://test_url", headers={"X-Test": "test header 4"})

    assert (httpx_mock.get_request(url=httpx.URL("http://test_url"),
                                   method="PATCH").read() == b"sent content 5")
    assert (httpx_mock.get_request(url=httpx.URL("http://test_url"),
                                   method="HEAD").read() == b"")
    assert (httpx_mock.get_request(url=httpx.URL("http://test_url"),
                                   method="PUT").read() == b"sent content 3")
    assert (httpx_mock.get_request(
        url=httpx.URL("http://test_url"),
        method="GET").headers["x-test"] == "test header 1")
    assert (httpx_mock.get_request(url=httpx.URL("http://test_url"),
                                   method="POST").read() == b"sent content 2")
    assert (httpx_mock.get_request(
        url=httpx.URL("http://test_url"),
        method="DELETE").headers["x-test"] == "test header 4")
Exemplo n.º 25
0
def test_is_not_available(tid, httpx_mock: HTTPXMock, leopold_sold_out):
    httpx_mock.add_response(data=leopold_sold_out.read())
    assert is_available(tid) is False
Exemplo n.º 26
0
def test_query_api_key_is_sent_in_api_key_by_default(httpx_mock: HTTPXMock):
    auth = httpx_auth.QueryApiKey("my_provided_api_key")
    # Mock a dummy response
    httpx_mock.add_response(url="http://authorized_only?api_key=my_provided_api_key")
    # Send a request to this dummy URL with authentication
    httpx.get("http://authorized_only", auth=auth)
Exemplo n.º 27
0
async def test_with_many_responses_urls_str(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="http://test_url?param1=test",
                            method="GET",
                            data=b"test content 1")
    httpx_mock.add_response(url="http://test_url?param2=test",
                            method="POST",
                            data=b"test content 2")
    httpx_mock.add_response(url="http://test_url?param3=test",
                            method="PUT",
                            data=b"test content 3")
    httpx_mock.add_response(url="http://test_url?param4=test",
                            method="DELETE",
                            data=b"test content 4")
    httpx_mock.add_response(url="http://test_url?param5=test",
                            method="PATCH",
                            data=b"test content 5")
    httpx_mock.add_response(url="http://test_url?param6=test",
                            method="HEAD",
                            data=b"test content 6")

    async with httpx.AsyncClient() as client:
        response = await client.post(
            httpx.URL("http://test_url", params={"param2": "test"}))
        assert response.content == b"test content 2"

        response = await client.get(
            httpx.URL("http://test_url", params={"param1": "test"}))
        assert response.content == b"test content 1"

        response = await client.put(
            httpx.URL("http://test_url", params={"param3": "test"}))
        assert response.content == b"test content 3"

        response = await client.head(
            httpx.URL("http://test_url", params={"param6": "test"}))
        assert response.content == b"test content 6"

        response = await client.patch(
            httpx.URL("http://test_url", params={"param5": "test"}))
        assert response.content == b"test content 5"

        response = await client.delete(
            httpx.URL("http://test_url", params={"param4": "test"}))
        assert response.content == b"test content 4"