How to use configure_response method in responses

Best Python code snippet using responses

test_dump.py

Source:test_dump.py Github

copy

Full Screen

...93 self.adapter = mock.Mock(spec=self.adapter_spec)94 self.response.connection = self.adapter95 self.response.request = self.request96 self.response.raw = self.httpresponse97 def configure_response(self, content=b'', proxy_manager=None, url=None,98 reason=b''):99 """Helper function to configure a mocked response."""100 self.adapter.proxy_manager = proxy_manager or {}101 self.response.content = content102 self.response.url = url103 self.response.reason = reason104 def configure_request(self, body=b'', headers=None, method=None,105 url=None):106 """Helper function to configure a mocked request."""107 self.request.body = body108 self.request.headers = headers or {}109 self.request.method = method110 self.request.url = url111 def configure_httpresponse(self, headers=None, reason=b'', status=200,112 version=HTTP_1_1):113 """Helper function to configure a mocked urllib3 response."""114 self.httpresponse.headers = HTTPHeaderDict(headers or {})115 self.httpresponse.reason = reason116 self.httpresponse.status = status117 self.httpresponse.version = version118class TestResponsePrivateFunctions(RequestResponseMixin):119 """Excercise private functions using responses."""120 def test_get_proxy_information_sans_proxy(self):121 """Show no information is returned when not using a proxy."""122 self.configure_response()123 assert dump._get_proxy_information(self.response) is None124 def test_get_proxy_information_with_proxy_over_http(self):125 """Show only the request path is returned for HTTP requests.126 Using HTTP over a proxy doesn't alter anything except the request path127 of the request. The method doesn't change a dictionary with the128 request_path is the only thing that should be returned.129 """130 self.configure_response(131 proxy_manager={'http://': 'http://local.proxy:3939'},132 )133 self.configure_request(134 url='http://example.com',135 method='GET',136 )137 assert dump._get_proxy_information(self.response) == {138 'request_path': 'http://example.com'139 }140 def test_get_proxy_information_with_proxy_over_https(self):141 """Show that the request path and method are returned for HTTPS reqs.142 Using HTTPS over a proxy changes the method used and the request path.143 """144 self.configure_response(145 proxy_manager={'http://': 'http://local.proxy:3939'},146 )147 self.configure_request(148 url='https://example.com',149 method='GET',150 )151 assert dump._get_proxy_information(self.response) == {152 'method': 'CONNECT',153 'request_path': 'https://example.com'154 }155 def test_dump_request_data(self):156 """Build up the request data into a bytearray."""157 self.configure_request(158 url='http://example.com/',159 method='GET',160 )161 array = bytearray()162 prefixes = dump.PrefixSettings('request:', 'response:')163 dump._dump_request_data(164 request=self.request,165 prefixes=prefixes,166 bytearr=array,167 proxy_info={},168 )169 assert b'request:GET / HTTP/1.1\r\n' in array170 assert b'request:Host: example.com\r\n' in array171 def test_dump_request_data_with_proxy_info(self):172 """Build up the request data into a bytearray."""173 self.configure_request(174 url='http://example.com/',175 method='GET',176 )177 array = bytearray()178 prefixes = dump.PrefixSettings('request:', 'response:')179 dump._dump_request_data(180 request=self.request,181 prefixes=prefixes,182 bytearr=array,183 proxy_info={184 'request_path': b'fake-request-path',185 'method': b'CONNECT',186 },187 )188 assert b'request:CONNECT fake-request-path HTTP/1.1\r\n' in array189 assert b'request:Host: example.com\r\n' in array190 def test_dump_response_data(self):191 """Build up the response data into a bytearray."""192 self.configure_response(193 url='https://example.com/redirected',194 content=b'foobarbogus',195 reason=b'OK',196 )197 self.configure_httpresponse(198 headers={'Content-Type': 'application/json'},199 reason=b'OK',200 status=201,201 )202 array = bytearray()203 prefixes = dump.PrefixSettings('request:', 'response:')204 dump._dump_response_data(205 response=self.response,206 prefixes=prefixes,207 bytearr=array,208 )209 assert b'response:HTTP/1.1 201 OK\r\n' in array210 assert b'response:Content-Type: application/json\r\n' in array211 def test_dump_response_data_with_older_http_version(self):212 """Build up the response data into a bytearray."""213 self.configure_response(214 url='https://example.com/redirected',215 content=b'foobarbogus',216 reason=b'OK',217 )218 self.configure_httpresponse(219 headers={'Content-Type': 'application/json'},220 reason=b'OK',221 status=201,222 version=HTTP_0_9,223 )224 array = bytearray()225 prefixes = dump.PrefixSettings('request:', 'response:')226 dump._dump_response_data(227 response=self.response,228 prefixes=prefixes,229 bytearr=array,230 )231 assert b'response:HTTP/0.9 201 OK\r\n' in array232 assert b'response:Content-Type: application/json\r\n' in array233 def test_dump_response_data_with_unknown_http_version(self):234 """Build up the response data into a bytearray."""235 self.configure_response(236 url='https://example.com/redirected',237 content=b'foobarbogus',238 reason=b'OK',239 )240 self.configure_httpresponse(241 headers={'Content-Type': 'application/json'},242 reason=b'OK',243 status=201,244 version=HTTP_UNKNOWN,245 )246 array = bytearray()247 prefixes = dump.PrefixSettings('request:', 'response:')248 dump._dump_response_data(249 response=self.response,250 prefixes=prefixes,251 bytearr=array,252 )253 assert b'response:HTTP/? 201 OK\r\n' in array254 assert b'response:Content-Type: application/json\r\n' in array255class TestResponsePublicFunctions(RequestResponseMixin):256 """Excercise public functions using responses."""257 def test_dump_response_fails_without_request(self):258 """Show that a response without a request raises a ValueError."""259 del self.response.request260 assert hasattr(self.response, 'request') is False261 with pytest.raises(ValueError):262 dump.dump_response(self.response)263 def test_dump_response_uses_provided_bytearray(self):264 """Show that users providing bytearrays receive those back."""265 self.configure_request(266 url='http://example.com/',267 method='GET',268 )269 self.configure_response(270 url='https://example.com/redirected',271 content=b'foobarbogus',272 reason=b'OK',273 )274 self.configure_httpresponse(275 headers={'Content-Type': 'application/json'},276 reason=b'OK',277 status=201,278 )279 arr = bytearray()280 retarr = dump.dump_response(self.response, data_array=arr)281 assert retarr is arr282class TestDumpRealResponses(object):283 """Exercise dump utilities against real data."""...

