Esempio n. 1
0
def test_dest_returns_unparseable_json_response(mock_server):
    with open("tests/resources/circrequests/valid_src_response.json") as file:
        valid_src_response = file.read()

    with open(
            "tests/resources/circrequests/unparseable_json_dest_response.json"
    ) as file:
        unparseable_json_dest_response = file.read()

    # Set up mock server with required behavior
    imposter = Imposter([
        Stub(Predicate(path="/src"), Response(body=valid_src_response)),
        Stub(Predicate(path="/dest", method="POST"),
             Response(body=unparseable_json_dest_response)),
    ])

    # Create a temporary file to use as last success lookup
    try:
        [temp_file_handle, temp_success_filename] = tempfile.mkstemp()
        with open(temp_success_filename, 'w') as f:
            f.write('etc/items_FIRST.json')

        with tempfile.TemporaryDirectory() as temp_storage_dir, mock_server(
                imposter) as server:
            setup_environment(imposter, temp_storage_dir,
                              temp_success_filename)

            start_time = '20200521132905'
            args = []

            with pytest.raises(JSONDecodeError):
                command = Command()
                result = command(start_time, args)
                assert result.was_successful() is False

            files_in_storage_dir = [
                f for f in listdir(temp_storage_dir)
                if isfile(join(temp_storage_dir, f))
            ]
            expected_file_regex = re.compile('.*\\.dest_response_body\\..*')

            # There should be a "dest_circrequests_response_body" file, even
            # though the JSON was unparseable
            if not any(
                    expected_file_regex.match(x)
                    for x in files_in_storage_dir):
                pytest.fail(
                    f"Expected file matching '#{expected_file_regex.pattern}' was not found."
                )

            # There should have been three requests to the server
            assert 2 == len(server.get_actual_requests()[imposter.port])
            assert_that(server,
                        had_request().with_path("/src").and_method("GET"))
            assert_that(server,
                        had_request().with_path("/dest").and_method("POST"))
    finally:
        # Clean up the temporary file
        os.close(temp_file_handle)
        os.remove(temp_success_filename)
Esempio n. 2
0
def test_add_stubs_to_running_impostor(mock_server):
    impostor = Imposter(
        Stub(Predicate(path="/test0"), Response(body="response0")),
        default_response=HttpResponse(body="default"),
    )

    with mock_server(impostor):

        responses = [requests.get(f"{impostor.url}/test{i}") for i in range(3)]
        assert_that(
            responses,
            contains_exactly(
                is_response().with_body("response0"),
                is_response().with_body("default"),
                is_response().with_body("default"),
            ),
        )

        impostor.add_stubs(
            [
                Stub(Predicate(path="/test1"), Response(body="response1")),
            ]
        )
        responses = [requests.get(f"{impostor.url}/test{i}") for i in range(3)]
        assert_that(
            responses,
            contains_exactly(
                is_response().with_body("response0"),
                is_response().with_body("response1"),
                is_response().with_body("default"),
            ),
        )
Esempio n. 3
0
def test_query_all_imposters(mock_server):
    imposter1 = Imposter(
        Stub(Predicate(path="/test1"), Response(body="sausages")))
    imposter2 = Imposter(Stub(Predicate(path="/test2"), Response(body="egg")))

    with mock_server([imposter1, imposter2]) as server:
        actual = list(server.query_all_imposters())
        assert_that(
            actual,
            contains_inanyorder(
                has_identical_properties_to(
                    imposter1,
                    ignoring={
                        "host", "url", "server_url", "configuration_url",
                        "attached"
                    },
                ),
                has_identical_properties_to(
                    imposter2,
                    ignoring={
                        "host", "url", "server_url", "configuration_url",
                        "attached"
                    },
                ),
            ),
        )
