Exemplo n.º 1
0
 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',
     }
Exemplo n.º 2
0
def get_mock():
    mock = HTTPMock('127.0.0.1', 50000)

    mock.when('GET /blockchain/memberships/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\
        .reply(body=bytes(json.dumps(bma_memberships_empty_array), "utf-8"),
                times=FOREVER,
                headers={'Content-Type': 'application/json'})

    return mock
Exemplo n.º 3
0
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
Exemplo n.º 4
0
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
Exemplo n.º 5
0
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)
Exemplo n.º 6
0
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_in_secs + 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)
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
class NapiprojektMock(object):

    DEFAULT_ADDRESS = 'napiserver'
    DEFAULT_PORT = 8000

    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 getUrl(self):
        return self.http.pretend_url

    def getRequest(self, n=0):
        return self.http.get_request(n)

    def programPlainRequest(self, blob=None, status=None, times=1):

        body = None
        data = blob.getData() if blob else ''
        if not status:
            status = 200 if blob else 404

        self.http.when('GET /unit_napisy/dl.php',
                       body=body).reply(data,
                                        status=status,
                                        headers=self.defaultHeaders,
                                        times=times)

    def programXmlRequest(self,
                          media,
                          subtitles=None,
                          cover=None,
                          movieDetails=None,
                          times=1):
        status = 200
        # pretenders matches body from the beginning of the string - due to
        # that body filtering at the moment is out of question
        body = None
        self.http.when('POST /api/api-napiprojekt3.php',
                       body=body).reply(xml_result.XmlResult(
                           subtitles, cover, movieDetails).toString(),
                                        status=status,
                                        headers=self.defaultHeaders,
                                        times=times)
Exemplo n.º 9
0
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()
Exemplo n.º 10
0
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
    )
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
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)
Exemplo n.º 13
0
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()
Exemplo n.º 14
0
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")
Exemplo n.º 15
0
 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")
Exemplo n.º 16
0
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')
Exemplo n.º 17
0
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)
Exemplo n.º 18
0
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)
Exemplo n.º 19
0
class MockServer:
    def __init__(self, host='localhost', port=8000):
        self._address = host, port
        self.server = HTTPMock(host, port)

    def server_address(self):
        return self._address

    def setup_normal(self):
        self.server.reset()

        # FIXME: Endpoint is a placeholder!
        self.server.when("GET /important_data").reply('OK', status=200, times=FOREVER)

    def setup_error(self):
        self.server.reset()

        # FIXME: Endpoint is a placeholder!
        self.server.when("GET /important_data").reply('ERROR', status=500, times=FOREVER)
