def _mock_commerce_api(self, status, body=None): self.assertTrue(httpretty.is_enabled(), 'httpretty must be enabled to mock Commerce API calls.') body = body or {} url = '{}/courses/{}/'.format(settings.COMMERCE_API_URL.rstrip('/'), self.course.id) httpretty.register_uri(httpretty.PUT, url, status=status, body=json.dumps(body), content_type=JSON)
def test_http_test_pass_streaming(): assert is_enabled() msgs = [MsgPrintDep(text='foo'), MsgPrintDep(text='bar'), MsgPrintDep(text='baz')] register_uri(GET, BASE_STATION_URI, mock_streaming_msgs([m.to_binary() for m in msgs]), content_type="application/vnd.swiftnav.broker.v1+sbp2", streaming=True) register_uri(PUT, BASE_STATION_URI, body='', content_type="application/vnd.swiftnav.broker.v1+sbp2", streaming=True) with HTTPDriver(device_uid="Swift22", url=BASE_STATION_URI) as driver: assert driver.connect_read() assert driver.read_ok assert driver.read(size=255) == ''.join([m.to_binary() for m in msgs]) assert driver.read(size=255) == '' assert not driver.read_close() assert driver.read_response is None assert not driver.read_ok with pytest.raises(ValueError): driver.read(size=255)
def mock_course_api(self, url, body=None, **kwargs): """ Registers an HTTP mock for the specified course API path. The mock returns the specified data. The calling test function MUST activate httpretty. Arguments url -- URL to be mocked body -- Data returned by the mocked API kwargs -- Additional arguments passed to httpretty.register_uri() """ # Avoid developer confusion when httpretty is not active and fail the test now. if not httpretty.is_enabled(): self.fail('httpretty is not enabled. The mock will not be used!') body = body or {} default_kwargs = { 'body': kwargs.get('body', json.dumps(body)), 'content_type': 'application/json' } default_kwargs.update(kwargs) httpretty.register_uri(httpretty.GET, url, **default_kwargs) logger.debug('Mocking Course API URL: %s', url)
def mock_enrollment_api(self, status=200): self.assertTrue(httpretty.is_enabled()) httpretty.register_uri(httpretty.GET, get_lms_enrollment_api_url(), status=status, body=json.dumps(self.data), content_type='application/json')
def register_api_route(service, path, method=httpretty.GET, adding_headers=None, **kwargs): """ Handy wrapper for adding URIs to the HTTPretty state. """ assert httpretty.is_enabled() base_url_map = { "auth": "https://auth.globus.org/", "nexus": "https://nexus.api.globusonline.org/", "transfer": "https://transfer.api.globus.org/v0.10", "search": "https://search.api.globus.org/", } assert service in base_url_map base_url = base_url_map.get(service) full_url = slash_join(base_url, path) # can set it to `{}` explicitly to clear the default if adding_headers is None: adding_headers = {"Content-Type": "application/json"} httpretty.register_uri(method, full_url, adding_headers=adding_headers, **kwargs)
def _configure_testshib_provider(self, **kwargs): """ Enable and configure the TestShib SAML IdP as a third_party_auth provider """ fetch_metadata = kwargs.pop('fetch_metadata', True) assert_metadata_updates = kwargs.pop('assert_metadata_updates', True) kwargs.setdefault('name', self.PROVIDER_NAME) kwargs.setdefault('enabled', True) kwargs.setdefault('visible', True) kwargs.setdefault('idp_slug', self.PROVIDER_IDP_SLUG) kwargs.setdefault('entity_id', TESTSHIB_ENTITY_ID) kwargs.setdefault('metadata_source', TESTSHIB_METADATA_URL) kwargs.setdefault('icon_class', 'fa-university') kwargs.setdefault('attr_email', 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6') # eduPersonPrincipalName kwargs.setdefault('max_session_length', None) self.configure_saml_provider(**kwargs) if fetch_metadata: self.assertTrue(httpretty.is_enabled()) num_total, num_skipped, num_attempted, num_updated, num_failed, failure_messages = fetch_saml_metadata() if assert_metadata_updates: self.assertEqual(num_total, 1) self.assertEqual(num_skipped, 0) self.assertEqual(num_attempted, 1) self.assertEqual(num_updated, 1) self.assertEqual(num_failed, 0) self.assertEqual(len(failure_messages), 0)
def _register_cloudcast_list(self, user, cloudcasts): assert httpretty.is_enabled() url = "{root}/{user}/cloudcasts/".format(root=self.api_root, user=user.key) def make_cc_data(cc): keys_ok = ["tags", "name", "slug", "user", "created_time"] return {k: cc[k] for k in keys_ok} def cloudcast_list(method, uri, headers): query_string = urlparse.urlparse(uri).query query_params = urlparse.parse_qs(query_string) limit = None offset = None if "limit" in query_params: limit = int(query_params["limit"][-1]) if "offset" in query_params: offset = int(query_params["offset"][-1]) data = [make_cc_data(cc) for cc in cloudcasts] if offset is not None: data = data[offset:] if limit is not None: data = data[:limit] body = json.dumps({"data": data}) return (200, headers, body) httpretty.register_uri(httpretty.GET, url, body=cloudcast_list)
def mock_credentials_api(self, user, data=None, status_code=200, reset_url=True, is_next_page=False): """Utility for mocking out Credentials API URLs.""" self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock Credentials API calls.') internal_api_url = CredentialsApiConfig.current().internal_api_url.strip('/') url = internal_api_url + '/user_credentials/?username='******'/user_credentials/?page=2&username='******'next'] = next_page_url next_page_body = json.dumps(self.CREDENTIALS_NEXT_API_RESPONSE) httpretty.register_uri( httpretty.GET, next_page_url, body=body, content_type='application/json', status=status_code ) httpretty.register_uri( httpretty.GET, url, body=next_page_body, content_type='application/json', status=status_code ) else: httpretty.register_uri( httpretty.GET, url, body=body, content_type='application/json', status=status_code )
def _register_cloudcast_list(self, user, cloudcasts): assert httpretty.is_enabled() url = '{root}/{user}/cloudcasts/'.format(root=self.api_root, user=user.key) def make_cc_data(cc): keys_ok = ['tags', 'name', 'slug', 'user', 'created_time'] return {k: cc[k] for k in keys_ok} def cloudcast_list(method, uri, headers): query_string = urlparse.urlparse(uri).query query_params = urlparse.parse_qs(query_string) limit = None offset = None if 'limit' in query_params: limit = int(query_params['limit'][-1]) if 'offset' in query_params: offset = int(query_params['offset'][-1]) data = [make_cc_data(cc) for cc in cloudcasts] if offset is not None: data = data[offset:] if limit is not None: data = data[:limit] body = json.dumps({'data': data}) return (200, headers, body) httpretty.register_uri(httpretty.GET, url, body=cloudcast_list)
def _register_cloudcast_only(self, user, cloudcast): assert httpretty.is_enabled() self.register_user(user) url = "{root}/{user}/{key}".format(root=self.api_root, user=user.key, key=cloudcast.key) cc_data = { "slug": cloudcast.key, "name": cloudcast.name, "sections": [ { "start_time": s.start_time, "track": { "name": s.track.name, "artist": {"slug": s.track.artist.key, "name": s.track.artist.name}, }, } for s in cloudcast.sections() ], "tags": [{"name": t} for t in cloudcast.tags], "description": cloudcast.description(), "user": {"username": user.key, "name": user.name}, "created_time": cloudcast.created_time.isoformat(), "pictures": {"large": "http://httpbin.org/status/418"}, } httpretty.register_uri(httpretty.GET, url, body=json.dumps(cc_data)) return cc_data
def _register_cloudcast_only(self, user, cloudcast): assert httpretty.is_enabled() self.register_user(user) url = '{root}/{user}/{key}'.format(root=self.api_root, user=user.key, key=cloudcast.key) cc_data = {'slug': cloudcast.key, 'name': cloudcast.name, 'sections': [{'start_time': s.start_time, 'track': {'name': s.track.name, 'artist': {'slug': s.track.artist.key, 'name': s.track.artist.name, }, }, } for s in cloudcast.sections()], 'tags': [{'name': t} for t in cloudcast.tags], 'description': cloudcast.description(), 'user': {'username': user.key, 'name': user.name, }, 'created_time': cloudcast.created_time.isoformat(), 'pictures': { 'large': 'http://httpbin.org/status/418', } } httpretty.register_uri(httpretty.GET, url, body=json.dumps(cc_data)) return cc_data
def register_user(self, user): assert httpretty.is_enabled() url = '{root}/{key}'.format(root=self.api_root, key=user.key) data = {'username': user.key, 'name': user.name, } httpretty.register_uri(httpretty.GET, url, body=json.dumps(data))
def register_artist(self, artist): assert httpretty.is_enabled() url = '{root}/artist/{key}'.format(root=self.api_root, key=artist.key) data = {'slug': artist.key, 'name': artist.name, } httpretty.register_uri(httpretty.GET, url, body=json.dumps(data))
def test_http_test_pass(): assert is_enabled() msg = MsgPrintDep(text='abcd') register_uri(GET, BASE_STATION_URI, msg.to_binary(), content_type="application/vnd.swiftnav.broker.v1+sbp2") register_uri(PUT, BASE_STATION_URI, '', content_type="application/vnd.swiftnav.broker.v1+sbp2") with HTTPDriver(device_uid="Swift22", url=BASE_STATION_URI) as driver: assert not driver.read_ok assert driver.connect_read() assert driver.read_ok assert driver.read(size=255) == msg.to_binary() with pytest.raises(IOError): assert driver.read(size=255) assert not driver.read_close() assert driver.read_response is None assert not driver.read_ok with pytest.raises(ValueError): driver.read(size=255) with HTTPDriver(device_uid="Swift22", url=BASE_STATION_URI) as http: with Handler(Framer(http.read, http.write, False)) as link: def tester(sbp_msg, **metadata): assert sbp_msg.payload == msg.payload link.add_callback(SBP_MSG_PRINT_DEP, tester) t0 = time.time() sleep = 0.1 while True: if time.time() - t0 < sleep: break
def register_cloudcasts(self, user, cloudcasts): assert httpretty.is_enabled() cc_data_list = [] for cloudcast in cloudcasts: cc_data = self._register_cloudcast_only(user, cloudcast) cc_data_list.append(cc_data) self._register_cloudcast_list(user, cc_data_list)
def json_request(context, method, url): data = None headers = {} content_type = 'application/json' if 'json_body' in context: data = json.dumps(context.json_body) if not httpretty.is_enabled(): httpretty.enable() if hasattr(context, 'mock_configurations'): for mock_configuration in context.mock_configurations: httpretty.register_uri(method=mock_configuration['method'].upper(), uri=mock_configuration['url'], status=mock_configuration['status'], body=mock_configuration['body'], match_querystring=True) client = app.app.test_client() response = getattr(client, method)(url, data=data, content_type=content_type, headers=headers) context.response = response try: context.response.json = json.loads(context.response.data) except Exception: pass
def mock_course_api(self, path, body=None, **kwargs): """ Registers an HTTP mock for the specified course API path. The mock returns the specified data. The calling test function MUST activate httpretty. Arguments body -- Data returned by the mocked API kwargs -- Additional arguments passed to httpretty.register_uri() """ # Avoid developer confusion when httpretty is not active and fail the test now. if not httpretty.is_enabled(): self.fail('httpretty is not enabled. The mock will not be used!') body = body or {} # Remove trailing slashes from the path. They will be added back later. path = path.strip(u'/') url = '{}/{}/'.format(settings.COURSE_API_URL, path) default_kwargs = { 'body': kwargs.get('body', json.dumps(body)), 'content_type': 'application/json' } default_kwargs.update(kwargs) httpretty.register_uri(httpretty.GET, url, **default_kwargs) logger.debug('Mocking Course API URL: %s', url)
def _mock_programs_api(self, responses, url=None): """Helper for mocking out Programs API URLs.""" self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock Programs API calls.') url = url if url else ProgramsApiConfig.current().internal_api_url.strip('/') + '/programs/' httpretty.register_uri(httpretty.GET, url, responses=responses)
def _configure_testshib_provider(self, **kwargs): """ Enable and configure the TestShib SAML IdP as a third_party_auth provider """ fetch_metadata = kwargs.pop('fetch_metadata', True) assert_metadata_updates = kwargs.pop('assert_metadata_updates', True) kwargs.setdefault('name', self.PROVIDER_NAME) kwargs.setdefault('enabled', True) kwargs.setdefault('visible', True) kwargs.setdefault("backend_name", "tpa-saml") kwargs.setdefault('slug', self.PROVIDER_IDP_SLUG) kwargs.setdefault('entity_id', TESTSHIB_ENTITY_ID) kwargs.setdefault('metadata_source', TESTSHIB_METADATA_URL) kwargs.setdefault('icon_class', 'fa-university') kwargs.setdefault('attr_email', 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6') # eduPersonPrincipalName kwargs.setdefault('max_session_length', None) kwargs.setdefault('send_to_registration_first', False) kwargs.setdefault('skip_email_verification', False) saml_provider = self.configure_saml_provider(**kwargs) # pylint: disable=no-member if fetch_metadata: assert httpretty.is_enabled() # lint-amnesty, pylint: disable=no-member num_total, num_skipped, num_attempted, num_updated, num_failed, failure_messages = fetch_saml_metadata() if assert_metadata_updates: assert num_total == 1 # lint-amnesty, pylint: disable=no-member assert num_skipped == 0 # lint-amnesty, pylint: disable=no-member assert num_attempted == 1 # lint-amnesty, pylint: disable=no-member assert num_updated == 1 # lint-amnesty, pylint: disable=no-member assert num_failed == 0 # lint-amnesty, pylint: disable=no-member assert len(failure_messages) == 0 # lint-amnesty, pylint: disable=no-member return saml_provider
def _mock_commerce_api(self, status, body=None): self.assertTrue(httpretty.is_enabled(), 'httpretty must be enabled to mock Commerce API calls.') body = body or {} url = '{}/courses/{}/'.format(get_lms_commerce_api_url().rstrip('/'), self.course.id) httpretty.register_uri(httpretty.PUT, url, status=status, body=json.dumps(body), content_type=JSON)
def _mock_lms_apis(self): self.assertTrue(httpretty.is_enabled(), 'httpretty must be enabled to mock LMS API calls.') # Mock Commerce API body = { 'name': self.course_name, 'verification_deadline': EXPIRES_STRING, } httpretty.register_uri(httpretty.GET, self.commerce_api_url, body=json.dumps(body), content_type=JSON) # Mock Course Structure API body = {'name': self.course_name} httpretty.register_uri(httpretty.GET, self.course_structure_url, body=json.dumps(body), content_type=JSON) # Mock Enrollment API body = { 'course_id': self.course_id, 'course_modes': [{ 'slug': mode, 'min_price': price, 'expiration_datetime': EXPIRES_STRING } for mode, price in self.prices.iteritems()] } httpretty.register_uri(httpretty.GET, self.enrollment_api_url, body=json.dumps(body), content_type=JSON)
def test_http_test_pass_retry(): assert is_enabled() msg = MsgPrintDep(text='abcd') get_responses = [ Response(body="first response", status=500, content_type="application/vnd.swiftnav.broker.v1+sbp2"), Response(body='second and last response', status=200, content_type="application/vnd.swiftnav.broker.v1+sbp2") ] post_responses = [ Response(body="", status=500, content_type="application/vnd.swiftnav.broker.v1+sbp2"), Response(body='', status=200, content_type="application/vnd.swiftnav.broker.v1+sbp2") ] register_uri(GET, BASE_STATION_URI, get_responses) register_uri(PUT, BASE_STATION_URI, post_responses) with HTTPDriver(device_uid="Swift22", url=BASE_STATION_URI) as driver: with pytest.raises(ValueError): driver.read(size=255) assert driver.connect_read() assert driver.read(size=255)
def _mock_catalog_api(self, responses, url=None): assert httpretty.is_enabled( ), 'httpretty must be enabled to mock Catalog API calls.' url = url if url else urljoin(f"{self.base_api_url}/", "programs/") httpretty.register_uri(httpretty.GET, url, responses=responses)
def test_http_test_pass_streaming(): assert is_enabled() msgs = [ MsgPrintDep(text='foo'), MsgPrintDep(text='bar'), MsgPrintDep(text='baz') ] register_uri(GET, BASE_STATION_URI, mock_streaming_msgs([m.to_binary() for m in msgs]), content_type="application/vnd.swiftnav.broker.v1+sbp2", streaming=True) register_uri(PUT, BASE_STATION_URI, body='', content_type="application/vnd.swiftnav.broker.v1+sbp2", streaming=True) with HTTPDriver(device_uid="Swift22", url=BASE_STATION_URI) as driver: assert driver.connect_read() assert driver.read_ok assert driver.read(size=255) == ''.join([m.to_binary() for m in msgs]) assert driver.read(size=255) == '' assert not driver.read_close() assert driver.read_response is None assert not driver.read_ok with pytest.raises(ValueError): driver.read(size=255)
def _configure_testshib_provider(self, **kwargs): """ Enable and configure the TestShib SAML IdP as a third_party_auth provider """ fetch_metadata = kwargs.pop('fetch_metadata', True) assert_metadata_updates = kwargs.pop('assert_metadata_updates', True) kwargs.setdefault('name', self.PROVIDER_NAME) kwargs.setdefault('enabled', True) kwargs.setdefault('visible', True) kwargs.setdefault('idp_slug', self.PROVIDER_IDP_SLUG) kwargs.setdefault('entity_id', TESTSHIB_ENTITY_ID) kwargs.setdefault('metadata_source', TESTSHIB_METADATA_URL) kwargs.setdefault('icon_class', 'fa-university') kwargs.setdefault( 'attr_email', 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6') # eduPersonPrincipalName kwargs.setdefault('max_session_length', None) self.configure_saml_provider(**kwargs) if fetch_metadata: self.assertTrue(httpretty.is_enabled()) num_total, num_skipped, num_attempted, num_updated, num_failed, failure_messages = fetch_saml_metadata( ) if assert_metadata_updates: self.assertEqual(num_total, 1) self.assertEqual(num_skipped, 0) self.assertEqual(num_attempted, 1) self.assertEqual(num_updated, 1) self.assertEqual(num_failed, 0) self.assertEqual(len(failure_messages), 0)
def i_am(self, user): assert httpretty.is_enabled() target_url = '{root}/{key}'.format(root=self.api_root, key=user.key) self.register_user(user) httpretty.register_uri(httpretty.GET, '{root}/me/'.format(root=self.api_root), status=302, location=target_url)
def register_artist(self, artist): assert httpretty.is_enabled() url = '{root}/artist/{key}'.format(root=self.api_root, key=artist.key) data = { 'slug': artist.key, 'name': artist.name, } httpretty.register_uri(httpretty.GET, url, body=json.dumps(data))
def register_user(self, user): assert httpretty.is_enabled() url = '{root}/{key}'.format(root=self.api_root, key=user.key) data = { 'username': user.key, 'name': user.name, } httpretty.register_uri(httpretty.GET, url, body=json.dumps(data))
def oauth_exchange(self): assert httpretty.is_enabled() target_url = '{root}/{endpoint}'.format(root=self.oauth_root, endpoint='access_token') data = {"access_token": "my_access_token"} httpretty.register_uri(httpretty.GET, target_url, body=json.dumps(data))
def register_post_thread_response(self, thread_data): """Register a mock response for POST on the CS commentable endpoint""" assert httpretty.is_enabled(), 'httpretty must be enabled to mock calls.' httpretty.register_uri( httpretty.POST, re.compile(r"http://localhost:4567/api/v1/(\w+)/threads"), body=_get_thread_callback(thread_data) )
def _mock_programs_api(self, data): """Helper for mocking out Programs API URLs.""" self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock Programs API calls.') url = ProgramsApiConfig.current().internal_api_url.strip('/') + '/programs/' body = json.dumps({'results': data}) httpretty.register_uri(httpretty.GET, url, body=body, content_type='application/json')
def _mock_catalog_api(self, responses, url=None): assert httpretty.is_enabled( ), 'httpretty must be enabled to mock Catalog API calls.' url = url if url else CatalogIntegration.current( ).get_internal_api_url().strip('/') + '/programs/' httpretty.register_uri(httpretty.GET, url, responses=responses)
def mock_programs_api(self, data): """Helper for mocking out Programs API URLs.""" self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock Programs API calls.') url = ProgramsApiConfig.current().internal_api_url.strip('/') + '/programs/' body = json.dumps({'results': data}) httpretty.register_uri(httpretty.GET, url, body=body, content_type='application/json')
def mock_api_response(self, path, body, post=True): assert httpretty.is_enabled() url = self._create_api_url(path) httpretty.register_uri(httpretty.POST if post else httpretty.GET, url, body=json.dumps(body), status=200)
def register_post_thread_response(self, thread_data): """Register a mock response for POST on the CS commentable endpoint""" assert httpretty.is_enabled( ), 'httpretty must be enabled to mock calls.' httpretty.register_uri( httpretty.POST, re.compile(r"http://localhost:4567/api/v1/(\w+)/threads"), body=_get_thread_callback(thread_data))
def register_get_username_replacement_response(self, user, status=200, body=""): assert httpretty.is_enabled(), 'httpretty must be enabled to mock calls.' httpretty.register_uri( httpretty.POST, "http://localhost:4567/api/v1/users/{id}/replace_username".format(id=user.id), body=body, status=status )
def _mock_programs_api(self, data): """Helper for mocking out Programs API URLs.""" self.assertTrue(httpretty.is_enabled(), msg="httpretty must be enabled to mock Programs API calls.") url = self.programs_config.internal_api_url.strip("/") + "/programs/" body = json.dumps({"results": data}) httpretty.register_uri(httpretty.GET, url, body=body, content_type="application/json")
def register_get_user_retire_response(self, user, status=200, body=""): """Register a mock response for GET on the CS user retirement endpoint""" assert httpretty.is_enabled(), 'httpretty must be enabled to mock calls.' httpretty.register_uri( httpretty.POST, "http://localhost:4567/api/v1/users/{id}/retire".format(id=user.id), body=body, status=status )
def test_http_test_pass(): assert is_enabled() msg = MsgPrintDep(text='abcd') register_uri(GET, BASE_STATION_URI, msg.to_binary(), content_type="application/vnd.swiftnav.broker.v1+sbp") with HTTPDriver(device_uid="Swift22", url=BASE_STATION_URI) as driver: assert driver.read(size=255) == msg.to_binary()
def _mock_badgr_tokens_api(self, result): assert httpretty.is_enabled() responses = [ httpretty.Response(body=json.dumps(result), content_type='application/json') ] httpretty.register_uri(httpretty.POST, 'https://example.com/o/token', responses=responses)
def mock_enrollment_api_success(self, course_id, mode='audit'): """ Returns a successful response indicating self.user is enrolled in the specified course mode. """ self.assertTrue(httpretty.is_enabled()) url = '{host}/{username},{course_id}'.format( host=get_lms_enrollment_api_url(), username=self.user.username, course_id=course_id ) httpretty.register_uri(httpretty.GET, url, body=json.dumps({'mode': mode}), content_type='application/json')
def register_get_thread_error_response(self, thread_id, status_code): """Register a mock error response for GET on the CS thread endpoint.""" assert httpretty.is_enabled(), 'httpretty must be enabled to mock calls.' httpretty.register_uri( httpretty.GET, "http://localhost:4567/api/v1/threads/{id}".format(id=thread_id), body="", status=status_code )
def register_get_user_retire_response(self, user, status=200, body=""): """Register a mock response for GET on the CS user retirement endpoint""" assert httpretty.is_enabled( ), 'httpretty must be enabled to mock calls.' httpretty.register_uri( httpretty.POST, f"http://localhost:4567/api/v1/users/{user.id}/retire", body=body, status=status)
def register_get_thread_error_response(self, thread_id, status_code): """Register a mock error response for GET on the CS thread endpoint.""" assert httpretty.is_enabled( ), 'httpretty must be enabled to mock calls.' httpretty.register_uri( httpretty.GET, f"http://localhost:4567/api/v1/threads/{thread_id}", body="", status=status_code)
def _mock_user_api(self, username, data, status_code=200): """ Helper method for mocking out User API URLs.""" self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock User API calls.') user_api_url = settings.USER_API_URL url = '{root}/accounts/{username}'.format(root=user_api_url.strip('/'), username=username) body = json.dumps(data) httpretty.reset() httpretty.register_uri(httpretty.GET, url, body=body, content_type=CONTENT_TYPE, status=status_code)
def _mock_programs_api(self, program_id, data, status_code=200): """ Utility for mocking out Programs API URLs.""" self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock Programs API calls.') programs_api_url = settings.PROGRAMS_API_URL url = '{root}/programs/{program_id}/'.format(root=programs_api_url.strip('/'), program_id=program_id) body = json.dumps(data) httpretty.reset() httpretty.register_uri(httpretty.GET, url, body=body, content_type=CONTENT_TYPE, status=status_code)
def mock_catalog_api(self, url, data, method=httpretty.GET, status_code=200): self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock Catalog API calls.') httpretty.reset() httpretty.register_uri( method, urljoin(MOCK_CATALOG_API_URL_ROOT, url), body=json.dumps(data), content_type='application/json', status=status_code )
def _mock_programs_api(self, responses, url=None): """Helper for mocking out Programs API URLs.""" self.assertTrue( httpretty.is_enabled(), msg='httpretty must be enabled to mock Programs API calls.') url = url if url else ProgramsApiConfig.current( ).internal_api_url.strip('/') + '/programs/' httpretty.register_uri(httpretty.GET, url, responses=responses)
def mock_creditcourse_endpoint(self, course_id, status, body=None): self.assertTrue(httpretty.is_enabled(), 'httpretty must be enabled to mock Credit API calls.') url = get_lms_url('/api/credit/v1/courses/{}/'.format(course_id)) httpretty.register_uri(httpretty.PUT, url, status=status, body=json.dumps(body), content_type=JSON)
def mock_api_response(self, path, body, post=True): assert httpretty.is_enabled() url = self._create_api_url(path) httpretty.register_uri( httpretty.POST if post else httpretty.GET, url, body=json.dumps(body), status=200 )
def mock_credentials_api(self, data): """Helper for mocking out Credentials API URLs.""" self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock Credentials API calls.') url = '{base}/user_credentials/?username={username}'.format( base=CredentialsApiConfig.current().internal_api_url.strip('/'), username=self.user.username ) body = json.dumps({'results': data}) httpretty.register_uri(httpretty.GET, url, body=body, content_type='application/json')