Python httmock.response() Examples

The following are 30 code examples of httmock.response(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module httmock , or try the search function .
Example #1
Source File: test_client.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_esipy_expired_header_noetag(self):
        def check_etag(url, request):
            self.assertNotIn('If-None-Match', request.headers)
            return httmock.response(
                status_code=200,
                content={
                    "players": 29597,
                    "server_version": "1313143",
                    "start_time": "2018-05-20T11:04:30Z"
                }
            )

        operation = self.app.op['get_status']()

        with httmock.HTTMock(eve_status_noetag):
            res = self.client.request(operation)
            self.assertEqual(res.data.server_version, "1313143")

        time.sleep(2)

        with httmock.HTTMock(check_etag):
            res = self.client.request(operation)
            self.assertEqual(res.data.server_version, "1313143") 
Example #2
Source File: test_session.py    From wechatpy with MIT License 6 votes vote down vote up
def wechat_api_mock(url, request):
    path = url.path.replace("/cgi-bin/", "").replace("/", "_")
    if path.startswith("_"):
        path = path[1:]
    res_file = os.path.join(_FIXTURE_PATH, f"{path}.json")
    content = {
        "errcode": 99999,
        "errmsg": f"can not find fixture {res_file}",
    }
    headers = {"Content-Type": "application/json"}
    try:
        with open(res_file, "rb") as f:
            content = json.loads(f.read().decode("utf-8"))
    except (IOError, ValueError) as e:
        print(e)
    return response(200, content, headers, request=request) 
Example #3
Source File: test_payment.py    From wechatpy with MIT License 6 votes vote down vote up
def wechat_api_mock(url, request):
    path = (url.path[1:] if url.path.startswith("/") else url.path).replace("/", "_")
    res_file = os.path.join(_FIXTURE_PATH, f"{path}.json")
    content = {
        "errcode": 99999,
        "errmsg": f"can not find fixture {res_file}",
    }
    headers = {"Content-Type": "application/json"}
    try:
        with open(res_file, "rb") as f:
            content = json.loads(f.read().decode("utf-8"))
    except (IOError, ValueError):
        pass
    content_sign = content.pop("sign", "")
    content_xml = dict_to_xml(content, content_sign)
    return response(200, content_xml, headers, request=request) 
Example #4
Source File: test_client.py    From wechatpy with MIT License 6 votes vote down vote up
def test_iter_tag_users(self):
        @urlmatch(netloc=r"(.*\.)?api\.weixin\.qq\.com$", path=r".*user/tag/get")
        def next_openid_mock(url, request):
            """伪造第二页的请求"""
            data = json.loads(request.body.decode())
            if not data.get("next_openid"):
                return wechat_api_mock(url, request)

            # 根据拿到的第二页请求响应 是没有data和next_openid的
            content = {"count": 0}
            headers = {"Content-Type": "application/json"}
            return response(200, content, headers, request=request)

        with HTTMock(next_openid_mock, wechat_api_mock):
            users = list(self.client.tag.iter_tag_users(101))
            self.assertEqual(2, len(users))
            self.assertIn("OPENID1", users)
            self.assertIn("OPENID2", users) 
Example #5
Source File: test_main.py    From satori with Apache License 2.0 6 votes vote down vote up
def test_process_single_event(self):
        from main import process_single_event
        from httmock import response, HTTMock, urlmatch

        @urlmatch(netloc=r'(api.nexmo.com|yunpian.com)')
        def response_content(url, request):
            print(url)
            headers = {'Content-Type': 'application/json'}
            if url.netloc == 'api.nexmo.com':
                return response(200, '{}', headers)
            elif url.netloc == 'yunpian.com':
                return response(200, '{"code": 0}', headers)
            else:
                raise Exception('Meh!')

        with HTTMock(response_content):
            process_single_event(alarm_example) 
Example #6
Source File: test_client.py    From wechatpy with MIT License 6 votes vote down vote up
def wechat_api_mock(url, request):
    path = url.path.replace("/cgi-bin/", "").replace("/", "_")
    if path.startswith("_"):
        path = path[1:]
    res_file = os.path.join(_FIXTURE_PATH, f"{path}.json")
    content = {
        "errcode": 99999,
        "errmsg": f"can not find fixture {res_file}",
    }
    headers = {"Content-Type": "application/json"}
    try:
        with open(res_file, "rb") as f:
            content = json.loads(f.read().decode("utf-8"))
    except (IOError, ValueError) as e:
        content["errmsg"] = f"Loads fixture {res_file} failed, error: {e}"
    return response(200, content, headers, request=request) 
Example #7
Source File: util_tests.py    From evesrp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def foxfour_esi(url, request):
    resp = {
        "killmail_id": 30290604,
        "killmail_time": "2013-05-05T18:09:00Z",
        "victim": {
            "damage_taken": 570,
            "ship_type_id": 670,
            "character_id": 92168909,
            "corporation_id": 109299958,
            "alliance_id": 434243723,
        },
        # Skipping the items array as it's not used
        "items": None,
        # Ditto for attackers
        "attackers": None,
        "solar_system_id": 30002062
    }
    return response(content=json.dumps(resp)) 
Example #8
Source File: mocked_network.py    From prometheus-api-client-python with MIT License 6 votes vote down vote up
def mock_response(
        content, url=None, path='', headers=None, response_url=None, status_code=200, cookies=None, func=None
):
    """Universal handler for specify mocks inplace"""
    if func is None:

        def mocked(url, request):
            mock = response(
                status_code=status_code, content=content, request=request, headers=headers
            )
            if cookies:
                mock.cookies = cookies
            mock.url = response_url if response_url else url
            return mock

    else:
        mocked = func

    if url:
        parsed = urlparse(url)
        return urlmatch(netloc=parsed.netloc, path=parsed.path)(func=mocked)
    elif path:
        return urlmatch(path=path)(func=mocked)
    else:
        return all_requests(func=mocked) 
Example #9
Source File: test_pycrest.py    From PyCrest with MIT License 6 votes vote down vote up
def test_cache_hit(self):
        @httmock.all_requests
        def prime_cache(url, request):
            headers = {'content-type': 'application/json',
                       'Cache-Control': 'max-age=300;'}
            return httmock.response(200, '{}'.encode('utf-8'), headers)

        with httmock.HTTMock(prime_cache):
            self.assertEqual(self.api()._dict, {})

        @httmock.all_requests
        def cached_request(url, request):
            raise RuntimeError(
                'A cached request should never yield a HTTP request')

        with httmock.HTTMock(cached_request):
            self.api._data = None
            self.assertEqual(self.api()._dict, {}) 
Example #10
Source File: test_pycrest.py    From PyCrest with MIT License 6 votes vote down vote up
def test_cache_invalidate(self):
        @httmock.all_requests
        def prime_cache(url, request):
            headers = {'content-type': 'application/json',
                       'Cache-Control': 'max-age=300;'}
            return httmock.response(
                200, '{"cached": true}'.encode('utf-8'), headers)

        # Prime cache and force the expiration
        with httmock.HTTMock(prime_cache):
            self.api()
            # Nuke _data so the .get() is actually being called the next call
            self.api._data = None
            for key in self.api.cache._dict:
                # Make sure the cache is concidered 'expired'
                self.api.cache._dict[key]['expires'] = 0

        @httmock.all_requests
        def expired_request(url, request):
            self.assertTrue(isinstance(request, PreparedRequest))
            return httmock.response(200, '{}'.encode('utf-8'))

        with httmock.HTTMock(expired_request):
            self.api() 
Example #11
Source File: test_k8saccessor.py    From quay with Apache License 2.0 6 votes vote down vote up
def test_get_qe_deployments(kube_config, expected_api, expected_query):
    config = KubernetesConfig(**kube_config)
    url_hit = [False]

    @urlmatch(netloc=r"www.customhost.com")
    def handler(request, _):
        assert request.path == expected_api
        assert request.query == expected_query
        url_hit[0] = True
        return response(200, "{}")

    with HTTMock(handler):
        KubernetesAccessorSingleton._instance = None
        assert KubernetesAccessorSingleton.get_instance(config).get_qe_deployments() is not None

    assert url_hit[0] 
Example #12
Source File: test_basic.py    From wechat-python-sdk with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def wechat_api_mock(url, request):
    path = url.path.replace('/cgi-bin/', '').replace('/', '_')
    if path.startswith('_'):
        path = path[1:]
    res_file = os.path.join(FIXTURE_PATH, '%s.json' % path)
    content = {
        'errcode': 99999,
        'errmsg': 'can not find fixture %s' % res_file,
    }
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        with open(res_file, 'rb') as f:
            content = json.loads(f.read().decode('utf-8'))
    except (IOError, ValueError) as e:
        print(e)
    return response(200, content, headers, request=request) 
Example #13
Source File: utils.py    From wechat-python-sdk with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def api_weixin_mock(url, request):
    path = url.path.replace('/cgi-bin/', '').replace('/', '_')
    if path.startswith('_'):
        path = path[1:]
    res_file = os.path.join(FIXTURE_PATH, '%s.json' % path)
    content = {
        'errcode': 99999,
        'errmsg': 'can not find fixture %s' % res_file,
    }
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        with open(res_file, 'rb') as f:
            content = json.loads(f.read().decode('utf-8'))
    except (IOError, ValueError) as e:
        print(e)
    return response(200, content, headers, request=request) 
Example #14
Source File: unittest_util.py    From aliyun-datahub-sdk-python with Apache License 2.0 6 votes vote down vote up
def gen_pb_mock_api(check):
    @urlmatch(netloc=r'(.*\.)?endpoint')
    def datahub_pb_api_mock(url, request):
        check(request)
        path = url.path.replace('/', '.')[1:]
        res_file = os.path.join(_FIXTURE_PATH, '%s.bin' % path)
        status_code = 200
        content = {
        }
        headers = {
            'Content-Type': 'application/x-protobuf',
            'x-datahub-request-id': 0
        }
        try:
            with open(res_file, 'rb') as f:
                content = f.read()
        except (IOError, InvalidParameterException) as e:
            content['ErrorMessage'] = 'Loads fixture %s failed, error: %s' % (res_file, e)
        return response(status_code, content, headers, request=request)

    return datahub_pb_api_mock 
Example #15
Source File: api_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_200_returns_response_body(self):
        @httmock.all_requests
        def response_content(_url_unused, request):
            headers = {
                'X-Consul-Index': 4,
                'X-Consul-Knownleader': 'true',
                'X-Consul-Lastcontact': 0,
                'Date': 'Fri, 19 Dec 2014 20:44:28 GMT',
                'Content-Length': 13,
                'Content-Type': 'application/json'
            }
            content = b'{"consul": []}'
            return httmock.response(200, content, headers, None, 0, request)

        with httmock.HTTMock(response_content):
            values = self.endpoint._get([str(uuid.uuid4())])
            self.assertEqual(values, {'consul': []}) 
Example #16
Source File: api_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_list_200_returns_response_body(self):
        @httmock.all_requests
        def response_content(_url_unused, request):
            headers = {
                'X-Consul-Index': 4,
                'X-Consul-Knownleader': 'true',
                'X-Consul-Lastcontact': 0,
                'Date': 'Fri, 19 Dec 2014 20:44:28 GMT',
                'Content-Length': 13,
                'Content-Type': 'application/json'
            }
            content = b'{"consul": []}'
            return httmock.response(200, content, headers, None, 0, request)

        with httmock.HTTMock(response_content):
            values = self.endpoint._get_list([str(uuid.uuid4())])
            self.assertEqual(values, [{'consul': []}]) 
Example #17
Source File: mock.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def oauth_token(url, request):
    """ Mock endpoint to get token (auth / refresh) """
    if 'fail_test' in request.body:
        return httmock.response(
            status_code=400,
            content={'message': 'Failed successfuly'}
        )

    if 'no_refresh' in request.body:
        return httmock.response(
            status_code=200,
            content={
                'access_token': 'access_token',
                'expires_in': 1200,
            }
        )

    return httmock.response(
        status_code=200,
        content={
            'access_token': 'access_token',
            'expires_in': 1200,
            'refresh_token': 'refresh_token'
        }
    ) 
Example #18
Source File: mock.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def public_incursion(url, request):
    """ Mock endpoint for incursion.
    Public endpoint
    """
    return httmock.response(
        headers={'Expires': make_expire_time_str()},
        status_code=200,
        content=[
            {
                "type": "Incursion",
                "state": "mobilizing",
                "staging_solar_system_id": 30003893,
                "constellation_id": 20000568,
                "infested_solar_systems": [
                    30003888,
                ],
                "has_boss": True,
                "faction_id": 500019,
                "influence": 1
            }
        ]
    ) 
Example #19
Source File: mock.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def public_incursion_no_expires_second(url, request):
    """ Mock endpoint for incursion.
    Public endpoint without cache
    """
    return httmock.response(
        status_code=200,
        content=[
            {
                "type": "Incursion",
                "state": "established",
                "staging_solar_system_id": 30003893,
                "constellation_id": 20000568,
                "infested_solar_systems": [
                    30003888,
                ],
                "has_boss": True,
                "faction_id": 500019,
                "influence": 1
            }
        ]
    ) 
Example #20
Source File: unittest_util.py    From aliyun-datahub-sdk-python with Apache License 2.0 6 votes vote down vote up
def gen_mock_api(check):
    @urlmatch(netloc=r'(.*\.)?endpoint')
    def datahub_api_mock(url, request):
        check(request)
        path = url.path.replace('/', '.')[1:]
        res_file = os.path.join(_FIXTURE_PATH, '%s.json' % path)
        status_code = 200
        content = {
        }
        headers = {
            'Content-Type': 'application/json',
            'x-datahub-request-id': 0
        }
        try:
            with open(res_file, 'rb') as f:
                content = json.loads(f.read().decode('utf-8'))
                if 'ErrorCode' in content:
                    status_code = 500
        except (IOError, ValueError) as e:
            content['ErrorMessage'] = 'Loads fixture %s failed, error: %s' % (res_file, e)
        return response(status_code, content, headers, request=request)

    return datahub_api_mock 
Example #21
Source File: mock.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def eve_status(url, request):
    """ Mock endpoint for character location.
    Authed endpoint that check for auth
    """
    return httmock.response(
        headers={
            'Expires': make_expire_time_str(1),
            'Etag': '"esipy_test_etag_status"'
        },
        status_code=200,
        content={
            "players": 29597,
            "server_version": "1313143",
            "start_time": "2018-05-20T11:04:30Z"
        }
    ) 
Example #22
Source File: mock.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def post_universe_id(url, request):
    """ Mock endpoint for character location.
    Authed endpoint that check for auth
    """
    return httmock.response(
        headers={'Expires': make_expire_time_str()},
        status_code=200,
        content={
            "characters": [
                {
                    "id": 123456789,
                    "name": "Foo"
                }
            ]
        }
    ) 
Example #23
Source File: mock.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def public_incursion_expired(url, request):
    """ Mock endpoint for incursion.
    Public endpoint returning Expires value in the past
    """
    return httmock.response(
        headers={'Expires': make_expired_time_str()},
        status_code=200,
        content=[
            {
                "type": "Incursion",
                "state": "mobilizing",
                "staging_solar_system_id": 30003893,
                "constellation_id": 20000568,
                "infested_solar_systems": [
                    30003888,
                ],
                "has_boss": True,
                "faction_id": 500019,
                "influence": 1
            }
        ]
    ) 
Example #24
Source File: mock.py    From EsiPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def meta_swagger(url, request):
    """ Mock endpoint for incursion.
    Public endpoint returning Expires value in the past
    """
    if request.headers.get('etag') == '"esipyetag"':
        return httmock.response(
            headers={
                'Expires': make_expire_time_str(),
                'Etag': '"esipyetag"'
            },
            status_code=304,
            content={}
        )

    swagger_json = open('test/resources/meta_swagger.json')
    resp = httmock.response(
        headers={
            'Expires': make_expire_time_str(),
            'Etag': '"esipyetag"'
        },
        status_code=200,
        content=swagger_json.read()
    )
    swagger_json.close()
    return resp 
Example #25
Source File: test_k8saccessor.py    From quay with Apache License 2.0 6 votes vote down vote up
def test_cycle_qe_deployments(kube_config, deployment_names, expected_api_hits):
    KubernetesAccessorSingleton._instance = None

    config = KubernetesConfig(**kube_config)
    url_hit = [False] * len(expected_api_hits)
    i = [0]

    @urlmatch(netloc=r"www.customhost.com", method="PATCH")
    def handler(request, _):
        assert request.path == expected_api_hits[i[0]]
        url_hit[i[0]] = True
        i[0] += 1
        return response(200, "{}")

    with HTTMock(handler):
        KubernetesAccessorSingleton.get_instance(config).cycle_qe_deployments(deployment_names)

    assert all(url_hit) 
Example #26
Source File: test_payment.py    From wechatpy with MIT License 5 votes vote down vote up
def test_apply_signing(self):
        response = self.client.withhold.apply_signing(
            plan_id="t1234", contract_code="w1111", contract_display_account="测试", notify_url="",
        )
        self.assertIn("base_url", response)
        self.assertIn("data", response)
        self.assertNotIn("nonce_str", response["data"]) 
Example #27
Source File: acl_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bootstrap_success(self):
        expectation = self.uuidv4()

        @httmock.all_requests
        def response_content(_url_unused, request):
            return httmock.response(
                200, json.dumps({'ID': expectation}), {}, None, 0, request)

        with httmock.HTTMock(response_content):
            result = self.consul.acl.bootstrap()

        self.assertEqual(result, expectation) 
Example #28
Source File: api_tests.py    From consulate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_list_404_returns_empty_list(self):
        @httmock.all_requests
        def response_content(_url_unused, request):
            headers = {
                'content-length': 0,
                'content-type': 'text/plain; charset=utf-8'
            }
            return httmock.response(404, None, headers, None, 0, request)

        with httmock.HTTMock(response_content):
            values = self.endpoint._get_list([str(uuid.uuid4())])
            self.assertEqual(values, []) 
Example #29
Source File: test_payment.py    From wechatpy with MIT License 5 votes vote down vote up
def test_query_order(self):
        with HTTMock(wechat_api_mock):
            response = self.client.withhold.query_order(out_trade_no="217752501201407033233368018")
            self.assertEqual(response["result_code"], "SUCCESS") 
Example #30
Source File: test_payment.py    From wechatpy with MIT License 5 votes vote down vote up
def test_query_signing(self):
        with HTTMock(wechat_api_mock):
            response = self.client.withhold.query_signing(contract_id="test1234")
            self.assertEqual(response["result_code"], "SUCCESS")