Full Screen

Full Screen

test_remote_standard_requests.py

Source:test_remote_standard_requests.py Github

copy

Full Screen

1import pytest2from freezegun import freeze_time3from unittest.mock import MagicMock, PropertyMock, create_autospec4from unittest import mock5from requests import HTTPError6from application.tests.conftest import rkwargs7from application.tests import FROZEN_DATETIME, FROZEN_TIME_STR8from application.tests.tracker.tests.remote.conftest import (9 TestRemotePetition,10 TestRemotePetitionRequests,11)12from application.tracker.remote import RemotePetition13import json, logging, requests14remote_petition_path = "application.tracker.remote"15logger = logging.getLogger(__name__)16## synchronous standard requests function tests17@freeze_time(FROZEN_TIME_STR)18class TestRemotePetitionFetch(TestRemotePetitionRequests):19 def configure(self):20 super().configure()21 self.url = self.petition_url()22 @pytest.mark.parametrize(23 'configure_response', [{24 "status_code": 200,25 "response_data": {"links": {}, "data": {}}26 }],27 indirect=True28 )29 def test_when_status_is_200(self, configure_response):30 self.response.url = f"{self.base_url}/{self.id}.json"31 result = RemotePetition.fetch(self.id)32 assert result.data == self.response_data33 assert result.timestamp == FROZEN_DATETIME.isoformat()34 @pytest.mark.parametrize('configure_response', [{"status_code": 404}], indirect=True)35 def test_when_status_is_404_and_wont_raise(self, configure_response):36 self.response.url = f"{self.base_url}/{self.id}.json"37 result = RemotePetition.fetch(self.id, raise_404=False)38 assert result is None39 @pytest.mark.parametrize('configure_response', [{"status_code": 404}], indirect=True)40 def test_when_status_is_404_and_will_raise(self, configure_response):41 expected_msg = f"404 Client Error: Not Found for url: {self.url}"42 error = None43 with pytest.raises(HTTPError) as error:44 result = RemotePetition.fetch(self.id, raise_404=True)45 assert str(error.value) == expected_msg46@freeze_time(FROZEN_TIME_STR)47class TestRemotePetitionGetPageRange(TestRemotePetitionRequests):48 def configure(self):49 super().configure()50 self.template = self.page_url_template("open")51 self.url = self.template % {"page": 1}52 @pytest.mark.parametrize('init_links', [{"next_num": 2, "last_num": 100}], indirect=True)53 @pytest.mark.parametrize('configure_response', [{"status_code": 200}], indirect=True)54 def test_when_status_is_200_and_next_page(self, init_links, configure_response):55 result = RemotePetition.get_page_range(self.template)56 expectation = list(range(1, self.last_num + 1))57 assert result == expectation58 @pytest.mark.parametrize('init_links', [{"next_num": None, "last_num": 1}], indirect=True)59 @pytest.mark.parametrize('configure_response', [{"status_code": 200}], indirect=True)60 def test_status_is_200_and_not_next_page(self, init_links, configure_response):61 result = RemotePetition.get_page_range(self.template)62 expectation = [1]63 assert result == expectation64 @pytest.mark.parametrize('configure_response', [{"status_code": 404}], indirect=True)65 def test_when_status_is_404(self, configure_response):66 expected_msg = f"404 Client Error: Not Found for url: {self.url}"67 error = None68 with pytest.raises(HTTPError) as error:69 result = RemotePetition.get_page_range(self.template)...

