def test_calls(self): # rpc call with positional parameters: def callback1(request): request_message = json.loads(request.body) self.assertEqual(request_message["params"], [42, 23]) return (200, {}, u'{"jsonrpc": "2.0", "result": 19, "id": 1}') responses.add_callback( responses.POST, 'http://mock/xmlrpc', content_type='application/json', callback=callback1, ) self.assertEqual(self.server.subtract(42, 23), 19) responses.reset() # rpc call with named parameters def callback2(request): request_message = json.loads(request.body) self.assertEqual(request_message["params"], {'y': 23, 'x': 42}) return (200, {}, u'{"jsonrpc": "2.0", "result": 19, "id": 1}') responses.add_callback( responses.POST, 'http://mock/xmlrpc', content_type='application/json', callback=callback2, ) self.assertEqual(self.server.subtract(x=42, y=23), 19) responses.reset()
def test_create_user(self): responses.reset() fixture = load_fixture("users/show/39.json") fixture = json.loads(fixture) fixture.update({'password':'******', 'password_confirmation':'password', 'login':'******'}) def check_user_was_created(request): body = json.loads(request.body) expected_data = { 'access_token': body['access_token'], 'user': fixture, } nose.tools.assert_equal(expected_data, body) return (200, {}, {}) mock_auth_response() responses.add_callback(responses.POST, RequestHandler._build_end_point_uri('/users/create'), callback=check_user_was_created, content_type='application/json') api = CsaAPI("admin", 'taliesin') api.create_user(fixture)
def test_user_can_update_self(self): # Mock requests for auth, get user mock_auth_response() fixture = mock_show_user_response(39) # Mock update request to modify the fixture def check_payload(request): payload = json.loads(request.body) nose.tools.assert_equal(1986, payload["grad_year"]) fixture['grad_year'] = payload["grad_year"] return (200, {}, {}) responses.add_callback(responses.PUT, RequestHandler._build_end_point_uri('/users/update/:id', {':id': '39'}), callback=check_payload, content_type='application/json') # Get the user and make some changes api = CsaAPI("cwl39", 'taliesin') user = api.get_user(39) user["grad_year"] = 1986 api.update_user(user) # Mock the updated user response responses.reset() mock_show_user_response(39, body=json.dumps(fixture)) # Check it matches resp = api.get_user(39) nose.tools.assert_equal(1986, resp["grad_year"])
def test_is_implemented(self): lists = load_fixture('lists.yml')['items'] fixt = lists[1] responses.add(responses.GET, pyholster.api.baseurl + '/lists/{}'.format(fixt['address']), status=400, body=json.dumps({'list': fixt})) lst = pyholster.MailingList(**fixt) assert not lst.is_implemented() assert len(responses.calls) is 1 responses.reset() responses.add(responses.GET, pyholster.api.baseurl + '/lists/{}'.format(fixt['address']), status=200, body=json.dumps({'list': fixt})) lst = pyholster.MailingList.load(fixt['address']) assert isinstance(lst, pyholster.MailingList) assert lst.address == fixt['address'] assert lst.name == fixt['name'] assert lst.description == fixt['description']
def test_parse_response(self): class MockResponse(object): def __init__(self, json_data, status_code=200): self.json_data = json_data self.status_code = status_code def json(self): return self.json_data # catch non-json responses with self.assertRaises(ProtocolError) as protocol_error: responses.add(responses.POST, 'http://mock/xmlrpc', body='not json', content_type='application/json') self.server.send_request('my_method', is_notification=False, params=None) if sys.version_info > (3, 0): self.assertEqual(protocol_error.exception.message, """Cannot deserialize response body: Expecting value: line 1 column 1 (char 0)""") else: self.assertEqual(protocol_error.exception.message, """Cannot deserialize response body: No JSON object could be decoded""") self.assertIsInstance(protocol_error.exception.server_response, requests.Response) responses.reset() with self.assertRaisesRegex(ProtocolError, 'Response is not a dictionary'): self.server.parse_response(MockResponse([])) with self.assertRaisesRegex(ProtocolError, 'Response without a result field'): self.server.parse_response(MockResponse({})) with self.assertRaises(ProtocolError) as protoerror: body = {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"} self.server.parse_response(MockResponse(body)) self.assertEqual(protoerror.exception.message, '''Error: -32601 Method not found''')
def test_idrac_scan_success(mock_args): responses.reset() responses.add(**MockResponses.idrac_fp) responses.add(**MockResponses.idrac_auth) reset_handlers() se = core.main() assert se.found_q.qsize() == 1
def test_notification(self): # Verify that we ignore the server response responses.add(responses.POST, 'http://mock/xmlrpc', body='{"jsonrpc": "2.0", "result": 19, "id": 3}', content_type='application/json') self.assertIsNone(self.server.subtract(42, 23, _notification=True)) responses.reset()
def test_update_with_invalid_mentenanceid(self): def request_callback(request): method = json.loads(request.body)['method'] if method == 'maintenance.get': return (200, {}, json.dumps(get_response('22'))) else: return (200, {}, json.dumps(update_response('22'))) responses.add( responses.POST, 'https://example.com/zabbix/api_jsonrpc.php', body=json.dumps({ 'result': 'authentication_token', 'id': 1, 'jsonrpc': '2.0' }), status=200, content_type='application/json' ) m = self._makeOne( host='https://example.com', user='******', password='******') maintenance_id = '22' responses.reset() responses.add_callback(responses.POST, 'https://example.com/zabbix/api_jsonrpc.php', callback=request_callback, content_type='application/json') for key in ('maintenanceid', 'name', 'active_since', 'active_till'): required_params = {'maintenanceid': maintenance_id, 'name': 'test', 'active_since': '2004-04-01T12:00+09:00', 'active_till': '2014-04-01T12:00+09:00'} with self.assertRaises(jsonschema.exceptions.ValidationError): required_params.pop(key) m.update(required_params)
def testTearDown(self): try: responses.stop() except RuntimeError: pass finally: responses.reset()
def test_extractor_post_triggers_slack_notification(self, testapp): ''' A valid heartbeat post triggers a Slack notification ''' # set up the extractor department = Department.create(name="Good Police Department", short_name="GPD", load_defaults=False) Extractor.create(username='******', email='*****@*****.**', password="******", department_id=department.id, next_month=10, next_year=2006) # set the correct authorization testapp.authorization = ('Basic', ('extractor', 'password')) # set a fake Slack webhook URL fake_webhook_url = 'http://webhook.example.com/' current_app.config['SLACK_WEBHOOK_URL'] = fake_webhook_url # create a mock to receive POST requests to that URL responses.add(responses.POST, fake_webhook_url, status=200) # post a sample json object to the heartbeat URL testapp.post_json("/data/heartbeat", params={"heartbeat": "heartbeat"}) # test the captured post payload post_body = json.loads(responses.calls[0].request.body) assert 'Comport Pinged by Extractor!' in post_body['text'] # delete the fake Slack webhook URL del(current_app.config['SLACK_WEBHOOK_URL']) # reset the mock responses.reset()
def test_update(self): fixt = load_fixture('routes.yml')['items'][0] responses.add(responses.GET, ph.api.baseurl + '/routes/{}'.format(fixt['id']), status=200, body=json.dumps(dict(route=fixt))) route = ph.Route.load(format(fixt['id'])) with pytest.raises(AttributeError): route.update(id=6) with pytest.raises(ph.errors.MailgunRequestException): route.update(priority=1) responses.add(responses.PUT, ph.api.baseurl + '/routes/{}'.format(fixt['id']), status=200, body="{}") route.update(priority=1, description="This is random.") assert route.priority is 1 assert route.description == "This is random." assert route.actions == fixt['actions'] responses.reset() with pytest.raises(ph.errors.MailgunException): route.update(priority=1)
def test_login_successful(self): "Mocks a login response to be successful to test authentication state" responses.add( responses.POST, self.get_api_url('API/login'), body=self.load_xml_response('200_login.xml'), status=200, content_type='application/xml') api = API( mode='test', account='test', password='******', auto_login=False) # Before login is called state should be not authenticated self.assertEqual(api._is_authenticated, False) api.login() # State should be authenticated after the login self.assertEqual(api._is_authenticated, True) # Use a response callback to assert whether or not login attempts # to log in again even if the object is already in an authenticated # state. This is done by setting a state in thread locals, if we ever # reach this point in the code. Bit of a hack. def http_callback(request): content = self.load_xml_response('200_login.xml') headers = { 'content-type': 'application/xml', } DATA.callback_reached = True return (200, headers, content) responses.reset() responses.add_callback( responses.POST, self.get_api_url('API/login'), callback=http_callback, content_type='application/xml') api.login() self.assertEqual(getattr(DATA, 'callback_reached', None), None)
def test_update_with_valid_mentenanceid(self): responses.add( responses.POST, 'https://example.com/zabbix/api_jsonrpc.php', body=json.dumps({ 'result': 'authentication_token', 'id': 1, 'jsonrpc': '2.0' }), status=200, content_type='application/json' ) m = self._makeOne( host='https://example.com', user='******', password='******') maintenance_id = '22' responses.reset() responses.add(responses.POST, 'https://example.com/zabbix/api_jsonrpc.php', body=json.dumps(update_response(maintenance_id)), status=200, content_type='application/json') r = m.update({'maintenanceid': maintenance_id, 'name': 'test', 'active_since': '2004-04-01T12:00+09:00', 'active_till': '2014-04-01T12:00+09:00'}) self.assertEqual(r[0]['maintenanceid'], maintenance_id)
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 test(): responses.reset() responses.add(**{ 'method': responses.GET, 'url': 'http://www.pixiv.net/', 'body': 'Just touch, Do not access it really.' ' Because they block us.', 'content_type': 'text/html; charset=utf-8', 'status': 200, }) responses.add(**{ 'method': responses.POST, 'url': 'https://www.pixiv.net/login.php', 'body': '誤入力が続いたため、アカウントのロックを行いました。' 'しばらく経ってからログインをお試しください。', 'content_type': 'text/html; charset=utf-8', 'status': 200, }) id, pw = fx_valid_id_pw runner = CliRunner() result = runner.invoke( ugoira, ['--id', id, '--password', pw, '53239740', 'test.gif'] ) assert result.exit_code == 1 assert result.output.strip() == \ 'Your login is restricted. Try it after.'
def test_with_return_create_status(self): class ResourceMethod(ResourceMethodBase): method = 'put' return_create_status = True responses.add( 'PUT', self.base_uri, json='world', status=201 ) instance = self.get_instance(ResourceMethod) assert_that( instance(), equal_to({ 'created': True, 'result': 'world' }) ) # test when not created responses.reset() responses.add( 'PUT', self.base_uri, json='world', status=200 ) assert_that( instance(), equal_to({ 'created': False, 'result': 'world' }) )
def test(): responses.reset() responses.add(**{ 'method': responses.GET, 'url': 'http://www.pixiv.net/member_illust.php' '?mode=medium&illust_id=53239740', 'body': fx_ugoira_body, 'content_type': 'text/html; charset=utf-8', 'status': 200, 'match_querystring': True, }) responses.add(**{ 'method': responses.HEAD, 'url': 'http://i1.pixiv.net/img-zip-ugoira/img/' '2015/10/27/22/10/14/53239740_ugoira600x600.zip', 'status': 200, }) responses.add(**{ 'method': responses.GET, 'url': 'http://i1.pixiv.net/img-zip-ugoira/img/' '2015/10/27/22/10/14/53239740_ugoira600x600.zip', 'body': fx_ugoira_zip, 'content_type': 'application/zip', 'status': 200, }) data, frames = download_zip(53239740) assert data == fx_ugoira_zip
def test_check_catches_connection_problems(self): # Try to actually hit http://dummy_host. It's bad practice to do live # requests in tests, but this is fast and doesn't actually go outside # the host (aka this test will work on an airplane). response = self.resource.check() self.assertEqual(response['status'], 'error') self.assertIn('Connection refused', response['error']) # Now mock es_urls = re.compile(r'https?://dummy_host.*') responses.add( responses.GET, es_urls, body=requests.exceptions.ConnectionError('Connection refused')) response = self.resource.check() self.assertEqual(response['status'], 'error') self.assertIn('Connection refused', response['error']) responses.reset() responses.add( responses.GET, es_urls, body=requests.exceptions.HTTPError('derp')) response = self.resource.check() self.assertEqual(response['status'], 'error') self.assertIn('derp', response['error'])
def test(): responses.reset() responses.add(**{ 'method': responses.GET, 'url': 'http://www.pixiv.net/member_illust.php' '?mode=medium&illust_id=53239740', 'body': fx_ugoira_body, 'content_type': 'text/html; charset=utf-8', 'status': 200, 'match_querystring': True, }) responses.add(**{ 'method': responses.HEAD, 'url': 'http://i1.pixiv.net/img-zip-ugoira/img/' '2015/10/27/22/10/14/53239740_ugoira600x600.zip', 'status': 200, }) responses.add(**{ 'method': responses.GET, 'url': 'http://i1.pixiv.net/img-zip-ugoira/img/' '2015/10/27/22/10/14/53239740_ugoira600x600.zip', 'body': fx_ugoira_zip, 'content_type': 'application/zip', 'status': 200, }) data, frames = download_zip(53239740) file = fx_tmpdir / 'test.gif' make_gif(str(file), data, fx_ugoira_frames, 10.0) with Image(filename=str(file)) as img: assert img.format == 'GIF' assert len(img.sequence) == 3 assert img.sequence[0].delay == 10 assert img.sequence[1].delay == 20 assert img.sequence[2].delay == 30
def test(): responses.reset() responses.add(**{ 'method': responses.GET, 'url': 'http://www.pixiv.net/', 'body': 'Just touch, Do not access it really.' ' Because they block us.', 'content_type': 'text/html; charset=utf-8', 'status': 200, }) responses.add(**{ 'method': responses.POST, 'url': 'https://www.pixiv.net/login.php', 'body': 'Just touch, Do not access it really.' ' Because they block us.', 'content_type': 'text/html; charset=utf-8', 'status': 301, 'adding_headers': { 'Location': 'http://example.com/' }, }) responses.add(**{ 'method': responses.GET, 'url': 'http://example.com/', 'body': 'Just touch, Do not access it really.' ' Because they block us.', 'content_type': 'text/html; charset=utf-8', 'status': 200, }) assert not login(*fx_invalid_id_pw)
def set_existing_search_response(self, name, content, hook_type, response_content=None, dld_url='http://www.someurl.com/'): responses.reset() responses.add( responses.GET, 'http://www.git-hooks.com/api/v1/hooks/', json={ 'count': 1, 'next': None, 'prev': None, 'results': [{ 'name': name, 'current_version': 1, 'content': { 'checksum': hashlib.sha256(content.encode()).hexdigest(), 'hook_type': hook_type, 'download_url': dld_url } }] }, status=200, ) responses.add( responses.GET, dld_url, body=response_content or content, status=200, )
def test(): responses.reset() responses.add(**{ 'method': responses.GET, 'url': 'http://www.pixiv.net/member_illust.php' '?mode=medium&illust_id=53239740', 'body': fx_ugoira_body, 'content_type': 'text/html; charset=utf-8', 'status': 200, 'match_querystring': True, }) responses.add(**{ 'method': responses.HEAD, 'url': 'http://i1.pixiv.net/img-zip-ugoira/img/' '2015/10/27/22/10/14/53239740_ugoira600x600.zip', 'status': 200, }) responses.add(**{ 'method': responses.GET, 'url': 'http://i1.pixiv.net/img-zip-ugoira/img/' '2015/10/27/22/10/14/53239740_ugoira600x600.zip', 'status': 403, }) with pytest.raises(PixivError): download_zip(53239740)
def test_no_accounts_recieved(self, mock_render_to_response, mock_get_user_info): responses.reset() responses.add( responses.GET, 'https://app.vssps.visualstudio.com/_apis/accounts', json={ 'value': [], 'count': 0, }, status=200, ) view = AccountConfigView() request = Mock() request.POST = {} request.user = self.user pipeline = Mock() pipeline.fetch_state = lambda key: {'data': {'access_token': '1234567890'}} pipeline.organization = self.organization view.dispatch(request, pipeline) assert mock_get_user_info.called is True assert mock_render_to_response.called is True assert mock_render_to_response.call_args[1]['context'] == {'no_accounts': True}
def test_request(self): """Validate the ``request`` method.""" responses.add( responses.GET, self.URL, body='', status=200, ) result = self.api.request(self.URL, 'GET') data = result.get('response') self.assertEqual(data, {}) # Reset responses here to test same URL with different content. responses.reset() content = u'{"some": "content"}' responses.add( responses.GET, self.URL, body=content, status=200, ) result = self.api.request(self.URL, 'GET') data = result.get('response') self.assertEqual(data, {'some': 'content'})
def testIncorrectResponseHeaders(): response = '{"meta":{"code":200,"message":"OK","details":[]},"data":{"key":"value"}}' responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=incorrect, body=response, status=200) api = Postmen('KEY', 'REGION') ret = api.get('labels') assert ret['key'] == 'value' responses.reset()
def test_we_can_update_a_bug_from_bugzilla(): responses.add( responses.GET, rest_url("bug", 1017315), body=json.dumps(example_return), status=200, content_type="application/json", match_querystring=True, ) bugzilla = Bugsy() bug = bugzilla.get(1017315) import copy bug_dict = copy.deepcopy(example_return) bug_dict["bugs"][0]["status"] = "REOPENED" responses.reset() responses.add( responses.GET, "https://bugzilla.mozilla.org/rest/bug/1017315", body=json.dumps(bug_dict), status=200, content_type="application/json", ) bug.update() assert bug.status == "REOPENED"
def testArgument18() : response = '{"meta":{"code":999,"message":"NOT OK","details":[]},"data":{}}' responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=headers, body=response, status=200) api = Postmen('KEY', 'REGION', raw=True) ret = api.get('labels') assert ret == response responses.reset()
def assert_setup_flow(self, team_id='TXXXXXXX1', authorizing_user_id='UXXXXXXX1'): responses.reset() resp = self.client.get(self.init_path) assert resp.status_code == 302 redirect = urlparse(resp['Location']) assert redirect.scheme == 'https' assert redirect.netloc == 'slack.com' assert redirect.path == '/oauth/authorize' params = parse_qs(redirect.query) assert params['scope'] == [' '.join(self.provider.identity_oauth_scopes)] assert params['state'] assert params['redirect_uri'] == ['http://testserver/extensions/slack/setup/'] assert params['response_type'] == ['code'] assert params['client_id'] == ['slack-client-id'] # once we've asserted on it, switch to a singular values to make life # easier authorize_params = {k: v[0] for k, v in six.iteritems(params)} responses.add( responses.POST, 'https://slack.com/api/oauth.token', json={ 'ok': True, 'access_token': 'xoxp-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx', 'team_id': team_id, 'team_name': 'Example', 'authorizing_user_id': authorizing_user_id, } ) responses.add( responses.GET, 'https://slack.com/api/team.info', json={ 'ok': True, 'team': { 'domain': 'test-slack-workspace', 'icon': {'image_132': 'http://example.com/ws_icon.jpg'}, }, } ) resp = self.client.get(u'{}?{}'.format( self.setup_path, urlencode({ 'code': 'oauth-code', 'state': authorize_params['state'], }) )) mock_request = responses.calls[0].request req_params = parse_qs(mock_request.body) assert req_params['grant_type'] == ['authorization_code'] assert req_params['code'] == ['oauth-code'] assert req_params['redirect_uri'] == ['http://testserver/extensions/slack/setup/'] assert req_params['client_id'] == ['slack-client-id'] assert req_params['client_secret'] == ['slack-client-secret'] assert resp.status_code == 200 self.assertDialogSuccess(resp)
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 testArguments7(): response = '{"meta":{"code":999,"message":"NOT OK","details":[]},"data":{}}' responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=headers, body=response, status=200, content_type='text/plain') api = Postmen('KEY', 'REGION') api.get('labels', safe=True) responses.reset() e = api.getError() assert "NOT OK" in str(e.message())
def test_bucketing_304(): @responses.activate def e_test_bucketing_200_again(): json_response = '{"campaigns":[{"variationGroups":[{"variations":[{"allocation":100,"modifications":{"type":"FLAG","value":{"featureEnabled":true}},"id":"xxxx"}],"targeting":{"targetingGroups":[{"targetings":[{"operator":"EQUALS","value":true,"key":"isVIPUser"}]}]},"id":"yyyy"},{"variations":[{"allocation":100,"modifications":{"type":"FLAG","value":{"featureEnabled":false}},"id":"cccc"}],"targeting":{"targetingGroups":[{"targetings":[{"operator":"EQUALS","value":false,"key":"isVIPUser"}]}]},"id":"vvvv"}],"type":"toggle","id":"aaaa"},{"variationGroups":[{"variations":[{"allocation":25,"modifications":{"type":"JSON","value":{"rank_plus":null,"rank":null}},"id":"zzzz","reference":true},{"allocation":25,"modifications":{"type":"JSON","value":{"rank_plus":null,"rank":1111}},"id":"eeee"},{"allocation":25,"modifications":{"type":"JSON","value":{"rank_plus":null,"rank":3333}},"id":"rrrr"},{"allocation":25,"modifications":{"type":"JSON","value":{"rank_plus":22.22,"rank":2222}},"id":"tttt"}],"targeting":{"targetingGroups":[{"targetings":[{"operator":"EQUALS","value":"password","key":"access"}]}]},"id":"yyyy"}],"type":"ab","id":"iiii"}]}' headers = { "Last-Modified": "Fri, 05 Jun 2023 12:20:40 GMT" } responses.reset() responses.add(responses.GET, 'https://cdn.flagship.io/my_env_id/bucketing.json', json=json.loads(json_response), status=200, adding_headers=headers) fs = Flagship.instance() fs.start("my_env_id", "my_api_key", Config(mode=Config.Mode.BUCKETING, polling_interval=-1)) with open("bucketing.json", 'r') as f: content = f.read() assert len(content) > 2 json_object = json.loads(content) last_modified = json_object['last_modified'] assert last_modified is not None assert last_modified == "Fri, 05 Jun 2023 12:20:40 GMT" json_response = '{}' headers = { "Last-Modified": "fake" } responses.reset() responses.add(responses.GET, 'https://cdn.flagship.io/my_env_id/bucketing.json', json=json.loads(json_response), status=304, adding_headers=headers) responses.add(responses.POST, 'https://decision.flagship.io/v2/my_env_id/events', json=json.loads('{}'), status=200) responses.add(responses.POST, 'https://decision.flagship.io/v2/activate', json=json.loads('{}'), status=200) fs = Flagship.instance() fs.start("my_env_id", "my_api_key", Config(mode=Config.Mode.BUCKETING, polling_interval=-1)) visitor = Flagship.instance().create_visitor("ä", {'isVIPUser': True, 'bin_a': 1, 'bin_b': 1}) # type: FlagshipVisitor visitor.update_context(('access', 'password'), True) assert visitor.get_modification('rank', "=null", True) != "=null" contains_activate = False contains_events = False for c in responses.calls: if contains_events is False and c.request.url.__contains__('events'): contains_events = True if contains_activate is False and c.request.url.__contains__('activate'): contains_events = True assert contains_events is True assert contains_events is True with open("bucketing.json", 'r') as f: content = f.read() assert len(content) > 2 json_object = json.loads(content) last_modified = json_object['last_modified'] assert last_modified is not None assert last_modified == "Fri, 05 Jun 2020 12:20:40 GMT" e_test_bucketing_200_again()
def test_sqla_flask_login(app, db, blueprint, request): login_manager = LoginManager(app) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) class OAuth(OAuthConsumerMixin, db.Model): user_id = db.Column(db.Integer, db.ForeignKey(User.id)) user = db.relationship(User) blueprint.backend = SQLAlchemyBackend(OAuth, db.session, user=current_user) db.create_all() def done(): db.session.remove() db.drop_all() request.addfinalizer(done) # create some users u1 = User(name="Alice") u2 = User(name="Bob") u3 = User(name="Chuck") db.session.add_all([u1, u2, u3]) db.session.commit() # configure login manager @login_manager.user_loader def load_user(userid): return User.query.get(userid) with record_queries(db.engine) as queries: with app.test_client() as client: # reset the session before the request with client.session_transaction() as sess: sess["test-service_oauth_state"] = "random-string" # set alice as the logged in user sess["user_id"] = u1.id # make the request resp = client.get( "/login/test-service/authorized?code=secret-code&state=random-string", base_url="https://a.b.c", ) # check that we redirected the client assert resp.status_code == 302 assert resp.headers["Location"] == "https://a.b.c/oauth_done" assert len(queries) == 4 # lets do it again, with Bob as the logged in user -- he gets a different token responses.reset() responses.add( responses.POST, "https://example.com/oauth/access_token", body='{"access_token":"abcdef","token_type":"bearer","scope":"bob"}', ) with record_queries(db.engine) as queries: with app.test_client() as client: # reset the session before the request with client.session_transaction() as sess: sess["test-service_oauth_state"] = "random-string" # set bob as the logged in user sess["user_id"] = u2.id # make the request resp = client.get( "/login/test-service/authorized?code=secret-code&state=random-string", base_url="https://a.b.c", ) # check that we redirected the client assert resp.status_code == 302 assert resp.headers["Location"] == "https://a.b.c/oauth_done" assert len(queries) == 4 # check the database authorizations = OAuth.query.all() assert len(authorizations) == 2 u1_oauth = OAuth.query.filter_by(user=u1).one() assert u1_oauth.provider == "test-service" assert u1_oauth.token == { "access_token": "foobar", "token_type": "bearer", "scope": [""], } u2_oauth = OAuth.query.filter_by(user=u2).one() assert u2_oauth.provider == "test-service" assert u2_oauth.token == { "access_token": "abcdef", "token_type": "bearer", "scope": ["bob"], } u3_oauth = OAuth.query.filter_by(user=u3).all() assert len(u3_oauth) == 0
def teardown_method(self, method): responses.reset() responses.stop()
def reset_mock_responses(): yield responses.reset()
def _stub_vsts(self): responses.reset() responses.add( responses.POST, "https://app.vssps.visualstudio.com/oauth2/token", json={ "access_token": self.access_token, "token_type": "grant", "expires_in": 300, # seconds (5 min) "refresh_token": self.refresh_token, }, ) responses.add( responses.GET, "https://app.vssps.visualstudio.com/_apis/accounts?ownerId=%s&api-version=4.1" % self.vsts_user_id, json={ "count": 1, "value": [{ "accountId": self.vsts_account_id, "accountUri": self.vsts_account_uri, "accountName": self.vsts_account_name, "properties": {}, }], }, ) responses.add( responses.GET, "https://app.vssps.visualstudio.com/_apis/resourceareas/79134C72-4A58-4B42-976C-04E7115F32BF?hostId=%s&api-preview=5.0-preview.1" % self.vsts_account_id, json={"locationUrl": self.vsts_base_url}, ) responses.add( responses.GET, "https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=1.0", json={ "id": self.vsts_user_id, "displayName": self.vsts_user_name, "emailAddress": self.vsts_user_email, }, ) responses.add( responses.GET, "https://app.vssps.visualstudio.com/_apis/connectionData/", json={ "authenticatedUser": { "subjectDescriptor": self.vsts_account_id } }, ) responses.add( responses.GET, u"https://{}.visualstudio.com/_apis/projects".format( self.vsts_account_name.lower()), json={"value": [self.project_a, self.project_b]}, ) responses.add( responses.POST, u"https://{}.visualstudio.com/_apis/hooks/subscriptions".format( self.vsts_account_name.lower()), json=CREATE_SUBSCRIPTION, ) responses.add( responses.GET, u"https://{}.visualstudio.com/_apis/git/repositories".format( self.vsts_account_name.lower()), json={ "value": [{ "id": self.repo_id, "name": self.repo_name, "project": { "name": self.project_a["name"] }, }] }, ) responses.add( responses.GET, u"https://{}.visualstudio.com/ProjectA/_apis/git/repositories/ProjectA" .format(self.vsts_account_name.lower()), json={ "repository": { "id": self.repo_id, "name": self.repo_name, "project": { "name": self.project_a["name"] }, } }, ) responses.add( responses.GET, u"https://{}.visualstudio.com/{}/_apis/wit/workitemtypes/{}/states" .format(self.vsts_account_name.lower(), self.project_a["name"], "Bug"), json={ "value": [ { "name": "resolve_status" }, { "name": "resolve_when" }, { "name": "regression_status" }, { "name": "sync_comments" }, { "name": "sync_forward_assignment" }, { "name": "sync_reverse_assignment" }, ] }, )
def _stub_vsts(self): responses.reset() responses.add( responses.POST, 'https://app.vssps.visualstudio.com/oauth2/token', json={ 'access_token': self.access_token, 'token_type': 'grant', 'expires_in': 300, # seconds (5 min) 'refresh_token': self.refresh_token, }, ) responses.add( responses.GET, 'https://app.vssps.visualstudio.com/_apis/accounts?ownerId=%s&api-version=4.1' % self.vsts_user_id, json={ 'count': 1, 'value': [{ 'accountId': self.vsts_account_id, 'accountUri': self.vsts_account_uri, 'accountName': self.vsts_account_name, 'properties': {}, }] }, ) responses.add( responses.GET, 'https://app.vssps.visualstudio.com/_apis/resourceareas/79134C72-4A58-4B42-976C-04E7115F32BF?hostId=%s&api-preview=5.0-preview.1' % self.vsts_account_id, json={ 'locationUrl': self.vsts_base_url, } ) responses.add( responses.GET, 'https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=1.0', json={ 'id': self.vsts_user_id, 'displayName': self.vsts_user_name, 'emailAddress': self.vsts_user_email, }, ) responses.add( responses.GET, 'https://app.vssps.visualstudio.com/_apis/connectionData/', json={ 'authenticatedUser': { 'subjectDescriptor': self.vsts_account_id, }, }, ) responses.add( responses.GET, u'https://{}.visualstudio.com/_apis/projects'.format( self.vsts_account_name.lower(), ), json={ 'value': [ self.project_a, self.project_b, ], }, ) responses.add( responses.POST, u'https://{}.visualstudio.com/_apis/hooks/subscriptions'.format( self.vsts_account_name.lower(), ), json=CREATE_SUBSCRIPTION, ) responses.add( responses.GET, u'https://{}.visualstudio.com/_apis/git/repositories'.format( self.vsts_account_name.lower(), ), json={ 'value': [{ 'id': self.repo_id, 'name': self.repo_name, 'project': { 'name': self.project_a['name'], }, }], }, ) responses.add( responses.GET, u'https://{}.visualstudio.com/ProjectA/_apis/git/repositories/ProjectA'.format( self.vsts_account_name.lower(), ), json={ 'repository': { 'id': self.repo_id, 'name': self.repo_name, 'project': { 'name': self.project_a['name'], }, }, }, ) responses.add( responses.GET, u'https://{}.visualstudio.com/{}/_apis/wit/workitemtypes/{}/states'.format( self.vsts_account_name.lower(), self.project_a['name'], 'Bug', ), json={ 'value': [{'name': 'resolve_status'}, {'name': 'resolve_when'}, {'name': 'regression_status'}, {'name': 'sync_comments'}, {'name': 'sync_forward_assignment'}, {'name': 'sync_reverse_assignment'}], } )
def assert_setup_flow(self, is_team=False, multi_config_org=None, no_name=False): class MockUuid4: hex = "1234567" self.mock_uuid4 = MockUuid4 responses.reset() access_json = { "user_id": "my_user_id", "access_token": "my_access_token", "installation_id": "my_config_id", } if is_team: team_query = "?teamId=my_team_id" access_json["team_id"] = "my_team_id" responses.add( responses.GET, "https://api.vercel.com/v1/teams/my_team_id%s" % team_query, json={ "name": "My Team Name", "slug": "my_team_slug" }, ) else: team_query = "" name = None if no_name else "My Name" responses.add( responses.GET, "https://api.vercel.com/www/user", json={"user": { "name": name, "username": "******" }}, ) responses.add(responses.POST, "https://api.vercel.com/v2/oauth/access_token", json=access_json) responses.add( responses.GET, "https://api.vercel.com/v4/projects/%s" % team_query, json={ "projects": [], "pagination": { "count": 0 } }, ) responses.add( responses.POST, "https://api.vercel.com/v1/integrations/webhooks%s" % team_query, json={"id": "webhook-id"}, ) params = { "configurationId": "config_id", "code": "oauth-code", "next": "https://example.com", } self.pipeline.bind_state("user_id", self.user.id) resp = self.client.get(self.setup_path, params) mock_request = responses.calls[0].request req_params = parse_qs(mock_request.body) assert req_params["grant_type"] == ["authorization_code"] assert req_params["code"] == ["oauth-code"] assert req_params["redirect_uri"] == [ "http://testserver/extensions/vercel/configure/" ] assert req_params["client_id"] == ["vercel-client-id"] assert req_params["client_secret"] == ["vercel-client-secret"] assert resp.status_code == 200 self.assertDialogSuccess(resp) integration = Integration.objects.get(provider=self.provider.key) external_id = "my_team_id" if is_team else "my_user_id" name = "My Team Name" if is_team else "my_user_name" if no_name else "My Name" installation_type = "team" if is_team else "user" assert integration.external_id == external_id assert integration.name == name configurations = { "my_config_id": { "access_token": "my_access_token", "webhook_id": "webhook-id", "organization_id": self.organization.id, } } if multi_config_org: configurations["orig_config_id"] = { "access_token": "orig_access_token", "webhook_id": "orig-webhook-id", "organization_id": multi_config_org.id, } assert integration.metadata == { "access_token": "my_access_token", "installation_id": "my_config_id", "installation_type": installation_type, "webhook_id": "webhook-id", "configurations": configurations, } assert OrganizationIntegration.objects.get( integration=integration, organization=self.organization) assert SentryAppInstallationForProvider.objects.get( organization=self.organization, provider="vercel")
def mock_url(): _add_mock_response(_URL, _DATA.tostring()) _add_mock_response(_URL + '.md5', _CHECKSUM + ' ' + Path(_URL).name) yield _URL responses.reset()
def assert_setup_flow(self, get_jwt, _, installation_id="install_id_1", app_id="app_1", user_id="user_id_1"): responses.reset() resp = self.client.get(self.init_path) assert resp.status_code == 200 resp = self.client.post(self.init_path, data=self.config) assert resp.status_code == 302 redirect = urlparse(resp["Location"]) assert redirect.scheme == "https" assert redirect.netloc == "github.example.org" assert redirect.path == "/github-apps/test-app" # App installation ID is provided, mveo thr resp = self.client.get("{}?{}".format( self.setup_path, urlencode({"installation_id": installation_id}))) assert resp.status_code == 302 redirect = urlparse(resp["Location"]) assert redirect.scheme == "https" assert redirect.netloc == "github.example.org" assert redirect.path == "/login/oauth/authorize" params = parse_qs(redirect.query) assert params["state"] assert params["redirect_uri"] == [ "http://testserver/extensions/github-enterprise/setup/" ] assert params["response_type"] == ["code"] assert params["client_id"] == ["client_id"] # once we've asserted on it, switch to a singular values to make life # easier authorize_params = {k: v[0] for k, v in six.iteritems(params)} access_token = "xxxxx-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx" responses.add( responses.POST, "https://github.example.org/login/oauth/access_token", json={"access_token": access_token}, ) responses.add( responses.POST, self.base_url + "/app/installations/{}/access_tokens".format(installation_id), json={ "token": access_token, "expires_at": "3000-01-01T00:00:00Z" }, ) responses.add(responses.GET, self.base_url + "/user", json={"id": user_id}) responses.add( responses.GET, self.base_url + "/app/installations/{}".format(installation_id), json={ "id": installation_id, "app_id": app_id, "account": { "login": "******", "type": "Organization", "avatar_url": "https://github.example.org/avatar.png", "html_url": "https://github.example.org/Test-Organization", }, }, ) responses.add( responses.GET, self.base_url + "/user/installations", json={"installations": [{ "id": installation_id }]}, ) resp = self.client.get("{}?{}".format( self.setup_path, urlencode({ "code": "oauth-code", "state": authorize_params["state"] }), )) mock_access_token_request = responses.calls[0].request req_params = parse_qs(mock_access_token_request.body) assert req_params["grant_type"] == ["authorization_code"] assert req_params["code"] == ["oauth-code"] assert req_params["redirect_uri"] == [ "http://testserver/extensions/github-enterprise/setup/" ] assert req_params["client_id"] == ["client_id"] assert req_params["client_secret"] == ["client_secret"] assert resp.status_code == 200 auth_header = responses.calls[2].request.headers["Authorization"] assert auth_header == b"Bearer jwt_token_1" self.assertDialogSuccess(resp)
def test_visitor_panic(): responses.reset() fs = Flagship.instance() fs.start("my_env_id", "my_api_key", Config(event_handler=None, mode=Config.Mode.API)) visitor = fs.create_visitor("visitor_1") json_response = '{"visitorId":"visitor_1","campaigns":[{"id":"xxxxd0qhl5801abv9ib0",' \ '"variationGroupId":"xxxxd0qhl5801abv9ic0","variation":{"id":"xxxxd0qhl5801abv9icg",' \ '"modifications":{"type":"FLAG","value":{"featureEnabled":true}}}}]} ' responses.add( responses.POST, 'https://decision.flagship.io/v2/my_env_id/campaigns/?exposeAllKeys=true&sendContextEvent=false', json=json.loads(json_response), status=200) responses.add(responses.POST, 'https://decision.flagship.io/v2/my_env_id/events', status=200) responses.add(responses.POST, 'https://ariane.abtasty.com/', status=200) visitor.synchronize_modifications() visitor.send_hit( Page("script.py").with_ip("133.3.223.1").with_locale( "fr-fr").with_resolution(640, 480).with_session_number(3)) responses.add(responses.POST, 'https://decision.flagship.io/v2/activate', status=200) visitor.activate_modification('featureEnabled') assert visitor.get_modification("featureEnabled", False) is True assert len(responses.calls) == 4 responses.reset() json_response_panic = '{"visitorId":"Toto3000","campaigns":[],"panic":true}' responses.add( responses.POST, 'https://decision.flagship.io/v2/my_env_id/campaigns/?exposeAllKeys=true&sendContextEvent=false', json=json.loads(json_response_panic), status=200) responses.add(responses.POST, 'https://decision.flagship.io/v2/my_env_id/events', status=200) responses.add(responses.POST, 'https://ariane.abtasty.com/', status=200) visitor.synchronize_modifications() visitor.send_hit( Page("script.py").with_ip("133.3.223.1").with_locale( "fr-fr").with_resolution(640, 480).with_session_number(3)) responses.add(responses.POST, 'https://decision.flagship.io/v2/activate', status=200) visitor.activate_modification('featureEnabled') visitor.synchronize_modifications() assert visitor._is_panic_mode() is True assert visitor.get_modification("featureEnabled", False) is False assert len(responses.calls) == 2
def test_unit_create_vcs_root_with_responses(): vcs_url = 'https://github.com/SurveyMonkey/pyteamcity.git' # Simulate failure creating a VCSRoot responses.add( responses.POST, tc.relative_url('app/rest/vcs-roots/'), status=500, body='Internal error', ) with pytest.raises(exceptions.HTTPError) as excinfo: tc.vcs_roots.all().create( name='pyteamcity', vcs_name='jetbrains.git', url=vcs_url, branch='master', ) assert str(excinfo.value) == 'Internal Server Error' assert excinfo.value.text == 'Internal error' # Simulate success creating a VCSRoot response_json = { 'name': 'pyteamcity', 'id': 'Root_Pyteamcity', 'href': '/guestAuth/app/rest/vcs-roots/id:Root_Pyteamcity', 'properties': { 'property': [ { 'name': 'url', 'value': vcs_url }, { 'name': 'branch', 'value': 'master' }, { "name": "teamcity:branchSpec", "value": "+:master\n+:<default>\n+:refs/heads/(<default>)\n+:refs/heads/(*)\n+:refs/pull/(*/merge)" }, # noqa: E501 ], }, } responses.reset() responses.add( responses.POST, tc.relative_url('app/rest/vcs-roots/'), json=response_json, status=200, content_type='application/json', ) branch_spec = '\n'.join([ '+:master', '+:<default>', '+:refs/heads/(<default>)', '+:refs/heads/(*)', '+:refs/pull/(*/merge)', ]) vcs_root = tc.vcs_roots.all().create( name='pyteamcity', vcs_name='jetbrains.git', url=vcs_url, branch='master', branch_spec=branch_spec, user_for_tags='tagman', username='******', id='Root_Pyteamcity', ) try: assert vcs_root.id == 'Root_Pyteamcity' assert 'pyteamcity' in repr(vcs_root) assert vcs_root.url == vcs_url assert vcs_root.branch == 'master' assert vcs_root.branch_spec == branch_spec finally: # Now test deleting the VCSRoot and it fails responses.add( responses.DELETE, tc.relative_url('app/rest/vcs-roots/id:Root_Pyteamcity'), status=500, ) with pytest.raises(exceptions.HTTPError): vcs_root.delete() # Now test deleting the VCSRoot and it succeeds responses.reset() responses.add( responses.DELETE, tc.relative_url('app/rest/vcs-roots/id:Root_Pyteamcity'), status=200, ) vcs_root.delete()
def test_visitor_synchronize(): json_response = '{"visitorId":"visitor_1","campaigns":[{"id":"xxxxd0qhl5801abv9ib0",' \ '"variationGroupId":"xxxxd0qhl5801abv9ic0","variation":{"id":"xxxxd0qhl5801abv9icg",' \ '"modifications":{"type":"FLAG","value":{"featureEnabled":true}}}}]} ' json_response2 = '{"visitorId":"visitor_1","campaigns":[{"id":"xxxxesjojh803lh57qo0",' \ '"variationGroupId":"xxxxesjojh803lh57qp0","variation":{"id":"xxxxesjojh803lh57qpg",' \ '"modifications":{"type":"FLAG","value":{"my_flag_nb":100}}}},{"id":"xxxxsp9j5mf4g0fdhkv2g",' \ '"variationGroupId":"xxxxp9j5mf4g0fdhkv3g","variation":{"id":"xxxxp9j5mf4g0fdhkv4g",' \ '"modifications":{"type":"JSON","value":{"btn-color":"red"}}}},{"id":"xxxxrfe4jaeg0gi1bhog",' \ '"variationGroupId":"xxxxrfe4jaeg0gi1bhpg","variation":{"id":"xxxxrfe4jaeg0gi1bhq0",' \ '"modifications":{"type":"FLAG","value":{"featureEnabled":true}}}},{"id":"xxxx9b1q4vl00quhh0rg",' \ '"variationGroupId":"xxxx9b1q4vl00quhh0sg","variation":{"id":"xxxx9b1q4vl00quhh0tg",' \ '"modifications":{"type":"JSON","value":{"k1":"v1","k2":null,"k3":null,"k6":"v6","k7":null}}}}]} ' fs = Flagship.instance() fs.start("my_env_id", "my_api_key", Config(event_handler=None, mode=Config.Mode.API)) visitor = fs.create_visitor("visitor_1") responses.reset() responses.add( responses.POST, 'https://decision.flagship.io/v2/my_env_id/campaigns/?exposeAllKeys=true&sendContextEvent=false', json=json.loads(json_response), status=200) responses.add(responses.POST, 'https://decision.flagship.io/v2/my_env_id/events', status=200) visitor.synchronize_modifications() assert 'featureEnabled' in visitor._modifications assert visitor._modifications['featureEnabled'].value is True assert visitor._modifications[ 'featureEnabled'].variation_group_id == 'xxxxd0qhl5801abv9ic0' assert visitor._modifications[ 'featureEnabled'].variation_id == 'xxxxd0qhl5801abv9icg' responses.reset() responses.add(responses.POST, 'https://decision.flagship.io/v2/my_env_id/events', status=200) responses.add( responses.POST, 'https://decision.flagship.io/v2/my_env_id/campaigns/?exposeAllKeys=true&sendContextEvent=false', json=json.loads(json_response2), status=200) visitor.synchronize_modifications() assert 'featureEnabled' in visitor._modifications assert visitor._modifications['featureEnabled'].value is True assert visitor._modifications[ 'featureEnabled'].variation_group_id == 'xxxxrfe4jaeg0gi1bhpg' assert visitor._modifications[ 'featureEnabled'].variation_id == 'xxxxrfe4jaeg0gi1bhq0' assert 'my_flag_nb' in visitor._modifications assert visitor._modifications['my_flag_nb'].value == 100 assert visitor._modifications[ 'my_flag_nb'].variation_group_id == 'xxxxesjojh803lh57qp0' assert visitor._modifications[ 'my_flag_nb'].variation_id == 'xxxxesjojh803lh57qpg' assert 'k7' in visitor._modifications assert visitor._modifications['k7'].value is None assert visitor._modifications[ 'k7'].variation_group_id == 'xxxx9b1q4vl00quhh0sg' assert visitor._modifications['k7'].variation_id == 'xxxx9b1q4vl00quhh0tg' info = visitor.get_modification_info('k7') assert info['campaignId'] == 'xxxx9b1q4vl00quhh0rg' assert info['variationGroupId'] == 'xxxx9b1q4vl00quhh0sg' assert info['variationId'] == 'xxxx9b1q4vl00quhh0tg'
def test_bucketing_alloc(): try: try: os.remove("bucketing.json") except Exception as e: print("No Bucketing file") json_response = '{"campaigns":[{"id":"bs8qvmo4nlr01fl9aaaa","type":"ab","variationGroups":[{"id":"bs8qvmo4nlr01fl9bbbb","targeting":{"targetingGroups":[{"targetings":[{"operator":"EQUALS","key":"fs_all_users","value":""}]}]},"variations":[{"id":"bs8qvmo4nlr01fl9cccc","modifications":{"type":"JSON","value":{"variation":null}},"reference":true},{"id":"bs8qvmo4nlr01fl9dddd","modifications":{"type":"JSON","value":{"variation":1}},"allocation":25},{"id":"bs8r09g4nlr01c77eeee","modifications":{"type":"JSON","value":{"variation":2}},"allocation":25},{"id":"bs8r09g4nlr01cdkffff","modifications":{"type":"JSON","value":{"variation":3}},"allocation":25},{"id":"bs8r09hsbs4011lbgggg","modifications":{"type":"JSON","value":{"variation":4}},"allocation":25}]}]},{"id":"bs8r119sbs4016mehhhh","type":"ab","variationGroups":[{"id":"bs8r119sbs4016meiiii","targeting":{"targetingGroups":[{"targetings":[{"operator":"EQUALS","key":"fs_all_users","value":""}]}]},"variations":[{"id":"bs8r119sbs4016mejjjj","modifications":{"type":"JSON","value":{"variation50":null}},"reference":true},{"id":"bs8r119sbs4016mekkkk","modifications":{"type":"JSON","value":{"variation50":1}},"allocation":50},{"id":"bs8r119sbs4016mellll","modifications":{"type":"JSON","value":{"variation50":2}},"allocation":50}]}]}]}' responses.reset() headers = { "Last-Modified": "Fri, 05 Jun 2020 12:20:40 GMT" } responses.add(responses.GET, 'https://cdn.flagship.io/my_env_id/bucketing.json', json=json.loads(json_response), status=200, headers=headers) responses.add(responses.POST, 'https://decision.flagship.io/v2/my_env_id/events', json=json.loads('{}'), status=200) fs = Flagship.instance() fs.start("my_env_id", "my_api_key", Config(mode=Config.Mode.BUCKETING, polling_interval=-1)) v150 = 0 v250 = 0 v125 = 0 v225 = 0 v325 = 0 v425 = 0 x = 50000 for i in range(0, x): v = Flagship.instance().create_visitor(get_random_string(10) + "_" + str(i)) v.synchronize_modifications() variation = v.get_modification("variation", 0) variation50 = v.get_modification("variation50", 0) if variation50 == 1: v150 += 1 elif variation50 == 2: v250 += 1 else: assert False if variation == 1: v125 += 1 elif variation == 2: v225 += 1 elif variation == 3: v325 += 1 elif variation == 4: v425 += 1 else: assert False print("Results : v150 {}, v250 {}".format(v150, v250)) print("Results : v125 {}, v225 {}, v325 {}, v425 {}".format(v125, v225, v325, v425)) min = (x / 2 - (x * 0.008)) max = (x / 2 + (x * 0.008)) assert min <= v150 <= max assert min <= v250 <= max assert v150 + v250 == x min1 = (x / 4 - (x * 0.008)) max1 = (x / 4 + (x * 0.008)) assert min1 <= v125 <= max1 assert min1 <= v225 <= max1 assert min1 <= v325 <= max1 assert min1 <= v425 <= max1 assert v125 + v225 + v325 + v425 == x except Exception as e: print(e) assert False
def tearDown(self): super().tearDown() responses.reset()
def tearDown(self): super(GitLabRepositoryProviderTest, self).tearDown() responses.reset()
def tearDown(self): responses.stop() responses.reset()
def tearDown(self): os.unlink(self.token_path) responses.reset()
def setUp(self): responses.reset() self.snapchat = Snapchat()
def tearDown(self): reset() db.session.commit() db.drop_all() self.app_context.pop()
def _stub_vsts(self): responses.reset() responses.add( responses.POST, 'https://app.vssps.visualstudio.com/oauth2/token', json={ 'access_token': self.access_token, 'token_type': 'grant', 'expires_in': 300, # seconds (5 min) 'refresh_token': self.refresh_token, }, ) responses.add( responses.GET, 'https://app.vssps.visualstudio.com/_apis/accounts', json=[{ 'AccountId': self.vsts_account_id, 'AccountUri': self.vsts_account_uri, 'AccountName': self.vsts_account_name, 'Properties': {}, }], ) responses.add( responses.GET, 'https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=1.0', json={ 'id': self.vsts_user_id, 'displayName': self.vsts_user_name, 'emailAddress': self.vsts_user_email, }, ) responses.add( responses.GET, 'https://app.vssps.visualstudio.com/_apis/connectionData/', json={ 'authenticatedUser': { 'subjectDescriptor': self.vsts_account_id, }, }, ) responses.add( responses.GET, 'https://{}.visualstudio.com/DefaultCollection/_apis/projects'. format(self.vsts_account_name.lower(), ), json={ 'value': [ self.project_a, self.project_b, ], }, ) responses.add( responses.POST, 'https://{}.visualstudio.com/_apis/hooks/subscriptions'.format( self.vsts_account_name.lower(), ), json=CREATE_SUBSCRIPTION, ) responses.add( responses.GET, 'https://{}.visualstudio.com/_apis/git/repositories'.format( self.vsts_account_name.lower(), ), json={ 'value': [{ 'id': self.repo_id, 'name': self.repo_name, 'project': { 'name': self.project_a['name'], }, }], }, ) responses.add( responses.GET, 'https://{}.visualstudio.com/{}/_apis/wit/workitemtypes/{}/states'. format( self.vsts_account_name.lower(), self.project_a['name'], 'Bug', ), json={ 'value': [{ 'name': 'resolve_status' }, { 'name': 'resolve_when' }, { 'name': 'regression_status' }, { 'name': 'sync_comments' }, { 'name': 'sync_forward_assignment' }, { 'name': 'sync_reverse_assignment' }], })
def test_fetch_translations(self, patched_logger): cds_host = 'https://some.host' cds_handler = CDSHandler(['el', 'en', 'fr'], 'some_token', host=cds_host) # add response for languages responses.add(responses.GET, cds_host + '/languages', json={ "data": [ { "code": "el", }, { "code": "en", }, { "code": "fr", }, ], "meta": { "some_key": "some_value" } }, status=200) # add response for translations responses.add(responses.GET, cds_host + '/content/el', json={ 'data': { 'key1': { 'string': 'key1_el' }, 'key2': { 'string': 'key2_el' }, }, 'meta': { "some_key": "some_value" } }, status=200) responses.add(responses.GET, cds_host + '/content/en', json={ 'data': { 'key1': { 'string': 'key1_en' }, 'key2': { 'string': 'key2_en' }, }, 'meta': {} }, status=200) # add response bad status response for a language here responses.add(responses.GET, cds_host + '/content/fr', status=404) resp = cds_handler.fetch_translations() assert resp == { 'el': (True, { 'key1': { 'string': 'key1_el' }, 'key2': { 'string': 'key2_el' }, }), 'en': (True, { 'key1': { 'string': 'key1_en' }, 'key2': { 'string': 'key2_en' }, }), 'fr': (False, {}) # that is due to the error status in response } responses.reset() # test fetch_languages fails with connection error responses.add(responses.GET, cds_host + '/languages', status=500) resp = cds_handler.fetch_translations() assert resp == {} patched_logger.error.assert_called_with( 'Error retrieving languages from CDS: UnknownError ' '(`500 Server Error: Internal Server Error for url: ' 'https://some.host/languages`)') responses.reset() patched_logger.reset_mock() # test language code responses.add(responses.GET, cds_host + '/content/el', json={ 'data': { 'key1': { 'string': 'key1_el' }, 'key2': { 'string': 'key2_el' }, }, 'meta': { "some_key": "some_value" } }, status=200) resp = cds_handler.fetch_translations(language_code='el') assert resp == { 'el': (True, { 'key1': { 'string': 'key1_el' }, 'key2': { 'string': 'key2_el' }, }) } responses.reset() assert patched_logger.error.call_count == 0 # test connection_error resp = cds_handler.fetch_translations(language_code='el') patched_logger.error.assert_called_with( 'Error retrieving translations from CDS: ConnectionError') assert resp == {'el': (False, {})}
def test_fetch_languages(self, patched_logger): cds_host = 'https://some.host' cds_handler = CDSHandler(['el', 'en'], 'some_token', host=cds_host) # correct response responses.add(responses.GET, cds_host + '/languages', json={ "data": [ { "code": "el", }, { "code": "en", }, ], "meta": { "some_key": "some_value" } }, status=200) languages_response = cds_handler.fetch_languages() assert self._lang_lists_equal(languages_response, [{ 'code': 'el' }, { 'code': 'en' }]) assert patched_logger.error.call_count == 0 responses.reset() # wrong payload structure responses.add(responses.GET, cds_host + '/languages', json={ "wrong_key": [ { "code": "el", }, { "code": "en", }, ], "meta": { "some_key": "some_value" } }, status=200) assert cds_handler.fetch_languages() == [] patched_logger.error.assert_called_with( 'Error retrieving languages from CDS: Malformed response') responses.reset() # bad request responses.add(responses.GET, cds_host + '/languages', json={ "data": [ { "code": "el", }, { "code": "en", }, ], "meta": { "some_key": "some_value" } }, status=400) assert cds_handler.fetch_languages() == [] patched_logger.error.assert_called_with( 'Error retrieving languages from CDS: UnknownError ' '(`400 Client Error: Bad Request for url: https://some.host/languages`)' ) responses.reset() # unauthorized responses.add(responses.GET, cds_host + '/languages', json={ "data": [ { "code": "el", }, { "code": "en", }, ], "meta": { "some_key": "some_value" } }, status=403) assert cds_handler.fetch_languages() == [] patched_logger.error.assert_called_with( 'Error retrieving languages from CDS: UnknownError ' '(`403 Client Error: Forbidden for url: https://some.host/languages`)' ) responses.reset() # connection error assert cds_handler.fetch_languages() == [] patched_logger.error.assert_called_with( 'Error retrieving languages from CDS: ConnectionError') responses.reset()
def test_es_scan_success(mock_args): responses.reset() responses.add(**MockResponses.elasticsearch) reset_handlers() se = core.main() assert se.found_q.qsize() == 1
def setUp(self): responses.reset() self.integration = Integration.objects.create( provider="msteams", name="Brute Squad", external_id="3x73rna1-id", metadata={ "service_url": "https://smba.trafficmanager.net/amer", "access_token": "inc0nc3iv4b13", "expires_at": int(time.time()) + 86400, }, ) self.integration.add_organization(self.event.project.organization, self.user) channels = [ { "id": "g_c" }, { "id": "p_o_d", "name": "Pit of Despair" }, ] first_users = [ { "name": "Wesley", "id": "d_p_r", "tenantId": "3141-5926-5358" }, { "name": "Buttercup", "id": "p_b", "tenantId": "2718-2818-2845" }, ] second_users = [{ "name": "Inigo", "id": "p_t_d", "tenantId": "1618-0339-8874" }] responses.add( responses.GET, "https://smba.trafficmanager.net/amer/v3/teams/3x73rna1-id/conversations", json={"conversations": channels}, ) responses.add( responses.GET, "https://smba.trafficmanager.net/amer/v3/conversations/3x73rna1-id/pagedmembers?pageSize=500", json={ "members": first_users, "continuationToken": "con71nu3" }, ) responses.add( responses.GET, "https://smba.trafficmanager.net/amer/v3/conversations/3x73rna1-id/pagedmembers?pageSize=500&continuationToken=con71nu3", json={"members": second_users}, ) def user_conversation_id_callback(request): payload = json.loads(request.body) if payload["members"] == [{ "id": "d_p_r" }] and payload["channelData"] == { "tenant": { "id": "3141-5926-5358" } }: return (200, {}, json.dumps({"id": "dread_pirate_roberts"})) elif payload["members"] == [{ "id": "p_b" }] and payload["channelData"] == { "tenant": { "id": "2718-2818-2845" } }: return (200, {}, json.dumps({"id": "princess_bride"})) elif payload["members"] == [{ "id": "p_t_d" }] and payload["channelData"] == { "tenant": { "id": "1618-0339-8874" } }: return (200, {}, json.dumps({"id": "prepare_to_die"})) responses.add_callback( responses.POST, "https://smba.trafficmanager.net/amer/v3/conversations", callback=user_conversation_id_callback, )
def mock_url(): _add_mock_response(_URL, _DATA.tostring()) _add_mock_response(_URL + '.md5', _CHECKSUM + ' ' + op.basename(_URL)) yield responses.reset()
def setUp(self): super(AuthenticationTestMixin, self).setUp() responses.reset()
def assert_setup_flow( self, team_id="TXXXXXXX1", authorizing_user_id="UXXXXXXX1", expected_client_id="slack-client-id", expected_client_secret="slack-client-secret", ): responses.reset() resp = self.client.get(self.init_path) assert resp.status_code == 302 redirect = urlparse(resp["Location"]) assert redirect.scheme == "https" assert redirect.netloc == "slack.com" assert redirect.path == "/oauth/v2/authorize" params = parse_qs(redirect.query) scopes = self.provider.identity_oauth_scopes assert params["scope"] == [" ".join(scopes)] assert params["state"] assert params["redirect_uri"] == [ "http://testserver/extensions/slack/setup/" ] assert params["response_type"] == ["code"] assert params["client_id"] == [expected_client_id] assert params.get("user_scope") == [ " ".join(self.provider.user_scopes) ] # once we've asserted on it, switch to a singular values to make life # easier authorize_params = {k: v[0] for k, v in params.items()} access_json = { "ok": True, "access_token": "xoxb-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx", "team": { "id": team_id, "name": "Example" }, "authed_user": { "id": authorizing_user_id }, } responses.add(responses.POST, "https://slack.com/api/oauth.v2.access", json=access_json) responses.add( responses.GET, "https://slack.com/api/users.lookupByEmail/", json={ "ok": True, "user": { "id": authorizing_user_id, "team_id": team_id, "profile": { "email": self.user.email, }, }, }, ) responses.add( responses.GET, "https://slack.com/api/team.info", json={ "ok": True, "team": { "domain": "test-slack-workspace", "icon": { "image_132": "http://example.com/ws_icon.jpg" }, }, }, ) resp = self.client.get("{}?{}".format( self.setup_path, urlencode({ "code": "oauth-code", "state": authorize_params["state"] }), )) mock_request = responses.calls[0].request req_params = parse_qs(mock_request.body) assert req_params["grant_type"] == ["authorization_code"] assert req_params["code"] == ["oauth-code"] assert req_params["redirect_uri"] == [ "http://testserver/extensions/slack/setup/" ] assert req_params["client_id"] == [expected_client_id] assert req_params["client_secret"] == [expected_client_secret] assert resp.status_code == 200 self.assertDialogSuccess(resp)
def assert_setup_flow(self, get_jwt, installation_id='install_id_1', user_id='user_id_1'): responses.reset() resp = self.client.get(self.init_path) assert resp.status_code == 302 redirect = urlparse(resp['Location']) assert redirect.scheme == 'https' assert redirect.netloc == 'github.com' assert redirect.path == '/apps/sentry-test-app' # App installation ID is provided, mveo thr resp = self.client.get('{}?{}'.format( self.setup_path, urlencode({'installation_id': installation_id}) )) assert resp.status_code == 302 redirect = urlparse(resp['Location']) assert redirect.scheme == 'https' assert redirect.netloc == 'github.com' assert redirect.path == '/login/oauth/authorize' params = parse_qs(redirect.query) assert params['state'] assert params['redirect_uri'] == ['http://testserver/extensions/github/setup/'] assert params['response_type'] == ['code'] assert params['client_id'] == ['github-client-id'] # once we've asserted on it, switch to a singular values to make life # easier authorize_params = {k: v[0] for k, v in six.iteritems(params)} access_token = 'xxxxx-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx' responses.add( responses.POST, 'https://github.com/login/oauth/access_token', json={'access_token': access_token} ) responses.add( responses.GET, 'https://api.github.com/user', json={'id': user_id} ) responses.add( responses.GET, u'https://api.github.com/app/installations/{}'.format(installation_id), json={ 'id': installation_id, 'account': { 'login': '******', 'avatar_url': 'http://example.com/avatar.png', 'html_url': 'https://github.com/Test-Organization', }, } ) responses.add( responses.GET, u'https://api.github.com/user/installations', json={ 'installations': [{'id': installation_id}], } ) resp = self.client.get('{}?{}'.format( self.setup_path, urlencode({ 'code': 'oauth-code', 'state': authorize_params['state'], }) )) mock_access_token_request = responses.calls[0].request req_params = parse_qs(mock_access_token_request.body) assert req_params['grant_type'] == ['authorization_code'] assert req_params['code'] == ['oauth-code'] assert req_params['redirect_uri'] == ['http://testserver/extensions/github/setup/'] assert req_params['client_id'] == ['github-client-id'] assert req_params['client_secret'] == ['github-client-secret'] assert resp.status_code == 200 auth_header = responses.calls[2].request.headers['Authorization'] assert auth_header == 'Bearer jwt_token_1' self.assertDialogSuccess(resp)
def fin(): responses.reset() responses.stop()
def tearDown(self): super(TestMigrateForks, self).tearDown() Node.remove() responses.stop() responses.reset() piwik_cache._cache = None