コード例 #1
0
ファイル: group_update_test.py プロジェクト: Manuelinux/kubeh
    def test_it_raises_on_any_other_SQLAlchemy_exception(self, factories):
        fake_session = mock.Mock()
        fake_session.flush.side_effect = SQLAlchemyError("foo")

        update_svc = GroupUpdateService(session=fake_session)
        group = factories.Group(authority_provided_id="foo",
                                authority="foo.com")

        with pytest.raises(SQLAlchemyError):
            update_svc.update(group, name="fingers")
コード例 #2
0
ファイル: models.py プロジェクト: TobKed/Home-Budgeting-App
 def save(self, *args, **kwargs):
     """Save the record and prevent the same subcategory within category."""
     if self.query.filter_by(
         user_id=self.user_id, label=self.label, parent_id=self.parent_id
     ).first():
         raise SQLAlchemyError(
             f"Error when creating {self}. "
             f"There cannot be two cannot be be two categories with the same name and the same parent."
         )
     return super().save(*args, **kwargs)
コード例 #3
0
    def test_edit_extension_with_error_from_dao(self, Session):
        session = Mock()
        session.commit.side_effect = SQLAlchemyError()
        Session.return_value = session

        extension = Extension(exten='extension', context='context')

        self.assertRaises(ElementEditionError, extension_dao.edit, extension)
        session.begin.assert_called_once_with()
        session.rollback.assert_called_once_with()
コード例 #4
0
 def check(*args, **kwargs):
     category_id = kwargs.pop("category_id")
     try:
         category = CategoryModel.query.get(category_id)
     except SQLAlchemyError as error:
         raise SQLAlchemyError(error)
     if not category:
         raise NotFoundError(
             f"Category with id {category_id} does not exist.")
     return func(category=category, *args, **kwargs)
コード例 #5
0
def test_invalid_create(app, db, es, test_data, search_url, content_type):
    """Test INVALID record creation request (POST .../records/)."""
    with app.test_client() as client:
        HEADERS = [('Accept', 'application/json'),
                   ('Content-Type', content_type)]

        # Invalid accept type
        headers = [('Content-Type', 'application/json'),
                   ('Accept', 'video/mp4')]
        res = client.post(search_url,
                          data=json.dumps(test_data[0]),
                          headers=headers)
        assert res.status_code == 406
        # check that nothing is indexed
        res = client.get(search_url, query_string=dict(page=1, size=2))
        assert_hits_len(res, 0)

        # Invalid content-type
        headers = [('Content-Type', 'video/mp4'),
                   ('Accept', 'application/json')]
        res = client.post(search_url,
                          data=json.dumps(test_data[0]),
                          headers=headers)
        assert res.status_code == 415
        res = client.get(search_url, query_string=dict(page=1, size=2))
        assert_hits_len(res, 0)

        # Invalid JSON
        res = client.post(search_url, data='{fdssfd', headers=HEADERS)
        assert res.status_code == 400
        res = client.get(search_url, query_string=dict(page=1, size=2))
        assert_hits_len(res, 0)

        # No data
        res = client.post(search_url, headers=HEADERS)
        assert res.status_code == 400
        res = client.get(search_url, query_string=dict(page=1, size=2))
        assert_hits_len(res, 0)

        # Posting a list instead of dictionary
        pytest.raises(TypeError,
                      client.post,
                      search_url,
                      data='[]',
                      headers=HEADERS)

        # Bad internal error:
        with patch('invenio_records_rest.views.db.session.commit') as m:
            m.side_effect = SQLAlchemyError()

            pytest.raises(SQLAlchemyError,
                          client.post,
                          search_url,
                          data=json.dumps(test_data[0]),
                          headers=HEADERS)
コード例 #6
0
def delete_item(user_id, item):
    if user_id != item.user_id:
        raise ForbiddenError("You are not allowed to edit this item.")

    try:
        db.session.delete(item)
        db.session.commit()
    except SQLAlchemyError as error:
        raise SQLAlchemyError(error)

    return jsonify({}), 200