Full Screen

Full Screen

discs_tests.py

Source:discs_tests.py Github

copy

Full Screen

2from django.conf import settings3from django.core.management import call_command4from django.test import TestCase5from dgf.models import Disc6def configure_response(opened_file):7 responses.add(responses.GET,8 settings.APPROVED_DISCS_URL, body=opened_file.read(),9 status=200)10class PdgaDiscsTest(TestCase):11 @responses.activate12 def test_three_discs_are_loaded(self):13 configure_response(open(f'{settings.BASE_DIR}/dgf/resources/test-pdga-approved-disc-golf-discs.csv'))14 Disc.objects.all().delete()15 call_command('update_approved_discs')16 self.assertNotEqual(Disc.objects.get(mold='PD3', manufacturer='Discmania'), None)17 self.assertNotEqual(Disc.objects.get(18 mold='Professional (1, 4, 10, 14, 15, 16, 17, 20, 20 A, 21, 23A, 23B, 24A, 24B & Pro Classic molds)',19 manufacturer='Wham-O / DTW'), None)20 self.assertNotEqual(Disc.objects.get(mold='Mirus', manufacturer='Latitude 64'), None)21 @responses.activate22 def test_different_molds_are_loaded(self):23 configure_response(24 open(f'{settings.BASE_DIR}/dgf/resources/test-more-molds-pdga-approved-disc-golf-discs.csv'))25 Disc.objects.all().delete()26 call_command('update_approved_discs')27 self.assertNotEqual(Disc.objects.get(mold='PD3', manufacturer='Discmania'), None)28 self.assertNotEqual(Disc.objects.get(29 mold='Professional (1, 4, 10, 14, 15, 16, 17, 20, 20 A, 21, 23A, 23B, 24A, 24B & Pro Classic molds)',30 manufacturer='Wham-O / DTW'), None)31 self.assertNotEqual(Disc.objects.get(mold='Mirus', manufacturer='Latitude 64'), None)32 self.assertNotEqual(Disc.objects.get(mold='Torque', manufacturer='Discraft'), None)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run responses automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful