def test_split_subset(self): test_path = Path("test", "example_test.rb") responses.replace( responses.POST, "{}/intake/organizations/{}/workspaces/{}/subset/456/slice".format( get_base_url(), self.organization, self.workspace), json={ 'testPaths': [[{ 'name': str(test_path) }]], 'rest': [], 'subsettingId': 123 }, status=200) rest = tempfile.NamedTemporaryFile(delete=False) result = self.cli('split-subset', '--subset-id', 'subset/456', '--base', str(self.test_files_dir), '--bin', '2/2', '--rest', rest.name, 'minitest') self.assertEqual(result.exit_code, 0) output = Path(self.test_files_dir, "test", "example_test.rb") self.assertEqual(str(output), result.output.rstrip("\n")) self.assertEqual(rest.read().decode().rstrip("\n"), str(output)) rest.close() os.unlink(rest.name)
def test_subset_without_session(self): responses.replace( responses.POST, "{}/intake/organizations/{}/workspaces/{}/subset".format( get_base_url(), self.organization, self.workspace), json={ 'testPaths': [[{ 'name': 'com.launchableinc.rocket_car_gradle.App2Test' }], [{ 'name': 'com.launchableinc.rocket_car_gradle.AppTest' }], [{ 'name': 'com.launchableinc.rocket_car_gradle.sub.App3Test' }], [{ 'name': 'com.launchableinc.rocket_car_gradle.utils.UtilsTest' }]] }, status=200) result = self.cli( 'subset', '--target', '10%', '--build', self.build_name, 'gradle', str(self.test_files_dir.joinpath('java/app/test').resolve())) self.assertEqual(result.exit_code, 0) output = '--tests com.launchableinc.rocket_car_gradle.App2Test --tests com.launchableinc.rocket_car_gradle.AppTest --tests com.launchableinc.rocket_car_gradle.sub.App3Test --tests com.launchableinc.rocket_car_gradle.utils.UtilsTest' self.assertEqual(result.output.rstrip('\n'), output)
def test_subset_split(self): test_path = Path("test", "example_test.rb") responses.replace( responses.POST, "{}/intake/organizations/{}/workspaces/{}/subset".format( get_base_url(), self.organization, self.workspace), json={ 'testPaths': [[{ 'name': str(test_path) }]], 'rest': [], 'subsettingId': 123, 'summary': { 'subset': { 'duration': 10, 'candidates': 1, 'rate': 100 }, 'rest': { 'duration': 0, 'candidates': 0, 'rate': 0 } }, "isBrainless": False, }, status=200) result = self.cli('subset', '--target', '20%', '--session', self.session, '--base', str(self.test_files_dir), '--split', 'minitest', str(self.test_files_dir) + "/test/**/*.rb") self.assertEqual(result.exit_code, 0) self.assertIn('subset/123', result.output)
def test_olm_start_sessions(self, device): responses.add(responses.POST, self.claim_url, json=example_claim_keys_response) user_devices = {self.alice: {self.alice_device_id}} # We don't have alice's keys device.olm_start_sessions(user_devices) assert not device.olm_sessions[self.alice_curve_key] # Cover logging part olm_device.logger.setLevel(logging.WARNING) # Now should be good device.device_keys[self.alice][ self.alice_device_id] = self.alice_device device.olm_start_sessions(user_devices) assert device.olm_sessions[self.alice_curve_key] # With failures and wrong signature device.olm_sessions.clear() payload = deepcopy(example_claim_keys_response) payload['failures'] = {'dummy': 1} key = payload['one_time_keys'][self.alice][self.alice_device_id] key['signed_curve25519:AAAAAQ']['test'] = 1 responses.replace(responses.POST, self.claim_url, json=payload) device.olm_start_sessions(user_devices) assert not device.olm_sessions[self.alice_curve_key] # Missing requested user and devices user_devices[self.alice].add('test') user_devices['test'] = 'test' device.olm_start_sessions(user_devices)
def test_prison_confirmation(self): current_prison = SAMPLE_PRISONS[0] new_prison = SAMPLE_PRISONS[1] mock_prison_response() self.login(responses, user_data=self.get_user_data(prisons=[current_prison], flags=[hmpps_employee_flag])) responses.add(responses.PATCH, api_url('/users/shall/'), json={}) responses.replace(responses.GET, api_url('/users/shall/'), json=self.get_user_data(prisons=[new_prison])) responses.add(responses.PUT, api_url('/users/shall/flags/%s/' % confirmed_prisons_flag), json={}) response = self.client.post(reverse('confirm_prisons'), data={'prisons': [new_prison['nomis_id']]}, follow=True) self.assertEqual( set(p['nomis_id'] for p in json.loads( responses.calls[-3].request.body.decode())['prisons']), set([new_prison['nomis_id']])) self.assertContains(response, '<!-- confirm_prisons_confirmation -->') self.assertIn(confirmed_prisons_flag, self.client.session[USER_DATA_SESSION_KEY]['flags']) self.assertIn(confirmed_prisons_flag, response.context['user'].user_data['flags']) self.assertEqual([new_prison], self.client.session[USER_DATA_SESSION_KEY]['prisons']) self.assertEqual([new_prison], response.context['user'].user_data['prisons'])
def test_proforma(self): backend = get_backend("fio-bank")(self.payment) self.assertIsNotNone(backend.initiate(None, "", "/complete/")) self.check_payment(Payment.PENDING) self.assertFalse(backend.complete(None)) self.check_payment(Payment.PENDING) responses.add(responses.GET, FIO_API, body=json.dumps(FIO_TRASACTIONS)) FioBank.fetch_payments() self.check_payment(Payment.PENDING) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Your pending payment on weblate.org") mail.outbox = [] received = copy(FIO_TRASACTIONS) proforma_id = backend.payment.invoice transaction = received["accountStatement"]["transactionList"]["transaction"] transaction[0]["column16"]["value"] = proforma_id transaction[1]["column16"]["value"] = proforma_id transaction[1]["column1"]["value"] = backend.payment.amount * 1.21 responses.replace(responses.GET, FIO_API, body=json.dumps(received)) FioBank.fetch_payments() payment = self.check_payment(Payment.ACCEPTED) self.maxDiff = None self.assertEqual( payment.details["transaction"]["recipient_message"], proforma_id ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Your payment on weblate.org")
def test_analyze_manifest_list(self): list_image_manifest_url = self.reg_url + \ 'org/image-name/manifests/sha256:d0fec089e611891a03f3282f10115bb186ed46093c3f083eceb250cee64b63eb' with open('tests/test_data/manifest.list.v2.json') as f: list_manifest = json.load(f) with open('tests/test_data/manifest.list.v2-image.json') as f: list_image_manifest = json.load(f) with open('tests/test_data/origin_vulnerabilities_list.json') as f: list_origin_data = json.load(f) responses.add(responses.GET, '%s/%s?features&vulnerabilities' % (self.v1_analyze_url, list_origin_data['Layer']['Name']), json=list_origin_data) responses.replace(responses.GET, self.manifest_url, json=list_manifest, status=200) responses.add(responses.GET, list_image_manifest_url, json=list_image_manifest, status=200) layers = [e['digest'] for e in list_image_manifest['layers']] responses.add(responses.DELETE, '%s/%s' % (self.v1_analyze_url, layers[0])) for layer in layers: responses.add(responses.GET, '%s/%s' % (self.v1_analyze_url, layer)) with patch('sys.argv', ['claircli', '-d', '-c', self.clair_url, self.name]): cli = ClairCli() cli.run() image = Image(self.name) self.assert_called_with_url() for index, layer in enumerate(image.images[0].layers, start=5): self.assertEqual( responses.calls[index].request.url, self.v1_analyze_url) req_body = json.loads(responses.calls[index].request.body) self.assertEqual(req_body['Layer']['Name'], layer) self.html = Report.get_report_path('{}/{}@{}'.format(self.reg, self.repo, image.manifest['manifests'][0]['digest']), '.html') self.assertTrue(isfile(self.html))
def test_validate_anvil_registration(self, mock_logger): url = TEST_TERRA_API_ROOT_URL + 'register' responses.add(responses.GET, url, status=404) r = validate_anvil_registration(GoogleOAuth2(), { 'access_token': '', 'email': '*****@*****.**' }) mock_logger.warning.assert_called_with( 'User [email protected] is trying to login without registration on AnVIL. None called Terra API: GET /register got status 404 with reason: Not Found' ) self.assertEqual(r.url, '/login?anvilLoginFailed=true') self.assertEqual(len(mock_logger.method_calls), 1) backend = GoogleOAuth2() backend.strategy.session_set('next', '/foo/bar') r = validate_anvil_registration(backend, { 'access_token': '', 'email': '*****@*****.**' }) self.assertEqual(r.url, '/login?anvilLoginFailed=true&next=%2Ffoo%2Fbar') mock_logger.reset_mock() responses.replace(responses.GET, url, status=200, body=REGISTER_RESPONSE) r = validate_anvil_registration(GoogleOAuth2(), { 'access_token': '', 'email': '*****@*****.**' }) mock_logger.warning.assert_not_called() self.assertIsNone(r)
def test_up_to_date_info(self): """ Do not update when the information is up-to-date. The hook must not patch when there is no different between local recipe and remote info. """ information = { "desc": "This a dummy library", "labels":["conan", "dummy", "qux", "baz"], "licenses":["MIT"], "website_url": "https://dummy.org", "issue_tracker_url":"https://github.com/foobar/community/issues", "vcs_url":"https://github.com/foobar/conan-dummy", "github_repo": "foobar/conan-dummy", "maturity":"Stable" } responses.replace(responses.GET, 'https://api.bintray.com/packages/foobar/conan/dummy%3Afoobar', json=information) tools.save('conanfile.py', content=self.conanfile_complete) self.conan(['export', '.', 'dummy/0.1.0@foobar/stable']) output = self.conan(['upload', '--remote=fake', 'dummy/0.1.0@foobar/stable']) self.assertIn("Uploading dummy/0.1.0@foobar/stable to remote 'fake'", output) self.assertIn("Uploaded conan recipe 'dummy/0.1.0@foobar/stable' to 'fake': https://bintray.com/foobar/conan", output) self.assertIn("post_upload_recipe(): Reading package info from Bintray.", output) self.assertIn("post_upload_recipe(): Inspecting recipe info.", output) self.assertNotIn("post_upload_recipe(): Bintray is outdated.", output) self.assertIn("post_upload_recipe(): Bintray package info is up-to-date.", output) self.assertNotIn("post_upload_recipe(): Bintray package information has been updated with success.", output)
def test_subset(self): test_session_id = 16 responses.replace(responses.GET, "{}/intake/organizations/{}/workspaces/{}/test_sessions/{}/events".format( get_base_url(), self.organization, self.workspace, test_session_id), json=[ {"testPath": [ {"type": "file", "name": "test_file1.py"}], "duration": 1.2, "stderr": "", "stdout": "", "createdAt": "2021-01-02T03:04:05.000+00:00", "status": "SUCCESS"}, {"testPath": [ {"type": "file", "name": "test_file3.py"}], "duration": 0.6, "stderr": "", "stdout": "", "createdAt": "2021-01-02T03:04:05.000+00:00", "status": "SUCCESS"}, {"testPath": [ {"type": "file", "name": "test_file4.py"}], "duration": 1.8, "stderr": "", "stdout": "", "createdAt": "2021-01-02T03:04:05.000+00:00", "status": "FAILURE"}, {"testPath": [ {"type": "file", "name": "test_file2.py"}], "duration": 0.1, "stderr": "", "stdout": "", "createdAt": "2021-01-02T03:04:05.000+00:00", "status": "FAILURE"}, ], status=200) result = self.cli('inspect', 'tests', '--test-session-id', test_session_id, mix_stderr=False) expect = """| Test Path | Duration (sec) | Status | Uploaded At | |--------------------|------------------|----------|-------------------------------| | file=test_file1.py | 1.2 | SUCCESS | 2021-01-02T03:04:05.000+00:00 | | file=test_file3.py | 0.6 | SUCCESS | 2021-01-02T03:04:05.000+00:00 | | file=test_file4.py | 1.8 | FAILURE | 2021-01-02T03:04:05.000+00:00 | | file=test_file2.py | 0.1 | FAILURE | 2021-01-02T03:04:05.000+00:00 | """ self.assertEqual(result.stdout, expect)
def test_update_strava_activity_changed(self): strava_activity = self.load_strava_activity_from_json( "manual_activity.json") activity = Activity(athlete=self.athlete, strava_id=strava_activity.id) # save the manual strava activity activity.update_with_strava_data(strava_activity) self.assertEqual(activity.description, "Manual Description") activity_url = ACTIVITY_URL.format(activity.strava_id) changed_json = read_data("manual_activity_changed.json", dir_path=CURRENT_DIR) responses.replace( responses.GET, activity_url, content_type="application/json", body=changed_json, status=200, ) strava_activity = activity.get_activity_from_strava() activity.update_with_strava_data(strava_activity) assert activity.description == "" assert Activity.objects.count() == 1
def test_refresh_token(self, mock_anvil_call, mock_logger): user = User.objects.get(username='******') with mock.patch( 'seqr.views.utils.terra_api_utils.time.time') as mock_time: mock_time.return_value = AUTH_EXTRA_DATA['auth_time'] + 60 * 60 + 10 responses.add(responses.POST, GOOGLE_ACCESS_TOKEN_URL, status=401) with self.assertRaises(TerraRefreshTokenFailedException) as te: _ = list_anvil_workspaces(user) self.assertEqual( str(te.exception), 'Refresh token failed. 401 Client Error: Unauthorized for url: https://accounts.google.com/o/oauth2/token' ) self.assertEqual(te.exception.status_code, 401) mock_logger.warning.assert_called_with( 'Refresh token failed. 401 Client Error: Unauthorized for url: https://accounts.google.com/o/oauth2/token', user) self.assertEqual(mock_logger.warning.call_count, 1) mock_logger.info.assert_called_with('Refreshing access token', user) self.assertEqual(mock_logger.info.call_count, 1) mock_logger.reset_mock() responses.replace(responses.POST, GOOGLE_ACCESS_TOKEN_URL, status=200, body=GOOGLE_TOKEN_RESULT) list_anvil_workspaces(user) mock_logger.warning.assert_not_called() mock_logger.info.assert_called_with('Refreshing access token', user) self.assertEqual(mock_logger.info.call_count, 1) self.assertEqual(mock_anvil_call.call_count, 1) self.assertEqual(mock_anvil_call.call_args.args[2], 'ya29.c.EXAMPLE')
def run(): responses.add(responses.GET, original) with pytest.raises(ValueError) as excinfo: responses.replace(responses.GET, replacement) assert "Response is not registered for URL %s" % replacement in str( excinfo.value )
def test_create_video_request_error(self) -> None: responses.add( responses.POST, "https://zoom.us/oauth/token", json={"access_token": "token"}, ) responses.add( responses.POST, "https://api.zoom.us/v2/users/me/meetings", status=400, ) response = self.client_get( "/calls/zoom/complete", { "code": "code", "state": '{"realm":"zulip","sid":""}' }, ) self.assertEqual(response.status_code, 200) response = self.client_post("/json/calls/zoom/create") self.assert_json_error(response, "Failed to create Zoom call") responses.replace( responses.POST, "https://api.zoom.us/v2/users/me/meetings", status=401, ) response = self.client_post("/json/calls/zoom/create") self.assert_json_error(response, "Invalid Zoom access token")
def test_create_video_refresh_error(self) -> None: responses.add( responses.POST, "https://zoom.us/oauth/token", json={ "access_token": "token", "expires_in": -60 }, ) response = self.client_get( "/calls/zoom/complete", { "code": "code", "state": '{"realm":"zulip","sid":""}' }, ) self.assertEqual(response.status_code, 200) responses.replace(responses.POST, "https://zoom.us/oauth/token", status=400) response = self.client_post("/json/calls/zoom/create") self.assert_json_error(response, "Invalid Zoom access token")
def test_create_subscription_unauthorized(self, mock_get_scopes): responses.replace( responses.POST, f"https://{self.vsts_account_name.lower()}.visualstudio.com/_apis/hooks/subscriptions", status=401, json={ "$id": 1, "message": "The user bob is not authorized to access this resource", "typeKey": "UnauthorizedRequestException", "errorCode": 0, "eventId": 3000, }, ) state = { "account": { "accountName": self.vsts_account_name, "accountId": self.vsts_account_id }, "base_url": self.vsts_base_url, "identity": { "data": { "access_token": self.access_token, "expires_in": "3600", "refresh_token": self.refresh_token, "token_type": "jwt-bearer", } }, } integration = VstsIntegrationProvider() with pytest.raises(IntegrationError) as err: integration.build_integration(state) assert "sufficient account access to create webhooks" in str(err)
def test_igv_genomes_proxyy(self): url_path = 'org.genomes/foo?query=true' url = reverse(igv_genomes_proxy, args=[url_path]) expected_body = {'genes': ['GENE1', 'GENE2']} responses.add( responses.GET, 'https://s3.amazonaws.com/igv.org.genomes/foo?query=true', match_querystring=True, content_type='application/json', body=json.dumps(expected_body)) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertDictEqual(json.loads(response.content), expected_body) self.assertIsNone(responses.calls[0].request.headers.get('Range')) # test with range header proxy expected_content = 'test file content' responses.replace( responses.GET, 'https://s3.amazonaws.com/igv.org.genomes/foo?query=true', match_querystring=True, body=expected_content) response = self.client.get(url, HTTP_RANGE='bytes=100-200') self.assertEqual(response.status_code, 200) self.assertEqual(response.content.decode(), expected_content) self.assertEqual(responses.calls[1].request.headers.get('Range'), 'bytes=100-200')
def test_get(self): self.mock_pypi() data = get_version_info() self.assertEqual(len(data), 47) responses.replace(responses.GET, PYPI, body="") data = get_version_info() self.assertEqual(len(data), 47)
def func(service, path, method=responses.GET, adding_headers=None, replace=False, match_querystring=False, **kwargs): base_url_map = { "auth": "https://auth.globus.org/", "nexus": "https://nexus.api.globusonline.org/", "transfer": "https://transfer.api.globus.org/v0.10", "search": "https://search.api.globus.org/", } assert service in base_url_map base_url = base_url_map.get(service) full_url = slash_join(base_url, path) # can set it to `{}` explicitly to clear the default if adding_headers is None: adding_headers = {"Content-Type": "application/json"} if replace: responses.replace(method, full_url, headers=adding_headers, match_querystring=match_querystring, **kwargs) else: responses.add(method, full_url, headers=adding_headers, match_querystring=match_querystring, **kwargs)
def test_record_tests(self): test_files_dir = Path(__file__).parent.joinpath( '../data/minitest/').resolve() responses.replace( responses.POST, "{base}/intake/organizations/{org}/workspaces/{ws}/builds/{build}/test_sessions/{session_id}/events" .format(base=get_base_url(), org=self.organization, ws=self.workspace, build=self.build_name, session_id=self.session_id), json=[], status=500) result = self.cli("record", "tests", "--session", self.session, "minitest", str(test_files_dir) + "/") self.assertEqual(result.exit_code, 0) responses.replace( responses.POST, "{base}/intake/organizations/{org}/workspaces/{ws}/builds/{build}/test_sessions/{session_id}/events" .format(base=get_base_url(), org=self.organization, ws=self.workspace, build=self.build_name, session_id=self.session_id), json=[], status=404) result = self.cli("record", "tests", "--session", self.session, "minitest", str(test_files_dir) + "/") self.assertEqual(result.exit_code, 0)
def test_refresh_token_after_some_time(refresh_tokens_response): # login the client for the first time client = TgtgClient(**tgtg_client_fake_tokens) client.login() new_access_token = "new_access_token" new_refresh_token = "new_refresh_token" responses.replace( responses.POST, urljoin(BASE_URL, REFRESH_ENDPOINT), json={ "access_token": new_access_token, "refresh_token": new_refresh_token }, status=200, ) # token lifetime is ok, no need to refresh with freeze_time(datetime.datetime.now() + datetime.timedelta( seconds=DEFAULT_ACCESS_TOKEN_LIFETIME)): client.login() assert client.access_token != new_access_token assert client.refresh_token != new_refresh_token # token lifetime expired, refresh needed with freeze_time(datetime.datetime.now() + datetime.timedelta( seconds=DEFAULT_ACCESS_TOKEN_LIFETIME + 1)): client.login() assert client.access_token == new_access_token assert client.refresh_token == new_refresh_token
def test_no_error_on_ignorable_slack_errors(self): responses.add("POST", "http://example.com/slack", status=403, body="action_prohibited") self.plugin.set_option("webhook", "http://example.com/slack", self.project) event = self.store_event( data={ "message": "Hello world", "level": "warning", "culprit": "foo.bar" }, project_id=self.project.id, ) rule = Rule.objects.create(project=self.project, label="my rule") notification = Notification(event=event, rule=rule) # No exception since certain errors are supposed to be ignored with self.options({"system.url-prefix": "http://example.com"}): self.plugin.notify(notification) responses.replace("POST", "http://example.com/slack", status=403, body="some_other_error") # Other exceptions should not be ignored with self.options({"system.url-prefix": "http://example.com"}): with pytest.raises(ApiError): self.plugin.notify(notification)
def test_get_display_name(self, user, room): displayname_url = HOSTNAME + MATRIX_V2_API_PATH + \ "/profile/{}/displayname".format(user.user_id) displayname = 'test' room_displayname = 'room_test' # No displayname assert user.get_display_name(room) == user.user_id responses.add(responses.GET, displayname_url, json={}) assert user.get_display_name() == user.user_id assert len(responses.calls) == 1 # Get global displayname responses.replace(responses.GET, displayname_url, json={"displayname": displayname}) assert user.get_display_name() == displayname assert len(responses.calls) == 2 # Global displayname already present assert user.get_display_name() == displayname # No new request assert len(responses.calls) == 2 # Per-room displayname room.members_displaynames[user.user_id] = room_displayname assert user.get_display_name(room) == room_displayname # No new request assert len(responses.calls) == 2
def test_anvil_call(self, mock_logger): url = '{}register'.format(TEST_TERRA_API_ROOT_URL) responses.add(responses.GET, url, status=200, body=REGISTER_RESPONSE) r = anvil_call('get', 'register', 'ya.EXAMPLE') self.assertDictEqual(r['userInfo'], { "userEmail": "*****@*****.**", "userSubjectId": "123456" }) mock_logger.info.assert_called_with( 'GET https://terra.api/register 200 127 None') self.assertEqual(len(mock_logger.method_calls), 1) mock_logger.reset_mock() responses.replace( responses.GET, url, status=404, body= '{"causes": [], "message": "google subject Id 123456 not found in sam", "source": "sam", "stackTrace": [], "statusCode": 404, "timestamp": 1605282720182}' ) with self.assertRaises(TerraNotFoundException) as te: _ = anvil_call('get', 'register', 'ya.EXAMPLE') self.assertEqual( str(te.exception), 'None called Terra API: GET /register got status 404 with reason: Not Found' ) self.assertEqual(len(mock_logger.method_calls), 0)
def test_unsupported_manifest(self): with open('tests/test_data/manifest.unsupported.json') as f: manifest = json.load(f) responses.replace(responses.GET, self.manifest_url, json=manifest, status=200) with self.assertRaises(ValueError): image = Image(self.name) image.layers
def test_list_manifest(self): with open('tests/test_data/manifest.list.v2.json') as f: list_manifest = json.load(f) responses.replace(responses.GET, self.manifest_url, json=list_manifest, status=200) image = Image(self.name) self.assertEqual(image.manifest, list_manifest) self.assert_called_with_url()
def run(): responses.add( Response(method=responses.GET, url="http://example.com/one")) with pytest.raises(ValueError) as excinfo: responses.replace( Response(method=responses.GET, url="http://example.com/two")) assert "Response is not registered for URL http://example.com/two" in str( excinfo.value)
def test_cache_disabled(self): responses.add(responses.GET, self.api_url, json={}, status=200) response = self.client.get(self.endpoint_url) self.assertEqual(200, response.status_code) responses.replace(responses.GET, self.api_url, body=ConnectionError()) response = self.client.get(self.endpoint_url) self.assertEqual(response.status_code, 502)
def test_layers_v1(self): with open('tests/test_data/manifest.v1.json') as f: manifest = json.load(f) responses.replace(responses.GET, self.image_manifest_url, json=manifest, status=200) image = Image(self.name) self.assertEqual(image.layers, [e['blobSum'] for e in manifest['fsLayers']][::-1]) self.assert_called_with_url()
def test_hmart(self): body = { 'tpldata': [ { 'custno': '123', 'custname': 'foo', 'trdate': '07/14/2018', 'point': '182', 'isdeleted': '0', }, ], } responses.add( responses.POST, HMART_POINTS_URL, json=body, ) self.mock_slack() bot.hmart() self.assert_calls(HMART_POINTS_URL, SLACK_MESSAGE_URL) self.assert_slack(responses.calls[1], '182 Hmart points as of 07/14/2018') self.reset_calls() bot.hmart() self.assert_calls(HMART_POINTS_URL) self.reset_calls() new_body = { 'tpldata': [ { 'custno': '123', 'custname': 'foo', 'trdate': '07/15/2018', 'point': '213', 'isdeleted': '0', }, ], } responses.replace( responses.POST, HMART_POINTS_URL, json=new_body, ) bot.hmart() self.assert_calls(HMART_POINTS_URL, SLACK_MESSAGE_URL) self.assert_slack(responses.calls[1], '213 Hmart points as of 07/15/2018')
def test_cache_disabled(self): test_url = "https://dashboard.snapcraft.io" session = requests.Session() responses.add(responses.GET, test_url, body="test_string", status=200) response = session.get(test_url) self.assertEqual(response.text, "test_string") responses.replace( responses.GET, test_url, body="Server error", status=500 ) response = session.get(test_url) self.assertNotEqual(response.text, "test_string")
def run(): responses.add(responses.GET, "http://example.com/one", body="test1") if isinstance(original, BaseResponse): responses.add(original) else: responses.add(responses.GET, original, body="test2") responses.add(responses.GET, "http://example.com/three", body="test3") responses.add( responses.GET, re.compile(r"http://example\.com/four"), body="test3" ) if isinstance(replacement, BaseResponse): responses.replace(replacement) else: responses.replace(responses.GET, replacement, body="testtwo") resp = requests.get("http://example.com/two") assert_response(resp, "testtwo")
def run(): responses.add(responses.GET, 'http://example.com/one', body='test1') if isinstance(original, BaseResponse): responses.add(original) else: responses.add(responses.GET, original, body='test2') responses.add(responses.GET, 'http://example.com/three', body='test3') responses.add( responses.GET, re.compile(r'http://example\.com/four'), body='test3') if isinstance(replacement, BaseResponse): responses.replace(replacement) else: responses.replace(responses.GET, replacement, body='testtwo') resp = requests.get('http://example.com/two') assert_response(resp, 'testtwo')
def run(): responses.add(responses.GET, original) with pytest.raises(ValueError): responses.replace(responses.GET, replacement)