def test_clusterRecord_error(self, testInstance, testRecord, mocker): clusterMocks = mocker.patch.multiple( ClusterProcess, tokenizeTitle=mocker.DEFAULT, findAllMatchingRecords=mocker.DEFAULT, clusterMatchedRecords=mocker.DEFAULT, createWorkFromEditions=mocker.DEFAULT, updateMatchedRecordsStatus=mocker.DEFAULT) clusterMocks['findAllMatchingRecords'].return_value = [] clusterMocks['clusterMatchedRecords'].return_value = (['ed1'], ['inst1']) clusterMocks['createWorkFromEditions'].return_value = ('testDBWork', [ 'uuid1', 'uuid2' ]) clusterMocks['tokenizeTitle'].return_value = set(['test', 'title']) mockSession = mocker.MagicMock() testInstance.session = mockSession testWork, testDeleted = testInstance.clusterRecord(testRecord) mockSession.flush.side_effect = DataError('test', {}, 'testing') with pytest.raises(ClusterError): testInstance.clusterRecord(testRecord)
def create_model(self, request, data, session=None): auth = request.cache.auth_backend user = data.pop('user', None) if user: return auth.create_token(request, user, **data) else: raise DataError('Missing user')
def get_default_role(): from flask import current_app as app result = AclRole.query.filter_by( name=app.config.get('DEFAULT_USER_ROLE')).first() if not result: from sqlalchemy.exc import DataError raise DataError('System is missing DEFAULT_ROLE') return result
def test_order_service_select_by_user_slug(service): service.db_session.query().filter().order_by().count.return_value = 10 service.db_session.query().filter().order_by().limit().offset( ).all.return_value = [MagicMock(autospec=True) for i in range(10)] result = service.select_by_user_slug(user_slug="WILLrogerPEREIRAslugBR") assert len(result["orders"]) == 10 assert result["total"] == 10 assert result["pages"] == 1 result = service.select_by_user_slug(user_slug="WILLrogerPEREIRAslugBR", page_size=3) assert result["pages"] == 4 service.db_session.query().filter().filter().order_by( ).count.return_value = 5 service.db_session.query().filter().filter().order_by().limit().offset( ).all.return_value = [MagicMock(autospec=True) for i in range(5)] result = service.select_by_user_slug(user_slug="WILLrogerPEREIRAslugBR", datespan={ "start": date.today() - timedelta(days=1), "end": date.today() + timedelta(days=1) }) assert len(result["orders"]) == 5 assert result["total"] == 5 assert result["pages"] == 1 service.db_session.query().filter().order_by().count.return_value = 0 service.db_session.query().filter().order_by().limit().offset( ).all.return_value = [] with pytest.raises(NoContentError): service.select_by_user_slug(user_slug="WILLrogerPEREIRAslugBR") with pytest.raises(SlugDecodeError): result = service.select_by_user_slug(user_slug="churros") with pytest.raises(TypeError): result = service.select_by_user_slug( user_slug="WILLrogerPEREIRAslugBR", datespan={ "start": "will", "end": "roger" }) service.db_session.query().filter().order_by().limit().offset( ).all.side_effect = DataError("statement", "params", "DETAIL: orig\n") with pytest.raises(DataError): service.select_by_user_slug(user_slug="WILLrogerPEREIRAslugBR")
def test_list_faq_method_captures_invalid_category_values( self, mock_filter_by): with self.app.app_context(): mock_filter_by.side_effect = DataError('statement', 'params', 'orig') faq_controller = FaqController(self.request_context) response = faq_controller.list_faqs(category='2019-04-04-invalid') self.assertEqual(response.status_code, 400) self.assertEqual( response.get_json()['msg'], "Category should be one of these values ['user_faq', 'admin_faq']" )
def test_commit_batch_failure(db, monkeypatch): """Assert rollback() and close() called and error re-raised when a DataError occurs""" # GIVEN monkeypatch.setattr(db.session, "commit", mock.Mock(side_effect=DataError(None, None, None))) monkeypatch.setattr(db.session, "rollback", mock.Mock()) monkeypatch.setattr(db.session, "close", mock.Mock()) with pytest.raises(DataError): # WHEN loader = Loader(db) loader.commit_batch() # THEN db.session.commit.assert_called_once() db.session.rollback.assert_called_once() db.session.close.assert_called_once()
def related_remove(modelname, entry_id, colname, relmodelname, rel_id): klass = get_model(modelname) relklass = get_model(relmodelname) metadata = models.get_column_metadata(klass, colname) # fetch parent and related objects dbrow = webhelpers.get_row(klass, entry_id) if metadata.uselist: reldbrow = webhelpers.get_row(relklass, rel_id) col = getattr(dbrow, colname) col.remove(reldbrow) else: if metadata.nullable: setattr(dbrow, colname, None) else: raise DataError("Removing non-nullable relation") try: webhelpers.dbsession.commit() except (DataError, IntegrityError), err: webhelpers.dbsession.rollback() raise
def test_write_data(self): """Assert that _write_data properly calls methods on Session.""" fake_data = MagicMock() _write_data(fake_data) # Assert that - if no DataError - that Session method calls are made self.session.merge.assert_called_once_with(fake_data) self.assertTrue(self.session.commit.called) # Assert that a DataError on Session.merge will call Session.rollback data_error = DataError(Mock(), Mock(), Mock(), Mock()) self.session.merge.side_effect = data_error _write_data(fake_data) self.assertTrue(self.session.rollback.called) self.session.reset_mock() # Assert that a DataError on Session.commit will call Session.rollback self.session.commit.side_effect = data_error _write_data(fake_data) self.assertTrue(self.session.rollback.called)
def raising_data_error(): raise DataError("There was a db problem", "params", "orig")
from schema import Schema, Or, Use from .test_company import company from unittest.mock import patch from app.views.product import (logical_delete, logical_restore, find_by_id, create, update, find) from random import randrange from sqlalchemy.exc import (NotSupportedError, OperationalError, ProgrammingError, IntegrityError, InternalError, DataError) from .test_user import user import unittest product = Product('id', company_id='company_id', value=10.00) integrity_error = IntegrityError('Mock', 'mock', Exception('mock', 'mock')) aleatory_errors = [ DataError('Mock', 'mock', Exception('mock', 'mock')), OperationalError('Mock', 'mock', Exception('mock', 'mock')), InternalError('Mock', 'mock', Exception('mock', 'mock')), ProgrammingError('Mock', 'mock', Exception('mock', 'mock')), NotSupportedError('Mock', 'mock', Exception('mock', 'mock')) ] product_validate = Schema({ 'id': Use(str), 'company_id': Use(str), 'value': Use(float), 'created': Or(str, None), 'updated': Or(str, None), 'removed': Or(str, None) })
def add_user(data): if data is None: raise DataError('create_user requires a data arg') name = data.get('name') password = data.get('password') role = data.get('user_type') email_address = data.get('email_address', None) framework_slug = data.get('framework', 'digital-marketplace') if email_address is None: email_address = data.get('emailAddress', None) if 'hashpw' in data and not data['hashpw']: password = password else: password = encryption.hashpw(password) if role == 'seller': role = 'applicant' now = datetime.utcnow() user = User(email_address=email_address.lower(), phone_number=data.get('phoneNumber', None), name=name, role=role, password=password, active=True, created_at=now, updated_at=now, password_changed_at=now) audit_data = {} if "supplier_code" in data: user.supplier_code = data['supplier_code'] audit_data['supplier_code'] = user.supplier_code if user.role == 'supplier' and user.supplier_code is None: raise ValueError( "'supplier_code' is required for users with 'supplier' role") if user.role != 'supplier' and user.supplier_code is not None: raise ValueError( "'supplier_code' is only valid for users with 'supplier' role, not '{}'" .format(user.role)) if "application_id" in data: user.application_id = data['application_id'] elif user.supplier_code is not None: appl = Application.query.filter_by( supplier_code=user.supplier_code).first() user.application_id = appl and appl.id or None if user.role == 'applicant' and user.application_id is None: raise ValueError( "'application id' is required for users with 'applicant' role") elif user.role != 'applicant' and user.role != 'supplier' and user.application_id is not None: raise ValueError( "'application_id' is only valid for users with applicant' or 'supplier' role, not '{}'" .format(user.role)) db.session.add(user) db.session.flush() framework = Framework.query.filter( Framework.slug == framework_slug).first() db.session.add(UserFramework(user_id=user.id, framework_id=framework.id)) audit = AuditEvent(audit_type=AuditTypes.create_user, user=email_address.lower(), data=audit_data, db_object=user) db.session.add(audit) db.session.commit() return user
json=overflow_datespan ) data = json.loads(response.data) ErrorSchema().load(data) assert response.status_code == 400 @pytest.mark.parametrize( "method,http_method,test_url,error,status_code", [ ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", NoContentError(), 204), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", HTTPException(), 400), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", ConnectionError(), 502), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", DataError("statement", "params", "DETAIL: orig\n"), 400), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", DatabaseError("statement", "params", "orig"), 400), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", SQLAlchemyError(), 504), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", Exception(), 500) ] ) def test_select_by_user_slug_controller_error(mocker, get_request_function, method, http_method, test_url, error, status_code): mocker.patch.object(OrderService, method, side_effect=error) make_request = get_request_function(http_method) response = make_request( test_url ) if status_code == 204:
def data_error(): raise DataError(None, None, None)