def update_by_params(session_obj: SessionType, model_cls, find_func, fields: Iterable[str], params: List[Dict], data): """This function is updates the instance of the model represented by the class in model_cls and identified by the arguments in the params parameter Arg(s) ------ session_obj: the object used to interact with the database model_cls: class representing the model whose instance needs to be updated find_func: function that needs to be called to find the details of the model that needs to be updated fields (Iterable[str]) -> list of fields that can be updated on the model before it's written to the database params (List[Dict]) -> parameters that will be used to identify the model instance that needs to be updated data (Dict) -> the fields that need to be updated with the values in the parameter Return(s) --------- returns raw instance or dictionary representing the raw instance based on json_result's value """ found_obj = find_func(session_obj, model_cls, params) if not found_obj: raise orm_exc.NoResultFound() for field in fields: if field in data: setattr(found_obj, field, data[field]) session_obj.add(found_obj) return found_obj
def test_get_vim_without_defined_default_vim_in_db(self): cfg.CONF.set_override('default_vim', 'VIM0', 'nfvo_vim', enforce_type=True) vimclient = vim_client.VimClient() service_plugins = mock.Mock() nfvo_plugin = mock.Mock() nfvo_plugin.get_default_vim.side_effect = \ orm_exc.NoResultFound() service_plugins.get.return_value = nfvo_plugin with mock.patch.object(manager.TackerManager, 'get_service_plugins', return_value=service_plugins): get_vim_by_name = \ mock.patch.object(vimclient, '_get_default_vim_by_name').start() get_vim_by_name.return_value = self.vim_info build_vim_auth = \ mock.patch.object(vimclient, '_build_vim_auth').start() build_vim_auth.return_value = mock.Mock() vimclient.get_vim(None) vimclient._get_default_vim_by_name.\ assert_called_once_with(mock.ANY, mock.ANY, 'VIM0')
def _find_key(self, session, last_key): """ Try to find unused tunnel key in TunnelKey table starting from last_key + 1. When all keys are used, raise sqlalchemy.orm.exc.NoResultFound """ # key 0 is used for special meanings. So don't allocate 0. # sqlite doesn't support # '(select order by limit) union all (select order by limit) ' # 'order by limit' # So do it manually # new_key = session.query("new_key").from_statement( # # If last_key + 1 isn't used, it's the result # 'SELECT new_key ' # 'FROM (SELECT :last_key + 1 AS new_key) q1 ' # 'WHERE NOT EXISTS ' # '(SELECT 1 FROM tunnelkeys WHERE tunnel_key = :last_key + 1) ' # # 'UNION ALL ' # # # if last_key + 1 used, # # find the least unused key from last_key + 1 # '(SELECT t.tunnel_key + 1 AS new_key ' # 'FROM tunnelkeys t ' # 'WHERE NOT EXISTS ' # '(SELECT 1 FROM tunnelkeys ti ' # ' WHERE ti.tunnel_key = t.tunnel_key + 1) ' # 'AND t.tunnel_key >= :last_key ' # 'ORDER BY new_key LIMIT 1) ' # # 'ORDER BY new_key LIMIT 1' # ).params(last_key=last_key).one() try: new_key = session.query("new_key").from_statement( # If last_key + 1 isn't used, it's the result 'SELECT new_key ' 'FROM (SELECT :last_key + 1 AS new_key) q1 ' 'WHERE NOT EXISTS ' '(SELECT 1 FROM tunnelkeys WHERE tunnel_key = :last_key + 1) ' ).params(last_key=last_key).one() except orm_exc.NoResultFound: new_key = session.query("new_key").from_statement( # if last_key + 1 used, # find the least unused key from last_key + 1 '(SELECT t.tunnel_key + 1 AS new_key ' 'FROM tunnelkeys t ' 'WHERE NOT EXISTS ' '(SELECT 1 FROM tunnelkeys ti ' ' WHERE ti.tunnel_key = t.tunnel_key + 1) ' 'AND t.tunnel_key >= :last_key ' 'ORDER BY new_key LIMIT 1) ').params(last_key=last_key).one() new_key = new_key[0] # the result is tuple. LOG.debug(_("last_key %(last_key)s new_key %(new_key)s"), locals()) if new_key > self.key_max: LOG.debug(_("No key found")) raise orm_exc.NoResultFound() return new_key
def test_get_vim_without_defined_default_vim(self): self.nfvo_plugin.get_default_vim.side_effect = \ orm_exc.NoResultFound() self.service_plugins.get.return_value = self.nfvo_plugin with mock.patch.object(manager.TackerManager, 'get_service_plugins', return_value=self.service_plugins): self.assertRaises(nfvo.VimDefaultNotDefined, self.vimclient.get_vim, None)
def update_verified(self, user_id, verified): with self.db.get_session() as session: user = session.query(User).get(user_id) if not user: raise orm_exc.NoResultFound(f"No user with id {user_id} found") user.verified = verified
def get_from_email(self, email): user = self.db.session.query(User).filter_by(email=email).one_or_none() if not user: raise orm_exc.NoResultFound(f"No user with email {email} found") return user
def get(self, user_id): user = self.db.session.query(User).get(user_id) if not user: raise orm_exc.NoResultFound(f"No user with id {user_id} found") return user
def test_get_vim_not_found_exception(self): vim_id = self.vim_info['id'] self.nfvo_plugin.get_vim.side_effect = \ orm_exc.NoResultFound() self.service_plugins.get.return_value = self.nfvo_plugin with mock.patch.object(manager.TackerManager, 'get_service_plugins', return_value=self.service_plugins): self.assertRaises(nfvo.VimNotFoundException, self.vimclient.get_vim, None, vim_id=vim_id)
def test_sqlalchemy_orm_exc(self): resp = ErrHandler.handler(orm_exc.NoResultFound()) assert resp.status_code == 404 data = json.loads(resp.get_data()) assert data['message'] == u'源数据未找到' resp = ErrHandler.handler(orm_exc.UnmappedError()) assert resp.status_code == 500 data = json.loads(resp.get_data()) assert data['message'] == u'服务器内部错误'
async def one(self) -> T: try: ret = await self.one_or_none() except orm_exc.MultipleResultsFound: raise orm_exc.MultipleResultsFound( "Multiple rows were found for one()") else: if ret is None: raise orm_exc.NoResultFound("No row was found for one()") return ret
def get_object(model, key): """Looks for model object with uid equal to given key. Returns this object or raises NoResultFound. """ try: object = model.query.filter(model.uid == key).one() return object except exc.NoResultFound: raise exc.NoResultFound("Member of {} with uid {} not found.".format( str(model), key))
def create_show_submission() -> str: form_data = request.form.to_dict() try: venue = Venue.query.filter_by(id=form_data["venue_id"]).one() except exc.NoResultFound: raise exc.NoResultFound( f"No venue id = {form_data['venue_id']} was found].") try: artist = Artist.query.filter_by(id=form_data["artist_id"]).one() except exc.NoResultFound: raise exc.NoResultFound( f"No artist id = {form_data['artist_id']} was found.'") data = { "venue_id": venue.id, "venue_name": venue.name, "venue_image_link": venue.image_link, "artist_id": artist.id, "artist_name": artist.name, "artist_image_link": artist.image_link, "start_time": (parser.parse( form_data["start_time"]).strftime("%Y-%m-%dT%H:%M:%S.%fZ")), } show = Show(**data) try: db.session.add(show) db.session.commit() flash("Show was successfully listed!") except SQLAlchemyError: db.session.rollback() flash("An error occurred. Show could not be listed.") return render_template("pages/home.html")
def one(self): ret = list(self) l = len(ret) if l == 1: return ret[0] elif l == 0: raise sqla_exc.NoResultFound("No row was found for one()") else: raise sqla_exc.MultipleResultsFound( "Multiple rows were found for one()")
def test_get_unsuccessful(config, runner_factory): runner = runner_factory(AccountsService) container = get_container(runner, AccountsService) storage = replace_dependencies(container, "storage") runner.start() storage.users.get.side_effect = orm_exc.NoResultFound() with entrypoint_hook(container, "get_user") as get_user: with pytest.raises(UserDoesNotExist): get_user(user_id=123)
def test_get_vim_without_defined_default_vim(self): vimclient = vim_client.VimClient() service_plugins = mock.Mock() meo_plugin = mock.Mock() meo_plugin.get_default_vim.side_effect = \ orm_exc.NoResultFound() service_plugins.get.return_value = meo_plugin with mock.patch.object(manager.ApmecManager, 'get_service_plugins', return_value=service_plugins): self.assertRaises(meo.VimDefaultNotDefined, vimclient.get_vim, None)
def get(cls, **kwargs): result = SESSION.query(cls).filter_by(**kwargs) quantity = result.count() if not quantity: raise orm_exc.NoResultFound('{}: {}'.format(cls.__name__, kwargs)) if quantity > 1: raise orm_exc.MultipleResultsFound('{}: {}'.format( cls.__name__, kwargs)) return result.first()
def test_get_vim_without_defined_default_vim(self): cfg.CONF.set_override('default_vim', '', 'nfvo_vim', enforce_type=True) vimclient = vim_client.VimClient() service_plugins = mock.Mock() nfvo_plugin = mock.Mock() nfvo_plugin.get_default_vim.side_effect = \ orm_exc.NoResultFound() service_plugins.get.return_value = nfvo_plugin with mock.patch.object(manager.TackerManager, 'get_service_plugins', return_value=service_plugins): self.assertRaises(nfvo.VimDefaultNameNotDefined, vimclient.get_vim, None)
def test_delete_user_unsuccessful(config, runner_factory): runner = runner_factory(AccountsService) container = get_container(runner, AccountsService) storage = replace_dependencies(container, "storage") runner.start() storage.users.delete.side_effect = orm_exc.NoResultFound() user_id = 100 with entrypoint_hook(container, "delete_user") as delete_user: with pytest.raises(UserDoesNotExist): delete_user(user_id=user_id) assert storage.users.delete.call_args == call(user_id)
def test_verify_user_missing_user(config, runner_factory): runner = runner_factory(AccountsService) container = get_container(runner, AccountsService) storage = replace_dependencies(container, "storage") runner.start() token = "token" email = "*****@*****.**" storage.users.get_from_email.side_effect = orm_exc.NoResultFound() with entrypoint_hook(container, "verify_user") as verify_user: with pytest.raises(UserNotAuthorised): verify_user(email=email, token=token) assert storage.users.get_from_email.call_args == call(email)
def test_user_already_exists_false(config, runner_factory): runner = runner_factory(AccountsService) container = get_container(runner, AccountsService) storage = replace_dependencies(container, "storage") runner.start() email = "*****@*****.**" storage.users.get_from_email.side_effect = orm_exc.NoResultFound() with entrypoint_hook(container, "user_already_exists") as user_already_exists: result = user_already_exists(email=email) assert result is False assert storage.users.get_from_email.call_args == call(email)
def update_by_params(session_obj: SessionType, model_cls, params: List[Dict], data, json_result=False): """This function is updates the instance of the model represented by the class in model_cls and identified by the arguments in the params parameter Arg(s) ------ session_obj: the object used to interact with the database model_cls: class representing the model whose instance needs to be updated params (List[Dict]) -> parameters that will be used to identify the model instance that needs to be updated data (Dict) -> the fields that need to be updated with the values in the parameter json_result (bool) -> indicates whether the resulting instances of the model needs to be converted to a dictionary or the raw instance needs to be returned Return(s) --------- returns raw instance or dictionary representing the raw instance based on json_result's value """ clean_data = sanitize_data(model_cls, data) if "ver" not in clean_data: clean_data["ver"] = id_helper.generate_id() if "updated_at" not in clean_data: clean_data["updated_at"] = datetime.now() found_obj = find_by_params(session_obj, model_cls, params) if not found_obj: raise orm_exc.NoResultFound() for field in model_cls.COLUMNS: if field in clean_data: setattr(found_obj, field, clean_data[field]) session_obj.add(found_obj) if not json_result: return found_obj return found_obj.to_dict()
def test_get_one(self, mock_warning): mock_one = mock.Mock() mock_one.one.return_value = True mock_filter = mock.Mock() mock_filter.filter.return_value = mock_one mock_session = mock.Mock() mock_session.query.return_value = mock_filter self.o.session = mock_session self.assertTrue(self.o._get_one()) mock_one.one.assert_called_with() self.assertTrue(mock_filter.filter.called) mock_session.query.assert_called_with(OngBD) mock_session.query.side_effect = UnboundLocalError() self.assertFalse(self.o._get_one()) mock_warning.assert_called_with('Try search in database without ong name or id.') mock_session.query.side_effect = exc.NoResultFound() self.assertFalse(self.o._get_one()) mock_warning.assert_called_with('Ong [None, anyOng] not found.') mock_session.query.side_effect = exc.MultipleResultsFound() self.assertFalse(self.o._get_one()) mock_warning.assert_called_with('Multiple results found for ong [None, anyOng].')
def one(self): if len(self.records) == 0: raise exc.NoResultFound() return self.records[0]
def test_get_lp_by_name_or_uuid_with_uuid(self, mock_img, mock_query): mock_img.return_value = fakes.FakeImage() mock_query.side_effect = exc.NoResultFound() image.Image().get_lp_by_name_or_uuid(self.ctx, self.data[0]['uuid']) mock_img.assert_called_once_with(self.ctx, self.data[0]['uuid'], False)