这是我的数据库模型(用户):
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class SqlAlchemyBase(DeclarativeBase):
"""Base SQL alchemy model."""
class User(SqlAlchemyBase):
"""User database model."""
__tablename__ = "users"
id_: Mapped[uuid] = mapped_column(primary_key=True, index=True, default=uuid.uuid4)
first_name: Mapped[str]
last_name: Mapped[str]
email: Mapped[str] = mapped_column(unique=True, index=True)
hashed_password: Mapped[str]
is_superuser: Mapped[bool]
这是我的上述模型的工厂:
import factory
import factory.fuzzy
class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = User
id_ = factory.Faker("uuid4")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
email = factory.LazyAttribute(lambda obj: f"{obj.first_name}.{obj.last_name}@gmail.com")
hashed_password = "HashedPwd"
is_superuser = False
如何创建 200 个用户?
这是我尝试过的一些事情......
尝试1:
根据工厂男孩文档here,在测试函数中,我尝试执行以下操作:
users = UserFactory().create_batch(200)
但是这失败了,并出现以下错误:
AttributeError: 'User' object has no attribute 'create_batch'
尝试2:
我也尝试了
UserFactory().build_batch(200)
但得到了同样的错误。
尝试3:
按照文档这里
import factory
factory.create_batch(UserFactory, size=200, FACTORY_CLASS=factory.alchemy.SQLAlchemyModelFactory)
这给了我错误:
TypeError: <class 'v1.database.models.test_factories.users.UserFactory'> is already a Factory
这是我正在使用的:
Python 3.11
SQLAlchemy~=2.0
工厂男孩~=3.3
pytest~=7.4
用户 = UserFactory().create_batch(200) 应该 用户 = UserFactory.create_batch(200)