コード例 #7
0
 def test_operationalerror_response(self, mocked_crud):
     error = SQLAlchemyError("Server closed the connection unexpectedly")
     error.orig = psycopg2.OperationalError(
         "Server closed the connection unexpectedly")
     mocked_crud.side_effect = error
     data = Domain(
         **{
             "name": ("%s" % uuid.uuid1())[:30],
             "description": "a super cool test domain",
         })
     response = self.client.open('/api/v1/domains',
                                 method='POST',
                                 data=json.dumps(data),
                                 content_type='application/json',
                                 headers=self.headers)
     r_data = json.loads(response.data)
     self.assertEqual(response.status_code, 500)
     self.assertEqual(
         r_data["error"],
         "OperationalError('Server closed the connection unexpectedly',)")
コード例 #8
0
def signin(data):
    try:
        existing_user = UserModel.query.filter_by(
            username=data["username"]).one_or_none()
    except SQLAlchemyError as error:
        raise SQLAlchemyError(error)
    if not existing_user or not validate_hashed_password(
            data["password"], existing_user.password):
        raise BadRequestError("Invalid credentials.")

    return jsonify({"access_token": generate_token(existing_user.id)}), 200
コード例 #9
0
    def test_user_create_unable_to_commit(self, session_scope_mock):
        """
        Test create user end point unable to commit account
        """
        session_scope_mock.side_effect = SQLAlchemyError()
        form_data = {"username": "******", "password": "******"}

        response = self.client.post('/api/account/create', data=form_data, headers=self.headers)
        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.get_json(), {"title": "Auth service account create db error",
                                               "detail": "Unable to commit account to database"})
コード例 #10
0
    def test_edit_with_errors(self, Session):
        session = Mock()
        session.commit.side_effect = SQLAlchemyError()
        Session.return_value = session

        user_cti_profile = UserCtiProfile(user_id=1, cti_profile_id=2)

        self.assertRaises(ElementEditionError, user_cti_profile_dao.edit,
                          user_cti_profile)
        session.begin.assert_called_once_with()
        session.rollback.assert_called_once_with()
コード例 #11
0
    def __init__(self):
        try:
            # the elements for connection are got by environment variables
            self.engine = create_engine('postgresql+psycopg2://')

        except SQLAlchemyError as error:
            logging.error(f'PostgreSQLConnection.__init__() - An error occurred during engine creation.')
            logging.error(f'PostgreSQLConnection.__init__() - error.code: {error.code} - error.args: {error.args}')
            logging.error(f'PostgreSQLConnection.__init__() - error: {error}\n')

            raise SQLAlchemyError(error)
コード例 #12
0
    def test_delete_user_unable_to_commit(self, session_scope_mock):
        """
        Test delete user end point unable to commit account
        """
        session_scope_mock.side_effect = SQLAlchemyError()
        form_data = {"username": "******"}

        response = self.client.delete('/api/account/user', data=form_data, headers=self.headers)
        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.get_json(), {"title": "Auth service delete user error",
                                               "detail": "Unable to commit delete operation"})
コード例 #13
0
    def test_undo_delete_user_unable_to_commit(self, session_scope_mock):
        """
        Test patch user end point unable to commit account
        """
        session_scope_mock.side_effect = SQLAlchemyError()
        form_data = {"mark_for_deletion": False}

        response = self.client.patch('/api/account/user/[email protected]', data=form_data, headers=self.headers)
        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.get_json(), {"title": "Auth service undo delete user error",
                                               "detail": "Unable to commit undo delete operation"})
コード例 #14
0
ファイル: test_db_utils.py プロジェクト: jaunis/xivo-dao
    def test_given_row_added_when_error_then_rollback_and_error_raised(self):
        row = Mock()
        session = Mock()
        session.commit.side_effect = SQLAlchemyError()
        element = Mock()

        with self.assertRaises(CustomException):
            with db_utils.commit_or_abort(session, CustomException, element):
                session.add(row)

        session.begin.assert_called_once_with()
        session.rollback.assert_called_once_with()
