def test_add_status_already_exists(status, statuses): ''' Test error detection for add_status ''' with patch('user_status.sql'): statuses.table.create.side_effect = IntegrityError() assert not statuses.add_status(*status)
def test_add_user_already_exists(user, accounts): ''' Test that add_user responds to errors correctly ''' with patch('users.sql'): accounts.table.create.side_effect = IntegrityError() assert not accounts.add_user(*user)
def validate(item): """проверяет корректоность введенных данных""" if 'is_archive' in item: val = item['is_archive'].lower() if val not in ('true', 'false'): raise IntegrityError('invalid input is_archive not Boolean') item['is_archive'] = True if val == 'true' else False if 'sex' in item: if item['sex'] not in (x[0] for x in Person.SEX_CHOICES): raise IntegrityError('invalid input sex incorrect') if 'birthday' in item: val = item['birthday'] try: datetime.datetime.strptime(val, '%Y-%m-%d') except ValueError: raise IntegrityError( "Incorrect data format, should be YYYY-MM-DD") return item
def create_record(cls, row): try: cls.model.create(**row) except IntegrityError as err: query = cls.model.select().where( cls.model.product_name == row['product_name']) if not len(query) == 1: raise IntegrityError(err) if row.get('date_updated', True): row['date_updated'] = datetime.datetime.strftime( datetime.datetime.now(), '%m/%d/%Y') cls.model.update(**row).where( cls.model.product_name == row['product_name']).execute()
def register_user(username, password, is_food_provider=False): with db_request("User") as User: try: row = User.select()\ .where(fn.lower(User.username) == username.lower()).first() if row is not None: raise IntegrityError() User.insert(username=username, password_hash=salted_sha256_string(password), registration_date=datetime.now(), is_food_service=is_food_provider).execute() except IntegrityError: raise ValueError( "User \"{}\" already registered!".format(username))
def attach_volunteer(account): if account.volunteer is None: query = Volunteer.select().where( Volunteer.account == None & Volunteer.local_first_name == account.first_name & Volunteer.local_last_name == account.last_name) if query.count() == 1: volunteer = next(query.iterator()) volunteer.account = account volunteer.save() return volunteer else: return Volunteer.create(account=account) raise IntegrityError( "Account with id {} already has an associated Volunteer, but attach_volunteer was called" .format(account.id))
def update(id, item): """обновляет значение полей элемента с заданным id""" try: item = ItemList.validate(item) p = Person.get_by_id(id) for key, v in item.items(): if getattr(p, key) != v: setattr(p, key, v) if not p.save_optimistic(): raise IntegrityError() return model_to_dict(p) except Person.DoesNotExist as err: raise IndexError('Элемента с данным ID нет') except IntegrityError as err: raise err except OutdatedError as err: raise err
def save(self, force_insert=False, only=None): if not Regex.email(self.site_email): raise IntegrityError('Email inválido') if not Regex.map_url(self.map_url): raise IntegrityError('URL do endereço inválido') if not Regex.phone_number(self.phones): raise IntegrityError('Telefones inválidos') if not Regex.phone_number(self.whats_app_phones): raise IntegrityError('Telefones WhatsApp inválidos') if not Regex.facebook_url(self.facebook_url): raise IntegrityError('Facebook inválido') if not Regex.twitter_url(self.twitter_url): raise IntegrityError('Twitter inválido') super(Site, self).save(force_insert, only)
def add_data_source(self, create_data_source_dto: CreateDataSourceDto, user_id=None, username=None): """Creates a new data source Arguments: create_data_source_dto {CreateDataSourceDto} -- Data transfer object containing the description of the data source and user Keyword Arguments: user_id {int} -- Optional: id of user (default: {None}) username {str} -- Optional: username of user (default: {None}) """ result = None # try to lookup the user try: result = _get_user(create_data_source_dto, user_id, username) except Exception: raise if result is not None and isinstance(result, User): try: return model_to_dict( DataSource.create( description=create_data_source_dto.description, source=create_data_source_dto.source, user=result)) except IntegrityError: raise IntegrityError( HTTPStatus.CONFLICT, f'Data source with name' f' \"{create_data_source_dto.source}\"' f' already exists') except Exception: raise ValueError(HTTPStatus.INTERNAL_SERVER_ERROR, "Unable to create data source")
def save_row(row, **kwargs): """Save a database row. Parameters ---------- row Returns ------- row_id : int """ try: row.save() except IntegrityError as e: if 'unique' in e.message.lower(): raise IntegrityError('\n'.join([ 'Record already exists.', e.message ])) else: raise IntegrityError except DoesNotExist: raise return row.id
def save(self, force_insert=False, only=None): if not Regex.email(self.email): raise IntegrityError('Email inválido') str_hash = self.email + datetime.now().strftime('%d/%m/%Y %H:%M:%S') self.user_hash = sha256(str_hash.encode()).hexdigest() super(User, self).save(force_insert, only)
def validate_email(self, email): user = User.get_or_none(User.email == email) if user: raise IntegrityError('Email address has already been taken')
def validate_username(self, username): user = User.get_or_none(User.username == username) if user: raise IntegrityError('Username has already been taken')
def save(self, *args, **kwargs): team = self.team if len(team.votes) >= team.members: raise IntegrityError('No More votes allowed for team') return super().save(*args, **kwargs)