def _test__get_file_tree(self, addon_short_name): requests_made = [] def callback(request, uri, headers): path = request.querystring['path'][0] requests_made.append(path) return (200, headers, json.dumps(self.RESP_MAP[path])) for path in self.RESP_MAP.keys(): url = waterbutler_url_for( 'metadata', provider=addon_short_name, path=path, node=self.src, user=self.user, view_only=True, ) httpretty.register_uri(httpretty.GET, url, body=callback, content_type='applcation/json') addon = self.src.get_or_add_addon(addon_short_name, auth=self.auth) root = { 'path': '/', 'name': '', 'kind': 'folder', } file_tree = addon._get_file_tree(root, self.user) assert_equal(FILE_TREE, file_tree) assert_equal(requests_made, ['/', '/qwerty']) # no requests made for files
def test_add_results_for_cases(client, suite, run): base = re.escape(client.base_url) httpretty.register_uri(httpretty.POST, re.compile(base + r'add_results_for_cases/.*'), body=json.dumps([{'id': 5, 'status_id': 4}]), match_querystring=True) cases = suite.cases() for case in cases[:-1]: case.add_result(status_id=1, comment="test result comment") new_results = run.add_results_for_cases(cases) expected = { "results": [ { "case_id": 3, "assignedto_id": None, "comment": "test result comment", "defects": None, "elapsed": None, "status_id": 1, "version": None, }, ] } result = json.loads(httpretty.last_request().body) assert expected == result assert type(new_results) is list assert type(new_results[0]) is Result assert new_results[0].id == 5
def test_error_if_response_is_null_and_allow_null_not_given(self): self.register_urls() httpretty.register_uri( httpretty.GET, "http://localhost/test_http", body=json.dumps(None)) resource = SwaggerClient(u'http://localhost/api-docs').api_test self.assertRaises(TypeError, resource.testHTTP().result)
def test_delayed_report(self, mock_time): responses = list(self.RESPONSES) responses.insert(0, self.create_runreport_response(1, 'Report has been created')) responses.insert(1, self.create_results_response()) httpretty.register_uri( httpretty.POST, TEST_URL, responses=[ httpretty.Response(body=r) for r in responses ] ) mock_time.time.return_value = 123456789012.1 self.task.run() self.assertEqual(mock_time.time.call_count, 1) mock_time.sleep.assert_has_calls([ call(5), call(5) ]) expected_record = ['2015-08-28', 'paypal', 'testing', 'EDX-123456', 'USD', '50.00', '1.40', 'sale', 'instant_transfer', 'paypal', '1FW12345678901234'] self.assertEquals(self.output_target.value.strip(), '\t'.join(expected_record))
def test_add_run_to_plan(client, plan): base = re.escape(client.base_url) httpretty.register_uri(httpretty.POST, re.compile(base + r'add_plan_entry/.*'), body=json.dumps({'runs': [{'id': 8}]}), match_querystring=True) run = Run(suite_id=14, milestone_id=15, name="test_run", description="test description", case_ids=[1, 2], config_ids=[16]) plan.add_run(run) expected = { "suite_id": 14, "name": "test_run", "description": "test description", "include_all": False, "case_ids": [1, 2], "config_ids": [16], "runs": [ { "name": "test_run", "description": "test description", "case_ids": [1, 2], "config_ids": [16] } ] } result = json.loads(httpretty.last_request().body) assert expected == result assert run.id == 8
def test_error_on_wrong_type_instead_of_complex_type(self): self.register_urls() httpretty.register_uri( httpretty.GET, "http://localhost/test_http", body='"NOT_COMPLEX_TYPE"') self.assertRaises(TypeError, SwaggerClient( u'http://localhost/api-docs').api_test.testHTTP().result)
def test_alllow_null_as_response_if_allow_null_is_given(self): self.register_urls() httpretty.register_uri( httpretty.GET, "http://localhost/test_http", body=json.dumps(None)) resource = SwaggerClient(u'http://localhost/api-docs').api_test resource.testHTTP().result(allow_null=True)
def test_fetching_program_discounted_price(self): """ Authenticated users eligible for one click purchase should see the purchase button - displaying program's discounted price if it exists. - leading to ecommerce basket page """ self._prepare_program_for_discounted_price_calculation_endpoint() mock_discount_data = { 'total_incl_tax_excl_discounts': 200.0, 'currency': 'USD', 'total_incl_tax': 50.0 } httpretty.register_uri( httpretty.GET, self.ECOMMERCE_CALCULATE_DISCOUNT_ENDPOINT, body=json.dumps(mock_discount_data), content_type='application/json' ) data = ProgramMarketingDataExtender(self.program, self.user).extend() self._update_discount_data(mock_discount_data) self.assertEqual( data['skus'], [course['course_runs'][0]['seats'][0]['sku'] for course in self.program['courses']] ) self.assertEqual(data['discount_data'], mock_discount_data)
def test_fetching_program_discounted_price_as_anonymous_user(self): """ Anonymous users should see the purchase button same way the authenticated users do when the program is eligible for one click purchase. """ self._prepare_program_for_discounted_price_calculation_endpoint() mock_discount_data = { 'total_incl_tax_excl_discounts': 200.0, 'currency': 'USD', 'total_incl_tax': 50.0 } httpretty.register_uri( httpretty.GET, self.ECOMMERCE_CALCULATE_DISCOUNT_ENDPOINT, body=json.dumps(mock_discount_data), content_type='application/json' ) data = ProgramMarketingDataExtender(self.program, AnonymousUserFactory()).extend() self._update_discount_data(mock_discount_data) self.assertEqual( data['skus'], [course['course_runs'][0]['seats'][0]['sku'] for course in self.program['courses']] ) self.assertEqual(data['discount_data'], mock_discount_data)
def test_checksending(self): httpretty.register_uri( httpretty.POST, urljoin(SmsAero.URL_GATE, '/checksending/'), body='{"reason": {"33460579": "smsc reject", \ "33460580": "delivery success"}, \ "result": "accepted"}', status=200, content_type='text/json', ) self.api.checksending(322) httpretty.register_uri( httpretty.POST, urljoin(SmsAero.URL_GATE, '/checksending/'), body='{"reason": "empty field", "result": "reject"}', status=200, content_type='text/json', ) try: self.api.checksending('') self.assertTrue(False) except SmsAeroError: pass
def test__request(self): httpretty.register_uri( httpretty.POST, urljoin(SmsAero.URL_GATE, '/send/'), body='{}', status=500, ) try: self.api.send('89111111111', 'message') self.assertTrue(False) except SmsAeroHTTPError: pass def exceptionCallback(request, uri, headers): raise requests.Timeout('Connection timed out.') httpretty.register_uri( httpretty.POST, urljoin(SmsAero.URL_GATE, '/send/'), body=exceptionCallback, status=200, content_type='text/json', ) try: self.api.send('89111111111', 'message') self.assertTrue(False) except SmsAeroHTTPError: pass
def test_podcast_file_sync(self): # download only one podcast episode with utils.temp_podcast(self.client, archive_type='soundcloud', max_allowed=1) as podcast: url = urls.soundcloud_track_list(podcast['broadcast_id'], self.client.soundcloud_client_id) httpretty.register_uri(httpretty.GET, url, body=json.dumps(soundcloud_one_track.DATA)) self.client.episode_sync() episode_list = self.client.episode_list(only_files=False) with utils.temp_audio_file() as mp3_body: utils.mock_mp3_download(episode_list[0]['download_url'], mp3_body) self.client.podcast_file_sync() episode_list = self.client.episode_list() self.assert_not_none(episode_list[0]['file_path']) first_episode_date = episode_list[0]['date'] # add an additional, newer podcast, make sure things are deleted url = urls.soundcloud_track_list(podcast['broadcast_id'], self.client.soundcloud_client_id) httpretty.register_uri(httpretty.GET, url, body=json.dumps(soundcloud_two_tracks.DATA)) self.client.episode_sync() episode_list = self.client.episode_list(only_files=False) with utils.temp_audio_file() as mp3_body: utils.mock_mp3_download(episode_list[1]['download_url'], mp3_body) self.client.podcast_file_sync() # make sure 2 episodes in db, but only 1 with a file path episode_list = self.client.episode_list() self.assert_not_none(episode_list[0]['file_path']) all_episodes = self.client.episode_list(only_files=False) self.assertNotEqual(len(episode_list), len(all_episodes)) second_episode_date = episode_list[0]['date'] self.assertTrue(datetime.strptime(second_episode_date, self.client.datetime_output_format) > datetime.strptime(first_episode_date, self.client.datetime_output_format))
def register_post_thread_response(self, thread_data): """Register a mock response for POST on the CS commentable endpoint""" httpretty.register_uri( httpretty.POST, re.compile(r"http://localhost:4567/api/v1/(\w+)/threads"), body=_get_thread_callback(thread_data) )
def setup_method(self, method): httpretty.enable() httpretty.reset() httpretty.register_uri( httpretty.POST, 'http://%s:8181/api/osd/configure/' % INSTALL_HOST, body=self.post_request_callback, content_type='application/json') self.requests = []
def test_podcast_location_update(self): # check fails with invalid data with self.assertRaises(HathorException) as error: self.client.podcast_update_file_location(1, 'foo') self.check_error_message('Podcast not found for ID:1', error) # check works with valid data with utils.temp_podcast(self.client, archive_type='rss', broadcast_url=True, max_allowed=2) as podcast: httpretty.register_uri(httpretty.GET, podcast['broadcast_id'], body=history_on_fire.DATA) self.client.episode_sync() episode_list = self.client.episode_list(only_files=False) with utils.temp_audio_file() as mp3_body: utils.mock_mp3_download(episode_list[0]['download_url'], mp3_body) self.client.episode_download(episode_list[0]['id']) old_episode = self.client.episode_show(episode_list[0]['id'])[0] with utils.temp_dir(delete=False) as temp: self.client.podcast_update_file_location(podcast['id'], temp) # make sure episode path changed new_episode = self.client.episode_show(episode_list[0]['id'])[0] self.assertTrue(new_episode['file_path'].startswith(temp)) self.assertNotEqual(old_episode['file_path'], new_episode['file_path']) # make sure podcast path changed new_podcast = self.client.podcast_show(podcast['id'])[0] self.assertNotEqual(podcast['file_location'], new_podcast['file_location'])
def test_deploy_so_sanity(self): # initialization kind = Kind('http://schemas.mobile-cloud-networking.eu/occi/sm#', 'myservice', title='Test Service', attributes={'mcn.test.attribute1': 'immutable'}, related=[Resource.kind], actions=[]) entity = Resource('my-id', kind, None) entity.extras = {} host = 'test.mcn.org:8888/myservice' entity.extras['host'] = host extras = {} extras['token'] = 'test_token' extras['tenant_name'] = 'test_tenantname' body_content = '123456789' httpretty.register_uri(httpretty.POST, 'http://' + host + '/action=deploy', status=200, body=body_content, content_type='text/occi') # Test method self.som._SOManager__deploy_so(entity, extras) # Asserts self.assertEqual(entity.extras['stack_id'], body_content)
def test_requesting_an_event_id_that_doest_exist_throws_error(self): httpretty.register_uri(httpretty.POST, FAKE_EXCHANGE_URL, status=401, body="", ) self.connection.send(b'yo')
def test_create_app(self): # Initialization # Tentative Kind/Resource Creation kind = Kind('http://schemas.mobile-cloud-networking.eu/occi/sm#', 'myservice', title='Test Service', attributes={'mcn.test.attribute1': 'immutable'}, related=[Resource.kind], actions=[]) entity = Resource('my-id', kind, None) httpretty.register_uri(httpretty.POST, 'http://*****:*****@git.mcn.eu:myserv.git"' }) # Test method repo_uri = self.som._SOManager__create_app(entity, None) # Asserts self.assertEqual(repo_uri, '[email protected]:myserv.git')
def test_init_so(self): # initialization kind = Kind('http://schemas.mobile-cloud-networking.eu/occi/sm#', 'myservice', title='Test Service', attributes={'mcn.test.attribute1': 'immutable'}, related=[Resource.kind], actions=[]) entity = Resource('my-id', kind, None) entity.extras = {} host = 'localhost:8888/myservice' entity.extras['host'] = host extras = {} extras['token'] = 'test_token' extras['tenant_name'] = 'test_tenantname' httpretty.register_uri(httpretty.POST, 'http://' + host + '/action=init', status=200, content_type='text/occi') # Test method self.som._SOManager__init_so(entity, extras) # Asserts sent_headers = httpretty.last_request().headers self.assertEqual(sent_headers['X-Auth-Token'], 'test_token') self.assertEqual(sent_headers['X-Tenant-Name'], 'test_tenantname')
def test_find_archives_with_offset(self): httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key), body=textwrap.dedent(u("""\ { "count" : 6, "items" : [ { "createdAt" : 1395183243000, "duration" : 544, "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9", "name" : "", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 78499758, "status" : "available", "hasAudio": true, "hasVideo": true, "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, { "createdAt" : 1394396753000, "duration" : 24, "id" : "b8f64de1-e218-4091-9544-4cbf369fc238", "name" : "showtime again", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 2227849, "status" : "available", "hasAudio": true, "hasVideo": true, "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, { "createdAt" : 1394321113000, "duration" : 1294, "id" : "832641bf-5dbf-41a1-ad94-fea213e59a92", "name" : "showtime", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 42165242, "status" : "available", "hasAudio": true, "hasVideo": true, "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641bf-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } ] }""")), status=200, content_type=u('application/json')) archive_list = self.opentok.get_archives(offset=3) expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret) expect(httpretty.last_request().headers[u('user-agent')]).to.contain(u('OpenTok-Python-SDK/')+__version__) expect(httpretty.last_request().headers[u('content-type')]).to.equal(u('application/json')) expect(httpretty.last_request()).to.have.property("querystring").being.equal({ u('offset'): [u('3')] }) expect(archive_list).to.be.an(ArchiveList) expect(archive_list).to.have.property(u('count')).being.equal(6) expect(list(archive_list.items)).to.have.length_of(3)
def test_find_archive_with_unknown_properties(self): archive_id = u('f6e7ee58-d6cf-4a59-896b-6d56b158ec71') httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive/{1}').format(self.api_key, archive_id), body=textwrap.dedent(u("""\ { "createdAt" : 1395187836000, "duration" : 62, "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71", "name" : "", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 8347554, "status" : "expired", "url" : null, "hasAudio": true, "hasVideo": true, "notarealproperty" : "not a real value" }""")), status=200, content_type=u('application/json')) archive = self.opentok.get_archive(archive_id) expect(archive).to.be.an(Archive)
def test_create_identifiers_exists(self): identifier = self.node._id doi = settings.EZID_FORMAT.format(namespace=settings.DOI_NAMESPACE, guid=identifier) url = furl.furl('https://ezid.cdlib.org/id') url.path.segments.append(doi) httpretty.register_uri( httpretty.PUT, url.url, body='identifier already exists', status=400, ) httpretty.register_uri( httpretty.GET, url.url, body=to_anvl({ 'success': doi, }), status=200, ) res = self.app.post( self.node.api_url_for('node_identifiers_post'), auth=self.user.auth, ) self.node.reload() assert_equal( res.json['doi'], self.node.get_identifier_value('doi') ) assert_equal( res.json['ark'], self.node.get_identifier_value('ark') ) assert_equal(res.status_code, 201)
def test_arxiv_results(self): """Test that bad matching results are handled correctly.""" from invenio_records.api import Record from invenio.base.globals import cfg from inspire.modules.workflows.tasks.matching import match_by_arxiv_id httpretty.register_uri( httpretty.GET, cfg["WORKFLOWS_MATCH_REMOTE_SERVER_URL"], body="[1234]", content_type="application/json" ) record = Record({"arxiv_id": "arXiv:1505.12345"}) res = match_by_arxiv_id(record) self.assertTrue(res) record = Record({"report_numbers": [ { "value": "arXiv:1505.12345", "source": "arXiv", } ]}) res = match_by_arxiv_id(record) self.assertTrue(res)
def test_text_500_with_false_success(self): httpretty.register_uri(httpretty.GET, 'http://www.ckan.org/', body=u'{"success": false}', content_type='html/text', status=500) r = requests.get('http://www.ckan.org/') jobs.check_response(r, 'http://www.ckan.org/', 'Me')
def test_text_404_ignore(self): httpretty.register_uri(httpretty.GET, 'http://www.ckan.org/', body=u'{"success": true}', content_type='html/text', status=404) r = requests.get('http://www.ckan.org/') jobs.check_response(r, 'http://www.ckan.org/', 'Me', good_status=(200, 201, 404))
def test_resource_update(self): url = 'http://www.ckan.org/api/3/action/resource_update' httpretty.register_uri(httpretty.POST, url, body=u'{"success": true}', content_type="application/json") jobs.update_resource({'foo': 42}, 'my_key', 'http://www.ckan.org/') assert json.loads(httpretty.last_request().body)['url_type'] == 'datapusher'
def test_text_409_with_broken_json(self): httpretty.register_uri(httpretty.GET, 'http://www.ckan.org/', body=u"This is someone's text. With ümlauts.", content_type='html/text', status=409) r = requests.get('http://www.ckan.org/') jobs.check_response(r, 'http://www.ckan.org/', 'Me')
def test_create_identifiers_not_exists(self): identifier = self.node._id url = furl.furl('https://ezid.cdlib.org/id') doi = settings.EZID_FORMAT.format(namespace=settings.DOI_NAMESPACE, guid=identifier) url.path.segments.append(doi) httpretty.register_uri( httpretty.PUT, url.url, body=to_anvl({ 'success': '{doi}osf.io/{ident} | {ark}osf.io/{ident}'.format( doi=settings.DOI_NAMESPACE, ark=settings.ARK_NAMESPACE, ident=identifier, ), }), status=201, priority=1, ) res = self.app.post( self.node.api_url_for('node_identifiers_post'), auth=self.user.auth, ) self.node.reload() assert_equal( res.json['doi'], self.node.get_identifier_value('doi') ) assert_equal( res.json['ark'], self.node.get_identifier_value('ark') ) assert_equal(res.status_code, 201)
def test_delete_datastore(self): url = 'http://www.ckan.org/api/3/action/datastore_delete' httpretty.register_uri(httpretty.POST, url, body=u'{"success": true}', content_type="application/json") jobs.delete_datastore_resource('an_id', 'my_key', 'http://www.ckan.org/') assert json.loads(httpretty.last_request().body)['id'] == 'an_id'
def test_token_refresh(self): """expired tokens should refresh automatically, the new token should be passed to token_updater()""" def token_updater(token): self.assertEqual(token['access_token'], self.mock_token['access_token']) self.assertEqual(token['refresh_token'], self.mock_token['refresh_token']) json_body_token = json.dumps(self.mock_token) httpretty.register_uri(httpretty.POST, self.mock_token_url, body=json_body_token, status=201, content_type="application/json") json_body_incident = json.dumps({'result': [{'number': self.mock_incident_number}]}) httpretty.register_uri(httpretty.GET, "%s%s" % (self.client.base_url, '/api/now/table/incident'), body=json_body_incident, status=200, content_type="application/json") c = self.client c.token_updater = token_updater c.set_token(self.mock_token_expired) r = c.query(table='incident', query={}).get_one() number = r['number'] self.assertEqual(number, self.mock_incident_number)
def myreg(*argc, **kwargs): url = argc[0] method = httpretty.PUT if ec2.API_TOKEN_ROUTE in url else httpretty.GET return httpretty.register_uri(method, *argc, **kwargs)
def setUp(self): """ Mock out HTTP calls to various endpoints using httpretty. """ super(SuccessFactorsIntegrationTest, self).setUp() # Mock the call to the SAP SuccessFactors assertion endpoint SAPSF_ASSERTION_URL = 'http://successfactors.com/oauth/idp' def assertion_callback(_request, _uri, headers): """ Return a fake assertion after checking that the input is what we expect. """ self.assertIn(b'private_key=fake_private_key_here', _request.body) self.assertIn(b'user_id=myself', _request.body) self.assertIn( b'token_url=http%3A%2F%2Fsuccessfactors.com%2Foauth%2Ftoken', _request.body) self.assertIn(b'client_id=TatVotSEiCMteSNWtSOnLanCtBGwNhGB', _request.body) return (200, headers, 'fake_saml_assertion') httpretty.register_uri(httpretty.POST, SAPSF_ASSERTION_URL, content_type='text/plain', body=assertion_callback) SAPSF_BAD_ASSERTION_URL = 'http://successfactors.com/oauth-fake/idp' def bad_callback(_request, _uri, headers): """ Return a 404 error when someone tries to call the URL. """ return (404, headers, 'NOT AN ASSERTION') httpretty.register_uri(httpretty.POST, SAPSF_BAD_ASSERTION_URL, content_type='text/plain', body=bad_callback) # Mock the call to the SAP SuccessFactors token endpoint SAPSF_TOKEN_URL = 'http://successfactors.com/oauth/token' def token_callback(_request, _uri, headers): """ Return a fake assertion after checking that the input is what we expect. """ self.assertIn(b'assertion=fake_saml_assertion', _request.body) self.assertIn(b'company_id=NCC1701D', _request.body) self.assertIn( b'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Asaml2-bearer', _request.body) self.assertIn(b'client_id=TatVotSEiCMteSNWtSOnLanCtBGwNhGB', _request.body) return (200, headers, '{"access_token": "faketoken"}') httpretty.register_uri(httpretty.POST, SAPSF_TOKEN_URL, content_type='application/json', body=token_callback) # Mock the call to the SAP SuccessFactors OData user endpoint ODATA_USER_URL = ( 'http://api.successfactors.com/odata/v2/User(userId=\'myself\')' '?$select=username,firstName,lastName,defaultFullName,email') def user_callback(request, _uri, headers): auth_header = request.headers.get('Authorization') self.assertEqual(auth_header, 'Bearer faketoken') return (200, headers, json.dumps({ 'd': { 'username': '******', 'firstName': 'John', 'lastName': 'Smith', 'defaultFullName': 'John Smith', 'email': '*****@*****.**', 'country': 'Australia', } })) httpretty.register_uri(httpretty.GET, ODATA_USER_URL, content_type='application/json', body=user_callback)
def register_uri(self): body = """<ListBucketResult xmlns="http://s3.amazonaws.com/"> </ListBucketResult> """ httpretty.register_uri(httpretty.GET, re.compile('.*'), body=body)
def mock_course_runs_endpoint( self, discovery_api_url, course_run=None, partner_code=None, query=None, course_run_info=None ): """ Helper function to register a discovery API endpoint for getting course runs information. """ if not course_run_info: course_run_info = { 'count': 1, 'next': None, 'previous': None, 'results': [{ 'key': course_run.id, 'title': course_run.name, 'start': '2016-05-01T00:00:00Z', 'image': { 'src': 'path/to/the/course/image' }, 'enrollment_start': '2016-05-01T00:00:00Z', 'enrollment_end': None }] if course_run else [{ 'key': 'test', 'title': 'Test course', 'enrollment_start': '2016-05-01T00:00:00Z', 'enrollment_end': None }], } course_run_info_json = json.dumps(course_run_info) course_run_url_with_query = '{}course_runs/?q={}'.format( discovery_api_url, query if query else 'id:course*' ) httpretty.register_uri( httpretty.GET, course_run_url_with_query, body=course_run_info_json, content_type='application/json' ) course_run_url_with_query_and_partner_code = '{}course_runs/?q={}&partner={}'.format( discovery_api_url, query if query else 'id:course*', partner_code if partner_code else 'edx' ) httpretty.register_uri( httpretty.GET, course_run_url_with_query_and_partner_code, body=course_run_info_json, content_type='application/json' ) course_run_url_with_key = '{}course_runs/{}/'.format( discovery_api_url, course_run.id if course_run else 'course-v1:test+test+test' ) httpretty.register_uri( httpretty.GET, course_run_url_with_key, body=json.dumps(course_run_info['results'][0]), content_type='application/json' )
def test_shell(self): '''Test to make sure this plugin integrates with neutronclient''' fake_tenant_id = "123456" fake_token = format(random.randint(0, 2**(32 * 4)), 'x') import os shell.os.environ.update({ "OS_USERNAME": "******", "OS_TENANT_NAME": "mock_id", "OS_AUTH_URL": "https://identity.api.rackspacecloud.com/v2.0/", "OS_PASSWORD": "******" }) def identity_callback(request, uri, headers): ''' This callback mocks the identity response with total success ''' identity_response_dict = { "access": # Randomly pick a token for authentication { 'token': { 'id': fake_token, 'RAX-AUTH:authenticatedBy': ['APIKEY'], 'expires': '2014-01-08T18:07:22.007Z', 'tenant': { 'id': fake_tenant_id, 'name': fake_tenant_id } }, "serviceCatalog": [ { u'endpoints': [ { u'publicURL': u'https://dfw.mock.api.rackspacecloud.com/v2/' + fake_tenant_id, u'region': u'DFW', u'tenantId': fake_tenant_id, u'versionId': u'2', u'versionInfo': u'https://dfw.mock.api.rackspacecloud.com/v2', u'versionList': u'https://dfw.mock.api.rackspacecloud.com/' }, ], u'name': u'mockCompute', u'type': u'compute' }, ], # Data not being used for these little tests "user": {} } } identity_response = json.dumps(identity_response_dict) return (200, headers, identity_response) httpretty.register_uri( httpretty.POST, "https://identity.api.rackspacecloud.com/v2.0/tokens", body=identity_callback, content_type="application/json") oscs = shell.OpenStackComputeShell() oscs.main(["endpoints"])
def test_get_pool_nodes_addrs(self): httpretty.register_uri(httpretty.GET, self.api_url, body=self.api_body) view = views.PoolMetric(request=self.request) addrs = view.get_pool_nodes("theonepool") self.assertEqual(addrs, ["128.0.0.1", "127.0.0.1", "myserver2.com"])
def mock_mozreview(): ''' Mock mozreview authentication process Need to use httpretty as mozreview uses low level urlopen ''' api_url = 'http://mozreview.test/api/' auth_url = api_url + 'extensions/mozreview.extension.MozReviewExtension/bugzilla-api-key-logins/' session_url = api_url + 'session/' def _response(name, extension='json'): path = os.path.join(MOCK_DIR, 'mozreview_{}.{}'.format(name, extension)) assert os.path.exists(path) return open(path).read() # Start httpretty session httpretty.enable() # API Root endpoint httpretty.register_uri( httpretty.GET, api_url, body=_response('root'), content_type='application/vnd.reviewboard.org.root+json', ) # Initial query to get auth endpoints httpretty.register_uri( httpretty.GET, auth_url, body=_response('auth'), content_type= 'application/vnd.reviewboard.org.bugzilla-api-key-logins+json', ) # Current session query httpretty.register_uri( httpretty.GET, session_url, body=_response('session'), content_type='application/vnd.reviewboard.org.session+json', ) # User details queries httpretty.register_uri( httpretty.GET, api_url + 'users/devbot/', body=_response('user'), content_type='application/vnd.reviewboard.org.user+json', ) httpretty.register_uri( httpretty.GET, api_url + 'users/anotherUser/', body=_response('user_another'), content_type='application/vnd.reviewboard.org.user+json', ) # Dummy Reviews list httpretty.register_uri( httpretty.GET, api_url + 'review-requests/12345/reviews/', body=_response('reviews_12345'), content_type='application/vnd.reviewboard.org.review+json', ) # Dummy Review comment list httpretty.register_uri( httpretty.GET, api_url + 'review-requests/12345/reviews/51/diff-comments/', body=_response('comments_12345_51'), content_type= 'application/vnd.reviewboard.org.review-diff-comments+json', ) # Dummy Review file diff httpretty.register_uri( httpretty.GET, api_url + 'review-requests/12345/diffs/2/files/', body=_response('files_12345'), content_type='application/vnd.reviewboard.org.files+json', adding_headers={ 'Item-Content-Type': 'application/vnd.reviewboard.org.file+json', }) def _filediff(request, uri, headers): if request.headers.get( 'Accept') == 'application/vnd.reviewboard.org.diff.data+json': # Diff data body = _response('filediff_12345_2_diffdata') headers[ 'content-type'] = 'application/vnd.reviewboard.org.diff.data+json' else: # Basic data body = _response('filediff_12345_2') headers[ 'content-type'] = 'application/vnd.reviewboard.org.file+json' return (200, headers, body) httpretty.register_uri( httpretty.GET, api_url + 'review-requests/12345/diffs/2/files/31/', body=_filediff, ) def _check_credentials(request, uri, headers): # Dirty multipart form data "parser" form = dict( re.findall(r'name="([\w_]+)"\r\n\r\n(\w+)\r\n', request.body.decode('utf-8'))) assert form['username'] == 'devbot' assert form['api_key'] == 'deadbeef123' body = json.dumps({ 'stat': 'ok', 'bugzilla_api_key_login': { 'email': '*****@*****.**', }, }) return (201, headers, body) # Initial query to get auth endpoints httpretty.register_uri( httpretty.POST, auth_url, status_code=201, body=_check_credentials, content_type= 'application/vnd.reviewboard.org.bugzilla-api-key-logins+json', ) # Pass context to test runtime yield # Close httpretty session httpretty.disable()
def test_fetch_from_date(self): """Test when return from date""" issues_page_1 = read_file( 'data/launchpad/launchpad_issues_page_1_no_next') issue_1 = read_file('data/launchpad/launchpad_issue_1') issue_1_comments = read_file( 'data/launchpad/launchpad_issue_1_comments') issue_1_attachments = read_file( 'data/launchpad/launchpad_issue_1_attachments') issue_1_activities = read_file( 'data/launchpad/launchpad_issue_1_activities') user_1 = read_file('data/launchpad/launchpad_user_1') issue_1_expected = read_file( 'data/launchpad/launchpad_issue_1_expected') httpretty.register_uri( httpretty.GET, LAUNCHPAD_PACKAGE_PROJECT_URL + "?modified_since=1970-01-01T00%3A00%3A00%2B00%3A00&ws.op=searchTasks" "&omit_duplicates=false&order_by=date_last_updated&status=Confirmed&status=Expired" "&status=Fix+Committed&status=Fix+Released" "&status=In+Progress&status=Incomplete&status=Incomplete+%28with+response%29" "&status=Incomplete+%28without+response%29" "&status=Invalid&status=New&status=Opinion&status=Triaged" "&status=Won%27t+Fix" "&ws.size=1", body=issues_page_1, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1", body=issue_1, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/messages", body=issue_1_comments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/attachments", body=issue_1_attachments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/activity", body=issue_1_activities, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/~user", body=user_1, status=200) launchpad = Launchpad('mydistribution', consumer_key=CONSUMER_KEY, api_token=OAUTH_TOKEN, package="mypackage", items_per_page=2) from_date = datetime.datetime(2018, 8, 21, 16, 0, 0) issues = [issues for issues in launchpad.fetch(from_date=from_date)] issue_1_expected = json.loads(issue_1_expected) self.assertEqual(len(issues), 1) self.assertDictEqual(issues[0]['data'], issue_1_expected)
def test_fetch_from_date_from_archive(self): """Test whether a list of questions is returned from a given date from the archive.""" question_api_1 = read_file('data/askbot/askbot_api_questions.json') question_api_2 = read_file('data/askbot/askbot_api_questions_2.json') question_html_1 = read_file('data/askbot/askbot_question.html') question_html_2 = read_file( 'data/askbot/askbot_question_multipage_1.html') question_html_2_2 = read_file( 'data/askbot/askbot_question_multipage_2.html') comments = read_file('data/askbot/askbot_2481_multicomments.json') httpretty.register_uri(httpretty.GET, ASKBOT_QUESTIONS_API_URL, body=question_api_1, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTIONS_API_URL, body=question_api_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2481_URL, body=question_html_1, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2488_URL, body=question_html_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2488_URL, body=question_html_2_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_COMMENTS_API_URL, body=comments, status=200) from_date = datetime.datetime(2013, 1, 1) self._test_fetch_from_archive(from_date=from_date)
def test_fetch_from_cache(self): """Test whether a list of issues is returned from cache""" issues_page_1 = read_file('data/launchpad/launchpad_issues_page_1') issues_page_2 = read_file('data/launchpad/launchpad_issues_page_2') issues_page_3 = read_file('data/launchpad/launchpad_issues_page_3') issue_1 = read_file('data/launchpad/launchpad_issue_1') issue_2 = read_file('data/launchpad/launchpad_issue_2') issue_3 = read_file('data/launchpad/launchpad_issue_3') issue_1_activities_next_1 = read_file( 'data/launchpad/launchpad_issue_1_activities_next_1') issue_1_activities_next_2 = read_file( 'data/launchpad/launchpad_issue_1_activities_next_2') issue_1_comments_next_1 = read_file( 'data/launchpad/launchpad_issue_1_comments_next_1') issue_1_comments_next_2 = read_file( 'data/launchpad/launchpad_issue_1_comments_next_2') issue_1_attachments_next_1 = \ read_file('data/launchpad/launchpad_issue_1_attachments_next_1') issue_1_attachments_next_2 = \ read_file('data/launchpad/launchpad_issue_1_attachments_next_2') issue_2_activities = read_file( 'data/launchpad/launchpad_issue_2_activities') issue_2_comments = read_file( 'data/launchpad/launchpad_issue_2_comments') user_1 = read_file('data/launchpad/launchpad_user_1') empty_issue_comments = read_file( 'data/launchpad/launchpad_empty_issue_comments') empty_issue_attachments = read_file( 'data/launchpad/launchpad_empty_issue_attachments') empty_issue_activities = read_file( 'data/launchpad/launchpad_empty_issue_activities') httpretty.register_uri( httpretty.GET, LAUNCHPAD_PACKAGE_PROJECT_URL + "?modified_since=1970-01-01T00%3A00%3A00%2B00%3A00&ws.op=searchTasks" "&omit_duplicates=false&order_by=date_last_updated&status=Confirmed&status=Expired" "&status=Fix+Committed&status=Fix+Released" "&status=In+Progress&status=Incomplete&status=Incomplete+%28with+response%29" "&status=Incomplete+%28without+response%29" "&status=Invalid&status=New&status=Opinion&status=Triaged" "&status=Won%27t+Fix" "&ws.size=1&memo=2&ws.start=2", body=issues_page_3, status=200) httpretty.register_uri( httpretty.GET, LAUNCHPAD_PACKAGE_PROJECT_URL + "?modified_since=1970-01-01T00%3A00%3A00%2B00%3A00&ws.op=searchTasks" "&omit_duplicates=false&order_by=date_last_updated&status=Confirmed&status=Expired" "&status=Fix+Committed&status=Fix+Released" "&status=In+Progress&status=Incomplete&status=Incomplete+%28with+response%29" "&status=Incomplete+%28without+response%29" "&status=Invalid&status=New&status=Opinion&status=Triaged" "&status=Won%27t+Fix" "&ws.size=1&memo=1&ws.start=1", body=issues_page_2, status=200) httpretty.register_uri( httpretty.GET, LAUNCHPAD_PACKAGE_PROJECT_URL + "?modified_since=1970-01-01T00%3A00%3A00%2B00%3A00&ws.op=searchTasks" "&omit_duplicates=false&order_by=date_last_updated&status=Confirmed&status=Expired" "&status=Fix+Committed&status=Fix+Released" "&status=In+Progress&status=Incomplete&status=Incomplete+%28with+response%29" "&status=Incomplete+%28without+response%29" "&status=Invalid&status=New&status=Opinion&status=Triaged" "&status=Won%27t+Fix" "&ws.size=1&ws.start=0", body=issues_page_1, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1", body=issue_1, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/2", body=issue_2, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/3", body=issue_3, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/messages", body=issue_1_comments_next_2, params={ 'ws.size': 2, 'memo': 2, 'ws.start': 2 }, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/messages", body=issue_1_comments_next_1, params={ 'ws.size': 2, 'orderby': '-datecreated', 'ws.start': 0 }, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/2/messages", body=issue_2_comments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/3/messages", body=empty_issue_comments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/attachments", body=issue_1_attachments_next_2, params={ 'orderby': '-datecreated', 'ws.size': 2, 'memo': 2, 'ws.start': 2 }, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/attachments", body=issue_1_attachments_next_1, params={ 'orderby': '-datecreated', 'ws.size': 2, 'ws.start': 0 }, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/2/attachments", body=empty_issue_attachments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/3/attachments", body=empty_issue_attachments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/activity", body=issue_1_activities_next_2, params={ 'orderby': '-datecreated', 'ws.size': 2, 'memo': 2, 'ws.start': 2 }, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/activity", body=issue_1_activities_next_1, params={ 'orderby': '-datecreated', 'ws.size': 2, 'ws.start': 0 }, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/2/activity", body=issue_2_activities, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/3/activity", body=empty_issue_activities, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/~user", body=user_1, status=200) # First, we fetch the bugs from the server and store them in a cache cache = Cache(self.tmp_path) launchpad = Launchpad('mydistribution', consumer_key=CONSUMER_KEY, api_token=OAUTH_TOKEN, package="mypackage", cache=cache, items_per_page=2) issues = [issues for issues in launchpad.fetch()] # Now, we get the bugs from the cache. cache_issues = [ cache_issues for cache_issues in launchpad.fetch_from_cache() ] del issues[0]['timestamp'] del cache_issues[0]['timestamp'] del issues[1]['timestamp'] del cache_issues[1]['timestamp'] del issues[2]['timestamp'] del cache_issues[2]['timestamp'] self.assertEqual(len(issues), len(cache_issues)) self.assertDictEqual(issues[0], cache_issues[0]) self.assertDictEqual(issues[1], cache_issues[1]) self.assertDictEqual(issues[2], cache_issues[2])
def test_fetch(self): """Test whether a list of questions is returned""" question_api_1 = read_file('data/askbot/askbot_api_questions.json') question_api_2 = read_file('data/askbot/askbot_api_questions_2.json') question_html_1 = read_file('data/askbot/askbot_question.html') question_html_2 = read_file( 'data/askbot/askbot_question_multipage_1.html') question_html_2_2 = read_file( 'data/askbot/askbot_question_multipage_2.html') comments = read_file('data/askbot/askbot_2481_multicomments.json') httpretty.register_uri(httpretty.GET, ASKBOT_QUESTIONS_API_URL, body=question_api_1, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTIONS_API_URL, body=question_api_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2481_URL, body=question_html_1, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2488_URL, body=question_html_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2488_URL, body=question_html_2_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_COMMENTS_API_URL, body=comments, status=200) backend = Askbot(ASKBOT_URL) questions = [question for question in backend.fetch()] json_comments = json.loads(comments) self.assertEqual(len(questions[0]['data']['answers']), len(questions[0]['data']['answer_ids'])) self.assertTrue(questions[0]['data']['answers'][0]['accepted']) self.assertEqual(questions[0]['tag'], 'http://example.com') self.assertEqual(questions[0]['uuid'], '3fb5f945a0dd223c60218a98ad35bad6043f9f5f') self.assertEqual(questions[0]['updated_on'], 1408116902.0) self.assertEqual(questions[0]['data']['id'], 2488) self.assertEqual(questions[0]['category'], backend.metadata_category(questions[0])) self.assertEqual(questions[0]['data']['comments'][0], json_comments[0]) self.assertEqual(len(questions[0]['data']['comments']), len(json_comments)) self.assertEqual(len(questions[1]['data']['answers']), len(questions[1]['data']['answer_ids'])) self.assertFalse(questions[1]['data']['answers'][0]['accepted']) self.assertEqual(questions[1]['tag'], 'http://example.com') self.assertEqual(questions[1]['uuid'], 'ecc1320265e400edb28700cc3d02efc6d76410be') self.assertEqual(questions[1]['updated_on'], 1349928216.0) self.assertEqual(questions[1]['data']['id'], 2481) self.assertEqual(questions[1]['category'], backend.metadata_category(questions[1]))
def test_fetch(self): """Test whether a list of issues is returned""" issues_page_1 = read_file('data/launchpad/launchpad_issues_page_1') issues_page_2 = read_file('data/launchpad/launchpad_issues_page_2') issues_page_3 = read_file('data/launchpad/launchpad_issues_page_3') issue_1 = read_file('data/launchpad/launchpad_issue_1') issue_2 = read_file('data/launchpad/launchpad_issue_2') issue_3 = read_file('data/launchpad/launchpad_issue_3') issue_1_comments = read_file( 'data/launchpad/launchpad_issue_1_comments') issue_1_attachments = read_file( 'data/launchpad/launchpad_issue_1_attachments') issue_1_activities = read_file( 'data/launchpad/launchpad_issue_1_activities') issue_2_activities = read_file( 'data/launchpad/launchpad_issue_2_activities') issue_2_comments = read_file( 'data/launchpad/launchpad_issue_2_comments') user_1 = read_file('data/launchpad/launchpad_user_1') empty_issue_comments = read_file( 'data/launchpad/launchpad_empty_issue_comments') empty_issue_attachments = read_file( 'data/launchpad/launchpad_empty_issue_attachments') empty_issue_activities = read_file( 'data/launchpad/launchpad_empty_issue_activities') issue_1_expected = read_file( 'data/launchpad/launchpad_issue_1_expected') issue_2_expected = read_file( 'data/launchpad/launchpad_issue_2_expected') issue_3_expected = read_file( 'data/launchpad/launchpad_issue_3_expected') httpretty.register_uri( httpretty.GET, LAUNCHPAD_PACKAGE_PROJECT_URL + "?modified_since=1970-01-01T00%3A00%3A00%2B00%3A00&ws.op=searchTasks" "&omit_duplicates=false&order_by=date_last_updated&status=Confirmed&status=Expired" "&status=Fix+Committed&status=Fix+Released" "&status=In+Progress&status=Incomplete&status=Incomplete+%28with+response%29" "&status=Incomplete+%28without+response%29" "&status=Invalid&status=New&status=Opinion&status=Triaged" "&status=Won%27t+Fix" "&ws.size=1&memo=2&ws.start=2", body=issues_page_3, status=200) httpretty.register_uri( httpretty.GET, LAUNCHPAD_PACKAGE_PROJECT_URL + "?modified_since=1970-01-01T00%3A00%3A00%2B00%3A00&ws.op=searchTasks" "&omit_duplicates=false&order_by=date_last_updated&status=Confirmed&status=Expired" "&status=Fix+Committed&status=Fix+Released" "&status=In+Progress&status=Incomplete&status=Incomplete+%28with+response%29" "&status=Incomplete+%28without+response%29" "&status=Invalid&status=New&status=Opinion&status=Triaged" "&status=Won%27t+Fix" "&ws.size=1&memo=1&ws.start=1", body=issues_page_2, status=200) httpretty.register_uri( httpretty.GET, LAUNCHPAD_PACKAGE_PROJECT_URL + "?modified_since=1970-01-01T00%3A00%3A00%2B00%3A00&ws.op=searchTasks" "&omit_duplicates=false&order_by=date_last_updated&status=Confirmed&status=Expired" "&status=Fix+Committed&status=Fix+Released" "&status=In+Progress&status=Incomplete&status=Incomplete+%28with+response%29" "&status=Incomplete+%28without+response%29" "&status=Invalid&status=New&status=Opinion&status=Triaged" "&status=Won%27t+Fix" "&ws.size=1", body=issues_page_1, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1", body=issue_1, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/2", body=issue_2, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/3", body=issue_3, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/messages", body=issue_1_comments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/2/messages", body=issue_2_comments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/3/messages", body=empty_issue_comments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/attachments", body=issue_1_attachments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/2/attachments", body=empty_issue_attachments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/3/attachments", body=empty_issue_attachments, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/1/activity", body=issue_1_activities, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/2/activity", body=issue_2_activities, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/bugs/3/activity", body=empty_issue_activities, status=200) httpretty.register_uri(httpretty.GET, LAUNCHPAD_API_URL + "/~user", body=user_1, status=200) launchpad = Launchpad('mydistribution', package="mypackage", items_per_page=2) issues = [issues for issues in launchpad.fetch()] issue_1_expected = json.loads(issue_1_expected) issue_2_expected = json.loads(issue_2_expected) issue_3_expected = json.loads(issue_3_expected) self.assertEqual(len(issues), 3) self.assertEqual(len(issues[0]['data']['activity_data']), 1) self.assertEqual(len(issues[0]['data']['messages_data']), 2) self.assertDictEqual(issues[0]['data']['assignee_data'], issue_1_expected['assignee_data']) self.assertDictEqual(issues[0]['data']['owner_data'], issue_1_expected['owner_data']) self.assertListEqual(issues[0]['data']['activity_data'], issue_1_expected['activity_data']) self.assertListEqual(issues[0]['data']['messages_data'], issue_1_expected['messages_data']) self.assertDictEqual(issues[0]['data'], issue_1_expected) self.assertDictEqual(issues[1]['data']['assignee_data'], issue_2_expected['assignee_data']) self.assertDictEqual(issues[1]['data']['owner_data'], issue_2_expected['owner_data']) self.assertEqual(len(issues[1]['data']['activity_data']), 1) self.assertEqual(len(issues[1]['data']['messages_data']), 1) self.assertListEqual(issues[1]['data']['activity_data'], issue_2_expected['activity_data']) self.assertListEqual(issues[1]['data']['messages_data'], issue_2_expected['messages_data']) self.assertDictEqual(issues[1]['data'], issue_2_expected) self.assertDictEqual(issues[2]['data']['assignee_data'], issue_3_expected['assignee_data']) self.assertDictEqual(issues[2]['data']['owner_data'], issue_3_expected['owner_data']) self.assertEqual(len(issues[2]['data']['activity_data']), 0) self.assertEqual(len(issues[2]['data']['messages_data']), 0) self.assertListEqual(issues[2]['data']['activity_data'], issue_3_expected['activity_data']) self.assertListEqual(issues[2]['data']['messages_data'], issue_3_expected['messages_data']) self.assertDictEqual(issues[2]['data'], issue_3_expected)
def test_create_bad_request_validation_errors(self): uri = self.uri_root + '/workout/' content_returned = '{"_diagnostics":{"validation_failures":[["user filter required"]]},"_links":{"self":[{"href":"\/v7.0\/workout\/?limit=20&offset=0"}],"documentation":[{"href":"https:\/\/developer.mapmyapi.com\/docs\/Workout"}]}}' httpretty.register_uri(httpretty.POST, uri, body=content_returned, status=400) self.assertRaisesRegexp(BadRequestException, 'user filter required.', self.mmf.workout.create, valid_workout)
def test_fetch_from_date(self): """Test whether a list of questions is returned from a given date.""" question_api_1 = read_file('data/askbot/askbot_api_questions.json') question_api_2 = read_file('data/askbot/askbot_api_questions_2.json') question_html_1 = read_file('data/askbot/askbot_question.html') question_html_2 = read_file( 'data/askbot/askbot_question_multipage_1.html') question_html_2_2 = read_file( 'data/askbot/askbot_question_multipage_2.html') comments = read_file('data/askbot/askbot_2481_multicomments.json') httpretty.register_uri(httpretty.GET, ASKBOT_QUESTIONS_API_URL, body=question_api_1, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTIONS_API_URL, body=question_api_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2481_URL, body=question_html_1, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2488_URL, body=question_html_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2488_URL, body=question_html_2_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_COMMENTS_API_URL, body=comments, status=200) backend = Askbot(ASKBOT_URL) from_date = datetime.datetime(2013, 1, 1) questions = [ question for question in backend.fetch(from_date=from_date) ] self.assertEqual(questions[0]['tag'], 'http://example.com') self.assertEqual(questions[0]['uuid'], '3fb5f945a0dd223c60218a98ad35bad6043f9f5f') self.assertEqual(questions[0]['updated_on'], 1408116902.0) self.assertEqual(questions[0]['data']['id'], 2488) self.assertEqual(len(questions), 1)
def register_uri(self): httpretty.register_uri(httpretty.POST, re.compile('.*'), body=GET_PASSWORD_DATA_RESPONSE)
def test_too_many_redirects(self): """Test whether a too many redirects error is properly handled""" question_api_1 = read_file('data/askbot/askbot_api_questions.json') question_api_2 = read_file('data/askbot/askbot_api_questions_2.json') question_html_2 = read_file( 'data/askbot/askbot_question_multipage_1.html') question_html_2_2 = read_file( 'data/askbot/askbot_question_multipage_2.html') comments = read_file('data/askbot/askbot_2481_multicomments.json') httpretty.register_uri(httpretty.GET, ASKBOT_QUESTIONS_API_URL, body=question_api_1, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTIONS_API_URL, body=question_api_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2481_URL, location=ASKBOT_QUESTION_2481_URL, status=301) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2488_URL, body=question_html_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_QUESTION_2488_URL, body=question_html_2_2, status=200) httpretty.register_uri(httpretty.GET, ASKBOT_COMMENTS_API_URL, body=comments, status=200) backend = Askbot(ASKBOT_URL) questions = [question for question in backend.fetch()] self.assertEqual(len(questions), 1)
def test_authorization_header(self): url = "http://target/api" httpretty.register_uri(httpretty.POST, url, status=200) self.m.request("post", "/api") self.assertEqual("bearer 123", httpretty.last_request().headers["authorization"])
def mock_program_detail_endpoint(self, program_uuid, discovery_api_url, empty=False, title='Test Program', include_entitlements=True, status='active'): """ Mocks the program detail endpoint on the Catalog API. Args: program_uuid (uuid): UUID of the mocked program. Returns: dict: Mocked program data. """ partner = PartnerFactory() data = None if not empty: courses = [] for i in range(1, 5): uuid = '268afbfc-cc1e-415b-a5d8-c58d955bcfc' + str(i) entitlement = create_or_update_course_entitlement('verified', 10, partner, uuid, uuid) entitlements = [] if include_entitlements: entitlements.append( { "mode": "verified", "price": "10.00", "currency": "USD", "sku": entitlement.stockrecords.first().partner_sku } ) key = 'course-v1:test-org+course+' + str(i) course_runs = [] for __ in range(1, 4): course_run = CourseFactory(partner=self.partner) course_run.create_or_update_seat('audit', False, Decimal(0)) course_run.create_or_update_seat('verified', True, Decimal(100)) course_runs.append({ 'key': course_run.id, 'seats': [{ 'type': mode_for_product(seat), 'sku': seat.stockrecords.get(partner=self.partner).partner_sku, } for seat in course_run.seat_products] }) courses.append({'key': key, 'uuid': uuid, 'course_runs': course_runs, 'entitlements': entitlements, }) program_uuid = str(program_uuid) data = { 'uuid': program_uuid, 'title': title, 'status': status, 'type': 'MicroMockers', 'courses': courses, 'applicable_seat_types': [ 'verified', 'professional', 'credit' ], } self.mock_access_token_response() httpretty.register_uri( method=httpretty.GET, uri='{base}/programs/{uuid}/'.format( base=discovery_api_url.strip('/'), uuid=program_uuid ), body=json.dumps(data), content_type='application/json' ) return data
def test_clipboard_with_subsubclass(self): driver = self.android_w3c_driver(SubSubWebDriver) httpretty.register_uri(httpretty.GET, appium_command('/session/1234567890/context'), body='{"value": "NATIVE"}') assert driver.current_context == 'NATIVE'
def test_password_empty(self): """No password is set if the metadata service returns an empty string.""" httpretty.register_uri(httpretty.GET, self.password_url, body="") self.assertFalse(get_password())
def test_get_issues(self): """Test get issues API call""" from_date = str_to_datetime('2015-01-01') requests = [] bodies_json = [ read_file('data/jira/jira_issues_page_1.json'), read_file('data/jira/jira_issues_page_2.json') ] bodies = bodies_json[:] bodies = list(bodies_json) def request_callback(method, uri, headers): body = bodies.pop(0) requests.append(httpretty.last_request()) return 200, headers, body httpretty.register_uri(httpretty.GET, JIRA_SEARCH_URL, responses=[ httpretty.Response(body=request_callback) for _ in range(2) ]) client = JiraClient(url='http://example.com', project='perceval', user='******', password='******', verify=False, cert=None, max_results=2) pages = [page for page in client.get_issues(from_date)] expected_req = [{ 'expand': ['renderedFields,transitions,operations,changelog'], 'jql': [ 'project = perceval AND updated > 1420070400000 order by updated asc' ], 'maxResults': ['2'], 'startAt': ['0'] }, { 'expand': ['renderedFields,transitions,operations,changelog'], 'jql': [ 'project = perceval AND updated > 1420070400000 order by updated asc' ], 'maxResults': ['2'], 'startAt': ['2'] }] self.assertEqual(len(pages), 2) self.assertEqual(requests[0].method, 'GET') self.assertRegex(requests[0].path, '/rest/api/2/search') self.assertDictEqual(requests[0].querystring, expected_req[0]) self.assertEqual(requests[1].method, 'GET') self.assertRegex(requests[1].path, '/rest/api/2/search') self.assertDictEqual(requests[1].querystring, expected_req[1]) self.assertEqual(pages[0], bodies_json[0]) self.assertEqual(pages[1], bodies_json[1])
def test_versioned(self): url = "http://target/1.2/api" httpretty.register_uri(httpretty.POST, url, status=200) self.m.request("post", "/api", version=1.2) self.assertEqual("/1.2/api", httpretty.last_request().path)
def test_fetch(self): """Test whether a list of issues is returned""" requests = [] bodies_json = [ read_file('data/jira/jira_issues_page_1.json'), read_file('data/jira/jira_issues_page_2.json') ] comment_json = read_file('data/jira/jira_comments_issue_page_2.json') empty_comment = read_file('data/jira/jira_comments_issue_empty.json') body = read_file('data/jira/jira_fields.json') def request_callback(method, uri, headers): body = bodies_json.pop(0) requests.append(httpretty.last_request()) return 200, headers, body httpretty.register_uri(httpretty.GET, JIRA_SEARCH_URL, responses=[ httpretty.Response(body=request_callback) for _ in range(2) ]) httpretty.register_uri(httpretty.GET, JIRA_ISSUE_1_COMMENTS_URL, body=empty_comment, status=200) httpretty.register_uri(httpretty.GET, JIRA_ISSUE_2_COMMENTS_URL, body=comment_json, status=200) httpretty.register_uri(httpretty.GET, JIRA_ISSUE_3_COMMENTS_URL, body=empty_comment, status=200) httpretty.register_uri(httpretty.GET, JIRA_FIELDS_URL, body=body, status=200) jira = Jira(JIRA_SERVER_URL) issues = [issue for issue in jira.fetch()] body_json = json.loads(body) custom_fields = filter_custom_fields(body_json) expected_req = [{ 'expand': ['renderedFields,transitions,operations,changelog'], 'jql': ['updated > 0 order by updated asc'], 'startAt': ['0'], 'maxResults': ['100'] }, { 'expand': ['renderedFields,transitions,operations,changelog'], 'jql': ['updated > 0 order by updated asc'], 'startAt': ['2'], 'maxResults': ['100'] }] for i in range(len(expected_req)): self.assertEqual(requests[i].method, 'GET') self.assertRegex(requests[i].path, '/rest/api/2/search') self.assertDictEqual(requests[i].querystring, expected_req[i]) self.assertEqual(len(issues), 3) issue = issues[0] self.assertEqual(issue['origin'], 'http://example.com') self.assertEqual(issue['uuid'], '6a7ba2a01aee56603b9d8a5f6b40c843fc089b2f') self.assertEqual(issue['updated_on'], 1457015567) self.assertEqual(issue['category'], 'issue') self.assertEqual(issue['tag'], 'http://example.com') self.assertEqual(issue['data']['key'], 'HELP-6043') self.assertEqual(issue['data']['fields']['issuetype']['name'], 'extRequest') self.assertEqual(issue['data']['fields']['creator']['name'], 'user2') self.assertEqual(issue['data']['fields']['assignee']['name'], 'user1') self.assertEqual(issue['data']['fields']['assignee']['name'], 'user1') self.assertEqual(issue['data']['fields']['assignee']['name'], 'user1') self.assertEqual(issue['data']['fields']['assignee']['name'], 'user1') self.assertEqual(issue['data']['fields']['customfield_10301']['id'], custom_fields['customfield_10301']['id']) self.assertEqual(issue['data']['fields']['customfield_10301']['name'], custom_fields['customfield_10301']['name']) self.assertEqual(issue['data']['fields']['customfield_10400']['id'], custom_fields['customfield_10400']['id']) self.assertEqual(issue['data']['fields']['customfield_10400']['name'], custom_fields['customfield_10400']['name']) self.assertEqual(issue['data']['fields']['customfield_10600']['id'], custom_fields['customfield_10600']['id']) self.assertEqual(issue['data']['fields']['customfield_10600']['name'], custom_fields['customfield_10600']['name']) self.assertEqual(issue['data']['fields']['customfield_10603']['id'], custom_fields['customfield_10603']['id']) self.assertEqual(issue['data']['fields']['customfield_10603']['name'], custom_fields['customfield_10603']['name']) self.assertEqual(issue['data']['comments_data'], []) issue = issues[1] self.assertEqual(issue['origin'], 'http://example.com') self.assertEqual(issue['uuid'], '3c3d67925b108a37f88cc6663f7f7dd493fa818c') self.assertEqual(issue['updated_on'], 1457015417) self.assertEqual(issue['category'], 'issue') self.assertEqual(issue['tag'], 'http://example.com') self.assertEqual(issue['data']['key'], 'HELP-6042') self.assertEqual(issue['data']['fields']['issuetype']['name'], 'extRequest') self.assertEqual(issue['data']['fields']['creator']['name'], 'user2') self.assertEqual(issue['data']['fields']['assignee']['name'], 'user1') self.assertEqual(issue['data']['fields']['customfield_10301']['id'], custom_fields['customfield_10301']['id']) self.assertEqual(issue['data']['fields']['customfield_10301']['name'], custom_fields['customfield_10301']['name']) self.assertEqual(issue['data']['fields']['customfield_10400']['id'], custom_fields['customfield_10400']['id']) self.assertEqual(issue['data']['fields']['customfield_10400']['name'], custom_fields['customfield_10400']['name']) self.assertEqual(issue['data']['fields']['customfield_10600']['id'], custom_fields['customfield_10600']['id']) self.assertEqual(issue['data']['fields']['customfield_10600']['name'], custom_fields['customfield_10600']['name']) self.assertEqual(issue['data']['fields']['customfield_10603']['id'], custom_fields['customfield_10603']['id']) self.assertEqual(issue['data']['fields']['customfield_10603']['name'], custom_fields['customfield_10603']['name']) self.assertEqual(len(issue['data']['comments_data']), 2) self.assertEqual( issue['data']['comments_data'][0]['author']['displayName'], 'Tim Monks') self.assertEqual( issue['data']['comments_data'][1]['author']['displayName'], 'Scott Monks') issue = issues[2] self.assertEqual(issue['origin'], 'http://example.com') self.assertEqual(issue['uuid'], '1c7765e2a5d27495cf389f5f951c544693c4655f') self.assertEqual(issue['updated_on'], 1457006245) self.assertEqual(issue['category'], 'issue') self.assertEqual(issue['tag'], 'http://example.com') self.assertEqual(issue['data']['key'], 'HELP-6041') self.assertEqual(issue['data']['fields']['issuetype']['name'], 'extRequest') self.assertEqual(issue['data']['fields']['creator']['name'], 'user2') self.assertEqual(issue['data']['fields']['assignee']['name'], 'user3') self.assertEqual(issue['data']['fields']['customfield_10301']['id'], custom_fields['customfield_10301']['id']) self.assertEqual(issue['data']['fields']['customfield_10301']['name'], custom_fields['customfield_10301']['name']) self.assertEqual(issue['data']['fields']['customfield_10400']['id'], custom_fields['customfield_10400']['id']) self.assertEqual(issue['data']['fields']['customfield_10400']['name'], custom_fields['customfield_10400']['name']) self.assertEqual(issue['data']['fields']['customfield_10600']['id'], custom_fields['customfield_10600']['id']) self.assertEqual(issue['data']['fields']['customfield_10600']['name'], custom_fields['customfield_10600']['name']) self.assertEqual(issue['data']['fields']['customfield_10603']['id'], custom_fields['customfield_10603']['id']) self.assertEqual(issue['data']['fields']['customfield_10603']['name'], custom_fields['customfield_10603']['name']) self.assertEqual(issue['data']['comments_data'], [])
def test_github(self, confirm=None, fail=False): """Test GitHub integration""" try: # psa creates copy of settings... orig_backends = social_django.utils.BACKENDS social_django.utils.BACKENDS = GH_BACKENDS httpretty.register_uri( httpretty.POST, 'https://github.com/login/oauth/access_token', body=json.dumps({ 'access_token': '123', 'token_type': 'bearer', })) httpretty.register_uri( httpretty.GET, 'https://api.github.com/user', body=json.dumps({ 'email': '*****@*****.**', 'login': '******', 'id': 1, 'name': 'Test Weblate Name', }), ) httpretty.register_uri(httpretty.GET, 'https://api.github.com/user/emails', body=json.dumps([{ 'email': '*****@*****.**', 'verified': False, 'primary': False, }, { 'email': '*****@*****.**', 'verified': True, 'primary': True }])) response = self.client.post( reverse('social:begin', args=('github', ))) self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].startswith( 'https://github.com/login/oauth/authorize')) query = parse_qs(urlparse(response['Location']).query) return_query = parse_qs(urlparse(query['redirect_uri'][0]).query) response = self.client.get( reverse('social:complete', args=('github', )), { 'state': query['state'][0], 'redirect_state': return_query['redirect_state'][0], 'code': 'XXX' }, follow=True) if fail: self.assertContains( response, 'are already associated with another account') return if confirm: self.assertContains(response, 'Confirm new association') response = self.client.post(reverse('confirm'), {'password': confirm}, follow=True) self.assertContains(response, 'Test Weblate Name') user = User.objects.get(username='******') self.assertEqual(user.full_name, 'Test Weblate Name') self.assertEqual(user.email, '*****@*****.**') finally: social_django.utils.BACKENDS = orig_backends
def __assert_waf(self, host, vendor, fake_headers): httpretty.register_uri(httpretty.GET, 'http://%s/' % host, body='fake text', adding_headers=fake_headers) attacker = WafW00F(host) waf = attacker.wafdetections[vendor](attacker) self.assertTrue(waf)
def test_fetch_from_date(self): """Test whether a list of issues is returned from a given date""" from_date = str_to_datetime('2015-01-01') bodies_json = read_file('data/jira/jira_issues_page_2.json') empty_comment = read_file('data/jira/jira_comments_issue_empty.json') body = read_file('data/jira/jira_fields.json') httpretty.register_uri(httpretty.GET, JIRA_SEARCH_URL, body=bodies_json, status=200) httpretty.register_uri(httpretty.GET, JIRA_FIELDS_URL, body=body, status=200) httpretty.register_uri(httpretty.GET, JIRA_ISSUE_3_COMMENTS_URL, body=empty_comment, status=200) jira = Jira(JIRA_SERVER_URL) issues = [issue for issue in jira.fetch(from_date=from_date)] self.assertEqual(len(issues), 1) issue = issues[0] self.assertEqual(issue['origin'], 'http://example.com') self.assertEqual(issue['uuid'], '1c7765e2a5d27495cf389f5f951c544693c4655f') self.assertEqual(issue['updated_on'], 1457006245) self.assertEqual(issue['category'], 'issue') self.assertEqual(issue['tag'], 'http://example.com') self.assertEqual(issue['data']['comments_data'], []) requests = httpretty.HTTPretty.latest_requests request = requests[-2] expected_req = { 'expand': ['renderedFields,transitions,operations,changelog'], 'jql': ['updated > 1420070400000 order by updated asc'], 'startAt': ['0'], 'maxResults': ['100'] } self.assertEqual(request.method, 'GET') self.assertRegex(request.path, '/rest/api/2/search') self.assertDictEqual(request.querystring, expected_req) request = requests[-1] expected_req = { 'jql': ['updated > 0 order by updated asc'], 'startAt': ['0'], 'maxResults': ['100'] } self.assertEqual(request.method, 'GET') self.assertRegex(request.path, '/rest/api/2/issue/3/comment') self.assertDictEqual(request.querystring, expected_req)
def test_send_resource_to_datastore(self): url = 'http://www.ckan.org/api/3/action/datastore_create' httpretty.register_uri(httpretty.POST, url, body='{"success": true}', content_type="application/json") jobs.send_resource_to_datastore({'id': 'an_id'}, [], [], False, 'my_key', 'http://www.ckan.org/')
def register_post_thread_response(self, thread_data): """Register a mock response for POST on the CS commentable endpoint""" httpretty.register_uri( httpretty.POST, re.compile(r"http://localhost:4567/api/v1/(\w+)/threads"), body=_get_thread_callback(thread_data))
def test_throw_exception_when_regexper_svg_has_no_root(self): httpretty.register_uri( httpretty.GET, settings.REGEX_SVG_ENDPOINT, body="<div><div><svg></svg></div></div>") with self.assertRaises(InvalidRegexException): regex_viz('test-pattern')
def setup_http_server(): http_requests = [] bodies_bugs = [ read_file('data/bugzilla/bugzilla_rest_bugs.json', mode='rb'), read_file('data/bugzilla/bugzilla_rest_bugs_next.json', mode='rb'), read_file('data/bugzilla/bugzilla_rest_bugs_empty.json', mode='rb') ] body_comments = [ read_file('data/bugzilla/bugzilla_rest_bugs_comments.json', mode='rb'), read_file('data/bugzilla/bugzilla_rest_bugs_comments_empty.json', mode='rb') ] body_history = [ read_file('data/bugzilla/bugzilla_rest_bugs_history.json', mode='rb'), read_file('data/bugzilla/bugzilla_rest_bugs_history_empty.json', mode='rb') ] body_attachments = [ read_file('data/bugzilla/bugzilla_rest_bugs_attachments.json', mode='rb'), read_file('data/bugzilla/bugzilla_rest_bugs_attachments_empty.json', mode='rb') ] def request_callback(method, uri, headers): if uri.startswith(BUGZILLA_BUGS_COMMENTS_1273442_URL): body = body_comments[0] elif uri.startswith(BUGZILLA_BUGS_HISTORY_1273442_URL): body = body_history[0] elif uri.startswith(BUGZILLA_BUGS_ATTACHMENTS_1273442_URL): body = body_attachments[0] elif uri.startswith(BUGZILLA_BUG_947945_URL): if uri.find('comment') > 0: body = body_comments[1] elif uri.find('history') > 0: body = body_history[1] else: body = body_attachments[1] else: body = bodies_bugs.pop(0) http_requests.append(httpretty.last_request()) return (200, headers, body) httpretty.register_uri(httpretty.GET, BUGZILLA_BUGS_URL, responses=[ httpretty.Response(body=request_callback) for _ in range(3) ]) http_urls = [ BUGZILLA_BUGS_COMMENTS_1273442_URL, BUGZILLA_BUGS_HISTORY_1273442_URL, BUGZILLA_BUGS_ATTACHMENTS_1273442_URL ] suffixes = ['comment', 'history', 'attachment'] for http_url in [BUGZILLA_BUG_947945_URL]: for suffix in suffixes: http_urls.append(http_url + suffix) for req_url in http_urls: httpretty.register_uri( httpretty.GET, req_url, responses=[httpretty.Response(body=request_callback)]) return http_requests