Skip to content

Commit

Permalink
✅(dashboard) update tests with factory boy
Browse files Browse the repository at this point in the history
- Add factory-boy to Pipfile
- add factories for apps: auth, content, core
- Update tests with new factories
  • Loading branch information
ssorin committed Nov 26, 2024
1 parent 773e47b commit 1cfa47f
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 72 deletions.
1 change: 1 addition & 0 deletions src/dashboard/Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ black = "==24.10.0"
django-extensions = "==3.2.3"
django-stubs = {extras = ["compatible-mypy"], version = "==5.1.1"}
djlint = "==1.36.1"
factory-boy = "==3.3.1"
honcho = "==2.0.0"
mypy = "==1.13.0"
pytest = "==8.3.3"
Expand Down
27 changes: 26 additions & 1 deletion src/dashboard/Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions src/dashboard/apps/auth/factories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Dashboard auth factories."""

import factory
from django.contrib.auth import get_user_model


class UserFactory(factory.django.DjangoModelFactory):
"""Factory class for creating a “standard” user."""

username = factory.Faker("user_name")
password = factory.django.Password("foo")

class Meta: # noqa: D106
model = get_user_model()


class AdminUserFactory(UserFactory):
"""Factory class for creating a superuser."""

@classmethod
def _create(cls, model_class, *args, **kwargs):
"""Override the default ``_create`` with ``create_superuser``."""
manager = cls._get_manager(model_class)
# The default would use ``manager.create(*args, **kwargs)``
return manager.create_superuser(*args, **kwargs)
13 changes: 5 additions & 8 deletions src/dashboard/apps/auth/tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
"""Dashboard auth models tests."""

import pytest
from django.contrib.auth import get_user_model

from apps.auth.factories import AdminUserFactory, UserFactory


@pytest.mark.django_db
def test_create_user():
"""Tests the creation of a default user model."""
User = get_user_model()
user = User.objects.create_user(username="john", password="foo") # noqa: S106
user = UserFactory(username="John")

assert user.username == "john"
assert user.username == "John"
assert user.is_active is True
assert user.is_staff is False
assert user.is_superuser is False
Expand All @@ -19,10 +19,7 @@ def test_create_user():
@pytest.mark.django_db
def test_create_superuser():
"""Tests the creation of a superuser with the user model."""
User = get_user_model()
admin_user = User.objects.create_superuser(
username="superadmin", password="foo" # noqa: S106
)
admin_user = AdminUserFactory(username="superadmin")

assert admin_user.username == "superadmin"
assert admin_user.is_active is True
Expand Down
24 changes: 24 additions & 0 deletions src/dashboard/apps/consent/factories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Dashboard consent factories."""

from datetime import timedelta

import factory
from django.utils import timezone
from factory import fuzzy

from apps.auth.factories import UserFactory
from apps.core.factories import DeliveryPointFactory

from .models import Consent


class ConsentFactory(factory.django.DjangoModelFactory):
"""Factory class for creating instances of the Consent model."""

delivery_point = factory.SubFactory(DeliveryPointFactory)
created_by = factory.SubFactory(UserFactory)
start = fuzzy.FuzzyDateTime(timezone.now())
end = factory.LazyAttribute(lambda o: o.start + timedelta(days=90))

class Meta: # noqa: D106
model = Consent
35 changes: 12 additions & 23 deletions src/dashboard/apps/consent/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,25 @@
from datetime import timedelta

import pytest
from django.contrib.auth import get_user_model
from django.utils import formats, timezone
from django.utils import formats

from apps.auth.factories import UserFactory
from apps.consent.factories import ConsentFactory
from apps.consent.models import Consent
from apps.core.models import DeliveryPoint
from apps.core.factories import DeliveryPointFactory


@pytest.mark.django_db
def test_create_consent():
"""Tests the creation of a consent."""
# create user
User = get_user_model()
user1 = User.objects.create_user(username="user1", password="foo") # noqa: S106
user1 = UserFactory()
delivery_point = DeliveryPointFactory()

# create delivery point
delivery_point = DeliveryPoint.objects.create(provider_id="provider_1234")