コード例 #15
0
    def test_create_from_list_db_error(self, session_init, create_call_log):
        session = Mock()
        session.commit.side_effect = SQLAlchemyError()
        session_init.return_value = session
        create_call_log.return_value = 13

        call_logs = (self._mock_call_log(), self._mock_call_log())

        self.assertRaises(ElementCreationError, call_log_dao.create_from_list,
                          call_logs)
        session.begin.assert_called_once_with()
        session.rollback.assert_called_once_with()
コード例 #16
0
    def _session_exception_handler(self, exception: SQLAlchemyError):
        """

        :param exception:
        """
        cap.logger.exception(exception)
        self._session.rollback()

        if isinstance(exception, DBError):
            flask.abort(httpcode.CONFLICT,
                        response={"cause": exception.as_dict()})
        flask.abort(httpcode.INTERNAL_SERVER_ERROR)
コード例 #17
0
ファイル: usernames.py プロジェクト: prnss/cerbottana
async def antonio200509(msg: Message) -> None:
    db = Database.open("veekun")
    with db.get_session() as session:
        stmt = (select(v.PokemonSpeciesNames).filter_by(
            local_language_id=msg.language_id).order_by(func.random()))
        # TODO: remove annotation
        species: v.PokemonSpeciesNames = session.scalar(stmt)
        if not species:
            raise SQLAlchemyError("Missing PokemonSpeciesNames data")
        species_name = species.name
    numbers = str(random.randint(0, 999999)).zfill(6)
    await msg.reply(f'Antonio{numbers} guessed "{species_name}"!')
コード例 #18
0
def session_context():
    """
    Provide a transactional scope around a series of operations.
    No session is created or closed since Flask-SQLAlchemy provides a session scope.
    http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it 
    """
    try:
        yield
        db.session.commit()
    except SQLAlchemyError as e:
        db.session.rollback()
        raise SQLAlchemyError(e)
コード例 #19
0
def test_error_on_database_error(database):
    """Error written to logs on query execution failure."""
    query = 'query'
    batch = [1, 2, 3]
    parameters = []
    exception = SQLAlchemyError('<error>')

    database.connection = Mock()
    database.connection.execute.side_effect = exception
    with patch('rabbithole.sql.LOGGER') as logger:
        database.batch_ready_cb('<sender>', query, parameters, batch)
        assert logger.error.call_count == 2
コード例 #20
0
def test_pid_unassign_noobject(logger, app):
    """Test unassign."""
    with app.app_context():
        pid = PersistentIdentifier.create('recid', '101')
        assert pid.unassign()
        pid.assign('rec', uuid.uuid4())
        with patch('invenio_pidstore.models.db.session.begin_nested') as mock:
            mock.side_effect = SQLAlchemyError()
            pytest.raises(SQLAlchemyError, pid.unassign)
            assert logger.exception.call_args[0][0].startswith(
                "Failed to unassign")
            assert 'pid' in logger.exception.call_args[1]['extra']
コード例 #21
0
 def test_get_contacts_500_get_contacts_failure(self):
     """test getting contacts but throws SQL error"""
     # mock return value of get_contacts to throw an error
     self.mocked_db.return_value.get_contacts.side_effect = SQLAlchemyError(
     )
     # send request to test client
     response = self.test_app.get("/contacts/{}".format(EXAMPLE_USER),
                                  headers=EXAMPLE_HEADERS)
     # assert 200 response code
     self.assertEqual(response.status_code, 500)
     # assert we get correct error message
     self.assertEqual(response.data, b"failed to retrieve contacts list")
コード例 #22
0
    def test_edit_with_database_error(self, Session):
        session = Mock()
        session.commit.side_effect = SQLAlchemyError()
        Session.return_value = session

        user = User(id=123,
                    firstname='toto',
                    lastname='kiki',
                    language='fr_FR')

        self.assertRaises(ElementEditionError, user_dao.edit, user)
        session.begin.assert_called_once_with()
        session.rollback.assert_called_once_with()
