Пример #1
0
def test_and_predicate_and_query_strings(mock_server):
    imposter = Imposter(
        Stub(
            Predicate(query={"foo": "bar"})
            & Predicate(query={"dinner": "chips"}),
            Response(body="black pudding"),
        ))

    with mock_server(imposter) as s:
        logger.debug("server: %s", s)

        r1 = requests.get(f"{imposter.url}/",
                          params={
                              "dinner": "chips",
                              "foo": "bar"
                          })
        r2 = requests.get(f"{imposter.url}/", params={"dinner": "chips"})

        assert_that(
            r1,
            is_response().with_status_code(200).and_body("black pudding"))
        assert_that(
            r2,
            not_(
                is_response().with_status_code(200).and_body("black pudding")))
Пример #2
0
def test_response_matcher_cookies():
    # Given
    response = MOCK_RESPONSE

    # When

    # Then
    assert_that(response, is_response().with_cookies({"name": "value"}))
    assert_that(response, not_(is_response().with_cookies({"name": "nope"})))
    assert_that(
        str(is_response().with_cookies({"name": "value"})),
        contains_string("response with cookies: <{'name': 'value'}"),
    )
    assert_that(
        is_response().with_cookies({"name": "nope"}),
        mismatches_with(
            response,
            contains_string(
                "was response with cookies: was <{'name': 'value'}")),
    )
    assert_that(
        is_response().with_cookies({"name": "value"}),
        matches_with(
            response,
            contains_string(
                "was response with cookies: was <{'name': 'value'}")),
    )
Пример #3
0
def test_response_matcher_elapsed():
    # Given
    response = MOCK_RESPONSE

    # When

    # Then
    assert_that(response, is_response().with_elapsed(timedelta(seconds=1)))
    assert_that(response,
                not_(is_response().with_elapsed(timedelta(seconds=60))))
    assert_that(
        str(is_response().with_elapsed(timedelta(seconds=1))),
        contains_string("response with elapsed: <0:00:01>"),
    )
    assert_that(
        is_response().with_elapsed(timedelta(seconds=60)),
        mismatches_with(
            response,
            contains_string("was response with elapsed: was <0:00:01>")),
    )
    assert_that(
        is_response().with_elapsed(timedelta(seconds=1)),
        matches_with(
            response,
            contains_string("was response with elapsed: was <0:00:01>")),
    )
Пример #4
0
def test_response_matcher_content():
    # Given
    stub_response = MOCK_RESPONSE

    # When

    # Then
    assert_that(stub_response, is_response().with_content(b"content"))
    assert_that(stub_response, not_(is_response().with_content(b"chips")))
    assert_that(
        str(is_response().with_content(b"content")),
        contains_string("response with content: <b'content'>"),
    )
    assert_that(
        is_response().with_content(b"chips"),
        mismatches_with(
            stub_response,
            contains_string("was response with content: was <b'content'>")),
    )
    assert_that(
        is_response().with_content(b"content"),
        matches_with(
            stub_response,
            contains_string("was response with content: was <b'content'>")),
    )
Пример #5
0
def test_response_matcher_url():
    # Given
    response = MOCK_RESPONSE

    # When

    # Then
    assert_that(response, is_response().with_url(is_url().with_path("/path0")))
    assert_that(response,
                not_(is_response().with_url(is_url().with_path("/nope"))))
    assert_that(
        str(is_response().with_url(is_url().with_path("/path0"))),
        contains_string("response with url: URL with path: '/path0'"),
    )
    assert_that(
        is_response().with_url(is_url().with_path("/nope")),
        mismatches_with(
            response,
            contains_string(
                "was response with url: was URL with path: was </path0>")),
    )
    assert_that(
        is_response().with_url(is_url().with_path("/path0")),
        matches_with(
            response,
            contains_string(
                "was response with url: was URL with path: was </path0>")),
    )
Пример #6
0
def test_proxy_uses_path_predicate_generator(mock_server):
    proxy_imposter = Imposter(
        Stub(responses=Proxy(
            to="https://httpbin.org",
            mode=Proxy.Mode.ONCE,
            predicate_generators=[PredicateGenerator(path=True)],
        )))

    with mock_server(proxy_imposter):
        response = requests.get(proxy_imposter.url / "status/418")
        assert_that(
            response,
            is_response().with_status_code(418).and_body(
                contains_string("teapot")))
        response = requests.get(proxy_imposter.url / "status/200")
        assert_that(response, is_response().with_status_code(200))

        recorded_stubs = proxy_imposter.playback()

    playback_impostor = Imposter(recorded_stubs)
    with mock_server(playback_impostor):
        response = requests.get(playback_impostor.url / "status/418")
        assert_that(
            response,
            is_response().with_status_code(418).and_body(
                contains_string("teapot")))
        response = requests.get(playback_impostor.url / "status/200")
        assert_that(response, is_response().with_status_code(200))
