litestar-org / litestar-org/polyfactory
Enhancement: provide a mechanism to use the `faker` pytest fixture Faker instance
- Dominant language
- Python
- Stars
- 1.5k
- Forks
- 120
- PR merge metrics
- No merged PRs in 30d
Description
### Summary
Faker comes with a built-in pytest fixture. For both efficiency sake and control over the faker instance customization (e.g. custom faker providers, locales and randomness) it would be nice if there were a way to use that shared instance.
### Basic Example
The approach I'm imagining is either as an extra option to `pytest_plugin.registry_factory(... use_fake_fixture=True)` or as a completely separate pytest plugin method.
In that case, when the Factory class doesn't define its own `__faker__` instance, the pytest `faker` fixture would be used.
e.g.
```python
@pytest.fixture(scope="session", autouse=True)
def faker_seed() -> int:
return 42
@pytest.fixture(scope="session", autouse=True)
def faker_session_locale():
return ['en_US']
@pytest.fixture(autouse=True)
def customize_faker(faker: Faker):
faker.add_provider(MyCustomProvider)
class MyPersonFactory(ModelFactory[Person]):
__model__ = Person
register_fixture(PersonFactory, use_faker_fixture=True)
```
### Drawbacks and Impact
_No response_
### Unresolved questions
- Ideally, BaseFactory could be changed to set the default `__faker__ = Faker()` instance to a sentinel value to avoid creating extra `Faker` instances.
- Faker's pytest plugin by default exposes a function scope fixture but caches the singleton Faker instance (although that behavior can be modified e.g. to get a fresh faker instance per function to test different locales.
- I haven't though through all the implications of how this would interact with the function scope custom locale faker instances. I'm assuming the implementation would set the faker instance class var once (when register is called) rather that resolved during each pytest function invocation.
Contributor guide
Research direction
Start by tracing pytest_plugin.registry_factory, register_fixture, and BaseFactory.__faker__ to understand how factory Faker instances are selected. Review the faker fixture's scope and customization behavior, then define tests for using the shared fixture, preserving an explicitly configured factory instance, and handling locale and scope changes. Done means the supported API and its lifecycle behavior are documented and covered by tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing-qa
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100