Esempio n. 4
0
def test_dest_returns_denied_key(mock_server):
    with open("tests/resources/circrequests/valid_src_response.json") as file:
        valid_src_response = file.read()

    with open(
            "tests/resources/circrequests/valid_dest_response_denied_key.json"
    ) as file:
        valid_dest_response_denied_key = file.read()

    # Set up mock server with required behavior
    imposter = Imposter([
        Stub(Predicate(path="/src"), Response(body=valid_src_response)),
        Stub(Predicate(path="/dest", method="POST"),
             Response(body=valid_dest_response_denied_key)),
    ])

    try:
        # Create a temporary file to use as last success lookup
        [temp_success_file_handle, temp_success_filename] = tempfile.mkstemp()
        with open(temp_success_filename, 'w') as f:
            f.write('etc/circrequests_FIRST.json')

        # Create a temporary file to use as denied keys file
        [temp_denied_keys_file_handle,
         temp_denied_keys_filename] = tempfile.mkstemp()
        with open(temp_denied_keys_filename, 'w') as f:
            f.write('{}')

        with tempfile.TemporaryDirectory() as temp_storage_dir, mock_server(
                imposter) as server:
            setup_environment(imposter, temp_storage_dir,
                              temp_success_filename, temp_denied_keys_filename)

            start_time = '20200521132905'
            args = []

            command = Command()
            result = command(start_time, args)
            assert result.was_successful() is True

            assert_that(server,
                        had_request().with_path("/src").and_method("GET"))
            assert_that(server,
                        had_request().with_path("/dest").and_method("POST"))
    finally:
        # Clean up the temporary files
        os.close(temp_success_file_handle)
        os.remove(temp_success_filename)

        os.close(temp_denied_keys_file_handle)
        # Verify that "denied keys" file contains denied entry
        with open(temp_denied_keys_filename) as file:
            denied_keys = json.load(file)
            denied_item_time = datetime.datetime.strptime(
                start_time, '%Y%m%d%H%M%S').isoformat()
            assert denied_keys == {'31430023550355': denied_item_time}
        os.remove(temp_denied_keys_filename)
Esempio n. 5
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"))
Esempio n. 6
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"))
Esempio n. 7
0
def test_query_all_imposters(mock_server):
    imposter1 = Imposter(
        Stub(Predicate(path="/test1"), Response(body="sausages")))
    imposter2 = Imposter(Stub(Predicate(path="/test2"), Response(body="egg")))

    with mock_server([imposter1, imposter2]) as server:
        actual = server.query_all_imposters()
        assert_that(
            actual,
            contains_inanyorder(has_identical_properties_to(imposter1),
                                has_identical_properties_to(imposter2)),
        )
Esempio n. 8
0
def test_remove_and_replace_impostor_from_running_server(mock_server):
    # Set up server
    with mock_server([
            Imposter(Stub(Predicate(path="/test"), Response(body="sausage")),
                     name="sausage"),
            Imposter(Stub(Predicate(path="/test"), Response(body="egg")),
                     name="egg"),
            Imposter(Stub(Predicate(path="/test"), Response(body="chips")),
                     name="chips"),
    ]) as server:

        # Retrieve impostor details from running server, and check they work
        initial = server.query_all_imposters()

        responses = [requests.get(f"{initial[i].url}/test") for i in range(3)]
        assert_that(
            responses,
            contains_inanyorder(
                is_response().with_body("sausage"),
                is_response().with_body("egg"),
                is_response().with_body("chips"),
            ),
        )

        # Delete one impostor, make sure it's gone, and that the rest still work
        egg_impostor = [i for i in initial if i.name == "egg"][0]
        other_impostors = [i for i in initial if i.name != "egg"]
        server.delete_impostor(egg_impostor)

        with pytest.raises(requests.exceptions.ConnectionError):
            requests.get(f"{egg_impostor.url}/test")
        responses = [requests.get(f"{i.url}/test") for i in other_impostors]
        assert_that(
            responses,
            contains_inanyorder(
                is_response().with_body("sausage"),
                is_response().with_body("chips"),
            ),
        )

        # Reset the server from the initial impostors, and check it's back to normal
        server.delete_imposters()
        server.add_imposters(initial)

        responses = [requests.get(f"{initial[i].url}/test") for i in range(3)]
        assert_that(
            responses,
            contains_inanyorder(
                is_response().with_body("sausage"),
                is_response().with_body("egg"),
                is_response().with_body("chips"),
            ),
        )
