Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Populate DB and Factories for tests #1090

Open
to-sta opened this issue Aug 26, 2024 · 0 comments
Open

Populate DB and Factories for tests #1090

to-sta opened this issue Aug 26, 2024 · 0 comments

Comments

@to-sta
Copy link

to-sta commented Aug 26, 2024

Description

I am trying to achive two things with a factory:

  1. Populate the database with dummy data
  2. Use Factories for test with pytest

For populating the database, I want to create X users with X organization, hence the query. Because I don't want to have an additional X amount of users, created with the SubFactory.

My attempt was to solve it with a conditional.

created_by = (
    factory.Iterator(UserModel.objects.exclude(username="admin").all())
    if UserModel.objects.exclude(username="admin").exists()
    else factory.SubFactory("authentication.factories.UserFactory")
)
RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

To Reproduce

The bug is occuring whenever I ran pytest.

Model / Factory code
class OrganizationFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Organization

    name = factory.Faker("word")
    tagline = factory.Faker("word")
    social_links = ["https://www.instagram.com/activist_org/"]
    created_by = (
        factory.Iterator(UserModel.objects.exclude(username="admin").all())
        if UserModel.objects.exclude(username="admin").exists()
        else factory.SubFactory("authentication.factories.UserFactory")
    )
    status = factory.SubFactory("entities.factories.StatusTypeFactory", name="Active")
    is_high_risk = factory.Faker("boolean")
    location = factory.Faker("city")
    acceptance_date = factory.LazyFunction(datetime.datetime.now)
The issue

Add a short description along with your code

# Include the code that provoked the bug, including as full a stack-trace as possible
  1. Populating the database:
OrganizationFactory.create_batch(number_of_orgs)
  1. Test:
organization = OrganizationFactory.build()

Notes

I haven't seen a solution for my problem in the docs..

@to-sta to-sta changed the title Populate DB and factories for tests Populate DB and Factories for tests Aug 26, 2024
@github-staff github-staff deleted a comment from vineet1401 Oct 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants
@to-sta and others