def test_multiple_http_mocks_independently_served(): """ Ask for two http mocks and set up different presets. Make calls against each. We should get the correct responses back. """ http_mock_1 = HTTPMock('localhost', 8000) http_mock_2 = HTTPMock('localhost', 8000) fake_client_1 = get_fake_client(http_mock_1) fake_client_2 = get_fake_client(http_mock_2) http_mock_1.reset() http_mock_2.reset() http_mock_1.when('GET /test_mock1_get').reply(b'You tested a get', 201, times=FOREVER) http_mock_2.when('GET /test_mock2_get').reply(b'You tested a get', 200, times=FOREVER) assert_equals(201, fake_client_1.get(url="/test_mock1_get")[0].status) assert_equals(200, fake_client_2.get(url="/test_mock2_get")[0].status) # Check that they both 404 if used against the other url. assert_equals(404, fake_client_1.get(url="/test_mock2_get")[0].status) assert_equals(404, fake_client_2.get(url="/test_mock1_get")[0].status)
def test_check_single_model_access(tmpdir, test_data_path): mock = HTTPMock('localhost', 8000) mock.when('POST /login').reply( '"security-token"', headers={'Content-Type': 'application/json'}, times=FOREVER) mock.when('POST /access/list', body=".+\"test_user\".+", headers={ 'Authorization': 'Bearer security-token' }).reply('[true]', headers={'Content-Type': 'application/json'}, times=FOREVER) mock.when('POST /access/list', body=".+\"non_granted_user\".+", headers={ 'Authorization': 'Bearer security-token' }).reply('[false]', headers={'Content-Type': 'application/json'}, times=FOREVER) test_props = create_local_testdb(db_path=tmpdir, data_path=test_data_path / 'testdb', auth_url=mock.pretend_url) mp = ixmp.Platform(dbprops=test_props) mp.set_log_level('DEBUG') granted = mp.check_access('test_user', 'test_model') assert granted granted = mp.check_access('non_granted_user', 'test_model') assert not granted granted = mp.check_access('non_existing_user', 'test_model') assert not granted
def __init__(self, address=DEFAULT_ADDRESS, port=DEFAULT_PORT): self.address = address self.port = port self.http = HTTPMock(self.address, self.port) self.defaultHeaders = { 'Content-Type': 'text/xml; charset=UTF-8', }
def HttpMock(process_runner, jenkins): process = None with TemporaryDirectory() as dir: try: server_ip, server_port = target_facing_host_ip_and_free_port( jenkins.ip) process = process_runner( '{python} -m pretenders.server.server --host {ip} -p {port}'. format(python=sys.executable, ip=server_ip, port=str(server_port)), wait=False, cwd=dir) def mock_server_is_up(): try: r = requests.get('http://{ip}:{port}'.format( ip=server_ip, port=server_port)) if r.status_code == 200: return r else: return False except requests.exceptions.ConnectionError: return False wait_for(mock_server_is_up, 10) yield HTTPMock(server_ip, server_port) finally: if process: process.kill()
def test_multiple_mock_servers_only_see_their_presets_and_history(): first_mock = HTTPMock('localhost', 8000, timeout=30) second_mock = HTTPMock('localhost', 8000, timeout=30) first_mock_response_body = b"a 1st mock fake response" second_mock_response_body = b"a 2nd mock fake response" # Set up the two mocks to respond differently: # Set up first mock to respond with a 200 twice. for i in range(2): first_mock.when('POST /someplace').reply(first_mock_response_body, 200) second_mock.when('POST /someplace').reply(second_mock_response_body, 601) # create some fake clients that will post to the mock servers. first_fake_client = get_fake_client(first_mock) second_fake_client = get_fake_client(second_mock) # Make some requests using the clients # We alternate between the client calls, asserting that the responses match # those set up above. for i in range(2): post_body = "first_mock_{0}".format(i).encode() response = first_fake_client.post(url='/someplace', body=post_body) assert_response_equal(response, first_mock_response_body, 200) # Check that the historical values match those requested. request = first_mock.get_request(i) assert_equals(request.method, 'POST') assert_equals(request.url, '/someplace') assert_equals(request.body, post_body) for i in range(2): post_body = "second_mock_{0}".format(i).encode() response = second_fake_client.post(url='/someplace', body=post_body) assert_response_equal(response, second_mock_response_body, 601) # Check that the historical values match those requested. request = second_mock.get_request(i) assert_equals(request.method, 'POST') assert_equals(request.url, '/someplace') assert_equals(request.body, post_body)
def mock(server): # Create the mock server httpmock = HTTPMock("localhost", 8000) # Common responses for both tests httpmock.when("POST /login").reply( '"security-token"', headers={"Content-Type": "application/json"}, times=FOREVER) yield httpmock
def test_creating_second_mock_server_by_same_name_gives_original_server(): # Create 1 h1 = HTTPMock('localhost', 8000, timeout=5, name='duplicate_test') # Create another h2 = HTTPMock('localhost', 8000, timeout=5, name='duplicate_test_2') # Creation of one with a duplicate name should succeed. h3 = HTTPMock('localhost', 8000, name='duplicate_test') # Requests to h1 should be visible by h3. h2 should only be seen by it. get_fake_client(h1).get(url='/h1_get') get_fake_client(h2).get(url='/h2_get') get_fake_client(h3).get(url='/h3_get') # assert that the requests h1 and h3 requests can be seen via both mocks. assert_equals(h1.get_request(0).url, h3.get_request(0).url) assert_equals(h1.get_request(1).url, h3.get_request(1).url) assert_equals(h2.get_request(0).url, '/h2_get') h1.delete_mock() h2.delete_mock()
def setUpClass(cls: TestCase) -> None: super().setUpClass() cls.pretender_boss = subprocess.Popen( [ "python", "-m", "pretenders.server.server", "--host", "127.0.0.1", "--port", "8888" ], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) sleep(1) cls.mock_sentry = HTTPMock("127.0.0.1", 8888, name="mock_sentry")
def mock(): proc = Popen([ sys.executable, '-m', 'pretenders.server.server', '--host', 'localhost', '--port', '8000' ]) print('Mock server started with pid {}'.format(proc.pid)) # Wait for server to start up sleep(1) yield HTTPMock('localhost', 8000) proc.terminate() print('Mock server terminated')
def test_pretender_expired_add_preset_404(): """ Test that an expired pretender cannot have a preset assigned. This tries to test a race condition: The maintainer deletes expired Mocks. It does this by polling. Between polls, it is possible that a mock has expired and someone tries to apply a preset. In such a case, we should get a 404. """ http_mock = HTTPMock('localhost', 8000, timeout=0.1) time.sleep(0.3) preset = http_mock.when('POST /fred/test/one') assert_raises(ConfigurationError, preset.reply, b'You tested fred well', 200)
def test_clear_down_of_stale_mock_servers_taking_place(): #Test that stale mock servers are cleared out # TODO: Once the timeout specification can be dictated by the client # the sleep in this test can be reduced. http_mock = HTTPMock('localhost', 8000, timeout=5) pretender = http_mock.get_pretender() assert_equal(http_mock.pretend_access_point_id, pretender.name) # Sleep for enough time for the maintainer to have run and killed the # process. which means the total of STALE_DELETE_FREQUENCY + timeout # time.sleep(STALE_DELETE_FREQUENCY + pretender.timeout.seconds) assert_raises(ResourceNotFound, http_mock.get_pretender)
def test_clear_down_removes_history(): # Test that when we clear down a pretender, the history is removed. # Otherwise we end up slowly creeping up the memory usage! http_mock = HTTPMock('localhost', 8000, timeout=5) pretender = http_mock.get_pretender() pretender_client = get_fake_client(http_mock) pretender_client.get(url="/some_url") assert_equal(http_mock.get_request(0).url, '/some_url') time.sleep(STALE_DELETE_FREQUENCY + pretender.timeout.seconds + 1) assert_raises(ResourceNotFound, http_mock.get_pretender) # Check that there is no history now! req = http_mock.get_request(0) assert_equal(req, None)
def test_clear_down_only_happens_if_no_request_for_timeout_period(): # Test that stale mock servers are not cleared if they # recently made a request. # TODO: Once the timeout specification can be dictated by the client # the sleep in this test can be reduced. http_mock = HTTPMock('localhost', 8000, timeout=5) pretender = http_mock.get_pretender() timeout_server = pretender.timeout.seconds assert_equal(pretender.last_call, pretender.start) for i in range(3): # Sleep for a while, check that the server is still running and then # make a call to the mock server. time.sleep(timeout_server / 2) # Check that we are still running pretender = http_mock.get_pretender() # Make a call to the mock server. pretender_client = get_fake_client(http_mock) pretender_client.get(url="/some_url")
def test_get_mock_server_by_name(): http_mock = HTTPMock('localhost', 8000, timeout=5, name='fred') # Check that we are using the name path assert_equals(http_mock.pretend_access_point, "localhost:8000") assert_equals(http_mock.pretend_access_path, "/mockhttp/fred") # Set up a rule http_mock.when('POST /someplace').reply(b"something interesting", 200) # Perform a post from a pretend application fake_client = get_fake_client(http_mock) response, data = fake_client.post(url='/someplace', body="anything".encode()) # check the app would receive back the response from the rule we set up. assert_equals(response.status, 200) assert_equals(data, b'something interesting') # finally, check that we can look at the history via the http_mock. req = http_mock.get_request(0) assert_equals(req.method, 'POST') assert_equals(req.url, '/someplace') http_mock.delete_mock()
def __init__(self, host='localhost', port=8000): self._address = host, port self.server = HTTPMock(host, port)
"DepartureTime": "\\/Date(1538973840000-0500)\\/", "Description": "Fremont Av\\/Brklyn Ctr\\/Transit Ctr", "Gate": "", "Route": "5", "RouteDirection": "SOUTHBOUND", "Terminal": "M", "VehicleHeading": 0, "VehicleLatitude": 44.85284, "VehicleLongitude": -93.23808 } ]""", headers={'Content-Type': 'application/json'}, status=200) mock = HTTPMock('localhost', 55555) @pytest.fixture def cli_runner(): def runner(command, *arguments): p = subprocess.Popen([command] + list(arguments), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() return dict(returncode=p.returncode, stdout=stdout.decode('ASCII'), stderr=stderr.decode('ASCII')) return runner
def test_start_http_pretender(): """ Test that the http client continues to use the boss for mock calls. """ new_mock = HTTPMock('localhost', 8000) assert_true(new_mock.pretend_access_point == "localhost:8000")
import socket from nose.tools import assert_equals, assert_true, assert_raises import requests from pretenders.common.constants import FOREVER from pretenders.common.exceptions import ConfigurationError from pretenders.client.http import HTTPMock from . import get_fake_client http_mock = HTTPMock('localhost', 8000) fake_client = get_fake_client(http_mock) def add_test_preset(rule='POST /fred/test/one', body=b'You tested fred well', status=200): http_mock.when(rule).reply(body, status) def test_configure_request_and_check_values(): "Requires a running pretender.http.server instance" http_mock.reset() add_test_preset() response, data = fake_client.post(url='/fred/test/one') assert_equals(response.status, 200) assert_equals(data, b'You tested fred well') request = http_mock.get_request(0) assert_equals(request.method, 'POST')
def test_pretend_url(): "Test that pretend url works" h1 = HTTPMock('localhost', 8000, timeout=5, name='some_mock') assert_equals(h1.pretend_url, 'http://localhost:8000/mockhttp/some_mock')
def test_get_response_when_none_queued(): h1 = HTTPMock('localhost', 8000, timeout=5, name='existent') THIRD_PARTY_ADDRESS = 'http://localhost:8000/mockhttp/existent' resp = requests.get(THIRD_PARTY_ADDRESS + '/hello') assert_equals(resp.status_code, 404)
def test_can_create_a_forever_mock(): # Just test that we can actually create one of these chaps. # We won't actually check if it is still around in an eternity. mock = HTTPMock('localhost', 8000, timeout=FOREVER) assert_equal(FOREVER, mock.get_pretender().timeout)