Пример #7
0
def test_response_matcher_json():
    # Given
    stub_response = MOCK_RESPONSE

    # When

    # Then
    assert_that(stub_response, is_response().with_json({"a": "b"}))
    assert_that(stub_response, not_(is_response().with_json({"a": "c"})))
    assert_that(
        str(is_response().with_json({"a": "b"})),
        contains_string("response with json: <{'a': 'b'}>"),
    )
    assert_that(
        is_response().with_json([1, 2, 4]),
        mismatches_with(
            stub_response,
            contains_string("was response with json: was <{'a': 'b'}>")),
    )
    assert_that(
        is_response().with_json({"a": "b"}),
        matches_with(
            stub_response,
            contains_string("was response with json: was <{'a': 'b'}>")),
    )
Пример #8
0
def test_proxy_uses_query_predicate_generator_with_key(mock_server):
    proxy_imposter = Imposter(
        Stub(responses=Proxy(
            to="https://httpbin.org",
            mode=Proxy.Mode.ONCE,
            predicate_generators=[
                PredicateGenerator(query={"foo": "whatever"})
            ],
        )))

    with mock_server(proxy_imposter):
        response = requests.get(proxy_imposter.url / "get",
                                params={
                                    "foo": "bar",
                                    "quxx": "buzz"
                                })
        assert_that(
            response,
            is_response().with_body(
                json_matching(
                    has_entries(args=has_entries(foo="bar", quxx="buzz")))),
        )
        response = requests.get(proxy_imposter.url / "get",
                                params={
                                    "foo": "baz",
                                    "quxx": "buxx"
                                })
        assert_that(
            response,
            is_response().with_body(
                json_matching(has_entries(args=has_entries(foo="baz")))),
        )

        recorded_stubs = proxy_imposter.playback()

    playback_impostor = Imposter(recorded_stubs)
    with mock_server(playback_impostor):
        response = requests.get(playback_impostor.url / "get",
                                params={
                                    "foo": "bar",
                                    "quxx": "whatever"
                                })
        assert_that(
            response,
            is_response().with_body(
                json_matching(
                    has_entries(args=has_entries(foo="bar", quxx="buzz")))),
        )
        response = requests.get(playback_impostor.url / "get",
                                params={
                                    "foo": "baz",
                                    "quxx": "anything"
                                })
        assert_that(
            response,
            is_response().with_body(
                json_matching(
                    has_entries(args=has_entries(foo="baz", quxx="buxx")))),
        )
Пример #9
0
def test_response_json():
    # Given

    # When
    actual = requests.get("https://httpbin.org/json")

    # Then
    assert_that(actual, is_response().with_json(has_key("slideshow")))
    assert_that(actual, not_(is_response().with_json(has_key("shitshow"))))
Пример #10
0
def test_response_encoding():
    # Given

    # When
    actual = requests.get("https://httpbin.org/encoding/utf8")

    # Then
    assert_that(actual, is_response().with_encoding("utf-8"))
    assert_that(actual, not_(is_response().with_encoding("ISO-8859-1")))
Пример #11
0
def test_response_matcher_builder():
    # Given
    stub_response = MOCK_RESPONSE
    matcher = (is_response().with_status_code(200).and_body(
        "sausages").and_content(b"content").and_json(has_entries(
            a="b")).and_headers(has_entries(key="value")).and_cookies(
                has_entries(name="value")).and_elapsed(
                    between(timedelta(seconds=1),
                            timedelta(minutes=1))).and_history(
                                contains_exactly(
                                    is_response().with_url(
                                        is_url().with_path("/path1")),
                                    is_response().with_url(
                                        is_url().with_path("/path2")),
                                )).and_url(is_url().with_path(
                                    "/path0")).and_encoding("utf-8"))
    mismatcher = is_response().with_body("kale").and_status_code(404)

    # When

    # Then
    assert_that(stub_response, matcher)
    assert_that(stub_response, not_(mismatcher))
    assert_that(
        matcher,
        has_string(
            "response with "
            "status_code: <200> "
            "body: 'sausages' "
            "content: <b'content'> "
            "json: a dictionary containing {'a': 'b'} "
            "headers: a dictionary containing {'key': 'value'} "
            "cookies: a dictionary containing {'name': 'value'} "
            "elapsed: (a value greater than or equal to <0:00:01> and a value less than or equal to <0:01:00>) "
            "history: a sequence containing "
            "[response with url: URL with path: '/path1', response with url: URL with path: '/path2'] "
            "url: URL with path: '/path0' "
            "encoding: 'utf-8'"),
    )
    assert_that(
        mismatcher,
        mismatches_with(
            stub_response,
            contains_string(
                "was response with status code: was <200> body: was 'sausages'"
            ),
        ),
    )
    assert_that(
        matcher,
        matches_with(
            stub_response,
            contains_string(
                "was response with status code: was <200> body: was 'sausages'"
            ),
        ),
    )
