factory-bot 0.1.0__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- factory_bot-0.2.0/CHANGELOG.md +78 -0
- factory_bot-0.2.0/PKG-INFO +149 -0
- factory_bot-0.2.0/README.md +128 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/pyproject.toml +2 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/src/factory_bot/__init__.py +19 -3
- factory_bot-0.2.0/src/factory_bot/_core.py +1652 -0
- factory_bot-0.2.0/src/factory_bot/_dsl.py +534 -0
- factory_bot-0.2.0/src/factory_bot/_factory_boy.py +251 -0
- factory_bot-0.2.0/src/factory_bot/_fake.py +197 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/src/factory_bot/pytest_plugin.py +4 -6
- factory_bot-0.2.0/tests/support/django_app/models.py +24 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/support/django_setup.py +6 -1
- factory_bot-0.2.0/tests/test_as_factory_boy.py +775 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_associations.py +8 -4
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_attributes_for.py +1 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_build.py +8 -7
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_create.py +95 -22
- factory_bot-0.2.0/tests/test_django.py +154 -0
- factory_bot-0.2.0/tests/test_docs.py +469 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_dsl.py +183 -2
- factory_bot-0.2.0/tests/test_errors.py +494 -0
- factory_bot-0.2.0/tests/test_factory_boy.py +318 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_fake.py +193 -15
- factory_bot-0.2.0/tests/test_frozen.py +301 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_handle.py +4 -1
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_isolation.py +4 -4
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_lazy.py +37 -3
- factory_bot-0.2.0/tests/test_lint.py +218 -0
- factory_bot-0.2.0/tests/test_logging.py +144 -0
- factory_bot-0.2.0/tests/test_misuse.py +265 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_pytest_plugin.py +63 -4
- factory_bot-0.2.0/tests/test_save.py +159 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_sequences.py +16 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_sqlalchemy.py +24 -2
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_typing.py +43 -5
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_value_rules.py +4 -3
- factory_bot-0.1.0/CHANGELOG.md +0 -44
- factory_bot-0.1.0/PKG-INFO +0 -160
- factory_bot-0.1.0/README.md +0 -139
- factory_bot-0.1.0/src/factory_bot/_core.py +0 -858
- factory_bot-0.1.0/src/factory_bot/_dsl.py +0 -210
- factory_bot-0.1.0/src/factory_bot/_fake.py +0 -117
- factory_bot-0.1.0/tests/support/django_app/models.py +0 -10
- factory_bot-0.1.0/tests/test_django.py +0 -63
- factory_bot-0.1.0/tests/test_docs.py +0 -50
- factory_bot-0.1.0/tests/test_errors.py +0 -246
- factory_bot-0.1.0/tests/test_lint.py +0 -116
- {factory_bot-0.1.0 → factory_bot-0.2.0}/.gitignore +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/LICENSE.txt +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/src/factory_bot/py.typed +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/conftest.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/support/django_app/__init__.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/support/models.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/support/sa_models.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_callbacks.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_children.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_introspection.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_lists.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_package.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_persist_owners.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_plan.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_traits.py +0 -0
- {factory_bot-0.1.0 → factory_bot-0.2.0}/tests/test_transient.py +0 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0 - 2026-12-06
|
|
4
|
+
|
|
5
|
+
### What you must do
|
|
6
|
+
|
|
7
|
+
- Call `fake.seed(x)` instead of `factory_bot.seed(x)` or `Faker.seed(x)`. Applies if you seed with either: `factory_bot.seed` is gone, and `Faker.seed()`, on the class, seeds only Faker's shared generator, never `fake`. `fake.seed(x)` also clears `fake.unique` and seeds every locale, `fake["ja_JP"]`, which shares its stream.
|
|
8
|
+
- Call `fake.seed()` in the test, or in a function-scoped fixture, if the test's own data should follow it. Applies if a module- or session-scoped fixture calls `fake.seed()`: the seed now covers that fixture only, so whichever test sets it up gets the same data alone and in the suite.
|
|
9
|
+
- Pass the function, `f.created = datetime.now`, or wrap the expression in a lambda, `f.id = lambda: str(uuid4())`. Applies if a factory or trait body calls a clock or random function outside a lambda or def, and your pytest config turns warnings into errors (`filterwarnings = ["error"]`): every build shared the one value, and it now warns with `FactoryWarning`. For one fixed value on purpose, compute it outside the body.
|
|
10
|
+
- Translate or remove a `class Meta`, `class Params`, `_create` or undecorated def left in a factory or trait body: the model goes in `@factory(Model)`, saving in `persist_with(...)`, `Params` values become `f.x = transient(default)` and `@trait`s, and a `post_generation` hook becomes `@after_create`. Applies if a body defines a class or def that nothing uses: it was dropped silently, and is now an error naming it and its line. A helper the body calls, or a lambda uses, is fine.
|
|
11
|
+
- Remove the `return` from a factory or trait body, and declare with `f.name = value`. Applies if a body returns something other than `None`: the value was dropped silently, and is now an error.
|
|
12
|
+
- Write factory_bot's form of a factory_boy declaration: `f.name = fake.name` for `factory.Faker("name")`, `association(F)` for `SubFactory(F)`, `@after_create` for `post_generation`, and so on. Applies if a body, an override or an `association()` to a factory_bot factory holds one: it was stored as the value, and is now an error naming the replacement.
|
|
13
|
+
- Drop the default from a parameter named after an attribute: `lambda first_name: ...`. Applies if a def or lambda in the factory's module gives such a parameter a default: the default was always used, never the attribute, and it is now an error.
|
|
14
|
+
- Put a sequence's counter first: `sequence(lambda n, title: ...)`. Applies if a sequence's first parameter is named after another attribute: it got the number, and is now an error.
|
|
15
|
+
- Declare the key in the factory, or add it to the result: `{**build(payload), "extra": 1}`. Applies if you pass an override the factory doesn't declare to a factory whose model is `dict`, or a subclass such as a `TypedDict`: it went into the dict silently, typos included, and is now an error suggesting the attribute you probably meant. A `TypedDict`'s own keys, `NotRequired` ones included, are allowed.
|
|
16
|
+
- Fix the typo, declare the attribute, or add it to `attributes_for`'s result: `{**attributes_for(signup), "password2": ...}`. Applies if you pass an override one typo from a declared attribute or transient (`frist_name` for `first_name`), and not a field of the model, to `attributes_for`, or to a factory whose model takes only `**kwargs` (Django, SQLAlchemy and dataclass models check their own): it reached the result silently, and is now an error suggesting the name you meant.
|
|
17
|
+
- Override the association itself: `author=association("author", name="Bea")`. Applies if you pass a factory_boy-style deep override, `author__name="Bea"` where `author` is an association, to a factory whose model takes `**kwargs`: it reached the model as a keyword, and is now an error suggesting this form, filled in with your values. Other models, which rejected it already, get the same suggestion, as does an `author` declared only in a trait you didn't apply.
|
|
18
|
+
- Pass `persist_with` a function that saves, `persist_with(lambda obj: ...)`. Applies if you passed it a class or an `async def`: `create()` saved nothing, and that is now an error.
|
|
19
|
+
- Import the module that defines your factories before `lint()` runs, e.g. `import factories` in tests/conftest.py. Applies if a test calls `lint()` with no factories registered: it checked nothing and passed, and it is now an error saying so.
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- `FactoryWarning`, a `UserWarning`, flags a clock or random call anywhere in a factory or trait body outside a lambda or def, as in `f.created = datetime.now()`, `f.id = str(uuid4())` or `if random.random() < 0.5:`. The body runs once, when the factory is defined, so every build would share the result. The warning points at the body's line and shows the fix. It knows `datetime.now`/`utcnow`/`today`, `date.today`, `time.time`/`time_ns`/`monotonic`, `uuid.uuid1`/`uuid4`, Django's `timezone.now`, and the value-making functions of `random` and `secrets`, under any alias. Turn it into an error with pytest's `-W error::factory_bot.FactoryWarning`.
|
|
24
|
+
- The `factory_bot` logger writes one DEBUG line per object built, associations indented under their parent: `create user ['admin'] overrides=[email] 60µs saved by persist_with(session) (conftest.py:12)`. It names the strategy, factory, traits, overridden attributes (names only, never values), sequence numbers drawn, elapsed time, and for `create`, the `persist_with` call that saved it or `obj.save()`. Turn it on with pytest's `--log-level=DEBUG`.
|
|
25
|
+
- `save(obj)` saves an object the way `create` would, so an `after_create` callback can save a related object it made by hand under any `persist_with`. Inside a `persist_with` function, it saves with the `persist_with` of the next test or fixture out, else `obj.save()`, so a fixture can wrap the saving it inherits: `persist_with(lambda obj: (stamp(obj), save(obj)))`.
|
|
26
|
+
- `lint()` returns the calls it checked, `["build('user')", "build('user', 'admin')"]`. It raises `LintError`, a `FactoryError`, whose `failures` hold each failing call as data: `call`, `factory`, `traits`, the `error`, and the `location` (`file:line`) of the attribute or callback that failed.
|
|
27
|
+
- `as_factory_boy(post)` is a factory_boy class, `PostFactory`, that builds and creates through factory_bot's `post`, so a factory_boy parent can write `SubFactory(as_factory_boy(post))`. It takes factory_boy's keywords: `author__name=` overrides the `author` association at any depth, and `admin=True` turns on the `admin` trait (and sets an `admin` attribute, if the factory declares one). pytest-factoryboy's `register(as_factory_boy(post))` generates `post` and `post_factory`, with each bare association wired to the fixture named after its target's model. It generates no value fixture for a plain attribute, such as `post__title`, so a test that parametrizes one gets the default, as does a `register()` keyword for one: pass the value to `post_factory()`, or hand-write the fixture. An association named like a member of factory_boy's `Factory`, such as `build` or `_meta`, is an error asking you to rename it. The migration guide's "register() with as_factory_boy" section has the details.
|
|
28
|
+
- `association()`, `build()`, `create()`, `build_list()` and `create_list()` take a factory_boy factory class, so a suite can move factories and call sites to factory_bot in any order. factory_boy makes the object its own way, `F.build()` or `F.create()` to match the strategy, so its `SubFactory`s, `django_get_or_create`, session and `post_generation` behave as before, and `persist_with` doesn't apply. A trait name passes `name=True`, turning on that `Params` trait; overrides pass through, `author__name=` included. factory_bot never imports factory_boy.
|
|
29
|
+
- `fake["ja_JP"]`, or any other locale Faker knows, is a Faker for that locale. It draws from `fake`'s seeded stream and shares `fake.unique`'s values, so `fake.seed()` and the pytest plugin make its data reproducible, and calling it in a body is the same error as calling `fake`. It's kept, so a provider added to it stays.
|
|
30
|
+
|
|
31
|
+
### Changed
|
|
32
|
+
|
|
33
|
+
- A Faker method passed at build time is called, as in a body: `build(author, name=fake.name)` gives a name, and so do `fake["ja_JP"].name`, `fake.unique.name`, a provider you added, or another `Faker()`'s method, in `build()`'s overrides and in those of an `association()` called during a build. Any other function you pass is still stored.
|
|
34
|
+
- `persist_with(Mock())` calls the mock. A callable object counts as a session only if its class defines `add` and `flush`, as `scoped_session` does.
|
|
35
|
+
- Errors say what to write instead: an unknown factory lists the registered ones, says when none are (import the factories module), or names the `clear_factories()` call that removed it; an association to an unregistered factory asks whether its module is imported; `build_list(user, "admin", 3)` says the count comes first; a rejected `count=` suggests `build_list`; `user.build()`, `user.create_batch()` and `factory_bot.create_batch` name factory_bot's function; `build(User)` names the model's factory; a parameter declared only in another trait, or named like factory_boy's `o` or `create`, says why it isn't filled; a model rejecting a declared attribute names its `f.x =` line; a Django many-to-many in a body points at the recipe; a failed save names the `persist_with` call whose hook raised.
|
|
36
|
+
|
|
37
|
+
## 0.1.0 - 2026-10-19
|
|
38
|
+
|
|
39
|
+
### What you must do
|
|
40
|
+
|
|
41
|
+
- Rewrite factory and trait bodies without the `f` parameter: `from factory_bot import f`, `def user():`, and `@trait` instead of `@f.trait`. Applies if you wrote factories for 0.0.1. An old-style body raises an error showing the new form.
|
|
42
|
+
- Write `lambda: SomeClass()` where you want a class, or another callable object that isn't a function, called per build. Applies if you assigned one as a value: only functions (defs, lambdas, methods, builtins like `datetime.now`, `functools.partial`) are called now, and every other object is stored, so `f.status = Status` gives the `Enum` class and `f.client = Mock()` gives that `Mock`.
|
|
43
|
+
- Drop the parentheses from `fake` calls in bodies (`f.name = fake.first_name`), or wrap a call that needs arguments in a lambda. Applies if a body calls `fake.x()`, `fake.random.x()`, `fake.parse()` or `fake.format()`: that gave every build the same value, and is now an error.
|
|
44
|
+
- Replace `build(...)` or `attributes_for(...)` called directly in a body with `association(...)`, or wrap it in a lambda. Applies if a body calls one: it ran once, at import, so every build shared one object. It's now an error, and so is `create(...)`.
|
|
45
|
+
- Rename or remove one of the two. Applies if a factory defines two traits with the same name: the second used to replace the first silently, and is now an error.
|
|
46
|
+
- Remove a `seed()` call made once for the whole run, or disable the plugin with `-p no:factory_bot`. Applies if you seed `fake` in a conftest: the new pytest plugin reseeds before every test.
|
|
47
|
+
- Upgrade Faker to 23.2 or later. Applies if your project pins an older one: factory_bot now requires it, since before 23.2 `fake["en_US"]` hands back Faker's generator, which the body-call check can't see.
|
|
48
|
+
- Install Django or SQLAlchemy yourself. Applies if you installed `factory_bot[django]` or `factory_bot[sqlalchemy]`: the extras are gone, since factory_bot never imports either.
|
|
49
|
+
|
|
50
|
+
### Added
|
|
51
|
+
|
|
52
|
+
- `create` builds, then saves: `obj.save()` by default. `persist_with(fn)` saves with a function instead, and `persist_with(session)` adds and flushes to a SQLAlchemy `Session` or `scoped_session`, never committing, so the test's transaction still decides. `persist_with(None)` restores `obj.save()`. The most recent call wins, and under pytest one set by a test or fixture lasts until that test or fixture ends. An `AsyncSession` or `async_sessionmaker` is an error naming the fix: its `sync_session`, with `create()` called inside `await session.run_sync(...)`.
|
|
53
|
+
- `build_list` and `create_list`.
|
|
54
|
+
- `association(factory, *traits, **overrides)` makes another factory's object with the parent's strategy: built for `build`, created first for `create`. Called during a build, from a lambda or a callback, it makes the object right away, for associations that depend on other attributes or come in lists. `attributes_for` leaves associations out unless you pass them. Overrides written in a body work like the other factory's own attributes: `association(author, name=fake.name)` gives each author a fresh name, and a function's parameters are filled from that factory's attributes; passed at build time, or to an `association()` called during a build, they are used as given. Passing `<name>_id=` skips association `<name>` and still reaches the model, so `create("book", author_id=a.id)` makes no spare author. It applies only to an attribute declared as `association(...)` or `transient(association(...))`.
|
|
55
|
+
- `transient(value)` declares an input other attributes and callbacks can use, which never reaches the model or `attributes_for`.
|
|
56
|
+
- Child factories: `@factory(parent=user)` defines a child that inherits its parent's model, attributes, traits, sequences and callbacks, typed `Factory[User]`; `@factory(Admin, parent=user)` switches model.
|
|
57
|
+
- `@after_build` and `@after_create` callbacks get the object first, then other attributes by name, transients included. They run parent first, then child, then traits.
|
|
58
|
+
- `@factory(User)` returns a `Factory[User]`. Pass it wherever a name goes, as in `build(user)` or `association(user)`, and a type checker knows the result is a `User`. Names still work and give `Any`. Assigning one as a value, `f.author = user`, is an error suggesting `association(user)`.
|
|
59
|
+
- A sequence's function gets the counter first, then other attributes by name: `sequence(lambda n, title: f"{slugify(title)}-{n}")`.
|
|
60
|
+
- `lint()` builds every factory once, then once with each trait, and raises one error listing every call that failed, ready to paste into a test.
|
|
61
|
+
- A pytest plugin, on by default. It seeds `fake` before collection, so fake values in `parametrize` give stable test ids, reseeds it before each test from the test's id, and for each fixture from its name, where it's defined, its param and the test, module or session it belongs to, so every test and fixture gets the same fake data alone, in the suite, in any order or under pytest-xdist; with pytest-randomly, `--randomly-seed` drives it. A fixture that calls `seed()` keeps that seed. It ends a `persist_with` with the test or fixture that set it. `factory_bot_reset_sequences = true` restarts sequences per test. The report header shows the seed and whether sequences reset: `factory_bot: seed=0, reset_sequences=off`. Disable it with `-p no:factory_bot`.
|
|
62
|
+
|
|
63
|
+
### Changed
|
|
64
|
+
|
|
65
|
+
- Every list, dict, set and tuple written in a body, their subclasses included (`defaultdict`, `Counter`, `OrderedDict`, a namedtuple), plus deques and bytearrays, nested ones too, is copied per build with its type, `default_factory` and order kept, so `f.settings = {"roles": []}` no longer leaks between tests. A cyclic value is copied with its cycle. Anything you pass at build time is used exactly as given.
|
|
66
|
+
- A `sequence` passed as an override is evaluated, not passed to the model as a raw object; so are the new `association` and `transient`. A `sequence` inside a container, or returned from a lambda, is an error naming the attribute, instead of reaching the model unevaluated.
|
|
67
|
+
- An `async def` or a generator function as an attribute, a sequence's function or a callback is an error, and so is a function that returns a coroutine, instead of handing the model an un-awaited coroutine or an unrun generator.
|
|
68
|
+
- `seed()` also clears `fake.unique`, so the same seed gives the same data whatever ran before. `fake.seed(...)` is an error pointing at `factory_bot.seed(...)`, instead of Faker's pointing at `Faker.seed()`, which doesn't seed `fake`.
|
|
69
|
+
- A lazy attribute's positional-only parameters are injected like the others.
|
|
70
|
+
- On Python 3.14+, a function whose annotations name a type imported only under `if TYPE_CHECKING:` works as a lazy attribute, a sequence's function or a callback, instead of raising `NameError`: factory_bot reads its parameters without evaluating annotations.
|
|
71
|
+
- Errors say where they happened. A `FactoryError` names the factory, the innermost when builds nest. An exception from a model, lambda or callback keeps its type and gains notes naming the factory and attribute with its file:line. A model's unknown-keyword `TypeError` suggests the attribute you probably meant.
|
|
72
|
+
- "Factory 'user' is already defined" shows the first definition's full path and suggests `clear_factories()` for a REPL or a reload; when that path is the line being defined, it says the file was imported under two module names.
|
|
73
|
+
- Reading `f.x` raises an `AttributeError` too, so `hasattr(f, ...)`, `inspect.unwrap` and doctest work.
|
|
74
|
+
- A one-parameter function, `def make_point(x)`, can be a model; only a lone parameter named `f` is read as an old-style body.
|
|
75
|
+
|
|
76
|
+
## 0.0.1 - 2026-10-18
|
|
77
|
+
|
|
78
|
+
- Define factories with `@factory(Model)` and build them with `build` / `attributes_for`: static, lazy (dependencies injected by parameter name) and `sequence` attributes, traits, and a shared seedable `fake`. Faker is now a dependency.
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: factory_bot
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Generate realistic test data with ease
|
|
5
|
+
Project-URL: Homepage, https://github.com/dpep/py_factory_bot
|
|
6
|
+
Project-URL: Issues, https://github.com/dpep/py_factory_bot/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/dpep/py_factory_bot/blob/main/CHANGELOG.md
|
|
8
|
+
Author: Daniel Pepper
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Keywords: factories,factory_bot,fixtures,testing
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Framework :: Pytest
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Software Development :: Testing
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Requires-Dist: faker>=23.2
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# factory_bot
|
|
23
|
+
|
|
24
|
+
Generate realistic test data with ease.
|
|
25
|
+
|
|
26
|
+
**Writing tests with factory_bot, or a coding agent doing it for you? Start with the [cheat sheet](https://github.com/dpep/py_factory_bot/blob/main/docs/cheatsheet.md):** the whole API on one page, with links to the details.
|
|
27
|
+
|
|
28
|
+
Describe your test data once, and each test asks only for the fields it cares about: `build(user)`, `create(user, "admin", first_name="Jane")`, `build_list(post, 3)`. The factory fills in the rest, with fake values from [Faker](https://faker.readthedocs.io) where you want them. It works with anything that takes keyword arguments: classes, dataclasses, dicts, Django and SQLAlchemy models. Under pytest, a test gets the same fake data alone, in the suite, or in any order.
|
|
29
|
+
|
|
30
|
+
Early development: the API is still settling.
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
pip install factory_bot
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
## Quick start
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from dataclasses import dataclass
|
|
44
|
+
|
|
45
|
+
from factory_bot import build, create, f, factory, fake, sequence, trait
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class User:
|
|
50
|
+
first_name: str
|
|
51
|
+
last_name: str
|
|
52
|
+
email: str
|
|
53
|
+
username: str
|
|
54
|
+
admin: bool = False
|
|
55
|
+
|
|
56
|
+
def save(self):
|
|
57
|
+
pass # your ORM's save(); create() calls it
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@factory(User)
|
|
61
|
+
def user():
|
|
62
|
+
f.first_name = fake.first_name # no parens: a fresh name on every build
|
|
63
|
+
f.last_name = fake.last_name
|
|
64
|
+
f.email = lambda first_name, last_name: f"{first_name}.{last_name}@example.com"
|
|
65
|
+
f.username = sequence(lambda n: f"user{n}")
|
|
66
|
+
|
|
67
|
+
@trait
|
|
68
|
+
def admin():
|
|
69
|
+
f.admin = True
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
build(user)
|
|
73
|
+
# User(first_name='Diane', last_name='Butler', email='Diane.Butler@example.com', username='user1', admin=False)
|
|
74
|
+
|
|
75
|
+
create(user, "admin", first_name="Jane")
|
|
76
|
+
# User(first_name='Jane', last_name='Turner', email='Jane.Turner@example.com', username='user2', admin=True)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
A factory is a plain function that assigns attributes to `f`. A function value, like `email`'s lambda, is called on every build, with its parameters filled from the attributes of the same name, so `email` follows the `first_name="Jane"` override. Overrides beat traits, and later traits beat earlier ones.
|
|
80
|
+
|
|
81
|
+
`@factory` returns the factory, so `build(user)` is typed as a `User`. Its name works too: `build("user")`.
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
## Associations
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from factory_bot import association
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@factory(dict)
|
|
91
|
+
def author():
|
|
92
|
+
f.name = "Ann"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@factory(dict)
|
|
96
|
+
def book():
|
|
97
|
+
f.title = "Dune"
|
|
98
|
+
f.author = association(author, name="Frank")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
assert build(book) == {"title": "Dune", "author": {"name": "Frank"}}
|
|
102
|
+
assert build(book, author_id=7) == {"title": "Dune", "author_id": 7}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
An association follows the parent: `build` builds it, and `create` creates it first. Pass your own with `author=`, or `author_id=` to skip making one.
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
## Saving
|
|
109
|
+
|
|
110
|
+
`create` builds, then calls `obj.save()`, so a Django model needs nothing more. For SQLAlchemy, hand `persist_with` the test's session; each created object is added and flushed, never committed:
|
|
111
|
+
|
|
112
|
+
<!-- doctest: sqlalchemy-conftest -->
|
|
113
|
+
```python
|
|
114
|
+
# tests/conftest.py
|
|
115
|
+
import pytest
|
|
116
|
+
from sqlalchemy import create_engine
|
|
117
|
+
from sqlalchemy.orm import Session
|
|
118
|
+
|
|
119
|
+
from factory_bot import persist_with
|
|
120
|
+
from myapp.models import Base # your declarative base
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@pytest.fixture
|
|
124
|
+
def session():
|
|
125
|
+
engine = create_engine("sqlite://")
|
|
126
|
+
Base.metadata.create_all(engine)
|
|
127
|
+
with Session(engine) as session:
|
|
128
|
+
persist_with(session) # undone when the fixture ends (by the pytest plugin)
|
|
129
|
+
yield session
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
For anything else, `persist_with(fn)` saves with your function. See [Saving](https://github.com/dpep/py_factory_bot/blob/main/docs/guide.md#saving) for the rest, and [SQLAlchemy fixtures](https://github.com/dpep/py_factory_bot/blob/main/docs/guide.md#sqlalchemy-fixtures) for a fixture that rolls back.
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
## Reproducible data
|
|
136
|
+
|
|
137
|
+
The pytest plugin is on once factory_bot is installed. It reseeds `fake` for every test and fixture, so a test that fails in the suite fails with the same data alone, in another order, or under pytest-xdist. The seed is in the header (`factory_bot: seed=0, reset_sequences=off`), and follows [pytest-randomly](https://github.com/pytest-dev/pytest-randomly)'s `--randomly-seed`. Sequences keep counting across tests. Details: [Test isolation](https://github.com/dpep/py_factory_bot/blob/main/docs/guide.md#test-isolation).
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
## Learn more
|
|
141
|
+
|
|
142
|
+
- [Cheat sheet](https://github.com/dpep/py_factory_bot/blob/main/docs/cheatsheet.md): the whole API on one page.
|
|
143
|
+
- [Guide](https://github.com/dpep/py_factory_bot/blob/main/docs/guide.md): the manual, with recipes for Django, SQLAlchemy and checking every factory.
|
|
144
|
+
- [Migrating from factory_boy](https://github.com/dpep/py_factory_bot/blob/main/docs/migrating-from-factory-boy.md): a concept map, and how to move one factory at a time.
|
|
145
|
+
|
|
146
|
+
Inspired by thoughtbot's [factory_bot](https://github.com/thoughtbot/factory_bot) for Ruby.
|
|
147
|
+
|
|
148
|
+
----
|
|
149
|
+
[](https://pypi.org/project/factory_bot)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# factory_bot
|
|
2
|
+
|
|
3
|
+
Generate realistic test data with ease.
|
|
4
|
+
|
|
5
|
+
**Writing tests with factory_bot, or a coding agent doing it for you? Start with the [cheat sheet](https://github.com/dpep/py_factory_bot/blob/main/docs/cheatsheet.md):** the whole API on one page, with links to the details.
|
|
6
|
+
|
|
7
|
+
Describe your test data once, and each test asks only for the fields it cares about: `build(user)`, `create(user, "admin", first_name="Jane")`, `build_list(post, 3)`. The factory fills in the rest, with fake values from [Faker](https://faker.readthedocs.io) where you want them. It works with anything that takes keyword arguments: classes, dataclasses, dicts, Django and SQLAlchemy models. Under pytest, a test gets the same fake data alone, in the suite, or in any order.
|
|
8
|
+
|
|
9
|
+
Early development: the API is still settling.
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
pip install factory_bot
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
## Quick start
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
|
|
24
|
+
from factory_bot import build, create, f, factory, fake, sequence, trait
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class User:
|
|
29
|
+
first_name: str
|
|
30
|
+
last_name: str
|
|
31
|
+
email: str
|
|
32
|
+
username: str
|
|
33
|
+
admin: bool = False
|
|
34
|
+
|
|
35
|
+
def save(self):
|
|
36
|
+
pass # your ORM's save(); create() calls it
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@factory(User)
|
|
40
|
+
def user():
|
|
41
|
+
f.first_name = fake.first_name # no parens: a fresh name on every build
|
|
42
|
+
f.last_name = fake.last_name
|
|
43
|
+
f.email = lambda first_name, last_name: f"{first_name}.{last_name}@example.com"
|
|
44
|
+
f.username = sequence(lambda n: f"user{n}")
|
|
45
|
+
|
|
46
|
+
@trait
|
|
47
|
+
def admin():
|
|
48
|
+
f.admin = True
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
build(user)
|
|
52
|
+
# User(first_name='Diane', last_name='Butler', email='Diane.Butler@example.com', username='user1', admin=False)
|
|
53
|
+
|
|
54
|
+
create(user, "admin", first_name="Jane")
|
|
55
|
+
# User(first_name='Jane', last_name='Turner', email='Jane.Turner@example.com', username='user2', admin=True)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
A factory is a plain function that assigns attributes to `f`. A function value, like `email`'s lambda, is called on every build, with its parameters filled from the attributes of the same name, so `email` follows the `first_name="Jane"` override. Overrides beat traits, and later traits beat earlier ones.
|
|
59
|
+
|
|
60
|
+
`@factory` returns the factory, so `build(user)` is typed as a `User`. Its name works too: `build("user")`.
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
## Associations
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from factory_bot import association
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@factory(dict)
|
|
70
|
+
def author():
|
|
71
|
+
f.name = "Ann"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@factory(dict)
|
|
75
|
+
def book():
|
|
76
|
+
f.title = "Dune"
|
|
77
|
+
f.author = association(author, name="Frank")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
assert build(book) == {"title": "Dune", "author": {"name": "Frank"}}
|
|
81
|
+
assert build(book, author_id=7) == {"title": "Dune", "author_id": 7}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
An association follows the parent: `build` builds it, and `create` creates it first. Pass your own with `author=`, or `author_id=` to skip making one.
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
## Saving
|
|
88
|
+
|
|
89
|
+
`create` builds, then calls `obj.save()`, so a Django model needs nothing more. For SQLAlchemy, hand `persist_with` the test's session; each created object is added and flushed, never committed:
|
|
90
|
+
|
|
91
|
+
<!-- doctest: sqlalchemy-conftest -->
|
|
92
|
+
```python
|
|
93
|
+
# tests/conftest.py
|
|
94
|
+
import pytest
|
|
95
|
+
from sqlalchemy import create_engine
|
|
96
|
+
from sqlalchemy.orm import Session
|
|
97
|
+
|
|
98
|
+
from factory_bot import persist_with
|
|
99
|
+
from myapp.models import Base # your declarative base
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@pytest.fixture
|
|
103
|
+
def session():
|
|
104
|
+
engine = create_engine("sqlite://")
|
|
105
|
+
Base.metadata.create_all(engine)
|
|
106
|
+
with Session(engine) as session:
|
|
107
|
+
persist_with(session) # undone when the fixture ends (by the pytest plugin)
|
|
108
|
+
yield session
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
For anything else, `persist_with(fn)` saves with your function. See [Saving](https://github.com/dpep/py_factory_bot/blob/main/docs/guide.md#saving) for the rest, and [SQLAlchemy fixtures](https://github.com/dpep/py_factory_bot/blob/main/docs/guide.md#sqlalchemy-fixtures) for a fixture that rolls back.
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
## Reproducible data
|
|
115
|
+
|
|
116
|
+
The pytest plugin is on once factory_bot is installed. It reseeds `fake` for every test and fixture, so a test that fails in the suite fails with the same data alone, in another order, or under pytest-xdist. The seed is in the header (`factory_bot: seed=0, reset_sequences=off`), and follows [pytest-randomly](https://github.com/pytest-dev/pytest-randomly)'s `--randomly-seed`. Sequences keep counting across tests. Details: [Test isolation](https://github.com/dpep/py_factory_bot/blob/main/docs/guide.md#test-isolation).
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
## Learn more
|
|
120
|
+
|
|
121
|
+
- [Cheat sheet](https://github.com/dpep/py_factory_bot/blob/main/docs/cheatsheet.md): the whole API on one page.
|
|
122
|
+
- [Guide](https://github.com/dpep/py_factory_bot/blob/main/docs/guide.md): the manual, with recipes for Django, SQLAlchemy and checking every factory.
|
|
123
|
+
- [Migrating from factory_boy](https://github.com/dpep/py_factory_bot/blob/main/docs/migrating-from-factory-boy.md): a concept map, and how to move one factory at a time.
|
|
124
|
+
|
|
125
|
+
Inspired by thoughtbot's [factory_bot](https://github.com/thoughtbot/factory_bot) for Ruby.
|
|
126
|
+
|
|
127
|
+
----
|
|
128
|
+
[](https://pypi.org/project/factory_bot)
|
|
@@ -40,6 +40,8 @@ dev = [
|
|
|
40
40
|
"pyright[nodejs]", # the nodejs extra ships node as a wheel, so no system node is needed
|
|
41
41
|
"django",
|
|
42
42
|
"sqlalchemy >= 2.1.5",
|
|
43
|
+
"factory_boy",
|
|
44
|
+
"pytest-factoryboy", # test_as_factory_boy checks register() names its fixtures; it skips without it
|
|
43
45
|
]
|
|
44
46
|
|
|
45
47
|
[tool.hatch.version]
|
|
@@ -1,6 +1,12 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING
|
|
2
|
+
|
|
1
3
|
from ._core import (
|
|
2
4
|
Factory,
|
|
3
5
|
FactoryError,
|
|
6
|
+
FactoryWarning,
|
|
7
|
+
LintError,
|
|
8
|
+
_missing_module_name,
|
|
9
|
+
as_factory_boy,
|
|
4
10
|
association,
|
|
5
11
|
attributes_for,
|
|
6
12
|
build,
|
|
@@ -11,20 +17,24 @@ from ._core import (
|
|
|
11
17
|
lint,
|
|
12
18
|
persist_with,
|
|
13
19
|
reset_sequences,
|
|
20
|
+
save,
|
|
14
21
|
sequence,
|
|
15
22
|
transient,
|
|
16
23
|
)
|
|
17
24
|
from ._dsl import after_build, after_create, f, factory, trait
|
|
18
|
-
from ._fake import fake
|
|
25
|
+
from ._fake import fake
|
|
19
26
|
|
|
20
27
|
__author__ = "dpepper"
|
|
21
|
-
__version__ = "0.
|
|
28
|
+
__version__ = "0.2.0"
|
|
22
29
|
|
|
23
30
|
__all__ = [
|
|
24
31
|
"Factory",
|
|
25
32
|
"FactoryError",
|
|
33
|
+
"FactoryWarning",
|
|
34
|
+
"LintError",
|
|
26
35
|
"after_build",
|
|
27
36
|
"after_create",
|
|
37
|
+
"as_factory_boy",
|
|
28
38
|
"association",
|
|
29
39
|
"attributes_for",
|
|
30
40
|
"build",
|
|
@@ -38,8 +48,14 @@ __all__ = [
|
|
|
38
48
|
"lint",
|
|
39
49
|
"persist_with",
|
|
40
50
|
"reset_sequences",
|
|
41
|
-
"
|
|
51
|
+
"save",
|
|
42
52
|
"sequence",
|
|
43
53
|
"trait",
|
|
44
54
|
"transient",
|
|
45
55
|
]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
if not TYPE_CHECKING: # a missing name stays a type error
|
|
59
|
+
|
|
60
|
+
def __getattr__(name):
|
|
61
|
+
raise _missing_module_name(name)
|