async def test_nested_global_contextmanager(client): with respx.mock: get_request = respx.get("https://foo/bar/", status_code=202) with respx.mock: post_request = respx.post("https://foo/bar/", status_code=201) response = await client.get("https://foo/bar/") assert get_request.called is True assert response.status_code == 202 assert respx.stats.call_count == 1 response = await client.post("https://foo/bar/") assert post_request.called is True assert response.status_code == 201 assert respx.stats.call_count == 2
async def test_get_without_id_mixin(self, gl): class M(GetWithoutIdMixin, FakeManager): pass request = respx.get( "http://localhost/api/v4/tests", headers={"Content-Type": "application/json"}, content='{"foo": "bar"}', status_code=codes.OK, ) mgr = M(gl) obj = await mgr.get() assert isinstance(obj, FakeObject) assert obj.foo == "bar" assert not hasattr(obj, "id")
async def test_refresh_mixin(self, gl): class O(RefreshMixin, FakeObject): pass request = respx.get( "http://localhost/api/v4/tests/42", headers={"Content-Type": "application/json"}, content={"id": 42, "foo": "bar"}, status_code=codes.OK, ) mgr = FakeManager(gl) obj = O(mgr, {"id": 42}) res = await obj.refresh() assert res is None assert obj.foo == "bar" assert obj.id == 42
async def test_asgi(): async with respx.mock: async with httpx.AsyncClient(app="fake-asgi") as client: url = "https://foo.bar/" jzon = {"status": "ok"} headers = {"X-Foo": "bar"} request = respx.get(url) % dict( status_code=202, headers=headers, json=jzon) response = await client.get(url) assert request.called is True assert response.status_code == 202 assert response.headers == httpx.Headers({ "Content-Type": "application/json", "Content-Length": "16", **headers }) assert response.json() == {"status": "ok"}
async def test_retrieve_many(self): """Should retrieve provisioning profiles from API.""" expected = [{ '_id': 'id', 'name': 'name', 'version': 4, 'status': 'active' }] rsps = respx.get(f'{PROVISIONING_API_URL}/users/current/provisioning-profiles') \ .mock(return_value=Response(200, json=expected)) profiles = await provisioning_client.get_provisioning_profiles( 5, 'active') assert rsps.calls[0].request.url == \ f'{PROVISIONING_API_URL}/users/current/provisioning-profiles?version=5&status=active' assert rsps.calls[0].request.headers[ 'auth-token'] == 'header.payload.sign' assert profiles == expected
def test_respond(): with respx.mock: route = respx.get("https://foo.bar/").respond( content="<apa>lundberg</apa>", content_type="text/xml", http_version="HTTP/2", ) response = httpx.get("https://foo.bar/") assert response.status_code == 200 assert response.headers.get("Content-Type") == "text/xml" assert response.http_version == "HTTP/2" with pytest.raises(TypeError, match="content can only be"): route.respond(content={}) with pytest.raises(TypeError, match="content can only be"): route.respond(content=Exception())
def test_size_page(): target_url_1 = "http://perdu.com/" target_url_2 = "http://perdu2.com/" target_url_3 = "http://perdu3.com/" page_headers_1 = [ ('content-length', '229,23'), ] page_headers_2 = [ ('content-length', '240;23'), ] page_content = """ <html> <head> <title>Test</title> </head> <body> </body> </html> """ respx.get(target_url_1).mock(return_value=httpx.Response( 200, text=page_content, headers=page_headers_1, )) resp = httpx.get(target_url_1, follow_redirects=False) page = Page(resp) assert page.size == 229 respx.get(target_url_2).mock(return_value=httpx.Response( 200, text=page_content, headers=page_headers_2, )) resp = httpx.get(target_url_2, follow_redirects=False) page = Page(resp) assert page.size == 240 respx.get(target_url_3).mock(return_value=httpx.Response( 200, text=page_content, headers=(), )) resp = httpx.get(target_url_3, follow_redirects=False) page = Page(resp) assert page.size == 122
def test_secure_req(self): respx.get("http://secure.page.edu.cn", content=httpx.ConnectionClosed()) respx.get("http://secure.page.edu.cn:8889", content=httpx.ConnectionClosed()) respx.get("https://fail.page.edu.cn", content=httpx.ConnectionClosed()) respx.get("https://secure.page.edu.cn") sess = Session() resp = sess._secure_req(partial(httpx.get, "http://secure.page.edu.cn")) assert resp.status_code == 200 resp = sess._secure_req( partial(httpx.get, "http://secure.page.edu.cn:8889")) assert resp.status_code == 200 with pytest.raises(httpx.exceptions.NetworkError): sess._secure_req(partial(httpx.get, "https://fail.page.edu.cn"))
def test_redirection_url_page(): target_url_1 = "http://perdu.com/" target_url_2 = "http://perdu2.com/" target_url_3 = "http://perdu3.com/" page_content = """ <html> <head> <title>Foobar</title> </head> <body> </body> </html> """ respx.get(target_url_1).mock(return_value=httpx.Response( 200, text=page_content, )) respx.get(target_url_2).mock(return_value=httpx.Response( 302, text=page_content, headers=[("Location", "index.html")], )) respx.get(target_url_3).mock(return_value=httpx.Response( 302, text=page_content, headers=[("Location", "http://perdu3.com/")], )) # No redirect resp = httpx.get(target_url_1, follow_redirects=False) page = Page(resp) assert page.redirection_url == "" assert page.is_directory_redirection is False # Redirection resp = httpx.get(target_url_2, follow_redirects=False) page = Page(resp) assert page.redirection_url == "http://perdu2.com/index.html" assert page.is_directory_redirection is False # Same url resp = httpx.get(target_url_3, follow_redirects=False) page = Page(resp) assert page.redirection_url == "http://perdu3.com/" assert page.is_directory_redirection is True
async def test_fetch_new(ff14, dummy_user_subinfo, ff14_newdata_json_0, ff14_newdata_json_1): newdata = respx.get( "https://ff.web.sdo.com/inc/newdata.ashx?url=List?gameCode=ff&category=5309,5310,5311,5312,5313&pageIndex=0&pageSize=5" ) newdata.mock(return_value=Response(200, json=ff14_newdata_json_0)) target = "" res = await ff14.fetch_new_post(target, [dummy_user_subinfo]) assert newdata.called assert len(res) == 0 newdata.mock(return_value=Response(200, json=ff14_newdata_json_1)) res = await ff14.fetch_new_post(target, [dummy_user_subinfo]) assert newdata.called post = res[0][1][0] assert post.target_type == "ff14" assert post.text == "最终幻想XIV 银质坠饰 <友谊永存>预售开启!\n最终幻想XIV 银质坠饰 <友谊永存>现已开启预售!" assert post.url == "https://ff.web.sdo.com/web8/index.html#/newstab/newscont/336870" assert post.target_name == "最终幻想XIV官方公告"
async def test_send_with_render( arknights, dummy_user_subinfo, arknights_list_0, arknights_list_1, monster_siren_list_0, monster_siren_list_1, ): ak_list_router = respx.get( "https://ak-conf.hypergryph.com/config/prod/announce_meta/IOS/announcement.meta.json" ) detail_router = respx.get( "https://ak.hycdn.cn/announce/IOS/announcement/805_1640074952.html") version_router = respx.get( "https://ak-conf.hypergryph.com/config/prod/official/IOS/version") preannouncement_router = respx.get( "https://ak-conf.hypergryph.com/config/prod/announce_meta/IOS/preannouncement.meta.json" ) monster_siren_router = respx.get( "https://monster-siren.hypergryph.com/api/news") terra_list = respx.get( "https://terra-historicus.hypergryph.com/api/recentUpdate") ak_list_router.mock(return_value=Response(200, json=arknights_list_0)) detail_router.mock( return_value=Response(200, text=get_file("arknights-detail-805"))) version_router.mock( return_value=Response(200, json=get_json("arknights-version-0.json"))) preannouncement_router.mock( return_value=Response(200, json=get_json("arknights-pre-0.json"))) monster_siren_router.mock( return_value=Response(200, json=monster_siren_list_0)) terra_list.mock( return_value=Response(200, json=get_json("terra-hist-0.json"))) target = "" res = await arknights.fetch_new_post(target, [dummy_user_subinfo]) assert ak_list_router.called assert len(res) == 0 assert not detail_router.called mock_data = arknights_list_1 ak_list_router.mock(return_value=Response(200, json=mock_data)) res3 = await arknights.fetch_new_post(target, [dummy_user_subinfo]) assert len(res3[0][1]) == 1 assert detail_router.called post = res3[0][1][0] assert post.target_type == "arknights" assert post.text == "" assert post.url == "" assert post.target_name == "明日方舟游戏内公告" assert len(post.pics) == 1 # assert(post.pics == ['https://ak-fs.hypergryph.com/announce/images/20210623/e6f49aeb9547a2278678368a43b95b07.jpg']) print(res3[0][1]) r = await post.generate_messages()
async def test_with_5_0_49_firmware(): """Verify with 5.0.49 firmware.""" version = "5.0.49" respx.get("/info.xml").mock(return_value=Response(200, text="")) respx.get("/production.json").mock( return_value=Response(200, json=_load_json_fixture(version, "production.json")) ) respx.get("/api/v1/production").mock( return_value=Response( 200, json=_load_json_fixture(version, "api_v1_production") ) ) respx.get("/api/v1/production/inverters").mock( return_value=Response( 200, json=_load_json_fixture(version, "api_v1_production_inverters") ) ) reader = EnvoyReader("127.0.0.1", inverters=True) await reader.getData() assert ( await reader.consumption() == "Consumption data not available for your Envoy device." ) assert await reader.production() == 4859 assert ( await reader.daily_consumption() == "Consumption data not available for your Envoy device." ) assert await reader.daily_production() == 5046 assert ( await reader.seven_days_consumption() == "Consumption data not available for your Envoy device." ) assert await reader.seven_days_production() == 445686 assert ( await reader.lifetime_consumption() == "Consumption data not available for your Envoy device." ) assert await reader.lifetime_production() == 88742152 assert isinstance(await reader.inverters_production(), dict)
async def test_list_other_url(self, gl): class M(ListMixin, FakeManager): pass request = respx.get( "http://localhost/api/v4/others", headers={"Content-Type": "application/json"}, content='[{"id": 42, "foo": "bar"}]', status_code=codes.OK, ) mgr = M(gl) obj_list = await mgr.list(path="/others", as_list=False) assert isinstance(obj_list, RESTObjectList) obj = await obj_list.anext() assert obj.id == 42 assert obj.foo == "bar" with pytest.raises(StopAsyncIteration): await obj_list.anext()
async def test_retrieve_subscribers_from_api(self): """Should retrieve subscribers from API.""" expected = [{ 'id': '577f095ab64b4d1710de34f6a28ab3bd', 'name': 'First Last', 'strategies': [{ 'id': 'ABCD', 'name': 'Test strategy' }] }] rsps = respx.get(f'{copy_factory_api_url}/users/current/subscribers') \ .mock(return_value=Response(200, json=expected)) accounts = await history_client.get_subscribers() assert rsps.calls[ 0].request.url == f'{copy_factory_api_url}/users/current/subscribers' assert rsps.calls[0].request.method == 'GET' assert rsps.calls[0].request.headers[ 'auth-token'] == 'header.payload.sign' assert accounts == expected
def test_should_not_resubmit_other_job_types(caplog): job = respx.get('/jobs/job-uuid').respond(200, json={ 'CreationTime': '20210210T084350.430751', 'CompletionTime': '20210210T224350.430751', 'Type': 'CreateDicomZip' }) event_dispatcher.register_event_handlers( {orthanc.ChangeType.JOB_FAILURE: handle_failed_forwarding_job(0.1)}, orthanc, client, logging_configuration=python_logging) caplog.set_level(logging.DEBUG) orthanc.on_change(orthanc.ChangeType.JOB_FAILURE, '', 'job-uuid') assert job.called assert caplog.messages[ -1] == 'not retrying "CreateDicomZip" job "job-uuid"'
async def test_token_auth(self, gl, is_gl_sync): name = "username" id_ = 1 request = respx.get( "http://localhost/api/v4/user", headers={"content-type": "application/json"}, content='{{"id": {0:d}, "username": "******"}}'.format( id_, name).encode("utf-8"), status_code=codes.OK, ) if is_gl_sync: gl.auth() else: await gl.auth() assert isinstance(gl.user, CurrentUser) assert gl.user.username == name assert gl.user.id == id_
async def test_with_3_9_36_firmware(): """Verify with 3.9.36 firmware.""" version = "3.9.36" respx.get("/info.xml").mock(return_value=Response(200, text="")) respx.get("/production.json").mock(return_value=Response(404)) respx.get("/api/v1/production").mock( return_value=Response( 200, json=_load_json_fixture(version, "api_v1_production") ) ) respx.get("/api/v1/production/inverters").mock( return_value=Response( 200, json=_load_json_fixture(version, "api_v1_production_inverters") ) ) reader = EnvoyReader("127.0.0.1", inverters=True) await reader.getData() assert ( await reader.consumption() == "Consumption data not available for your Envoy device." ) assert await reader.production() == 1271 assert ( await reader.daily_consumption() == "Consumption data not available for your Envoy device." ) assert await reader.daily_production() == 1460 assert ( await reader.seven_days_consumption() == "Consumption data not available for your Envoy device." ) assert await reader.seven_days_production() == 130349 assert ( await reader.lifetime_consumption() == "Consumption data not available for your Envoy device." ) assert await reader.lifetime_production() == 6012540 assert isinstance(await reader.inverters_production(), dict)
async def test_update_submodule(self, gl, gl_get_value): request_get_project = respx.get( "http://localhost/api/v4/projects/1", headers={"content-type": "application/json"}, content='{"name": "name", "id": 1}'.encode("utf-8"), status_code=codes.OK, ) request_update_submodule = respx.put( "http://localhost/api/v4/projects/1/repository/submodules/foo%2Fbar", headers={"content-type": "application/json"}, content="""{ "id": "ed899a2f4b50b4370feeea94676502b42383c746", "short_id": "ed899a2f4b5", "title": "Message", "author_name": "Author", "author_email": "*****@*****.**", "committer_name": "Author", "committer_email": "*****@*****.**", "created_at": "2018-09-20T09:26:24.000-07:00", "message": "Message", "parent_ids": [ "ae1d9fb46aa2b07ee9836d49862ec4e2c46fbbba" ], "committed_date": "2018-09-20T09:26:24.000-07:00", "authored_date": "2018-09-20T09:26:24.000-07:00", "status": null}""".encode("utf-8"), status_code=codes.OK, ) project = gl.projects.get(1) project = await gl_get_value(project) assert isinstance(project, Project) assert project.name == "name" assert project.id == 1 ret = project.update_submodule( submodule="foo/bar", branch="master", commit_sha="4c3674f66071e30b3311dac9b9ccc90502a72664", commit_message="Message", ) ret = await gl_get_value(ret) assert isinstance(ret, dict) assert ret["message"] == "Message" assert ret["id"] == "ed899a2f4b50b4370feeea94676502b42383c746"
def test_client(): trial = respx.get( "https://miraitranslate.com/trial", ).mock(return_value=Response( 200, content=open("tests/fixtures/index.html", "rb").read())) cli = Client(delay_sec=0) assert trial.called assert (cli._tran == "xx3At5tG4vPwk3VCwKfXOq43RqCBEzScNvCgRWNvrCH2fDf2yk0m1UGtktVOINQ5") translate = respx.post( "https://miraitranslate.com/trial/api/translate.php", ).mock( return_value=Response( 200, json={ "status": "success", "outputs": [{ "output": [{ "translation": "This is a test.", "sentences": [{ "original": "これはテスト", "originalPosition": 0, "originalLength": 6, "translation": "This is a test.", "translationPosition": 0, "translationLength": 15, "type": "mt", "target": "", "prefix": "", "boundary": [0, 4, 7, 9], "originalDelimiter": "", "delimiter": "", "words": [], "sentences": [], }], }] }], }, )) assert cli.translate("これはテスト", "ja", "en") == "This is a test." assert translate.called
def test_production(self, key_id, rsa_key, payment_id, get_payment_details_production_signature): route = respx.get( f'https://authservices.satispay.com/g_business/v1/payments/{payment_id}' ) satispaython.get_payment_details(key_id, rsa_key, payment_id) assert route.called assert route.call_count == 1 request = route.calls.last.request assert request.method == 'GET' assert request.content is b'' assert request.headers['Accept'] == 'application/json' assert request.headers['Host'] == 'authservices.satispay.com' assert request.headers['Date'] == 'Mon, 18 Mar 2019 15:10:24 +0000' assert request.headers[ 'Digest'] == 'SHA-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' assert request.headers['Authorization'] == f'Signature keyId="{key_id}", ' \ f'algorithm="rsa-sha256", ' \ f'headers="(request-target) host date digest", ' \ f'signature="{get_payment_details_production_signature}"'
async def test_get_project_snippet(self, gl, gl_get_value): title = "Example Snippet Title" visibility = "private" request = respx.get( "http://localhost/api/v4/projects/1/snippets/1", content={ "title": title, "description": "More verbose snippet description", "file_name": "example.txt", "content": "source code with multiple lines", "visibility": visibility, }, status_code=codes.OK, ) project = gl.projects.get(1, lazy=True) snippet = project.snippets.get(1) snippet = await gl_get_value(snippet) assert snippet.title == title assert snippet.visibility == visibility
async def test_retrieve_copyfactory_subscriber_from_api(self): """Should retrieve CopyFactory subscriber from API.""" expected = { '_id': 'e8867baa-5ec2-45ae-9930-4d5cea18d0d6', 'name': 'Demo account', 'reservedMarginFraction': 0.25, 'subscriptions': [ { 'strategyId': 'ABCD', 'multiplier': 1 } ] } rsps = respx.get(f'{copy_factory_api_url}/users/current/configuration/subscribers/' + 'e8867baa-5ec2-45ae-9930-4d5cea18d0d6').mock(return_value=Response(200, json=expected)) accounts = await copy_factory_client.get_subscriber('e8867baa-5ec2-45ae-9930-4d5cea18d0d6') assert rsps.calls[0].request.url == f'{copy_factory_api_url}/users/current/configuration/subscribers/' + \ 'e8867baa-5ec2-45ae-9930-4d5cea18d0d6' assert rsps.calls[0].request.method == 'GET' assert rsps.calls[0].request.headers['auth-token'] == 'header.payload.sign' assert accounts == expected
async def test_all_ommited_when_as_list(self, gl, gl_get_value): request = respx.get( "http://localhost/api/v4/tests", headers={ "content-type": "application/json", "X-Page": "2", "X-Next-Page": "2", "X-Per-Page": "1", "X-Total-Pages": "2", "X-Total": "2", }, content=[{ "c": "d" }], status_code=codes.OK, ) result = gl.http_list("/tests", as_list=False, all=True) result = await gl_get_value(result) assert isinstance(result, GitlabList)
def test_client(): trial = respx.get( "https://miraitranslate.com/trial", content=open("tests/fixtures/index.html", "rb").read(), ) cli = Client(delay_sec=0) assert trial.called assert (cli._tran == "jsXIHl5tgZHSJDgvPemaVRe9XIS1vME5eCoMOJfVJMN20TNpYaqTRu3PdvqzhVUm") translate = respx.post( "https://miraitranslate.com/trial/translate.php", content={ "status": "success", "outputs": [{ "output": "This is a test." }] }, ) assert cli.translate("これはテスト", "ja", "en") == "This is a test." assert translate.called
async def test_retrieve_signals(self): """Should retrieve signals.""" expected = [{ 'symbol': 'EURUSD', 'type': 'POSITION_TYPE_BUY', 'time': '2020-08-24T00:00:00.000Z', 'closeAfter': '2020-08-24T00:00:00.000Z', 'volume': 1 }] rsps = respx.get(url__startswith=f'{copy_factory_api_url}/users/current/subscribers/' + 'e8867baa-5ec2-45ae-9930-4d5cea18d0d6/signals') \ .mock(return_value=Response(200, json=expected)) signals = await trading_client.\ get_trading_signals('e8867baa-5ec2-45ae-9930-4d5cea18d0d6') assert rsps.calls[0].request.url == f'{copy_factory_api_url}/users/current/subscribers/' + \ 'e8867baa-5ec2-45ae-9930-4d5cea18d0d6/signals' assert rsps.calls[0].request.method == 'GET' assert rsps.calls[0].request.headers[ 'auth-token'] == 'header.payload.sign' expected[0]['time'] = date(expected[0]['time']) expected[0]['closeAfter'] = date(expected[0]['closeAfter']) assert signals == expected
async def test_retrieve_by_token(self): """Should retrieve MetaTrader account by token from API.""" expected = { '_id': 'id', 'login': '******', 'name': 'mt5a', 'server': 'ICMarketsSC-Demo', 'provisioningProfileId': 'f9ce1f12-e720-4b9a-9477-c2d4cb25f076', 'magic': 123456, 'application': 'MetaApi', 'connectionStatus': 'DISCONNECTED', 'state': 'DEPLOYED', 'type': 'cloud' } rsps = respx.get(f'{PROVISIONING_API_URL}/users/current/accounts/accessToken/token') \ .mock(return_value=Response(200, json=expected)) account_client = MetatraderAccountClient(http_client, 'token') accounts = await account_client.get_account_by_token() assert rsps.calls[ 0].request.url == f'{PROVISIONING_API_URL}/users/current/accounts/accessToken/token' assert rsps.calls[0].request.method == 'GET' assert accounts == expected
def test_on_failure_should_resubmit_job(caplog): # TODO: figure out why expectation not met in Timer thread. job = respx.get('/jobs/job-uuid').respond(200, json={ 'CreationTime': '20210210T084350.430751', 'CompletionTime': '20210210T084351.430751', 'Type': 'DicomModalityStore' }) resubmit = respx.post('/jobs/job-uuid/resubmit').respond(200) # NOQA event_dispatcher.register_event_handlers( {orthanc.ChangeType.JOB_FAILURE: handle_failed_forwarding_job(0.1)}, orthanc, client, logging_configuration=python_logging) caplog.set_level(logging.DEBUG) orthanc.on_change(orthanc.ChangeType.JOB_FAILURE, '', 'job-uuid') assert job.called # XXX # assert resubmit.called assert caplog.messages[-1] == 'resubmitting job "job-uuid" after 2 seconds'
def test_after_render(mocker, get_test_client): request = respx.get( f"http://prerender.bar.com/http://testserver/", content="<html><body>PRERENDERED</body></html>", ) future = asyncio.Future() future.set_result(None) after_render = mocker.MagicMock(return_value=future) test_client = get_test_client(after_render=after_render) response = test_client.request("GET", "/", headers={"user-agent": "googlebot"}) assert after_render.called assert type(after_render.call_args[0][0]) == Request assert type(after_render.call_args[0][1]) == HTMLResponse assert after_render.call_args[0][2] is False assert request.called assert response.text == "<html><body>PRERENDERED</body></html>" assert response.headers.get("content-type") == "text/html; charset=utf-8"
async def test_with_auth_url_headers_and_params_GET(self): url = 'http://www.example.com' headers = {'foo': 'bar'} ably = await RestSetup.get_ably_rest( key=None, auth_url=url, auth_headers={'this': 'will_not_be_used'}, auth_params={'this': 'will_not_be_used'}) auth_params = {'foo': 'auth', 'spam': 'eggs'} token_params = {'foo': 'token'} auth_route = respx.get(url, params={ 'foo': ['token'], 'spam': ['eggs'] }) def call_back(request): assert request.headers['foo'] == 'bar' assert 'this' not in request.headers assert not request.content return Response(status_code=200, json={ 'issued': 1, 'token': 'another_token_string' }) auth_route.side_effect = call_back token_details = await ably.auth.request_token( token_params=token_params, auth_url=url, auth_headers=headers, auth_params=auth_params) assert 'another_token_string' == token_details.token await ably.close()
async def test_list_mixin(self, gl): class M(ListMixin, FakeManager): pass request = respx.get( "http://localhost/api/v4/tests", headers={"Content-Type": "application/json"}, content='[{"id": 42, "foo": "bar"},{"id": 43, "foo": "baz"}]', status_code=codes.OK, ) mgr = M(gl) obj_list = await mgr.list(as_list=False) assert isinstance(obj_list, RESTObjectList) async for obj in obj_list: assert isinstance(obj, FakeObject) assert obj.id in (42, 43) obj_list = await mgr.list(all=True) assert isinstance(obj_list, list) assert obj_list[0].id == 42 assert obj_list[1].id == 43 assert isinstance(obj_list[0], FakeObject) assert len(obj_list) == 2