Пример #12
0
def test_multiple_responses(mock_server):
    imposter = Imposter(Stub(responses=[Response(body="sausages"), Response(body="egg")]))

    with mock_server(imposter):
        r1 = requests.get(imposter.url)
        r2 = requests.get(imposter.url)
        r3 = requests.get(imposter.url)

        assert_that(r1, is_response().with_body("sausages"))
        assert_that(r2, is_response().with_body("egg"))
        assert_that(r3, is_response().with_body("sausages"))
Пример #13
0
def test_not_predicate(mock_server):
    imposter = Imposter(
        Stub(~Predicate(query={"foo": "bar"}), Response(body="black pudding")))

    with mock_server(imposter) as s:
        logger.debug("server: %s", s)

        r1 = requests.get(f"{imposter.url}/", params={"foo": "baz"})
        r2 = requests.get(f"{imposter.url}/", params={"foo": "bar"})

        assert_that(r1, is_response().with_body("black pudding"))
        assert_that(r2, not_(is_response().with_body("black pudding")))
Пример #14
0
def test_default_response(mock_server):
    imposter = Imposter(
        Stub(Predicate(path="/test1"), Response(body="sausages")),
        default_response=HttpResponse("chips", status_code=201),
    )

    with mock_server(imposter):
        r1 = requests.get(f"{imposter.url}/test1")
        r2 = requests.get(f"{imposter.url}/test2")

    assert_that(r1, is_response().with_status_code(200).and_body("sausages"))
    assert_that(r2, is_response().with_status_code(201).and_body("chips"))
Пример #15
0
def test_multiple_imposters(mock_server):
    imposters = [
        Imposter(Stub(Predicate(path="/test1"), Response("sausages"))),
        Imposter([Stub([Predicate(path="/test2")], [Response("chips", status_code=201)])]),
    ]

    with mock_server(imposters):
        r1 = requests.get("{0}/test1".format(imposters[0].url))
        r2 = requests.get("{0}/test2".format(imposters[1].url))

    assert_that(r1, is_response().with_status_code(200).and_body("sausages"))
    assert_that(r2, is_response().with_status_code(201).and_body("chips"))
Пример #16
0
def test_response_content():
    # Given

    # When
    actual = requests.get("https://httpbin.org/anything?foo=bar",
                          headers={"X-Clacks-Overhead": "Sir Terry Pratchett"})

    # Then
    assert_that(actual, is_response().with_status_code(200))
    assert_that(
        actual,
        is_response().with_status_code(200).and_content(
            contains_bytestring(b"foo")))
    assert_that(actual, not_(is_response().with_content(b"seems unlikely")))
Пример #17
0
def test_json_payload(mock_server):
    # Given
    imposter = Imposter(
        Stub(Predicate(body={"foo": ["bar", "baz"]}),
             Response(body="sausages")))

    with mock_server(imposter):
        # When
        r1 = requests.post(imposter.url, json={"foo": ["bar", "baz"]})
        r2 = requests.post(imposter.url, json={"baz": ["bar", "foo"]})

        # Then
        assert_that(r1, is_response().with_body("sausages"))
        assert_that(r2, not_(is_response().with_body("sausages")))
Пример #18
0
def test_response_history():
    # Given

    # When
    actual = requests.get("https://httpbin.org/cookies/set?foo=bar")

    # Then
    assert_that(
        actual,
        is_response().with_status_code(200).and_url(
            is_url().with_path("/cookies")).and_history(
                contains_exactly(is_response().with_url(
                    is_url().with_path("/cookies/set")))),
    )
Пример #19
0
def test_response_status_code():
    # Given

    # When
    actual = requests.get("https://httpbin.org/status/345")

    # Then
    assert_that(actual, is_response().with_status_code(345))
    assert_that(actual, not_(is_response().with_status_code(201)))
    assert_that(
        is_response().with_status_code(201),
        mismatches_with(
            actual,
            contains_string("was response with status code: was <345>")),
    )
Пример #20
0
def test_default_imposter(mock_server):
    imposter = Imposter(Stub())

    with mock_server(imposter):
        r = requests.get("{0}/".format(imposter.url))

    assert_that(r, is_response().with_status_code(200).and_body(""))