コード例 #23
0
    def test_should_log_error_and_close_session_when_an_sql_alchemy_error_is_raised(
            self, logger_mock, does_view_exist_mock):
        # Given
        does_view_exist_mock.side_effect = SQLAlchemyError("", "", "")
        Session, local_session = _get_mocked_session()

        # When
        result = is_enriched_view_queryable(Session, "enriched_offer_data")

        # Then
        assert result is False
        local_session.close.assert_called_once()
        logger_mock.error.assert_called_once()
コード例 #24
0
def test_get_info_1(a):
    """Test get_info."""
    resp = DatabaseIngestion.get_info("test")
    assert resp == {
        'error': 'No information in the records',
        'is_valid': False
    }
    a.side_effect = SQLAlchemyError()
    with pytest.raises(Exception):
        DatabaseIngestion.get_info("test")
    a.side_effect = Exception()
    with pytest.raises(Exception):
        DatabaseIngestion.get_info("test")
コード例 #25
0
ファイル: test_anityalib.py プロジェクト: robled/anitya
 def test_create_project_general_error(self):
     """Assert general SQLAlchemy exceptions result in AnityaException."""
     self.session.flush = mock.Mock(side_effect=SQLAlchemyError('boop'))
     self.assertRaises(
         AnityaException,
         anitya.lib.create_project,
         self.session,
         name='geany',
         homepage='http://www.geany.org/',
         version_url='http://www.geany.org/Download/Releases',
         regex='DEFAULT',
         user_id='*****@*****.**',
     )
コード例 #26
0
    def test_associate_to_user_with_database_error(self, Session):
        session = Session.return_value = Mock()
        session.commit.side_effect = SQLAlchemyError()

        extension_row = Mock()
        user_row = Mock()

        self.assertRaises(ElementEditionError,
                          extension_dao.associate_destination,
                          extension_row.id, 'user', user_row.id)

        session.commit.assert_called_once_with()
        session.rollback.assert_called_once_with()
コード例 #27
0
 def test_record_message_failure(self):
     for test in self.failure_record_message:
         with patch(
                 "sqlalchemy.orm.session.Session.commit") as commit, patch(
                     "sqlalchemy.orm.session.Session.add") as add, patch(
                         "sqlalchemy.orm.session.Session.close") as close:
             add.side_effect = SQLAlchemyError()
             self.sc.recordMessage(test[EMAIL], test[MESSAGE],
                                   test[MSG_TYPE], test[DT])
             add.assert_called_once()
             self.assertRaises(SQLAlchemyError)
             commit.assert_not_called()
             close.assert_called_once()
コード例 #28
0
    def test_update_xivo_userid_sip_db_error(self, Session):
        session = Session.return_value = Mock()
        session.commit.side_effect = SQLAlchemyError()
        username = '******'
        secret = 'kiki'
        line_sip = self.add_usersip(name=username,
                                    username=username,
                                    secret=secret)
        line = self.add_line(protocolid=line_sip.id,
                             name=username,
                             context=line_sip.context)
        main_user = Mock(id=12)

        self.assertRaises(ElementEditionError, line_dao.update_xivo_userid, line, main_user)
コード例 #29
0
    def test_edit_with_database_error(self, Session):
        session = Mock()
        session.commit.side_effect = SQLAlchemyError()
        Session.return_value = session

        line_sip = self.add_usersip()
        line = LineSIP(id=123,
                       username='******',
                       secret='kiki',
                       protocolid=line_sip.id)

        self.assertRaises(ElementEditionError, line_dao.edit, line)
        session.begin.assert_called_once_with()
        session.rollback.assert_called_once_with()
コード例 #30
0
 def test_create_project_general_error(self):
     """Assert general SQLAlchemy exceptions result in AnityaException."""
     with mock.patch.object(
             self.session, 'flush', mock.Mock(side_effect=[SQLAlchemyError(), None])):
         self.assertRaises(
             AnityaException,
             utilities.create_project,
             self.session,
             name='geany',
             homepage='https://www.geany.org/',
             version_url='https://www.geany.org/Download/Releases',
             regex='DEFAULT',
             user_id='*****@*****.**',
         )