def _setUp(self): if self._output_schema: error_list = validate(self._output, self._output_schema) if error_list: msg = ( "While setting up a service mock for the '{s._service}' " "service's '{s._url}' endpoint, the specified output " "does not match the service's endpoint output schema.\n\n" "The errors are:\n{errors}\n\n").format( s=self, errors='\n'.join(error_list)) raise AssertionError(msg) config = get_service_locations() service_location = config.get(self._service) if service_location is None: raise AssertionError( "A service mock for the '%s' service was requested, but the " "mock has not been configured with a location for that " "service. Ensure set_service_locations has been " "called before the mock is required, and that the locations " "dictionary contains a key for the '%s' service." % (self._service, self._service)) full_url = urllib.parse.urljoin(service_location, self._url) def _callback(request): if self._input_schema: payload = json.loads(request.body.decode()) error_list = validate(payload, self._input_schema) if error_list: # TODO: raise AssertionError here, since this is in a test? return ( 400, { 'Content-Type': 'application/json' }, json.dumps(error_list), ) # TODO: Do we need to support more than just json responses? return (self._output_status, { "Content-Type": "application/json" }, json.dumps(self._output)) if ServiceMock._requests_mock is None: ServiceMock._requests_mock = responses.RequestsMock( assert_all_requests_are_fired=False) self.addCleanup(ServiceMock._clean_requests_mock) ServiceMock._requests_mock.start() self.addCleanup(ServiceMock._requests_mock.stop) for method in self._methods: self._requests_mock.add_callback(method, full_url, _callback)
def _callback(request): if self._input_schema: payload = json.loads(request.body.decode()) error_list = validate(payload, self._input_schema) if error_list: # TODO: raise AssertionError here, since this is in a test? return ( 400, {'Content-Type': 'application/json'}, json.dumps(error_list), ) # TODO: Do we need to support more than just json responses? return ( self._output_status, {"Content-Type": "application/json"}, json.dumps(self._output) )
def _validate(self, data_source_name, body, schema): if schema is not None: if body is None: error_list = ["Missing body"] else: if isinstance(body, bytes): body = body.decode("utf-8") try: data = json_loads(body) except ValueError as e: error_list = ['JSON decoding error: {}'.format(e)] else: error_list = validate(data, schema) if error_list: raise AssertionError( VALIDATION_ERROR_TEXT.format( data_source_name, body, schema, self._service_name, self._name, self._url, error_list, ))