Пример #21
0
def test_lookup_with_Path_type(mock_server):
    datasource_path = Path("tests") / "integration" / "behaviors" / "test_data" / "values.csv"
    imposter = Imposter(
        Stub(
            responses=Response(
                status_code="${row}['code']",
                body="Hello ${row}['Name'], have you done your ${row}['jobs'] today?",
                headers={"X-Tree": "${row}['tree']"},
                lookup=Lookup(
                    Key("path", UsingRegex("/(.*)$"), 1), datasource_path, "Name", "${row}"
                ),
            )
        )
    )

    with mock_server(imposter):
        response = requests.get(imposter.url / "liquid")

        assert_that(
            response,
            is_response()
            .with_status_code(400)
            .with_body("Hello liquid, have you done your farmer today?")
            .with_headers(has_entry("X-Tree", "mango")),
        )
Пример #22
0
def test_binary_mode(mock_server):
    imposter = Imposter(Stub(responses=Response(mode=Response.Mode.BINARY, body=b"c2F1c2FnZXM=")))

    with mock_server(imposter):
        response = requests.get(imposter.url)

        assert_that(response, is_response().with_content(b"sausages"))
Пример #23
0
def test_status(mock_server):
    imposter = Imposter(Stub(responses=Response(status_code=204)))

    with mock_server(imposter):
        response = requests.get(imposter.url)

        assert_that(response, is_response().with_status_code(204))
Пример #24
0
def test_body(mock_server):
    imposter = Imposter(Stub(responses=Response(body="sausages")))

    with mock_server(imposter):
        response = requests.get(imposter.url)

        assert_that(response, is_response().with_body("sausages"))
Пример #25
0
def test_regex_copy(mock_server):
    imposter = Imposter(
        Stub(responses=Response(
            status_code="${code}",
            headers={"X-Test": "${header}"},
            body="Hello, ${name}!",
            copy=[
                Copy("path", "${code}", UsingRegex("\\d+")),
                Copy({"headers": "X-Request"}, "${header}", UsingRegex(".+")),
                Copy({"query": "name"}, "${name}",
                     UsingRegex("AL\\w+", ignore_case=True)),
            ],
        )))

    with mock_server(imposter):
        response = requests.get(imposter.url / str(456),
                                params={"name": "Alice"},
                                headers={"X-REQUEST": "Header value"})

        assert_that(
            response,
            is_response().with_status_code(456).with_body(
                "Hello, Alice!").with_headers(
                    has_entry("X-Test", "Header value")),
        )
Пример #26
0
def test_jsonpath_copy(mock_server):
    imposter = Imposter(
        Stub(responses=Response(body="Have you read BOOK?",
                                copy=Copy("body", "BOOK",
                                          UsingJsonpath("$..title")))))

    with mock_server(imposter):
        response = requests.post(
            imposter.url,
            json={
                "books": [
                    {
                        "book": {
                            "title": "Game of Thrones",
                            "summary": "Dragons and political intrigue",
                        }
                    },
                    {
                        "book": {
                            "title": "Harry Potter",
                            "summary": "Dragons and a boy wizard"
                        }
                    },
                    {
                        "book": {
                            "title": "The Hobbit",
                            "summary": "A dragon and short people"
                        }
                    },
                ]
            },
        )

        assert_that(response,
                    is_response().with_body("Have you read Game of Thrones?"))
Пример #27
0
def test_decorate_response(mock_server):
    imposter = Imposter(Stub(responses=Response(body="Hello ${NAME}.", decorate=JS)))

    with mock_server(imposter):
        response = requests.get(imposter.url)

        assert_that(response, is_response().with_body("Hello World."))
Пример #28
0
def test_xml_payload(mock_server):
    # Given
    imposter = Imposter(
        Stub(
            Predicate(xpath="//foo", body="bar", operator=Predicate.Operator.EQUALS),
            Response(body="sausages"),
        )
    )

    with mock_server(imposter):
        # When
        r1 = requests.get(imposter.url, data=et2string(data2xml({"foo": "bar"})))
        r2 = requests.get(imposter.url, data=et2string(data2xml({"foo": "baz"})))

        # Then
        assert_that(r1, is_response().with_body("sausages"))
        assert_that(r2, is_response().with_body(not_("sausages")))
Пример #29
0
def test_response_matcher_invalid_json():
    # Given
    stub_response = mock.MagicMock(status_code=200,
                                   text="body",
                                   content=b"content",
                                   headers={"key": "value"})
    type(stub_response).json = mock.PropertyMock(side_effect=ValueError)

    # When

    # Then
    assert_that(stub_response, not_(is_response().with_json([1, 2, 4])))
    assert_that(
        is_response().with_json([1, 2, 4]),
        mismatches_with(stub_response,
                        contains_string("was response with json: was <None>")),
    )
Пример #30
0
def test_attach_to_existing(mock_server):
    imposter = Imposter(
        Stub(Predicate(path="/test"), Response(body="sausages")))
    with MountebankServer(port=mock_server.server_port)(imposter):
        response = requests.get("{0}/test".format(imposter.url))

        assert_that(response,
                    is_response().with_status_code(200).and_body("sausages"))