Esempio n. 9
0
def test_successful_job(mock_server):
    with open("tests/resources/items/valid_src_response.json") as file:
        valid_src_response = file.read()

    with open("tests/resources/items/valid_dest_new_items_response.json"
              ) as file:
        valid_dest_new_items_response = file.read()

    with open("tests/resources/items/valid_dest_updated_items_response.json"
              ) as file:
        valid_dest_updated_items_response = file.read()

    # Set up mock server with required behavior
    imposter = Imposter([
        Stub(Predicate(path="/src"), Response(body=valid_src_response)),
        Stub(Predicate(path="/dest/new", method="POST"),
             Response(body=valid_dest_new_items_response)),
        Stub(Predicate(path="/dest/updated", method="POST"),
             Response(body=valid_dest_updated_items_response)),
    ])

    # Create a temporary file to use as last success lookup
    try:
        [temp_file_handle, temp_success_filename] = tempfile.mkstemp()
        with open(temp_success_filename, 'w') as f:
            f.write('etc/items_FIRST.json')

        with tempfile.TemporaryDirectory() as temp_storage_dir, mock_server(
                imposter) as server:
            setup_environment(imposter, temp_storage_dir,
                              temp_success_filename)

            start_time = '20200521132905'
            args = []

            command = Command()
            result = command(start_time, args)
            assert result.was_successful() is True

            assert_that(server,
                        had_request().with_path("/src").and_method("GET"))
            assert_that(
                server,
                had_request().with_path("/dest/new").and_method("POST"))
            assert_that(
                server,
                had_request().with_path("/dest/updated").and_method("POST"))
    finally:
        # Clean up the temporary file
        os.close(temp_file_handle)
        os.remove(temp_success_filename)
Esempio n. 10
0
def test_import_impostor_from_running_server(mock_server):
    # Set up server
    with mock_server([
            Imposter(Stub(Predicate(path="/test"), Response(body="sausage")),
                     name="sausage"),
            Imposter(Stub(Predicate(path="/test"), Response(body="egg")),
                     name="egg"),
            Imposter(Stub(Predicate(path="/test"), Response(body="chips")),
                     name="chips"),
    ]) as server:
        initial = server.query_all_imposters()
        server.import_running_imposters()
        after = server.get_running_imposters()
        assert str(initial) == str(after)
Esempio n. 11
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")),
        )
Esempio n. 12
0
def test_send_updated_items_to_dest_valid_response(mock_server):
    with open("tests/resources/items/valid_dest_updated_items_response.json") as file:
        valid_dest_response = file.read()

    # Set up mock server with required behavior
    imposter = Imposter(Stub(Predicate(path="/items/updates", method="POST"),
                             Response(body=valid_dest_response)))

    with mock_server(imposter) as server:
        config = {
            'dest_updates_url': f"{imposter.url}/items/updates",
            'storage_dir': '/tmp',
            'last_success_lookup': 'tests/storage/items/items_last_success.txt',
            'caiasoft_api_key': "SOME_SECRET_KEY"
        }
        job_config = ItemsJobConfig(config, 'test')
        # Override dest_updated_items_request_body_filepath
        job_config["dest_updated_items_request_body_filepath"] = \
            "tests/resources/items/valid_dest_updated_items_request.json"

        with tempfile.TemporaryDirectory() as temp_storage_dir:
            job_config["dest_updated_items_response_body_filepath"] = \
                temp_storage_dir + "/dest_updated_items_response.json"

            send_updated_items_to_dest = SendUpdatedItemsToDest(job_config)
            step_result = send_updated_items_to_dest.execute()

            assert step_result.was_successful() is True
            assert os.path.exists(job_config["dest_updated_items_response_body_filepath"])
            assert_that(server, had_request().with_path("/items/updates").and_method("POST"))
            assert valid_dest_response == step_result.get_result()
Esempio n. 13
0
def test_404_response_from_server(mock_server):
    # Set up mock server with required behavior
    imposter = Imposter(
        Stub(Predicate(path="/holds"), Response(status_code=404)))

    with mock_server(imposter) as server:
        config = {
            'source_url':
            f"{imposter.url}/holds",
            'storage_dir':
            '/tmp',
            'last_success_lookup':
            'tests/storage/circrequests/circrequests_last_success.txt',
            'denied_keys_filepath':
            'tests/storage/circrequests/circrequests_denied_keys.json'
        }
        job_config = CircrequestsJobConfig(config, 'test')

        query_source_url = QuerySourceUrl(job_config)

        step_result = query_source_url.execute()

        assert step_result.was_successful() is False
        assert_that(server,
                    had_request().with_path("/holds").and_method("GET"))
        assert f"Retrieval of '{imposter.url}/holds' failed with a status code of 404" in \
               step_result.get_errors()
