igorsimb / mp-monitor

Django app for scraping Wildberries
1 stars 0 forks source link

[tests] Use Factory Boy #58

Closed igorsimb closed 6 months ago

igorsimb commented 7 months ago

Create a conftest file to contain a fixture that is autoused to access django db.

conftest.py

import pytest

@pytest.fixture(autouse=True)
# using aaa in name to make sure this fixture always runs first due to some alphabetical order in certain cases
def aaa_db(db):
    pass

Use Factory Boy (from Matt Layman stream)

Replaces the million fixtures. Factory boy is able to auto create any foreign_key dependancies that you may need in a test (after you create a factory for them) without having to specify them every time.

factories.py

import factory

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = "accounts.Customuser"

Write tests using the created factory

test_user.py

import pytest
from <bla-bla.factories> import UserFactory

class TestUser:
    def test_factory(self):
        user = UserFactory()

        assert user is not None
igorsimb commented 6 months ago

Factory Boy + Faker for the other model

test.py

from journal.entries.tests.factories import EntryFactory

class TestEntry:
    def test_factory(self):
    """A factory produced a valid journal etry."""
    entry = EntryFactory()

    assert entry.body != ""
    assert entry.when is no None
    assert entry.user is not None

factories.py

import factory
import datetime

class EntryFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = "entries.Entry"

    body = factory.Faker('paragraph')
    when = factory.LazyFunction(datetime.date.today)
    # basically a foreign key to the user factory that we created
    user = factory.SubFactory("journal.accounts.tests.factories.UserFactory")

models.py

class Entry(models.Model):
    """An entry stores the user's writing for the day"""
    body = models.Textfield()
    when = models.DateField()
    user = models.Foreignkey("accounts.CustomUser", on_delete=models.CASCADE, related_name="entries")
igorsimb commented 6 months ago

Closing as solved in https://github.com/igorsimb/mp-monitor/pull/72