def wrapper(*args, **kwargs): responses.start() responses.add(**response_dict) result = f(response_data=json.loads(response_dict["body"]), *args, **kwargs) responses.stop() responses.reset() return result
def setUp(self): super(VstsIntegrationTestCase, self).setUp() self.access_token = '9d646e20-7a62-4bcc-abc0-cb2d4d075e36' self.refresh_token = '32004633-a3c0-4616-9aa0-a40632adac77' self.vsts_account_id = 'c8a585ae-b61f-4ba6-833c-9e8d5d1674d8' self.vsts_account_name = 'MyVSTSAccount' self.vsts_account_uri = 'https://MyVSTSAccount.vssps.visualstudio.com:443/' self.vsts_user_id = 'd6245f20-2af8-44f4-9451-8107cb2767db' self.vsts_user_name = 'Foo Bar' self.vsts_user_email = '*****@*****.**' self.repo_id = '47166099-3e16-4868-9137-22ac6b05b06e' self.repo_name = 'cool-service' self.project_a = { 'id': 'eb6e4656-77fc-42a1-9181-4c6d8e9da5d1', 'name': 'ProjectA', } self.project_b = { 'id': '6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c', 'name': 'ProjectB', } responses.start() self._stub_vsts()
def mock_api(): """A mock for the PyPI JSON API.""" with open(os.path.join(HERE, 'response.json'), 'r') as fp: webargs_response = fp.read() # A valid package with a proper response responses.add( responses.GET, 'https://pypi.python.org/pypi/webargs/json', body=webargs_response, content_type='application/json' ) # A valid package with no releases with open(os.path.join(HERE, 'response_noreleases.json'), 'r') as fp: foo_response = fp.read() responses.add( responses.GET, 'https://pypi.python.org/pypi/foo/json', body=foo_response, content_type='application/json' ) # An invalid package name responses.add( responses.GET, 'https://pypi.python.org/pypi/nope/json', status=404 ) responses.start() yield responses responses.stop()
def mock_api(): # Mock get the license list. with open(path.join(ROOT, 'licenses.json')) as f: mock_response_body = f.read() responses.add(responses.GET, 'https://api.github.com/licenses', body=mock_response_body) # Mock get each license template. for license in os.listdir(path.join(ROOT, 'licenses')): with open(path.join(ROOT, 'licenses/{0}'.format(license))) as f: mock_response_body = f.read() responses.add(responses.GET, 'https://api.github.com/licenses/{0}'.format( path.splitext(license)[0]), body=mock_response_body, content_type='application/json') # Mock get the invalid license. with open(path.join(ROOT, 'not_found.json')) as f: mock_not_found_body = f.read() responses.add(responses.GET, 'https://api.github.com/licenses/invalid', body=mock_not_found_body, content_type='application/json') responses.start() yield responses responses.stop()
def init_connection(self): os.environ["system_file"] = "./tests/testing_data/system.yaml" Utility.load_environment() connect(**Utility.mongoengine_connection( Utility.environment['database']["url"])) tmp_dir = tempfile.mkdtemp() pytest.tmp_dir = tmp_dir from rasa import train # model without entities train_result = train( domain='tests/testing_data/model_tester/domain.yml', config='tests/testing_data/model_tester/config.yml', training_files=[ 'tests/testing_data/model_tester/nlu_with_entities/nlu.yml', 'tests/testing_data/model_tester/training_stories_success/stories.yml' ], output='tests/testing_data/model_tester/models', core_additional_arguments={"augmentation_factor": 100}, force_training=True) pytest.model_path = train_result.model responses.add( 'POST', Utility.environment["augmentation"]["paraphrase_url"], json={'data': { 'paraphrases': ['common training example'] }}) responses.start() yield None responses.stop() shutil.rmtree(pytest.tmp_dir) shutil.rmtree('tests/testing_data/model_tester/models')
def setup_method(self): responses.start() self.base_url = 'http://nopenopenope.nope' self.regular_html_template = "<html><head>{head}</head><body>{body}</body></html>" self.rss_feed_template = '<link type="application/rss+xml" href="{}" />' self.regular_feed_page = '<?xml version="1.0"?> <rss version="2.0"></rss>'
def mock_api(): with open(path.join(ROOT, 'signin.html'), encoding='utf-8') as f: mock_signin_body = f.read() responses.add(responses.POST, 'https://www.v2ex.com/signin', body=mock_signin_body) responses.add(responses.GET, 'https://www.v2ex.com/signin', body=mock_signin_body) with open(path.join(ROOT, 'once.html'), encoding='utf-8') as f: mock_once_body = f.read() responses.add(responses.GET, 'https://www.v2ex.com/mission/daily/redeem?once=51947', body=mock_once_body) with open(path.join(ROOT, 'balance.html'), encoding='utf-8') as f: mock_balance_body = f.read() responses.add(responses.GET, 'https://www.v2ex.com/balance', body=mock_balance_body) with open(path.join(ROOT, 'mission.html'), encoding='utf-8') as f: mock_mission_body = f.read() responses.add(responses.GET, 'https://www.v2ex.com/mission/daily', body=mock_mission_body) responses.start() yield responses responses.stop()
def setUp(self): super(AkismetClientTests, self).setUp() responses.start() Flag.objects.update_or_create( name=SPAM_CHECKS_FLAG, defaults={'everyone': True}, )
def enable_patching(self): botocore_mock.start() responses.start() for method in RESPONSES_METHODS: for backend in self.backends_for_urls.values(): for key, value in backend.urls.items(): responses.add( CallbackResponse( method=method, url=re.compile(key), callback=convert_flask_to_responses_response( value), stream=True, match_querystring=False, )) botocore_mock.add( CallbackResponse( method=method, url=re.compile(key), callback=convert_flask_to_responses_response( value), stream=True, match_querystring=False, ))
def test_trigger_history_deletion_for_bot(self, monkeypatch): bot = 'test_events_bot' user = '******' month = 1 sender_id = None event_url = "http://url.event" monkeypatch.setitem(Utility.environment['history_server']['deletion'], "event_url", event_url) responses.add("POST", event_url, json={"message": "Event triggered successfully!"}, status=200, match=[ responses.json_params_matcher( [{'name': 'BOT', 'value': bot}, {'name': 'USER', 'value': user}, {'name': 'MONTH', 'value': month}, {'name': 'SENDER_ID', 'value': sender_id}])], ) responses.start() EventsTrigger.trigger_history_deletion(bot, user, month) responses.stop() logs = list(HistoryDeletionLogProcessor.get_logs(bot)) assert len(logs) == 1 assert not logs[0].get('exception') assert logs[0]['start_timestamp'] assert not logs[0].get('end_timestamp') assert logs[0]['status'] == EVENT_STATUS.TASKSPAWNED.value
async def test_trigger_model_testing_event_run_tests_on_model(self, load_data, create_model, monkeypatch): import rasa.utils.common bot = 'test_events_bot' user = '******' config_path = 'tests/testing_data/model_tester/config.yml' domain_path = 'tests/testing_data/model_tester/domain.yml' nlu_path = 'tests/testing_data/model_tester/nlu_success/nlu.yml' stories_path = 'tests/testing_data/model_tester/training_stories_success/stories.yml' await load_data(config_path, domain_path, nlu_path, stories_path, bot, user) create_model(pytest.model_path, bot) def _mock_stories_output(*args, **kwargs): return { "precision": 0.91, "f1": 0.98, "accuracy": 0.99, "failed_stories": [], } monkeypatch.setattr(rasa.utils.common, 'run_in_loop', _mock_stories_output) responses.add('POST', Utility.environment["augmentation"]["paraphrase_url"], json={'data': {'paraphrases': ['common training example']}}) responses.start() EventsTrigger.trigger_model_testing(bot, user, False) logs = list(ModelTestingLogProcessor.get_logs(bot)) assert len(logs) == 2 assert not logs[0].get('exception') assert logs[0]['start_timestamp'] assert logs[0].get('data') assert logs[0].get('end_timestamp') assert not Utility.check_empty_string(logs[0].get('status')) assert logs[0]['event_status'] == EVENT_STATUS.COMPLETED.value assert not os.path.exists(os.path.join('./testing_data', bot))
def test_trigger_model_testing_event(self, monkeypatch): bot = 'test_events_bot' user = '******' event_url = "http://url.event" monkeypatch.setitem(Utility.environment['model']['test'], "event_url", event_url) responses.add("POST", event_url, json={"message": "Event triggered successfully!"}, status=200, match=[ responses.json_params_matcher( [{'name': 'BOT', 'value': bot}, {'name': 'USER', 'value': user}])], ) responses.start() EventsTrigger.trigger_model_testing(bot, user) responses.stop() logs = list(ModelTestingLogProcessor.get_logs(bot)) assert len(logs) == 5 assert not logs[0].get('exception') assert logs[0]['start_timestamp'] assert not logs[0].get('end_timestamp') assert not logs[0].get('status') assert logs[0]['event_status'] == EVENT_STATUS.TASKSPAWNED.value assert not os.path.exists(os.path.join('./testing_data', bot))
async def test_trigger_data_importer_validate_only_event(self, monkeypatch): bot = 'test_events_bot_1' user = '******' event_url = "http://url.event3" monkeypatch.setitem(Utility.environment['model']['data_importer'], "event_url", event_url) responses.add("POST", event_url, json={"message": "Event triggered successfully!"}, status=200, match=[ responses.json_params_matcher( [{'name': 'BOT', 'value': bot}, {'name': 'USER', 'value': user}, {'name': 'IMPORT_DATA', 'value': ''}, {'name': 'OVERWRITE', 'value': ''}])], ) responses.start() await EventsTrigger.trigger_data_importer(bot, user, False, False) responses.stop() logs = list(DataImporterLogProcessor.get_logs(bot)) assert len(logs) == 1 assert not logs[0].get('intents').get('data') assert not logs[0].get('stories').get('data') assert not logs[0].get('utterances').get('data') assert not [action.get('data') for action in logs[0].get('actions') if action.get('type') == 'http_actions'] assert not logs[0].get('training_examples').get('data') assert not logs[0].get('domain').get('data') assert not logs[0].get('config').get('data') assert not logs[0].get('exception') assert logs[0]['is_data_uploaded'] assert logs[0]['start_timestamp'] assert not logs[0].get('end_timestamp') assert not logs[0].get('status') assert logs[0]['event_status'] == EVENT_STATUS.TASKSPAWNED.value
def setup(): responses.add( responses.GET, "http://api.com/users/1/", json={"id": 1, "name": "John", "surname": "Doe"}, ) responses.start()
def setUp(self, single_full_app_fixture): self.single_full_app_fixture = single_full_app_fixture self.user = User(tx_name="User", tx_email="*****@*****.**") self.user.current_account = Account(name="Some Account", namespace="dev", owner="company") responses.add(method='GET', url=conf.MARATHON_ADDRESSES[0] + '/v2/apps//dev/foo', body=json.dumps({'app': self.single_full_app_fixture}), status=200) responses.start()
def setUp(self): super().setUp() self.access_token = "9d646e20-7a62-4bcc-abc0-cb2d4d075e36" self.refresh_token = "32004633-a3c0-4616-9aa0-a40632adac77" self.vsts_account_id = "c8a585ae-b61f-4ba6-833c-9e8d5d1674d8" self.vsts_account_name = "MyVSTSAccount" self.vsts_account_uri = "https://MyVSTSAccount.vssps.visualstudio.com:443/" self.vsts_base_url = "https://MyVSTSAccount.visualstudio.com/" self.vsts_user_id = "d6245f20-2af8-44f4-9451-8107cb2767db" self.vsts_user_name = "Foo Bar" self.vsts_user_email = "*****@*****.**" self.repo_id = "47166099-3e16-4868-9137-22ac6b05b06e" self.repo_name = "cool-service" self.project_a = { "id": "eb6e4656-77fc-42a1-9181-4c6d8e9da5d1", "name": "ProjectA" } self.project_b = { "id": "6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c", "name": "ProjectB" } responses.start() self._stub_vsts()
async def test_run_with_get_placeholder_vs_string_response( self, monkeypatch): action = HttpActionConfig( auth_token="", action_name= "test_run_with_get_string_http_response_placeholder_required", response="The value of ${a.b.3} in ${a.b.d.0} is ${a.b.d}", http_url="http://localhost:8080/mock", request_method="GET", params_list=None, bot="5f50fd0a56b698ca10d35d2e", user="******") def _get_action(*arge, **kwargs): return action.to_mongo().to_dict() monkeypatch.setattr(ActionUtility, "get_http_action_config", _get_action) http_url = 'http://localhost:8082/mock' resp_msg = "This is string http response" responses.start() responses.add( method=responses.GET, url=http_url, body=resp_msg, status=200, ) slots = { "bot": "5f50fd0a56b698ca10d35d2e", "http_action_config_test_run": "test_run_with_get_string_http_response_placeholder_required" } events = [{"event1": "hello"}, {"event2": "how are you"}] dispatcher: CollectingDispatcher = CollectingDispatcher() latest_message = { 'text': 'get intents', 'intent_ranking': [{ 'name': 'test_run' }] } tracker = Tracker(sender_id="sender1", slots=slots, events=events, paused=False, latest_message=latest_message, followup_action=None, active_loop=None, latest_action_name=None) domain: Dict[Text, Any] = None action.save().to_mongo().to_dict() actual: List[Dict[Text, Any]] = await HttpAction().run( dispatcher, tracker, domain) responses.stop() assert actual is not None assert str(actual[0]['name']) == 'KAIRON_ACTION_RESPONSE' assert str( actual[0]['value']) == 'I have failed to process your request'
def responses(): responses_lib.start() yield responses_lib responses_lib.stop() responses_lib.reset()
def setUp(self): super(ManualCourseEnrollmentOrderViewSetTests, self).setUp() self.url = reverse('api:v2:manual-course-enrollment-order-list') self.user = self.create_user(is_staff=True) self.client.login(username=self.user.username, password=self.password) self.course = CourseFactory(id='course-v1:MAX+CX+Course', partner=self.partner) self.course_uuid = '620a5ce5-6ff4-4b2b-bea1-a273c6920ae5' self.course_price = 50 self.course.create_or_update_seat( certificate_type='verified', id_verification_required=True, price=self.course_price ) self.course.create_or_update_seat( certificate_type='audit', id_verification_required=False, price=0 ) self.course_entitlement = create_or_update_course_entitlement( 'verified', 100, self.partner, self.course_uuid, 'Course Entitlement' ) self.mock_access_token_response() self.mock_course_run_detail_endpoint( self.course, discovery_api_url=self.site.siteconfiguration.discovery_api_url, course_run_info={ 'course_uuid': self.course_uuid } ) responses.start()
def mock_api(): """A mock for the PyPI JSON API.""" with open(os.path.join(HERE, 'response.json'), 'r') as fp: webargs_response = fp.read() # A valid package with a proper response responses.add(responses.GET, 'https://pypi.python.org/pypi/webargs/json', body=webargs_response, content_type='application/json') # A valid package with no releases with open(os.path.join(HERE, 'response_noreleases.json'), 'r') as fp: foo_response = fp.read() responses.add(responses.GET, 'https://pypi.python.org/pypi/foo/json', body=foo_response, content_type='application/json') # An invalid package name responses.add(responses.GET, 'https://pypi.python.org/pypi/nope/json', status=404) responses.start() yield responses responses.stop()
def setUp(self): self.ably = RestSetup.get_ably_rest(use_binary_protocol=False) # Mocked responses # without headers responses.add(responses.GET, 'http://rest.ably.io/channels/channel_name/ch1', body='[{"id": 0}, {"id": 1}]', status=200, content_type='application/json') # with headers responses.add_callback( responses.GET, 'http://rest.ably.io/channels/channel_name/ch2', self.get_response_callback( headers={ 'link': '<http://rest.ably.io/channels/channel_name/ch2?page=1>; rel="first",' ' <http://rest.ably.io/channels/channel_name/ch2?page=2>; rel="next"' }, body='[{"id": 0}, {"id": 1}]', status=200), content_type='application/json') # start intercepting requests responses.start() self.paginated_result = PaginatedResult.paginated_query( self.ably.http, url='http://rest.ably.io/channels/channel_name/ch1', response_processor=lambda response: response.to_native()) self.paginated_result_with_headers = PaginatedResult.paginated_query( self.ably.http, url='http://rest.ably.io/channels/channel_name/ch2', response_processor=lambda response: response.to_native())
def setUp(self): super(VstsIntegrationTestCase, self).setUp() self.access_token = '9d646e20-7a62-4bcc-abc0-cb2d4d075e36' self.refresh_token = '32004633-a3c0-4616-9aa0-a40632adac77' self.vsts_account_id = 'c8a585ae-b61f-4ba6-833c-9e8d5d1674d8' self.vsts_account_name = 'MyVSTSAccount' self.vsts_account_uri = 'https://MyVSTSAccount.vssps.visualstudio.com:443/' self.vsts_base_url = 'https://MyVSTSAccount.visualstudio.com/' self.vsts_user_id = 'd6245f20-2af8-44f4-9451-8107cb2767db' self.vsts_user_name = 'Foo Bar' self.vsts_user_email = '*****@*****.**' self.repo_id = '47166099-3e16-4868-9137-22ac6b05b06e' self.repo_name = 'cool-service' self.project_a = { 'id': 'eb6e4656-77fc-42a1-9181-4c6d8e9da5d1', 'name': 'ProjectA', } self.project_b = { 'id': '6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c', 'name': 'ProjectB', } responses.start() self._stub_vsts()
def _pre_setup(self): """ Mock requests and redis. """ super()._pre_setup() responses.start() patch('dumblock.redis', mock_strict_redis_client()).start()
def setUp(self): responses.start() self.api = api.API( self.BASE_URL, api_key='YOUR_API_KEY', lang='en', debug=True, )
def wrapper(*args, **kwargs): responses.start() for response in resps: responses.add(**response) result = f(responses=responses, *args, **kwargs) responses.stop() responses.reset() return result
def responses(request): resp_module.start() def done(): resp_module.stop() resp_module.reset() request.addfinalizer(done)
def setUp(self): self.mock = mock_s3() self.mock.start() # # Populate the data in mock S3 # conn = boto.connect_s3() # s3+dir lists_served bucket first b = conn.create_bucket(self.lists_served_bucket_name) for fname in ['mozpub-track-digest256.ini', 'testpub-bananas-digest256.ini']: k = Key(b) k.name = fname f = open(os.path.join( os.path.dirname(__file__), 'lists_served_s3', fname )) k.set_contents_from_file(f) # s3+file contents b = conn.create_bucket(self.bucket_name) k = Key(b) k.name = self.key_name with open(test_file(self.key_name), 'rb') as f: k.set_contents_from_file(f) # s3+dir keys and contents b = conn.create_bucket(self.dir_bucket_name) for fname in ('index.json', '1', '2', '3', '4', '5', '6'): k = Key(b) k.name = posixpath.join(self.dir_list_name, fname) with open(test_file(posixpath.join('delta_dir_source', fname)), 'rb') as f: k.set_contents_from_file(f) responses.start() GITHUB_API_URL = 'https://api.github.com' SHAVAR_PROD_LISTS_BRANCHES_PATH = ( '/repos/mozilla-services/shavar-prod-lists/branches' ) resp_body = """ [{ "name": "69.0", "commit": { "sha": "35665559e9e4a85c12bb8211b5f9217fbb96062d", "url": "https://api.github.com/repos/mozilla-services/\ shavar-prod-lists/commits/\ 35665559e9e4a85c12bb8211b5f9217fbb96062d" } }] """ responses.add( responses.GET, GITHUB_API_URL + SHAVAR_PROD_LISTS_BRANCHES_PATH, body=resp_body ) # initialize the internal list data structure via the normal method super(S3SourceListsTest, self).setUp()
def activate_responses(request): responses.start() def fin(): responses.reset() responses.stop() request.addfinalizer(fin)
def setUp(self): super(TestMigrateForks, self).setUp() # Create registration with correct settings self.user = UserFactory() self.consolidated_auth = Auth(user=self.user) # Create base project self.base_project = ProjectFactory( creator=self.user, piwik_site_id=1, ) self.base_component = NodeFactory( project=self.base_project, creator=self.user, piwik_site_id=2, ) # Create valid fork self.fork_project = self.base_project.fork_node( auth=self.consolidated_auth ) self.fork_project.piwik_site_id = 3 self.fork_project.save() self.fork_component = self.fork_project.nodes[0] self.fork_component.piwik_site_id = 4 self.fork_component.save() # Create broken fork self.bad_fork_project = self.base_project.fork_node( auth=self.consolidated_auth ) self.bad_fork_project.piwik_site_id = self.base_project.piwik_site_id self.bad_fork_project.save() self.bad_fork_component = self.bad_fork_project.nodes[0] self.bad_fork_component.piwik_site_id = self.base_component.piwik_site_id self.bad_fork_component.save() responses.start() responses.add( responses.GET, '{host}index.php?module=API&method=SitesManager.getAllSites&format=JSON&token_auth={auth_token}'.format( host=PIWIK_HOST, auth_token=PIWIK_ADMIN_TOKEN, ), status=200, content_type='application/json', body=json.dumps({ '1': {'name': 'Node: ' + self.base_project._id}, '2': {'name': 'Node: ' + self.base_component._id}, '3': {'name': 'Node: ' + self.fork_project._id}, '4': {'name': 'Node: ' + self.fork_component._id}, }), match_querystring=True, )
def setUp(self): super(EnterpriseOfferUpdateViewTests, self).setUp() self.enterprise_offer = factories.EnterpriseOfferFactory( partner=self.partner) self.path = reverse('enterprise:offers:edit', kwargs={'pk': self.enterprise_offer.pk}) responses.start() self.mock_specific_enterprise_customer_api( self.enterprise_offer.condition.enterprise_customer_uuid)
def setUp(self): feed_url = 'http://microblog.brianschrader.com/feed' self.feed = models.RemoteFeed.objects.create(feed_url=feed_url) with open(os.path.join(settings.BASE_DIR, 'tests', 'fixtures', 'sonic_feed.xml')) as fixture_file: self.test_feed = fixture_file.read() responses.add(responses.GET, feed_url, body=self.test_feed, status=200, content_type='application/xml') responses.start() self.feed.update_feed()
def test_hook_is_found_and_checksum_fails___hook_is_not_saved(self, name, content, hook_type): self.set_existing_search_response(name, content, hook_type, response_content=content + 'tamper') responses.start() with FakeRepoDir(): sys.argv = ['foo', 'install', hook_type, name] cmd.Hooks().run() self.assertFalse(os.path.exists(os.path.join(repo.hook_type_directory(hook_type), name)))
def setup_method(self, method): responses.start() request_data = self.requests_mock.get(method.__name__, {}) responses.add(method=request_data.get('method', responses.GET), url=request_data.get('uri', self.default_uri), body=request_data.get('body', '{}'), status=request_data.get('status', codes.ok), content_type=request_data.get('content_type', 'application/json'))
def test_hook_is_found_and_checksum_passes___hook_is_saved(self, name, content, hook_type): self.set_existing_search_response(name, content, hook_type) responses.start() with FakeRepoDir(): sys.argv = ['foo', 'install', hook_type, name] cmd.Hooks().run() with open(os.path.join(repo.hook_type_directory(hook_type), name)) as f: self.assertEqual(content, f.read())
def setUp(self): """ Setup variables for test cases. """ super(CouponUtilsTests, self).setUp() self.user = self.create_user(email='*****@*****.**') self.request.user = self.user self.request.GET = {} responses.start()
def _pre_setup(self): # Use Mocket to prevent any real network access from tests #Mocket.enable() # Mock at the level of requests library. # Connectivity tests can use lower level mocks at socket level instead. if self.mock_requests: responses.start() patch('dpm.main.DATAVALIDATE', False).start()
def modified_responses(): responses.start() responses_asserter = ResponsesAsserter() yield responses_asserter responses_asserter.reset_calls() try: responses.stop() except RuntimeError: # Ignore unittest.mock "stop called on unstarted patcher" exception pass
def mock_api(): for package_name in ['requests', 'flask', 'pip']: mock_package_response(package_name) for package_name in ['this_package_name_has_not_been_used', 'you_will_never_use_this_package_name', 'I_suck_and_my_tests_are_order_dependent']: mock_package_response(package_name, status_code=404) responses.start() yield responses responses.stop()
def fixture(): responses.add( responses.POST, url, status=status, body=json.dumps(data or {}), content_type='application/json', ) responses.start() yield responses responses.stop() responses.reset()
def mock_responses(request): def callback(http_request): responses.stop() response = testypie.get_response(http_request.url, http_request.headers) responses.start() return response['code'], response['headers'], response['body'] responses.start() responses.add_callback(responses.GET, re.compile('.*'), callback=callback) request.addfinalizer(responses.stop)
def responses(request): """ Set up the `responses` module for mocking HTTP requests https://github.com/getsentry/responses """ resp_module.start() def done(): resp_module.stop() resp_module.reset() request.addfinalizer(done)
def callback(req): # clean up after last callback add_downloaded_files(state['downloaded'], spec, state['previous_url']) if state['requests'] == state['total_requests']: raise MaxDownloadsReached() # make a real requests call somehow responses.stop() # when testing this testing function # (testTestutil.RepoTester.test_download_setfile) we # still want to disable responses, but we don't want # to make an actual HTTP call. Detect if we are # running that test by examining the stack, and if so, # mock the requests.get call in a different way. frames = [f for f in inspect.stack() if f[3] == "test_download_setfile"] if frames: frame = frames[0][0] resp = frame.f_locals['self']._myget(req.url) else: resp = requests.get(req.url) responses.start() # create a filename. use .html as suffix unless we # should use something else contenttype = resp.headers["Content-type"] stem = os.path.splitext(specfile)[0] suffix = {'application/pdf': 'pdf', 'application/json': 'json', 'text/plain': 'txt'}.get(contenttype, "html") outfile = "%s-%s.%s" % (stem, state['requests'], suffix) with open(outfile, "wb") as fp: fp.write(resp.content) if not frames and os.environ.get("TRAVIS") != "true": if suffix == "html": print( "requested %s, saved as %s. Edit if needed, then press enter" % (req.url, outfile)) x = input() else: print("requested %s, saved %s" % (req.url, outfile)) with open(outfile, "rb") as fp: content = fp.read() spec[req.url] = {'file': os.path.basename(outfile)} if resp.encoding != 'utf-8': spec[req.url]['encoding'] = resp.encoding state['requests'] += 1 state['previous_url'] = req.url return (resp.status_code, resp.headers, content)
def setUp(self): super(AkismetFormTests, self).setUp() responses.start() # reset Akismet client verification for each test AkismetTestForm.akismet_client._verified = None self.request = self.rf.get( '/', REMOTE_ADDR=self.remote_addr, HTTP_USER_AGENT=self.http_user_agent, HTTP_REFERER=self.http_referer, ) Flag.objects.update_or_create( name=SPAM_CHECKS_FLAG, defaults={'everyone': True}, )
def mock_requests(self, request, app): # Mock wasipaid validation results responses.add( responses.POST, 'https://wasipaid.com/receipt', body='VALID', status=200) # Mock the SEPA backend responses.add( responses.POST, app.config['SEPA_API'], body='{"success": true}', status=200) responses.start() def done(): responses.stop() responses.reset() request.addfinalizer(done)
def setup_module(): with open(os.path.join(HERE, 'response.json'), 'r') as fp: response_body = fp.read() responses.add( responses.GET, 'http://pypi.python.org/pypi/webargs/json', body=response_body, content_type='application/json' ) responses.add( responses.GET, 'http://pypi.python.org/pypi/nope/json', status=404 ) responses.start()
def setUp(self): self.ably = AblyRest(key=test_vars["keys"][0]["key_str"], rest_host=test_vars["host"], port=test_vars["port"], tls_port=test_vars["tls_port"], tls=test_vars["tls"], use_binary_protocol=False) # with headers self.token_requests = 0 self.publish_attempts = 0 self.tokens = ['a_token', 'another_token'] self.channel = uuid.uuid4().hex def call_back(request): headers = {'Content-Type': 'application/json'} body = {} self.token_requests += 1 body['token'] = self.tokens[self.token_requests - 1] body['expires'] = (time.time() + 60) * 1000 return (200, headers, json.dumps(body)) responses.add_callback( responses.POST, 'https://sandbox-rest.ably.io:443/keys/{}/requestToken'.format( test_vars["keys"][0]['key_name']), call_back) def call_back(request): headers = {'Content-Type': 'application/json'} self.publish_attempts += 1 if self.publish_attempts in [1, 3]: body = '[]' status = 201 else: body = {'error': {'message': 'Authentication failure', 'statusCode': 401, 'code': 40140}} status = 401 return (status, headers, json.dumps(body)) responses.add_callback( responses.POST, 'https://sandbox-rest.ably.io:443/channels/{}/publish'.format( self.channel), call_back) responses.start()
def start_responses_mocking(request): """Enable ``responses`` this enforcing us to explicitly mark tests that require internet usage. """ marker = request.node.get_closest_marker('allow_external_http_requests') if not marker: responses.start() yield try: if not marker: responses.stop() responses.reset() except RuntimeError: # responses patcher was already uninstalled pass
def setUp(self): responses.reset() responses.add( responses.GET, BasePage.scrape_url, """<html><body> <h1 class="foo" data-foo=1>Heading</h1> <h1 id="the-id">15</h1> <span class=float>3.14</span> <span class=int>42</span> <span class=bool></span> <span class=date>2016-04-23</span> <a href="/very-fake">link</a> <table> <tr>test123 <th>key</th> testmore <td>value</th></tr> <tr><th>key2<td>value2</tr> </table """) responses.start() self.addCleanup(responses.stop)
def setUp(self): self.ably = AblyRest(key=test_vars["keys"][0]["key_str"], rest_host=test_vars["host"], port=test_vars["port"], tls_port=test_vars["tls_port"], tls=test_vars["tls"], use_binary_protocol=False) # Mocked responses # without headers responses.add(responses.GET, 'http://rest.ably.io/channels/channel_name/ch1', body='[{"id": 0}, {"id": 1}]', status=200, content_type='application/json') # with headers responses.add_callback( responses.GET, 'http://rest.ably.io/channels/channel_name/ch2', self.get_response_callback( headers={ 'link': '<http://rest.ably.io/channels/channel_name/ch2?page=1>; rel="first",' ' <http://rest.ably.io/channels/channel_name/ch2?page=2>; rel="next"' }, body='[{"id": 0}, {"id": 1}]', status=200), content_type='application/json') # start intercepting requests responses.start() self.paginated_result = PaginatedResult.paginated_query( self.ably.http, 'http://rest.ably.io/channels/channel_name/ch1', {}, lambda response: response.to_native()) self.paginated_result_with_headers = PaginatedResult.paginated_query( self.ably.http, 'http://rest.ably.io/channels/channel_name/ch2', {}, lambda response: response.to_native())
def setUp(self): super(TestMigrateRegistrations, self).setUp() # Create registration with correct settings self.registration = RegistrationFactory() self.registration.registered_from.piwik_site_id = 1 self.registration.registered_from.save() self.registration.piwik_site_id = 2 self.registration.save() # Create registration with duplicated piwik_site_id self.broken_registration = RegistrationFactory() self.broken_registration.registered_from.piwik_site_id = 3 self.broken_registration.registered_from.save() self.broken_registration.piwik_site_id = 3 self.broken_registration.save() responses.start() responses.add( responses.GET, '{host}index.php?module=API&method=SitesManager.getAllSites&format=JSON&token_auth={auth_token}'.format( host=PIWIK_HOST, auth_token=PIWIK_ADMIN_TOKEN, ), status=200, content_type='application/json', body=json.dumps({ '1': {'name': 'Node: ' + self.registration.registered_from._id}, '2': {'name': 'Node: ' + self.registration._id}, '3': {'name': 'Node: ' + self.broken_registration.registered_from._id}, '4': {'name': 'Node: ' + self.broken_registration._id}, }), match_querystring=True, )
def mock_request(): with open(path.join(path.dirname(path.realpath(__file__)), 'fake_response.json')) as f: fake_response = json.load(f) responses.add( responses.GET, url=("https://www.bing.com/HPImageArchive.aspx?format" "=js&idx=0&n=1&nc=1409879295618&pid=hp"), json=fake_response, status=200, match_querystring=True ) responses.add( responses.GET, url=("https://www.bing.com/az/hprichbg/rb/HudsonBayPolars_" "ZH-CN10500767857_1920x1080.jpg"), status=200, body='Hello, world' ) responses.start() yield responses responses.stop()
def setUp(self): responses.start() self.api = api.API(self.BASE_URL)
def setup_limetypes(): responses.start()