def json_error(status_code=400, status_message='error', **kw): errors = Errors(status=status_code) kw.setdefault('location', 'body') kw.setdefault('name', '') kw.setdefault('description', '') errors.add(**kw) return _JSONError(errors, status_code, status_message)
def test_colander_schema_using_defaults(self): """ Schema could contains default values """ schema = CorniceSchema.from_colander(DefaultSchema) dummy_request = MockRequest('', {'bar': 'test'}) setattr(dummy_request, 'errors', Errors(dummy_request)) validate_colander_schema(schema, dummy_request) qs_fields = schema.get_attributes(location="querystring") errors = dummy_request.errors self.assertEqual(len(errors), 0) self.assertEqual(len(qs_fields), 2) expected = {'foo': 'foo', 'bar': 'test'} self.assertEqual(expected, dummy_request.validated) dummy_request = MockRequest('', {'bar': 'test', 'foo': 'test'}) setattr(dummy_request, 'errors', Errors(dummy_request)) validate_colander_schema(schema, dummy_request) qs_fields = schema.get_attributes(location="querystring") errors = dummy_request.errors self.assertEqual(len(errors), 0) self.assertEqual(len(qs_fields), 2) expected = {'foo': 'test', 'bar': 'test'} self.assertEqual(expected, dummy_request.validated)
def test_validate_associations_outing(self): associations_in = { 'routes': [{ 'document_id': self.route1.document_id }, { 'document_id': self.route2.document_id }], 'users': [{ 'document_id': self.user_profile1.document_id }], 'waypoints': [{ 'document_id': 'waypoints are ignored' }] } errors = Errors() associations = validate_associations_in(associations_in, OUTING_TYPE, errors) self.assertEqual(len(errors), 0) expected_associations = { 'users': [{ 'document_id': self.user_profile1.document_id, 'is_parent': True }], 'routes': [{ 'document_id': self.route1.document_id, 'is_parent': True }, { 'document_id': self.route2.document_id, 'is_parent': True }] } self.assertEqual(associations, expected_associations)
def test_captcha_validate_fail(self): """Assert an error when the captcha fails validation.""" request = mock.Mock() request.errors = Errors() request.errors.status = None request.registry.settings = validators.config request.user = None # We'll cheat since we know the captcha.secret and figure out the solution. plainkey, value = captcha.math_generator(None, validators.config) cipherkey = captcha.encrypt(plainkey, validators.config) request.session = {'captcha': cipherkey} # By adding a 0 onto the end of the value, we are wrong by 100! request.validated = { 'captcha_key': cipherkey, 'captcha_value': value + '0' } validators.validate_captcha(request) self.assertEqual( request.errors, [{ 'location': 'body', 'name': 'captcha_value', 'description': 'Incorrect response to the captcha.' }]) self.assertEqual(request.errors.status, exceptions.HTTPBadRequest.code)
def test_validation(self): app = TestApp(main({})) app.get('/service', status=400) res = app.post('/service', params='buh', status=400) self.assertTrue(b'Not a json body' in res.body) res = app.post('/service', params=json.dumps('buh')) self.assertEqual(res.body, json.dumps({ 'body': '"buh"' }).encode('ascii')) app.get('/service?paid=yup') # valid = foo is one res = app.get('/service?foo=1&paid=yup') self.assertEqual(res.json['foo'], 1) # invalid value for foo res = app.get('/service?foo=buh&paid=yup', status=400) # check that json is returned errors = Errors.from_json(res.body) self.assertEqual(len(errors), 1)
def _validate_associations(associations_in, document_type, errors): """Validate the provided associations: - Check that the linked documents exist. - Check that the linked documents have the right document type (e.g. a document listed as route association must really be a route). - Check that only valid association combinations are given. Returns the validated associations. """ new_errors = Errors() associations = {} _add_associations(associations, associations_in, document_type, 'users', USERPROFILE_TYPE, new_errors) _add_associations(associations, associations_in, document_type, 'routes', ROUTE_TYPE, new_errors) _add_associations(associations, associations_in, document_type, 'waypoints', WAYPOINT_TYPE, new_errors) _add_associations(associations, associations_in, document_type, 'images', IMAGE_TYPE, new_errors) _add_associations(associations, associations_in, document_type, 'waypoint_children', WAYPOINT_TYPE, new_errors) if new_errors: errors.extend(new_errors) return None _check_for_valid_documents_ids(associations, new_errors) if new_errors: errors.extend(new_errors) return None else: return associations
def test_colander_schema_using_drop(self): """ remove fields from validated data if they deserialize to colander's `drop` object. """ schema = CorniceSchema.from_colander(DropSchema) class MockRequest(object): def __init__(self, body): self.headers = {} self.matchdict = {} self.body = body self.GET = {} self.POST = {} self.validated = {} self.registry = { 'cornice_deserializers': { 'application/json': extract_json_data } } dummy_request = MockRequest('{"bar": "required_data"}') setattr(dummy_request, 'errors', Errors(dummy_request)) validate_colander_schema(schema, dummy_request) self.assertNotIn('foo', dummy_request.validated)
def __init__(self, real_request): # Hide errors added to this from the real request self.errors = Errors() # But proxy other attributes to the real request self.real_request = real_request for attr in ['db', 'registry', 'validated', 'buildinfo', 'user']: setattr(self, attr, getattr(self.real_request, attr))
def test_validate_associations_route(self): associations_in = { 'routes': [{ 'document_id': self.route1.document_id }, { 'document_id': self.route2.document_id }], 'waypoints': [{ 'document_id': self.waypoint1.document_id }] } errors = Errors() associations = _validate_associations(associations_in, ROUTE_TYPE, errors) self.assertEquals(len(errors), 0) expected_associations = { 'routes': [{ 'document_id': self.route1.document_id, 'is_parent': False }, { 'document_id': self.route2.document_id, 'is_parent': False }], 'waypoints': [{ 'document_id': self.waypoint1.document_id, 'is_parent': True }] } self.assertEqual(associations, expected_associations)
def test_release_with_no_override_tag(self): """If the request has a build associated to a release with no override tag, it should add an error to the request.""" build = self.db.query( models.Build).filter_by(nvr='bodhi-2.0-1.fc17').first() build.release.override_tag = "" self.db.commit() request = mock.Mock() request.db = self.db request.errors = Errors() request.validated = {'nvr': 'bodhi-2.0-1.fc17', 'edited': False} validators.validate_override_builds(request) assert request.errors == [{ 'location': 'body', 'name': 'nvr', 'description': 'Cannot create a buildroot override because the' ' release associated with the build does not support it.' }] assert request.errors.status == exceptions.HTTPBadRequest.code
def test_error_handler(self): errors = Errors(403) errors.add('body', 'data', "Can't update resource in current (draft) status") request = mock.MagicMock() request.matchdict = {'a': 'b'} request.errors = errors response = error_handler(request) self.assertEqual( response.body, '{"status": "error", "errors": [{"location": "body", "name": "data", "description": "Can\'t update resource in current (draft) status"}]}' ) self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.status, '403 Forbidden')
def test_validate_associations_waypoint(self): associations_in = { # routes are ignored 'routes': [{ 'document_id': self.route1.document_id }], 'waypoints': [{ 'document_id': self.waypoint1.document_id }], 'waypoint_children': [{ 'document_id': self.waypoint2.document_id }], 'outings': [{ 'document_id': 'outings are ignored' }] } errors = Errors() associations = _validate_associations(associations_in, WAYPOINT_TYPE, errors) self.assertEquals(len(errors), 0) expected_associations = { 'waypoints': [{ 'document_id': self.waypoint1.document_id, 'is_parent': True }], 'waypoint_children': [{ 'document_id': self.waypoint2.document_id, 'is_parent': False }] } self.assertEqual(associations, expected_associations)
def get_mock_request(body, get=None, headers=None): if get is None: get = {} if headers is None: headers = {} body = json.dumps(body) json_body = json.loads(body) # Construct a mock request with the given request body class MockTranslator(object): def translate(self, something): return something class MockRequest(object): def __init__(self, body, json_body, get, method='GET'): self.headers = {} self.method = method self.url = 'http://example.com/path?ok=1' self.path = '/path' self.matchdict = {} self.body = body self.json_body = json_body self.GET = get or {} self.POST = {} self.validated = {} self.cookies = {} self.registry = object() self.content_type = 'application/json' self.localizer = MockTranslator() dummy_request = MockRequest(body, json_body, get) setattr(dummy_request, 'errors', Errors(dummy_request)) return dummy_request
def test_validation(self): app = TestApp(main({})) app.get('/service', status=400) res = app.post('/service', params='buh', status=400) self.assertTrue('Not a json body' in res.body) res = app.post('/service', params=json.dumps('buh')) self.assertEqual(res.body, json.dumps({'body': '"buh"'})) app.get('/service?paid=yup') # valid = foo is one res = app.get('/service?foo=1&paid=yup') self.assertEqual(res.json['foo'], 1) # invalid value for foo res = app.get('/service?foo=buh&paid=yup', status=400) # check that json is returned errors = Errors.from_json(res.body) self.assertEqual(len(errors), 1) # the "apidocs" registry entry contains all the needed information # to build up documentation # in this case, this means the function is registered and the argument # of the service are defined (e.g "validator" is set) apidocs = app.app.registry.settings['apidocs'] self.assertTrue(_json in apidocs[('/service', 'POST')]['validators'])
def setup_method(self, method): """Sets up the environment for each test method call.""" super().setup_method(method) self.request = mock.Mock() self.request.db = self.db self.request.errors = Errors() self.request.validated = {'from_tag': 'f17-build-side-7777'}
def setup_method(self, method): """Sets up the environment for each test method call.""" super().setup_method(method) self.request = mock.Mock() self.request.db = self.db self.request.errors = Errors() self.request.validated = {}
def setup_method(self, method): """Sets up the environment for each test method call.""" super().setup_method(method) self.request = mock.Mock() self.request.db = self.db self.request.errors = Errors() self.release = models.Release.query.one()
def test_none(self): """An eol None should be OK.""" request = mock.Mock() request.errors = Errors() request.validated = {'eol': None} validators.validate_eol_date(request) assert not len(request.errors)
def test_equaltoLimit(self): """An expiration_date equal to the limit should pass the test.""" request = mock.Mock() request.errors = Errors() request.validated = {'expiration_date': datetime.utcnow() + timedelta(days=31)} validators.validate_expiration_date(request) assert not len(request.errors)
def test_correct_date(self): """A valid eol date should pass the test.""" request = mock.Mock() request.errors = Errors() request.validated = {'eol': date(2022, 11, 5)} validators.validate_eol_date(request) assert not len(request.errors)
def test_none(self): """Empty notes should be OK, since we will populate with a default text.""" request = mock.Mock() request.errors = Errors() request.validated = {'notes': None} validators.validate_override_notes(request) assert not len(request.errors)
def test_none(self): """An expiration_date of None should be OK.""" request = mock.Mock() request.errors = Errors() request.validated = {'expiration_date': None} validators.validate_expiration_date(request) assert not len(request.errors)
def wrap_request(event): """Adds a "validated" dict, a custom "errors" object and an "info" dict to the request object if they don't already exists """ request = event.request request.add_response_callback(apply_filters) request.add_response_callback(add_nosniff_header) if not hasattr(request, 'validated'): setattr(request, 'validated', {}) if not hasattr(request, 'errors'): if request.registry.settings.get("available_languages"): setattr(request, 'errors', Errors(localizer=request.localizer)) else: setattr(request, 'errors', Errors()) if not hasattr(request, 'info'): setattr(request, 'info', {})
def test_no_feedbacks(self): """Nothing to do if no feedback.""" request = mock.Mock() request.db = self.db request.errors = Errors() request.validated = {'update': models.Update.query.first()} validators.validate_testcase_feedback(request) assert request.errors == []
def setup_integration(): import organicseeds_webshop_api request = testing.DummyRequest() request.context = testing.DummyResource() request.errors = Errors(request) config = testing.setUp(request=request, settings=testconfig()) config.include("pyramid_zodbconn") request.root = organicseeds_webshop_api.root_factory(request) app_root = request.root.app_root return dict(request=request, config=config, app_root=app_root)
def test_forbidden(self): request = mock.MagicMock() request.errors = Errors() response = forbidden(request) self.assertEqual( response.body, '{"status": "error", "errors": [{"location": "url", "name": "permission", "description": "Forbidden"}]}' ) self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.status, '403 Forbidden')
def test_extra_params_qs(self): schema = CorniceSchema.from_colander(QsSchema) dummy_request = MockRequest('', {'foo': 'test', 'bar': 'test'}) setattr(dummy_request, 'errors', Errors(dummy_request)) validate_colander_schema(schema, dummy_request) errors = dummy_request.errors self.assertEqual(len(errors), 0) expected = {'foo': 'test'} self.assertEqual(expected, dummy_request.validated)
def test_captcha_not_configured(self): """Assert that no errors are noted if captcha is not configured.""" request = mock.Mock() request.errors = Errors() request.errors.status = None request.user = None request.validated = {} validators.validate_captcha(request) self.assertEqual(request.errors, []) self.assertEqual(request.errors.status, None)
def get_dummy_json_post_request(self, data, schema=None): ''' Useful method, returns a typical post request ''' request = self.get_dummy_request() request.method = 'POST' request.json = json.dumps(data) request.errors = Errors() if schema: request.validated = schema().serialize(data) del request.validated['_id'] return request
def test_authenticated_user(self): """An authenticated user should not have to solve a captcha.""" request = mock.Mock() request.errors = Errors() request.errors.status = None request.user = models.User.query.first() request.validated = {} validators.validate_captcha(request) self.assertEqual(request.errors, []) self.assertEqual(request.errors.status, None)
def _validate_request(self, request, data): """Raise a cornice compatible error when the application is not one of the defined ones""" if self.applications == {}: return application = request.matchdict.get('application') version = request.matchdict.get('version') errors = Errors() if application not in self.applications: errors.add("uri", "application", "the application %r is not defined, please use one of %s" % ( application, ", ".join(self.applications.keys()))) if version not in self.applications[application]: versions = self.applications[application] errors.add("uri", "version", ("the application %r is not defined for this version, please " "use one of %s") % (application, ", ".join(versions))) if len(errors) > 0: raise json_error(errors, 404)
def test_validation(self): app = TestApp(main({})) app.get('/service', status=400) res = app.post('/service', params='buh', status=400) self.assertTrue('Not a json body' in res.body) res = app.post('/service', params=json.dumps('buh')) self.assertEqual(res.body, json.dumps({'body': '"buh"'})) app.get('/service?paid=yup') # valid = foo is one res = app.get('/service?foo=1&paid=yup') self.assertEqual(res.json['foo'], 1) # invalid value for foo res = app.get('/service?foo=buh&paid=yup', status=400) # check that json is returned errors = Errors.from_json(res.body) self.assertEqual(len(errors), 1)
def test_validation(self): app = TestApp(main({})) app.get("/service", status=400) response = app.post("/service", params="buh", status=400) self.assertTrue(b"Not a json body" in response.body) response = app.post("/service", params=json.dumps("buh")) expected = json.dumps({"body": '"buh"'}).encode("ascii") self.assertEqual(response.body, expected) app.get("/service?paid=yup") # valid = foo is one response = app.get("/service?foo=1&paid=yup") self.assertEqual(response.json["foo"], 1) # invalid value for foo response = app.get("/service?foo=buh&paid=yup", status=400) # check that json is returned errors = Errors.from_json(response.body) self.assertEqual(len(errors), 1)
class TestErrorsHelper(TestCase): def setUp(self): self.errors = Errors() def test_add_to_supported_location(self): self.errors.add('') self.errors.add('body', description='!') self.errors.add('querystring', name='field') self.errors.add('url') self.errors.add('header') self.errors.add('path') self.errors.add('cookies') self.errors.add('method') self.assertEqual(len(self.errors), 8) def test_raises_an_exception_when_location_is_unsupported(self): with self.assertRaises(ValueError): self.errors.add('something')
def setUp(self): self.errors = Errors()
def json_error(status=400, location='body', name='', description='', **kw): errors = Errors(status=status) errors.add(location=location, name=name, description=description, **kw) return cornice_error(errors)