Exemplo n.º 20
0
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()
Exemplo n.º 21
0
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 = 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(response.read(), 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()
Exemplo n.º 22
0
 def __init__(self, host='localhost', port=8000):
     self._address = host, port
     self.server = HTTPMock(host, port)
Exemplo n.º 23
0
def get_mock():
    mock = HTTPMock('127.0.0.1', 50000)

    mock.when('GET /network/peering') \
        .reply(body=bytes(json.dumps(bma_peering), "utf-8"),
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/parameters') \
        .reply(body=bytes(json.dumps(bma_parameters), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/with/[UD|ud]') \
        .reply(body=bytes(json.dumps(bma_with_ud), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/current') \
        .reply(body=bytes(json.dumps(bma_blockchain_current), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/block/0') \
        .reply(body=bytes(json.dumps(bma_blockchain_0), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/block/15') \
        .reply(body=bytes(json.dumps(bma_blockchain_current), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /tx/history/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ/blocks/0/99') \
        .reply(body=bytes(json.dumps(bma_txhistory_john), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /tx/sources/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \
        .reply(body=bytes(json.dumps(bma_txsources_john), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /ud/history/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \
        .reply(body=bytes(json.dumps(bma_udhistory_john), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \
        .reply(body=bytes(json.dumps(bma_certifiers_of_john), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/certified-by/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \
        .reply(body=bytes(json.dumps(bma_certified_by_john), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/john') \
        .reply(body=bytes(json.dumps(bma_lookup_john), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \
        .reply(body=bytes(json.dumps(bma_lookup_john), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/doe') \
        .reply(body=bytes(json.dumps(bma_lookup_doe), "utf-8"),
               status=200,
               times=1,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn') \
        .reply(body=bytes(json.dumps(bma_lookup_doe), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/memberships/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \
        .reply(body=bytes(json.dumps(bma_membership_john), "utf-8"),
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/certifiers-of/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn') \
        .reply(body=b"No member matching this pubkey or uid",
               status=404,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/memberships/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn') \
        .reply(body=b"No member matching this pubkey or uid",
               status=404,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    mock.when('POST /tx/process') \
        .reply(body=b"",
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    return mock
Exemplo n.º 24
0
def get_mock():
    mock = HTTPMock('127.0.0.1', 50000)

    mock.when('GET /network/peering')\
        .reply(body=bma_peering,
                times=FOREVER,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/block/0')\
        .reply(body=b"Block not found",
               status=404,
               times=FOREVER,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/current')\
        .reply(body=b"Block not found",
               status=404,
               times=FOREVER,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\
            .reply(body=b"No member matching this pubkey or uid",
                status=404,
                times=1,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/john')\
            .reply(body=bma_lookup_test_john,
                status=200,
                times=1,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\
            .reply(body=bma_lookup_test_john,
                status=200,
                times=1,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/doe')\
            .reply(body=bma_lookup_test_doe,
                status=200,
                times=1,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn')\
            .reply(body=bma_lookup_test_doe,
                status=200,
                times=1,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/patrick')\
            .reply(body=bma_lookup_test_patrick,
                status=200,
                times=1,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn')\
            .reply(body=bma_lookup_test_patrick,
                status=200,
                times=1,
                headers={'Content-Type': 'application/json'})

    mock.when('POST /wot/add.*')\
        .reply(body=b"{}",
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})

    return mock
Exemplo n.º 25
0
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)
Exemplo n.º 26
0
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")
Exemplo n.º 27
0
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')
Exemplo n.º 28
0
        "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
Exemplo n.º 29
0
        with self.vcr.use_cassette(path_to_cassette):
            resp = requests.delete(url_to_open)
        return resp

    def post_with_cassette(self, path_to_cassette, url_to_open, body):
        with self.vcr.use_cassette(path_to_cassette):
            resp = requests.post(url_to_open, body)
        return resp

    def patch_with_cassette(self, path_to_cassette, url_to_open, body):
        with self.vcr.use_cassette(path_to_cassette):
            resp = requests.patch(url_to_open, body)
        return resp


mock = HTTPMock('localhost', 8888, timeout=20, name="zingfit_api")

mock.reset()
mock.when("GET /important_data$").reply(bytes('{"account": "10000", "outstanding": "10.00"}'), status=200,
                                        times=FOREVER)
mock.when("GET /important_data2$").reply(bytes('ERROR'), status=500, times=FOREVER)
mock.when("GET /important_data3$").reply(bytes('OK'), status=200, times=FOREVER)
mock.when("POST /important_data4$", body='{"account": "10000", "outstanding": "10.00"}').reply(bytes('{"id": "10"}'),
                                                                                               status=200,
                                                                                               times=FOREVER)

start_time = time.time()
vcr_new = VCR()
# res = open_with_cassette(vcr_new, 'iana.json', 'http://www.iana.org/domains/reserved')
# assert 'Example domains' in res
print("--- %s seconds ---" % (time.time() - start_time))
Exemplo n.º 30
0
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)
Exemplo n.º 31
0
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()
Exemplo n.º 32
0
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')
Exemplo n.º 33
0
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)
Exemplo n.º 34
0
def get_mock():
    mock = HTTPMock('127.0.0.1', 50000)

    mock.when('GET /network/peering')\
        .reply(body=bma_peering,
                times=FOREVER,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/block/0')\
        .reply(body=b"Block not found",
               status=404,
               times=FOREVER,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /blockchain/current')\
        .reply(body=b"Block not found",
               status=404,
               times=FOREVER,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\
            .reply(body=b"No member matching this pubkey or uid",
                status=404,
                times=1,
                headers={'Content-Type': 'application/json'})

    mock.when('GET /wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\
            .reply(body=b"No member matching this pubkey or uid",
                status=404,
                times=1,
                headers={'Content-Type': 'application/json'})

    mock.when('POST /wot/add.*')\
        .reply(body=bma_wot_add,
               status=200,
               times=FOREVER,
               headers={'Content-Type': 'application/json'})
    return mock