def make_http_response( status=200, reason="OK", method="GET", url="/", headers=None, content=None ): """Return a minimal ClientResponse with fields used in tests.""" url = URL(url) headers = CIMultiDict(headers or {}) request_info = RequestInfo(url=url, method=method, headers=headers) response = ClientResponse( method, url, writer=None, continue100=None, timer=None, request_info=request_info, traces=(), loop=get_event_loop(), session=None, ) response.status = status response.reason = reason response._headers = headers if isinstance(content, io.IOBase): response.content = FakeStreamReader(content) elif content is not None: response.content = FakeStreamReader( io.BytesIO(json_dumps(content).encode("utf8")) ) response.headers["Content-Type"] = "application/json" return response
async def test_authenticate(): st = AsyncSpaceTrackClient('identity', 'wrongpassword') loop = asyncio.get_event_loop() response = ClientResponse( 'post', ST_URL / 'ajaxauth/login', request_info=Mock(), writer=Mock(), continue100=None, timer=TimerNoop(), traces=[], loop=loop, session=st.session, ) response.status = 200 response.json = Mock() async def mock_post(url, data): response.json.return_value = asyncio.Future() if data['password'] == 'wrongpassword': response.json.return_value.set_result({'Login': '******'}) elif data['password'] == 'unknownresponse': # Space-Track doesn't respond like this, but make sure anything # other than {'Login': '******'} doesn't raise AuthenticationError response.json.return_value.set_result({'Login': '******'}) else: response.json.return_value.set_result('') return response async with st: with patch.object(st.session, 'post', mock_post): with pytest.raises(AuthenticationError): await st.authenticate() assert response.json.call_count == 1 st.password = '******' await st.authenticate() # This shouldn't make a HTTP request since we're already authenticated. await st.authenticate() assert response.json.call_count == 2 st = AsyncSpaceTrackClient('identity', 'unknownresponse') async with st: with patch.object(st.session, 'post', mock_post): await st.authenticate() response.close()
def build_response(self, method, url, params, data, headers): """""" try: if type(url) == URL: url = url.human_repr() # Check if we have to skip it if self.skip(url): return None, True # Go check see if response is in cassette if not data: data = {} if params: data.update(params) request = vcr.request.Request(method, url, data, headers) cassette = self.load_cassette(url) resp_json = cassette.play_response(request) except UnhandledHTTPRequestError: # Response not seen yet in cassette return None, False # Response was found in cassette cassette.play_counts = collections.Counter() # Create the response resp = ClientResponse( method, URL(url), request_info=Mock(), writer=Mock(), continue100=None, timer=TimerNoop(), traces=[], loop=Mock(), session=Mock(), ) # Replicate status code and reason resp.status = resp_json['status']['code'] resp.reason = resp_json['status']['message'] # Set headers and content resp._headers = CIMultiDict(resp_json['headers']) resp.content = StreamReader(Mock(), limit=DEFAULT_STREAM_LIMIT) # Get the data data = resp_json['body']['data'] resp.content.feed_data(data) resp.content.feed_eof() return resp, False
async def test_authenticate(): st = AsyncSpaceTrackClient('identity', 'wrongpassword') loop = asyncio.get_event_loop() response = ClientResponse( 'post', URL('https://www.space-track.org/ajaxauth/login')) # aiohttp 2.2 uses session try: response._post_init(loop) except TypeError: response._post_init(loop, st.session) response.status = 200 response.json = Mock() async def mock_post(url, data): response.json.return_value = asyncio.Future() if data['password'] == 'wrongpassword': response.json.return_value.set_result({'Login': '******'}) elif data['password'] == 'unknownresponse': # Space-Track doesn't respond like this, but make sure anything # other than {'Login': '******'} doesn't raise AuthenticationError response.json.return_value.set_result({'Login': '******'}) else: response.json.return_value.set_result('') return response with st, patch.object(st.session, 'post', mock_post): with pytest.raises(AuthenticationError): await st.authenticate() assert response.json.call_count == 1 st.password = '******' await st.authenticate() # This shouldn't make a HTTP request since we're already authenticated. await st.authenticate() assert response.json.call_count == 2 st = AsyncSpaceTrackClient('identity', 'unknownresponse') with st, patch.object(st.session, 'post', mock_post): await st.authenticate() response.close()
async def prepare_fake_response(url, *, method='GET', req_headers=None, resp_headers=None, resp_status=200, resp_reason='OK', resp_content=b''): resp = ClientResponse(method, URL(val=url), request_info=RequestInfo(url, method, req_headers or {})) resp._content = resp_content resp.status = resp_status resp.reason = resp_reason resp.headers = resp_headers or {} future = asyncio.Future() future.set_result(resp) return future
async def test_authenticate(): st = AsyncSpaceTrackClient('identity', 'wrongpassword') loop = asyncio.get_event_loop() response = ClientResponse( 'post', 'https://www.space-track.org/ajaxauth/login') response._post_init(loop) response.status = 200 response.json = Mock() async def mock_post(url, data): response.json.return_value = asyncio.Future() if data['password'] == 'wrongpassword': response.json.return_value.set_result({'Login': '******'}) elif data['password'] == 'unknownresponse': # Space-Track doesn't respond like this, but make sure anything # other than {'Login': '******'} doesn't raise AuthenticationError response.json.return_value.set_result({'Login': '******'}) else: response.json.return_value.set_result('') return response with st, patch.object(st.session, 'post', mock_post): with pytest.raises(AuthenticationError): await st.authenticate() assert response.json.call_count == 1 st.password = '******' await st.authenticate() # This shouldn't make a HTTP request since we're already authenticated. await st.authenticate() assert response.json.call_count == 2 st = AsyncSpaceTrackClient('identity', 'unknownresponse') with st, patch.object(st.session, 'post', mock_post): await st.authenticate() response.close()
async def request(self, *args, **kwargs) -> ClientResponse: try: data = self.requests.pop(0) response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), traces=[], loop=asyncio.get_running_loop(), session=mock.Mock()) response.status = 200 response._body = data response._headers = {'Content-Type': 'application/json'} return response except IndexError as e: print(f'error in pop requests') raise Exception(str(e)) from e
async def build_response(self, session, method, url, params=None, data=None, headers=None, *args, **kwargs): self.requests.append({ 'method': method, 'url': url, 'params': params, 'data': data, 'headers': headers }) url = URL(url) url_parts = [p.split('?')[-1] for p in url.parts] if data is None and 'json' in kwargs: data = json.dumps(kwargs['json']) resp = ClientResponse( method, url, request_info=Mock(), writer=Mock(), continue100=None, timer=TimerNoop(), traces=[], loop=Mock(), session=Mock(), ) func_name = '_'.join(url_parts[-2:]) func = None if hasattr(self, func_name): func = getattr(self, func_name) else: func_name = url_parts[-1] if hasattr(self, func_name): func = getattr(self, func_name) if func is not None: status, data, ct = await func(params or url.query, data, headers) resp.status = status else: print(f'Method {func_name} not implemented') resp.status = 200 if method.lower() == 'patch': resp.status = 204 ct = 'application/json' data = '{}' resp._headers = CIMultiDict({hdrs.CONTENT_TYPE: ct}) loop = asyncio.get_event_loop() protocol = Mock(_reading_paused=False) resp.content = StreamReader(protocol, loop=loop, limit=DEFAULT_STREAM_LIMIT) if isinstance(data, str): data = data.encode('utf8') resp.content.feed_data(data) resp.content.feed_eof() self.responses.append(resp) return resp
async def test_generic_request(): def mock_authenticate(self): result = asyncio.Future() result.set_result(None) return result def mock_download_predicate_data(self, class_, controller=None): result = asyncio.Future() data = [{ 'Default': '0000-00-00 00:00:00', 'Extra': '', 'Field': 'PUBLISH_EPOCH', 'Key': '', 'Null': 'NO', 'Type': 'datetime' }, { 'Default': '', 'Extra': '', 'Field': 'TLE_LINE1', 'Key': '', 'Null': 'NO', 'Type': 'char(71)' }, { 'Default': '', 'Extra': '', 'Field': 'TLE_LINE2', 'Key': '', 'Null': 'NO', 'Type': 'char(71)' }] result.set_result(data) return result st = AsyncSpaceTrackClient('identity', 'password') loop = asyncio.get_event_loop() response = ClientResponse( 'get', ST_URL / 'basicspacedata/query/class/tle_publish/format/tle', request_info=Mock(), writer=Mock(), continue100=None, timer=TimerNoop(), traces=[], loop=loop, session=st.session, ) tle = ( '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927\r\n' '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537\r\n' ) normalised_tle = tle.replace('\r\n', '\n') response.status = 200 response.text = Mock() response.text.return_value = asyncio.Future() response.text.return_value.set_result(tle) mock_get = asyncio.Future() mock_get.set_result(response) patch_authenticate = patch.object(AsyncSpaceTrackClient, 'authenticate', mock_authenticate) patch_download_predicate_data = patch.object(AsyncSpaceTrackClient, '_download_predicate_data', mock_download_predicate_data) patch_get = patch.object(st.session, 'get', return_value=mock_get) with patch_authenticate, patch_download_predicate_data, patch_get: assert await st.tle_publish(format='tle') == normalised_tle response.close() response = ClientResponse( 'get', ST_URL / 'basicspacedata/query/class/tle_publish', request_info=Mock(), writer=Mock(), continue100=None, timer=TimerNoop(), traces=[], loop=loop, session=st.session, ) response.status = 200 response.json = Mock() response.json.return_value = asyncio.Future() response.json.return_value.set_result({'a': 5}) mock_get = asyncio.Future() mock_get.set_result(response) patch_get = patch.object(st.session, 'get', return_value=mock_get) with patch_authenticate, patch_download_predicate_data, patch_get: result = await st.tle_publish() assert result['a'] == 5 response.close() await st.close()
async def test_generic_request(): def mock_authenticate(self): result = asyncio.Future() result.set_result(None) return result def mock_download_predicate_data(self, class_): result = asyncio.Future() data = [ { 'Default': '0000-00-00 00:00:00', 'Extra': '', 'Field': 'PUBLISH_EPOCH', 'Key': '', 'Null': 'NO', 'Type': 'datetime' }, { 'Default': '', 'Extra': '', 'Field': 'TLE_LINE1', 'Key': '', 'Null': 'NO', 'Type': 'char(71)' }, { 'Default': '', 'Extra': '', 'Field': 'TLE_LINE2', 'Key': '', 'Null': 'NO', 'Type': 'char(71)' } ] result.set_result(data) return result st = AsyncSpaceTrackClient('identity', 'password') loop = asyncio.get_event_loop() response = ClientResponse( 'get', 'https://www.space-track.org/basicspacedata/query/class' '/tle_publish/format/tle') response._post_init(loop) tle = ( '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927\r\n' '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537\r\n') normalised_tle = tle.replace('\r\n', '\n') response.status = 200 response.text = Mock() response.text.return_value = asyncio.Future() response.text.return_value.set_result(tle) mock_get = asyncio.Future() mock_get.set_result(response) patch_authenticate = patch.object( AsyncSpaceTrackClient, 'authenticate', mock_authenticate) patch_download_predicate_data = patch.object( AsyncSpaceTrackClient, '_download_predicate_data', mock_download_predicate_data) patch_get = patch.object(st.session, 'get', return_value=mock_get) with patch_authenticate, patch_download_predicate_data, patch_get: assert await st.tle_publish(format='tle') == normalised_tle response.close() response = ClientResponse( 'get', 'https://www.space-track.org/basicspacedata/query/class' '/tle_publish') response._post_init(loop) response.status = 200 response.json = Mock() response.json.return_value = asyncio.Future() response.json.return_value.set_result({'a': 5}) mock_get = asyncio.Future() mock_get.set_result(response) patch_get = patch.object(st.session, 'get', return_value=mock_get) with patch_authenticate, patch_download_predicate_data, patch_get: result = await st.tle_publish() assert result['a'] == 5 response.close() st.close()