# create consent
consent = Consent.objects.create(
consent = ConsentFactory(
delivery_point=delivery_point,
created_by=user1,
start=timezone.now(),
end=timezone.now() + timedelta(days=90),
)

assert consent.delivery_point == delivery_point
assert consent.created_by == user1
assert consent.status == Consent.AWAITING
Expand All @@ -48,20 +43,14 @@ def test_create_consent():
@pytest.mark.django_db
def test_update_consent_status():
"""Tests updating a consent status."""
# create user
User = get_user_model()
user1 = User.objects.create_user(username="user1", password="foo") # noqa: S106
user1 = UserFactory()
delivery_point = DeliveryPointFactory()

# create delivery point
delivery_point = DeliveryPoint.objects.create(provider_id="provider_1234")

# create consent
consent = Consent.objects.create(
consent = ConsentFactory(
delivery_point=delivery_point,
created_by=user1,
start=timezone.now(),
end=timezone.now() + timedelta(days=90),
)

new_updated_at = consent.updated_at

# update status to VALIDATED
Expand Down
43 changes: 43 additions & 0 deletions src/dashboard/apps/core/factories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Dashboard core factories."""

import factory

from .models import DeliveryPoint, Entity


class EntityFactory(factory.django.DjangoModelFactory):
"""Factory class for creating instances of the Entity model."""

name = factory.Faker("company")

class Meta: # noqa: D106
model = Entity

@factory.post_generation
def users(self, create, extracted, **kwargs):
"""Method to add users after the entity is created."""
if not create or not extracted:
# Simple build, or nothing to add, do nothing.
return

# Add the iterable of groups using bulk addition
self.users.add(*extracted)


class DeliveryPointFactory(factory.django.DjangoModelFactory):
"""Factory class for creating instances of the DeliveryPoint model."""

class Meta: # noqa: D106
model = DeliveryPoint

provider_id = factory.Sequence(lambda n: "provider_%d" % n)

@factory.post_generation
def entities(self, create, extracted, **kwargs):
"""Method to add entities after the delivery point is created."""
if not create or not extracted:
# Simple build, or nothing to add, do nothing.
return

# Add the iterable of groups using bulk addition
self.entities.add(*extracted)
61 changes: 21 additions & 40 deletions src/dashboard/apps/core/tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
"""Dashboard core models tests."""

import pytest
from django.contrib.auth import get_user_model
from django.db import IntegrityError

from apps.core.models import DeliveryPoint, Entity
from apps.auth.factories import UserFactory
from apps.core.factories import DeliveryPointFactory, EntityFactory
from apps.core.models import Entity


@pytest.mark.django_db
def test_create_entity():
"""Tests the creation of an entity."""
User = get_user_model()
user1 = User.objects.create_user(username="user1", password="foo") # noqa: S106
user2 = User.objects.create_user(username="user2", password="foo") # noqa: S106
user1 = UserFactory()
user2 = UserFactory()

entity = Entity.objects.create(name="abc_entity")
entity.users.add(user1)
entity.users.add(user2)
entity.save()
entity = EntityFactory(name="entity_1234", users=(user1, user2))

# test users have been added.
assert entity.name == "abc_entity"
assert all(user in [user1, user2] for user in entity.users.all())
assert entity.name == "entity_1234"
assert all(user in entity.users.all() for user in [user1, user2])

# test created_at and updated_at have been updated.
assert entity.created_at is not None
Expand All @@ -35,12 +32,8 @@ def test_create_entity():
@pytest.mark.django_db
def test_update_entity():
"""Tests updating an entity."""
User = get_user_model()
user1 = User.objects.create_user(username="user1", password="foo") # noqa: S106

entity = Entity.objects.create(name="abc_entity")
entity.users.add(user1)
entity.save()
user1 = UserFactory()
entity = EntityFactory(users=(user1,))

# test user1 have been removed
entity.users.remove(user1)
Expand All @@ -54,55 +47,43 @@ def test_update_entity():
def test_create_delivery_point():
"""Tests the creation of a delivery point."""
# create users
User = get_user_model()
user1 = User.objects.create_user(username="user1", password="foo") # noqa: S106
user1 = UserFactory()

# create entities
entity1 = Entity.objects.create(name="entity_1")
entity1.users.add(user1)
entity1.save()

entity2 = Entity.objects.create(name="entity_2")
entity2.users.add(user1)
entity2.save()
entity1 = EntityFactory(users=(user1,))
entity2 = EntityFactory(users=(user1,))

# create delivery point
delivery_point = DeliveryPoint.objects.create(provider_id="provider_1234")
delivery_point.entities.add(entity1)
delivery_point.entities.add(entity2)
delivery_point.save()
delivery_point = DeliveryPointFactory(
provider_id="provider_1234", entities=(entity1, entity2)
)

assert delivery_point.provider_id == "provider_1234"
assert delivery_point.is_active is True

# test entities have been added to delivery point.
assert all(entity in [entity1, entity2] for entity in delivery_point.entities.all())
assert all(entity in delivery_point.entities.all() for entity in [entity1, entity2])

# test created_at and updated_at have been updated.
assert delivery_point.created_at is not None
assert delivery_point.updated_at is not None

# test IntegrityError: provider must not be null
with pytest.raises(IntegrityError):
DeliveryPoint.objects.create(provider_id=None)
DeliveryPointFactory(provider_id=None)


@pytest.mark.django_db
def test_update_delivery_point():
"""Tests updating a delivery point."""
# create users
User = get_user_model()
user1 = User.objects.create_user(username="user1", password="foo") # noqa: S106
user1 = UserFactory()

# create entity
entity1 = Entity.objects.create(name="entity_1")
entity1.users.add(user1)
entity1.save()
entity1 = EntityFactory(users=(user1,))

# create delivery point
delivery_point = DeliveryPoint.objects.create(provider_id="provider_1234")
delivery_point.entities.add(entity1)
delivery_point.save()
delivery_point = DeliveryPointFactory(entities=(entity1,))

# test entity1 have been removed
delivery_point.entities.remove(entity1)
Expand Down

0 comments on commit 1cfa47f

Please sign in to comment.