Esempio n. 14
0
def test_valid_response_from_server(mock_server):
    with open("tests/resources/circrequests/valid_src_response.json") as file:
        valid_src_response = file.read()

    # Set up mock server with required behavior
    imposter = Imposter(
        Stub(Predicate(path="/holds"), Response(body=valid_src_response)))

    with mock_server(imposter) as server:
        config = {
            'source_url':
            f"{imposter.url}/holds",
            'storage_dir':
            '/tmp',
            'last_success_lookup':
            'tests/storage/circrequests/circrequests_last_success.txt',
            'denied_keys_filepath':
            'tests/storage/circrequests/circrequests_denied_keys.json'
        }
        job_config = CircrequestsJobConfig(config, 'test')

        query_source_url = QuerySourceUrl(job_config)

        step_result = query_source_url.execute()

        assert step_result.was_successful() is True
        assert_that(server,
                    had_request().with_path("/holds").and_method("GET"))
        assert valid_src_response == step_result.get_result()
Esempio n. 15
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")))
Esempio n. 16
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."))
Esempio n. 17
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?"))
Esempio n. 18
0
def test_cloud_api_timeout(mock_server):
    imposter = Imposter(
        Stub(Predicate(path="/hub/lan_ip"),
             Response(body='[ "127.0.0.1" ]', wait=6000)))
    with pytest.raises(ConnectionError) as e_info:
        with mock_server(imposter):
            cloud_api.lan_ip(base=imposter.url)
Esempio n. 19
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) as s:
        logger.debug("server: %s", s)
        r1 = requests.get("{0}/test1".format(imposters[0].url))
        r2 = requests.get("{0}/test2".format(imposters[1].url))

    assert_that(r1, response_with(status_code=200, body="sausages"))
    assert_that(r2, response_with(status_code=201, body="chips"))
Esempio n. 20
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)))
Esempio n. 21
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"))
Esempio n. 22
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")))
Esempio n. 23
0
def test_lookup(mock_server):
    datasource_path = str(
        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,
                    body="Hello liquid, have you done your farmer today?",
                    headers=has_entry("X-Tree", "mango"),
                )),
        )
Esempio n. 24
0
def test_wait(mock_server):
    imposter = Imposter(Stub(responses=Response(wait=100)))

    with mock_server(imposter), Timer() as timer:
        requests.get(imposter.url)

        assert_that(timer.elapsed, between(0.1, 0.25))
Esempio n. 25
0
def test_multiple_stubs(mock_server):
    imposter = Imposter(
        [
            Stub(Predicate(path="/test1"), Response(body="sausages")),
            Stub(Predicate(path="/test2"), Response(body="chips")),
        ],
        port=4567,
        name="bill",
    )

    with mock_server(imposter) as s:
        logger.debug("server: %s", s)
        r1 = requests.get("{0}/test1".format(imposter.url))
        r2 = requests.get("{0}/test2".format(imposter.url))

    assert_that(r1, is_response().with_body("sausages"))
    assert_that(r2, is_response().with_body("chips"))
Esempio n. 26
0
def test_imposter_had_request_matcher(mock_server):
    imposter = Imposter(Stub(Predicate(path="/test"), Response(body="sausages")))

    with mock_server(imposter):
        response = requests.get(f"{imposter.url}/test")

        assert_that(response, is_response().with_status_code(200).and_body("sausages"))
        assert_that(imposter, had_request().with_path("/test").and_method("GET"))
Esempio n. 27
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"))
Esempio n. 28
0
def test_decorate(mock_server):
    imposter = Imposter(Stub(responses=Response(body="The time is ${TIME}.", decorate=JS)))

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

        assert_that(
            response, is_response().with_body(matches_regexp(r"The time is \d\d:\d\d:\d\d\."))
        )
Esempio n. 29
0
def test_cloud_api_requestlogin(mock_server, tmp_cloud):
    imposter = Imposter(
        Stub(
            Predicate(method=Predicate.Method.POST)
            & Predicate(path="/user/requestlogin")
            & Predicate(query={"email": tmp_cloud.email}),
            Response(body='null')))
    with mock_server(imposter):
        cloud_api.requestlogin(email=tmp_cloud.email, base=imposter.url)
Esempio n. 30
0
def test_cloud_api_emaillogin(mock_server, tmp_cloud):
    imposter = Imposter(
        Stub(Predicate(path="/user/emaillogin"),
             Response(body=tmp_cloud.token)))
    with mock_server(imposter):
        token = cloud_api.emaillogin(email=tmp_cloud.email,
                                     otp='42',
                                     base=imposter.url)
        assert isinstance(token, str)