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"), ), )
def test_structure_inject(): expected_imposter = Imposter( Stub(responses=InjectionResponse(inject="function (request) {\n}")), port=4546) imposter_structure = expected_imposter.as_structure() imposter = Imposter.from_structure(imposter_structure) assert imposter.port == expected_imposter.port
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" }, ), ), )
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))
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")))), )
def test_decorate_proxy(mock_server): proxy_target = Imposter(Stub(responses=Response(body="Hello ${NAME}."))) mock_server.add_impostor(proxy_target) imposter = Imposter(Stub(responses=Proxy(to=proxy_target.url, decorate=JS))) with mock_server(imposter): response = requests.get(imposter.url) assert_that(response, is_response().with_body("Hello World."))
def test_proxy_delay(mock_server): target_imposter = Imposter(Stub(Predicate(path="/test"))) with mock_server(target_imposter) as server: proxy_imposter = Imposter( Stub(responses=Proxy(to=target_imposter.url, wait=100))) server.add_imposters(proxy_imposter) with Timer() as timer: requests.get(proxy_imposter.url / "test") assert_that(timer.elapsed, between(0.1, 0.2))
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)), )
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"), ), )
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"))
def test_imposter_complex_predicates(predicate): # Given expected = Imposter(Stub(predicate().build())) structure = expected.as_structure() # When actual = Imposter.from_structure(structure) # Then assert_that(actual, instance_of(Imposter)) assert_that( actual, has_identical_properties_to(expected, ignoring=["configuration_url"]))
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)
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))
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)
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()
def query_all_imposters(self) -> Iterator[Imposter]: """Yield all imposters running on the server, including those defined elsewhere.""" server_info = requests.get(self.server_url) imposters = server_info.json()["imposters"] for imposter in imposters: yield Imposter.from_structure( requests.get(imposter["_links"]["self"]["href"]).json())
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()
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()
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")))
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"), )), )
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."))
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?"))
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")), )
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"))
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"))
def test_decorate_proxy_binary(mock_server): proxy_target = Imposter( Stub( responses=Response( headers={"Content-Type": "application/octet-stream"}, body="Hello ${NAME}." ) ) ) mock_server.add_impostor(proxy_target) imposter = Imposter(Stub(responses=Proxy(to=proxy_target.url, decorate=JS_FOR_BINARY))) with mock_server(imposter): response = requests.get(imposter.url) assert_that(response, is_response().with_body("Hello World."))
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(""))
def test_methods(mock_server): # Given imposter = Imposter([ Stub(Predicate(method=Predicate.Method.GET), Response(body="get")), Stub(Predicate(method=Predicate.Method.PUT), Response(body="put")), Stub(Predicate(method=Predicate.Method.POST), Response(body="post")), Stub(Predicate(method=Predicate.Method.DELETE), Response(body="delete")), Stub(Predicate(method=Predicate.Method.PATCH), Response(body="patch")), Stub(Predicate(method=Predicate.Method.HEAD), Response(status_code=789)), ]) with mock_server(imposter) as s: logger.debug("server: %s", s) # When delete = requests.delete(imposter.url) post = requests.post(imposter.url) put = requests.put(imposter.url) patch = requests.patch(imposter.url) get = requests.get(imposter.url) head = requests.head(imposter.url) # Then assert_that(delete, is_response().with_body("delete")) assert_that(post, is_response().with_body("post")) assert_that(put, is_response().with_body("put")) assert_that(patch, is_response().with_body("patch")) assert_that(get, is_response().with_body("get")) assert_that(head, is_response().with_status_code(789))
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)))
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")))