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_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")))
def test_invalid_operator(): expected_predicate = Predicate(operator="deepEquals") predicate_structure = expected_predicate.as_structure() # Adds another operator predicate_structure["equals"] = {} with pytest.raises(Predicate.InvalidPredicateOperator): Predicate.from_structure(predicate_structure)
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)
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_default_predicate(): # Given predicate = Predicate() # When structure = predicate.as_structure() # Then assert_that(structure, has_entries(caseSensitive=True, equals=has_entries()))
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)
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)
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_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_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)
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_or_predicate_and_body(mock_server): imposter = Imposter( Stub( Predicate(body="foo") | Predicate(body="bar"), Response(body="oranges"))) with mock_server(imposter) as s: logger.debug("server: %s", s) r1 = requests.get(imposter.url, data="foo") r2 = requests.get(imposter.url, data="bar") r3 = requests.get(imposter.url, data="baz") assert_that(r1, is_(response_with(status_code=200, body="oranges"))) assert_that(r2, is_(response_with(status_code=200, body="oranges"))) assert_that(r3, not_(response_with(status_code=200, body="oranges")))
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_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_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 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_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"))
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"))
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"))
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)
def test_https_impostor_fails_if_cert_not_supplied(mock_server): imposter = Imposter( Stub(Predicate(path="/test"), Response(body="sausages")), protocol=Imposter.Protocol.HTTPS, ) with mock_server(imposter): with pytest.raises(SSLError): requests.get(f"{imposter.url}/test")
def test_xml_response(mock_server): # Given imposter = Imposter(Stub(Predicate(), Response(body=data2xml({"foo": {"bar": "baz"}})))) with mock_server(imposter): # When r = requests.get(imposter.url) # Then assert_that(r, is_response().with_body("<foo><bar>baz</bar></foo>"))
def test_hub_api_timeout(mock_server, tmp_hub): imposter = Imposter( Stub(Predicate(path="/hub/tz"), Response(body='Europe/Helsinki', wait=6000))) with pytest.raises(ConnectionError) as e_info: with mock_server(imposter): hub_api.tz(host=imposter.host, port=imposter.port, base='', hub_token=tmp_hub.token)
def test_allow_multiple_servers_on_different_ports(): # Given try: server1 = ExecutingMountebankServer(port=2526) server2 = ExecutingMountebankServer(port=2527) imposter1 = Imposter(Stub(Predicate(path="/test"), Response(body="sausages"))) imposter2 = Imposter(Stub(Predicate(path="/test"), Response(body="bacon"))) with server1(imposter1), server2(imposter2): response1 = requests.get(f"{imposter1.url}/test") response2 = requests.get(f"{imposter2.url}/test") assert_that(response1, is_response().with_status_code(200).and_body("sausages")) assert_that(response2, is_response().with_status_code(200).and_body("bacon")) finally: server1.close() server2.close()
def test_request_to_mock_server(mock_server): # Start mock server with required behavior imposter = Imposter(Stub(Predicate(path="/test"), Response(body="sausages"))) with mock_server(imposter) as server: # Make request to mock server response = requests.get(f"{imposter.url}/test") assert_that(response, is_response().with_status_code(200).and_body("sausages")) assert_that(server, had_request().with_path("/test").and_method("GET"))
def test_remove_and_replace_stub_from_running_impostor(mock_server): impostor = Imposter( stubs=[ Stub(Predicate(path="/test0"), Response(body="response0")), Stub(Predicate(path="/test1"), Response(body="response1")), Stub(Predicate(path="/test2"), Response(body="response2")), ], 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("response1"), is_response().with_body("response2"), ), ) impostor.delete_stub(1) 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("response2"), ), ) impostor.add_stub(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("response2"), ), )
def test_no_diff_job(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.json") as file: valid_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=valid_dest_response)), ]) # Create a temporary file to use as last success lookup # This will be comparing against the same response # (tests/resources/circrequests/valid_src_response.json) # so there will be no difference try: [temp_file_handle, temp_success_filename] = tempfile.mkstemp() with open(temp_success_filename, 'w') as f: f.write('tests/resources/circrequests/valid_src_response.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 # There should be only one request to the server (the /src request) assert 1 == len(server.get_actual_requests()[imposter.port]) assert_that(server, had_request().with_path("/src").and_method("GET")) finally: # Clean up the temporary file os.close(temp_file_handle) os.remove(temp_success_filename)