Reputation: 363
I am attempting to add some custom faker provider to use with factory_boy
and pytest
.
I put the provider in
faker_providers/foo.py/Provider
.
In my factories.py
file, I have to import foo.py
and then register by running:
factory.Faker.add_provider(foo.Provider)
I am thinking of using pytest_sessionstart(session)
to auto-register all the custom provider under faker_providers
. Is there a way to do that?
Any suggestions for other ways to organize and register custom providers would also be appreciated.
Upvotes: 10
Views: 2226
Reputation: 948
Instead of instantiating a Faker to import from conftest, as of 2022, you can do the following inside your conftest file:
from factory import Faker
Faker.add_provider(CustomProvider)
And now you can just import from factory import Faker
wherever you go. This works because the Faker class has a class attribute of type dictionary that saves your new providers.
The reason I put it in conftest is because this is where code is run initially for all pytest. You can also put this in a pytest plugin setup method as well, but I found this the easiest.
The other way of doing this that I implemented was to have a utils folder with all my custom providers. Then, in a providers.py, I would add all my providers:
from factory import Faker
from .custom_provider import CustomProvider
for provider in (CustomProvider,):
Faker.add_provider(provider)
Then in conftest.py, I would simply import this file:
import path.to.provider # noqa
This way, I don't clutter my conftest too much.
Upvotes: 4
Reputation: 1629
It seems like a design choice and only you know the best answer to it.
However, I would recommend instantiating faker = Faker()
once for all tests after that adding all providers
in a configuration file. And import faker
from that place to everywhere it's needed.
It seems like conftest.py
is a good choice for that.
Upvotes: 0