async def test_async_request(event_loop): async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(arsps.ANY, '/', 'get', arsps.Response(status=200, text='Running ok.')) is_it_up = check_url('http://duckduckgo.com') response = await is_it_up assert response['status_code'] == 200
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add(API_HOST, '/api', 'get', aresponses.Response(status=200)) raw = await logi._fetch(url='/api', raw=True) self.assertIsInstance(raw, aiohttp.ClientResponse) raw.close()
async def test_context_manager(event_loop): async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add('foo.com', '/', 'get', aresponses.Response(text='hi')) url = 'http://foo.com' async with aiohttp.ClientSession() as session: async with session.get(url) as response: text = await response.text() assert text == 'hi'
async def test_context_manager(event_loop): async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add("foo.com", "/", "get", aresponses.Response(text="hi")) url = "http://foo.com" async with aiohttp.ClientSession() as session: async with session.get(url) as response: text = await response.text() assert text == "hi"
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add( API_HOST, endpoint, 'post', aresponses.Response( status=200, text='{ "activities" : [] }', headers={'content-type': 'application/json'})) # Props should match fixture self.assertIsNone(await self.test_camera.get_last_activity())
async def test_no_xml(event_loop): """Test with empty xml.""" async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_PATH, "get", "") async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station_id = "3006904" await rmv.get_departures(station_id)
async def test_departures_error_server(event_loop): """Test server error handling.""" async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_PATH, "get", aresponses.Response(text="error", status=500)) async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station_id = "3006904" await rmv.get_departures(station_id)
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add( API_HOST, endpoint, 'get', aresponses.Response( status=200, text=self.fixtures['rtsp_uri'], headers={'content-type': 'application/json'})) rtsp_uri = await self.test_camera.live_stream.get_rtsp_url() self.assertEqual(expected_rtsp_uri, rtsp_uri)
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add(API_HOST, endpoint, 'put', aresponses.Response(status=500)) self.assertEqual(self.test_camera.streaming, True) # Prop should not update if PUT request fails with self.assertRaises(ClientResponseError): await self.test_camera.set_config('streaming', False) self.assertEqual(self.test_camera.streaming, True)
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add( AUTH_HOST, TOKEN_ENDPOINT, 'post', aresponses.Response( status=401, text=self.fixtures['failed_authorization'], headers={'content-type': 'application/json'})) # Mock authorization, and verify AuthProvider state with self.assertRaises(AuthorizationFailed): await logi.authorize('letmein')
async def async_error_requests(hostname, bot_id): mock: aresponses.ResponsesMockServer async with aresponses.ResponsesMockServer() as mock: mock.add( hostname, BotXAPI.V2.token.url.split("{host}", 1)[1].format(bot_id=bot_id), BotXAPI.V2.token.method.lower(), aresponses.Response( body=json.dumps({ "status": "error", "message": " error response" }), status=500, ), ) mock.add( hostname, BotXAPI.V3.notification.url.split("{host}", 1)[1], BotXAPI.V3.notification.method.lower(), aresponses.Response( body=json.dumps({ "status": "error", "message": " error response" }), status=500, ), ) mock.add( hostname, BotXAPI.V3.command.url.split("{host}", 1)[1], BotXAPI.V3.command.method.lower(), aresponses.Response( body=json.dumps({ "status": "error", "message": " error response" }), status=500, ), ) mock.add( hostname, BotXAPI.V1.file.url.split("{host}", 1)[1], BotXAPI.V1.file.method.lower(), aresponses.Response( body=json.dumps({ "status": "error", "message": " error response" }), status=500, ), ) yield mock
async def test_invalid_credentials(event_loop, invalid_credentials_json, v2_server): """Test that invalid credentials throw the correct exception.""" async with aresponses.ResponsesMockServer(loop=event_loop) as v2_server: v2_server.add( 'api.simplisafe.com', '/v1/api/token', 'post', aresponses.Response(text=json.dumps(invalid_credentials_json), status=403)) async with aiohttp.ClientSession(loop=event_loop) as websession: with pytest.raises(InvalidCredentialsError): await API.login_via_credentials(TEST_EMAIL, TEST_PASSWORD, websession)
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add(API_HOST, '/api', 'get', aresponses.Response(status=401)) arsps.add(AUTH_HOST, TOKEN_ENDPOINT, 'post', aresponses.Response(status=200, text=auth_fixture, headers={'content-type': 'application/json'})) arsps.add(API_HOST, '/api', 'get', aresponses.Response(status=401)) with self.assertRaises(AuthorizationFailed): await logi._fetch(url='/api')
async def test_no_timestamp(event_loop): """Test with no timestamp.""" with open("fixtures/request_no_timestamp.xml") as f: xml = f.read() async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_PATH, "get", xml) async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station_id = "3006904" await rmv.get_departures(station_id)
async def async_requests(hostname, bot_id): mock: aresponses.ResponsesMockServer async with aresponses.ResponsesMockServer() as mock: mock.add( hostname, BotXAPI.V2.token.url.split("{host}", 1)[1].format(bot_id=bot_id), BotXAPI.V2.token.method.lower(), aresponses.Response( body=json.dumps({ "status": "ok", "result": "token_for_operations" }), status=200, ), ) mock.add( hostname, BotXAPI.V3.notification.url.split("{host}", 1)[1], BotXAPI.V3.notification.method.lower(), aresponses.Response( body=json.dumps({ "status": "ok", "result": "notification_result_sent" }), status=200, ), ) mock.add( hostname, BotXAPI.V3.command.url.split("{host}", 1)[1], BotXAPI.V3.command.method.lower(), aresponses.Response( body=json.dumps({ "status": "ok", "result": "command_result_sent" }), status=200, ), ) mock.add( hostname, BotXAPI.V1.file.url.split("{host}", 1)[1], BotXAPI.V1.file.method.lower(), aresponses.Response(body=json.dumps({ "status": "ok", "result": "file_sent" }), status=200), ) yield mock
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add(API_HOST, '/api', 'get', aresponses.Response(status=401)) arsps.add(AUTH_HOST, TOKEN_ENDPOINT, 'post', aresponses.Response(status=200, text=auth_fixture, headers={'content-type': 'application/json'})) arsps.add(API_HOST, '/api', 'get', aresponses.Response(status=200, text='{ "foo" : "bar" }', headers={'content-type': 'application/json'})) get_result = await logi._fetch(url='/api') self.assertEqual(get_result['foo'], 'bar')
async def test__query_rmv_api_fail(event_loop, stops_request): """Test failing station search.""" async def response_handler(request): await asyncio.sleep(0.01) return aresponses.Response(body="page loaded") async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_SEARCH_PATH, "get", response_handler) with pytest.raises(asyncio.TimeoutError): async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session, timeout=0.005) url = f"https://{URL}{URL_SEARCH_PATH}" await rmv._query_rmv_api(url)
async def test_departures_products(event_loop, xml_request): """Test products filter.""" with open("fixtures/result_products_filter.json") as f: result_products_filter_json = json.load(f, object_hook=date_hook) async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_PATH, "get", xml_request) async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station_id = "3006904" products = ["S", "RB"] data = await rmv.get_departures(station_id, products=products, max_journeys=50) assert data == result_products_filter_json
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add( API_HOST, endpoint, 'post', aresponses.Response( status=200, text=self.fixtures['activities'], headers={'content-type': 'application/json'})) activities = await self.test_camera.query_activity_history( property_filter='prop_filter', date_filter=datetime.now(), date_operator='>', limit=100) self.assertIsInstance(activities, list) for activity in activities: self.assertIsInstance(activity, Activity)
async def test_midnight(event_loop): """Test departures around midnight.""" with open("fixtures/request_midnight.xml") as f: xml = f.read() with open("fixtures/result_midnight.json") as f: result = json.load(f, object_hook=date_hook) async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_PATH, "get", xml) async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station_id = "3006904" data = await rmv.get_departures(station_id) assert data == result
async def test_departures_bad_request(event_loop): """Test bad xml.""" with open("fixtures/bad_request.xml") as xml_file: xml_request = xml_file.read() with open("fixtures/result_bad.json") as json_file: result = json.load(json_file, object_hook=date_hook) async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_PATH, "get", xml_request) async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station_id = "3006904" direction_id = "3006905" data = await rmv.get_departures(station_id, direction_id) assert data == result
async def test_bug_3006907(event_loop, capsys): """Test bug 3006907.""" with open("fixtures/bug_3006907.xml") as f: xml_request = f.read() async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_PATH, "get", xml_request) async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station_id = "3006907" data = await rmv.get_departures( station_id, max_journeys=50, products=["U-Bahn", "Tram", "Bus", "S"]) assert data["filter"] == "0001111" assert data["stationId"] == "3006907" assert data["station"] == "Wiesbaden Hauptbahnhof"
async def test_search_station(event_loop, stops_request): """Test station search.""" async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_SEARCH_PATH, "get", stops_request) async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station = "Hauptwache" data = await rmv.search_station(station) assert data == { "003000001": { "name": "Frankfurt (Main) Hauptwache", "id": "003000001", "lat": 50.113963, "long": 8.679292, } }
async def test_script_unmodified(self): requested_html = '<script>Helloo, world</script>' processed_html = '<html><head><script>Helloo, world</script></head></html>' proxy = Proxy(listen_host='127.0.0.1', listen_port=8081, subst_host='127.0.0.1', subst_port=8081) async with aresponses.ResponsesMockServer(loop=self.loop) as aresp: aresp.add( 'habr.com', '/', 'GET', aresp.Response(text=requested_html, content_type='text/html')) req = make_mocked_request('GET', '/') resp = await proxy.proxy_handler(req) self.assertEqual(200, resp.status) self.assertEqual(processed_html, resp.text)
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add( API_HOST, endpoint, 'get', aresponses.Response( status=200, text=self.fixtures['accessory'], headers={'content-type': 'application/json'})) # Props should match fixture self.assertEqual(self.test_camera.battery_level, 100) self.assertEqual(self.test_camera.signal_strength_percentage, 74) await self.test_camera.update() # Props should have changed. self.assertEqual(self.test_camera.battery_level, 99) self.assertEqual(self.test_camera.signal_strength_percentage, 88)
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add( AUTH_HOST, TOKEN_ENDPOINT, 'post', aresponses.Response( status=200, text=auth_fixture, headers={'content-type': 'application/json'})) arsps.add( AUTH_HOST, TOKEN_ENDPOINT, 'post', aresponses.Response( status=200, text=refresh_fixture, headers={'content-type': 'application/json'})) # Mock authorization, and verify AuthProvider state await logi.authorize('beepboop123') self.assertTrue( logi.is_connected, 'API reports not connected after successful login') self.assertTrue( logi.authorized, 'API reports not authorized after successful login') self.assertIsNotNone( logi.auth_provider.session, 'Session not created after successful login') self.assertEqual(logi.auth_provider.refresh_token, dict_auth_fixture['refresh_token']) self.assertEqual(logi.auth_provider.access_token, dict_auth_fixture['access_token']) # Mock refresh of access token, and verify AuthProvider state await logi.auth_provider.refresh() self.assertTrue( logi.is_connected, 'API reports not connected after token refresh') self.assertTrue( logi.authorized, 'API reports not authorized after token_refresh') self.assertIsNotNone( logi.auth_provider.session, 'Session not created after token_refresh') self.assertEqual(logi.auth_provider.refresh_token, dict_refresh_fixture['refresh_token']) self.assertEqual(logi.auth_provider.access_token, dict_refresh_fixture['access_token'])
def v3_server( api_token_json, auth_check_json, event_loop, v3_sensors_json, v3_settings_json, v3_subscriptions_json, ): """Return a ready-to-query mocked v2 server.""" server = aresponses.ResponsesMockServer(loop=event_loop) server.add( "api.simplisafe.com", "/v1/api/token", "post", aresponses.Response(text=json.dumps(api_token_json), status=200), ) server.add( "api.simplisafe.com", "/v1/api/authCheck", "get", aresponses.Response(text=json.dumps(auth_check_json), status=200), ) server.add( "api.simplisafe.com", f"/v1/users/{TEST_USER_ID}/subscriptions", "get", aresponses.Response(text=json.dumps(v3_subscriptions_json), status=200), ) server.add( "api.simplisafe.com", f"/v1/ss3/subscriptions/{TEST_SUBSCRIPTION_ID}/sensors", "get", aresponses.Response(text=json.dumps(v3_sensors_json), status=200), ) server.add( "api.simplisafe.com", f"/v1/ss3/subscriptions/{TEST_SUBSCRIPTION_ID}/settings/pins", "get", aresponses.Response(text=json.dumps(v3_settings_json), status=200), ) return server
async def test_getdepartures(event_loop, xml_request, capsys): """Test departures with default setings.""" with open("fixtures/result_simple.json") as f: result_simple_json = json.load(f, object_hook=date_hook) with open("fixtures/result_simple.txt") as f: result_text = f.read() async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_PATH, "get", xml_request) async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station_id = "3006904" data = await rmv.get_departures(station_id) assert data == result_simple_json rmv.output() out, err = capsys.readouterr() assert out == result_text
async def run_test(): async with aresponses.ResponsesMockServer(loop=self.loop) as arsps: arsps.add('myfile.com', test_file_endpoint, 'get', aresponses.Response(status=200, text='123456', headers={'content-type': 'application/octet-stream'})) arsps.add('myfile.com', test_file_endpoint, 'get', aresponses.Response(status=200, text='789012', headers={'content-type': 'application/octet-stream'})) # Should serve file as bytes object if filename parameter not specified myfile = await self.activity._get_file('https://myfile.com/coolfile.mp4') self.assertEqual(myfile, b'123456') # Should download file await self.activity._get_file('https://myfile.com/coolfile.mp4', TEMP_FILE) with open(TEMP_FILE, 'r') as test_file: data = test_file.read() self.assertEqual(data, "789012")
async def test_search_station_fail(event_loop, stops_request): """Test failing station search.""" with open("fixtures/request_no_timestamp.xml") as f: xml = f.read() async with aresponses.ResponsesMockServer(loop=event_loop) as arsps: arsps.add(URL, URL_SEARCH_PATH, "get", xml) async with aiohttp.ClientSession(loop=event_loop) as session: rmv = RMVtransport(session) station = "Hauptwache" data = await rmv.search_station(station) assert data == { "003000001": { "name": "Frankfurt (Main) Hauptwache", "id": "003000001", "lat": 50.113963, "long": 8.679292, } }