From de7c4a69e85af63022f44f6add6b0f3012aefebc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabor=20K=C3=B6rber?= Date: Thu, 23 Jan 2025 14:34:20 +0100 Subject: [PATCH] feat: examples and tests --- examples/celestials/README.md | 3 + examples/celestials/app/__init__.py | 0 examples/celestials/app/app.py | 7 ++ examples/celestials/app/factories.py | 47 +++++++++ examples/celestials/app/galaxy.py | 47 +++++++++ examples/celestials/app/models.py | 50 ++++++++++ examples/celestials/app/tests.py | 93 ++++++++++++++++++ examples/celestials/manage.py | 22 +++++ examples/celestials/project/__init__.py | 0 examples/celestials/project/asgi.py | 16 +++ examples/celestials/project/settings.py | 123 ++++++++++++++++++++++++ examples/celestials/project/urls.py | 22 +++++ examples/celestials/project/wsgi.py | 16 +++ examples/celestials/pyproject.toml | 10 ++ 14 files changed, 456 insertions(+) create mode 100644 examples/celestials/README.md create mode 100644 examples/celestials/app/__init__.py create mode 100644 examples/celestials/app/app.py create mode 100644 examples/celestials/app/factories.py create mode 100644 examples/celestials/app/galaxy.py create mode 100644 examples/celestials/app/models.py create mode 100644 examples/celestials/app/tests.py create mode 100644 examples/celestials/manage.py create mode 100644 examples/celestials/project/__init__.py create mode 100644 examples/celestials/project/asgi.py create mode 100644 examples/celestials/project/settings.py create mode 100644 examples/celestials/project/urls.py create mode 100644 examples/celestials/project/wsgi.py create mode 100644 examples/celestials/pyproject.toml diff --git a/examples/celestials/README.md b/examples/celestials/README.md new file mode 100644 index 0000000..5a01aaf --- /dev/null +++ b/examples/celestials/README.md @@ -0,0 +1,3 @@ +# Celestials Test Database + +The galaxy.Stars helper class can create a sun system as test data. diff --git a/examples/celestials/app/__init__.py b/examples/celestials/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/celestials/app/app.py b/examples/celestials/app/app.py new file mode 100644 index 0000000..a245a67 --- /dev/null +++ b/examples/celestials/app/app.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + +# Only include tests in your INSTALLED_APPS if you want to test against django models. + +class CommonTestsConfig(AppConfig): + name = 'tests.celestials' + label = 'celestials_tests' diff --git a/examples/celestials/app/factories.py b/examples/celestials/app/factories.py new file mode 100644 index 0000000..a456063 --- /dev/null +++ b/examples/celestials/app/factories.py @@ -0,0 +1,47 @@ +from . import models +import factory +import factory.fuzzy + + +class CelestialFactory(factory.django.DjangoModelFactory): + orbits = factory.LazyAttribute(lambda c: CelestialFactory(celestial_type=c.celestial_type - 1) if c.celestial_type and c.celestial_type > 1 else None) + name = factory.Faker('city') + # 1 sun, 7 planets, 3 moons, 4 asteroids, 5 stations + celestial_type = factory.Iterator([1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]) + weight = factory.fuzzy.FuzzyFloat(100.0, 100000.0) + size = factory.fuzzy.FuzzyFloat(1.0, 8.0) + + class Meta: + model = models.Celestial + +class PersonFactory(factory.DjangoModelFactory): + origin = factory.SubFactory(CelestialFactory) + first_name = factory.Faker('first_name') + last_name = factory.Faker('last_name') + age = factory.fuzzy.FuzzyInteger(9, 79) + + class Meta: + model = models.Person + +class SpaceportFactory(factory.DjangoModelFactory): + name = factory.LazyAttribute(lambda sp: f'Port {sp.celestial.name}') + celestial = factory.SubFactory(CelestialFactory, celestial_type=factory.Iterator([2,2,3,4,5])) + + class Meta: + model = models.Spaceport + +class VisitorFactory(factory.DjangoModelFactory): + person = factory.SubFactory(PersonFactory) + spaceport = factory.SubFactory(SpaceportFactory) + luggage_weight = factory.fuzzy.FuzzyFloat(1.0, 100.0) + + class Meta: + model = models.Visitor + +class CitizenFactory(factory.DjangoModelFactory): + planet = factory.SubFactory(CelestialFactory, celestial_type=2) + person = factory.SubFactory(PersonFactory, origin=factory.SelfAttribute('planet')) + clearance_level = factory.fuzzy.FuzzyInteger(0, 4) + class Meta: + model = models.Citizen + diff --git a/examples/celestials/app/galaxy.py b/examples/celestials/app/galaxy.py new file mode 100644 index 0000000..8f3569e --- /dev/null +++ b/examples/celestials/app/galaxy.py @@ -0,0 +1,47 @@ +from .factories import CelestialFactory, SpaceportFactory + + +class Stars: + + @classmethod + def create_sol(cls, context=None): + if context is None: + context = object() + + celestials = [CelestialFactory(name="Sol", celestial_type=1, size=100)] + context.sun = sun = celestials[0] + + context.planets = planets = [ + CelestialFactory(name='Mercur', celestial_type=2, orbits=sun, size=2.4), #0 + CelestialFactory(name='Venus', celestial_type=2, orbits=sun, size=6), + CelestialFactory(name='Terra', celestial_type=2, orbits=sun, size=6.4), #2 + CelestialFactory(name='Mars', celestial_type=2, orbits=sun, size=3.4), + CelestialFactory(name='Jupiter',celestial_type=2, orbits=sun, size=69.9), #4 + CelestialFactory(name='Saturn', celestial_type=2, orbits=sun, size=58.2), + CelestialFactory(name='Uranus', celestial_type=2, orbits=sun, size=25.4), #6 + CelestialFactory(name='Neptune',celestial_type=2, orbits=sun, size=24.6), + CelestialFactory(name='Pluto',celestial_type=3, orbits=sun, size=1.1), #8 + ] + celestials.extend(planets) + + context.moons = moons = [ + CelestialFactory(name='Luna', celestial_type=3, orbits=planets[2], size=1.7), #0 + CelestialFactory(name='Phobos', celestial_type=4, orbits=planets[3], size=0.006), + CelestialFactory(name='Deimos', celestial_type=4, orbits=planets[3], size=0.011), #2 + CelestialFactory(name='Io', celestial_type=3, orbits=planets[4], size=1.8), + CelestialFactory(name='Europa', celestial_type=3, orbits=planets[4], size=1.5), #4 + CelestialFactory(name='Ganymede', celestial_type=3, orbits=planets[4], size=2.6), + CelestialFactory(name='Callisto', celestial_type=3, orbits=planets[4], size=2.4), #6 + #... + CelestialFactory(name='Charon', celestial_type=4, orbits=planets[8], size=0.6) + ] + celestials.extend(moons) + context.celestials = celestials + + # create space ports + context.spaceports = [ + SpaceportFactory(celestial=planets[2], name="Houston IPS", ), + SpaceportFactory(celestial=moons[0], name='Copernicus'), + SpaceportFactory(celestial=planets[3], name='Utopia Planitia'), + SpaceportFactory(celestial=moons[2], name='Ares Station'), + ] diff --git a/examples/celestials/app/models.py b/examples/celestials/app/models.py new file mode 100644 index 0000000..004241f --- /dev/null +++ b/examples/celestials/app/models.py @@ -0,0 +1,50 @@ +from django.db import models +from django_records.records import RecordManager + +class Celestial(models.Model): + CELESTIAL_TYPES = ((0, 'Unknown'), + (1, 'Star'), + (2, 'Planet'), + (3, 'Planetoid'), + (4, 'Asteroid'), + (5, 'Station')) + orbits = models.ForeignKey('self', blank=True, null=True, related_name='orbitals', on_delete=models.CASCADE) + name = models.CharField(max_length=100) + celestial_type = models.IntegerField(choices=CELESTIAL_TYPES, default=int) + weight = models.FloatField(default=float) + size = models.FloatField(default=float) + + objects = RecordManager() + + @property + def is_moon(self): + return 5 > self.celestial_type > 1 and self.orbits and 5 > self.orbits.celestial_type > 1 + +class Spaceport(models.Model): + name = models.CharField(max_length=100) + celestial = models.ForeignKey(Celestial, related_name='spaceports', on_delete=models.CASCADE) + + objects = RecordManager() + +class Person(models.Model): + origin = models.ForeignKey(Celestial, related_name='children', blank=True, null=True, on_delete=models.CASCADE) + first_name = models.CharField(max_length=100) + last_name = models.CharField(max_length=100) + age = models.IntegerField(blank=True, null=True) + + objects = RecordManager() + +class Visitor(models.Model): + person = models.ForeignKey(Person, related_name='as_visitor', on_delete=models.CASCADE) + spaceport = models.ForeignKey(Spaceport, related_name='visitors', on_delete=models.CASCADE) + luggage_weight = models.FloatField(blank=True, null=True, default=float) + + objects = RecordManager() + +class Citizen(models.Model): + planet = models.ForeignKey(Celestial, related_name='citizens', on_delete=models.CASCADE) + person = models.ForeignKey(Person, related_name='citizenships', on_delete=models.CASCADE) + clearance_level = models.IntegerField(blank=True, null=True) + + objects = RecordManager() + diff --git a/examples/celestials/app/tests.py b/examples/celestials/app/tests.py new file mode 100644 index 0000000..6047cb4 --- /dev/null +++ b/examples/celestials/app/tests.py @@ -0,0 +1,93 @@ +from dataclasses import dataclass +from unittest.case import skipIf +from unittest import mock + +from django.db.models import F +from django.test.testcases import TestCase +from django.test.utils import tag + +from django_records.adjuncts import MutValue, FixedValue, PostProcess +from django_records.handlers import RecordDictHandler + + +try: + from .models import Celestial + from .galaxy import Stars + celestials_installed = True +except RuntimeError: + celestials_installed = False + + +@dataclass +class Entity: + id: int + + +@dataclass +class SpaceRock: + id: int + name: str + orbits_name: str + is_moon: bool + + +@tag('library') +@skipIf(not celestials_installed, "Celestials Testpackage not installed into INSTALLED_APPS.") +class TestQueryBuilder(TestCase): + + def setUp(self): + super().setUp() + Stars.create_sol(context=self) + + def test_records(self): + entities = Celestial.objects.filter(orbits__name='Sol', celestial_type__lte=4).records(Entity) + self.assertEqual(len(entities), len(self.planets)) + + # test whether we really return dataclass as result, even with first. + self.assertIsInstance(entities.first(), Entity) + + # find moons. test whether i can use entities to do an SQL query. works because i have only one key. + self.assertEqual(len(self.moons), Celestial.objects.filter(orbits__in=entities).count()) + + # this is pretty much the same as + self.assertEqual(len(self.moons), len(Celestial.objects.filter( + orbits__in=Celestial.objects.filter(orbits__name='Sol', celestial_type__lte=4)).values_list('id', flat=True))) + + def test_handler_dict(self): + entities = Celestial.objects.filter(orbits__name='Sol', celestial_type__lte=4).records(RecordDictHandler()) + self.assertEqual(len(entities), len(self.planets)) + self.assertIsInstance(entities.first(), dict) + + def test_MutValue(self): + + # this tests whether our own celestial type or the celestial type of what we orbit is correct for being a moon. parameter is a dictionary. + is_moon = lambda entry: True if 5 > (entry.get('celestial_type') or 0) > 1 and 5 > (entry.get('orbits_type') or 0) > 1 else False + + entities = Celestial.objects.records(SpaceRock, # we want our output to be a SpaceRock dataclass. + 'celestial_type', # we include the key celestial_type into our query. + id=FixedValue(None), # we blank out id to test FixedValue working. + orbits_name=F('orbits__name'), # we set our custom orbits_name to a related field value + orbits_type=F('orbits__celestial_type'), # our MutValue needs this data. + is_moon=MutValue(is_moon)) # MutValue over result + + self.assertEqual(len(entities), len(self.celestials)) + + for idx, entity in enumerate(entities): + dbdata = self.celestials[idx] + model = Celestial.objects.filter(id=dbdata.id).first() + self.assertEqual(entity.name, dbdata.name) + self.assertIsNone(entity.id) + self.assertEqual(entity.is_moon, model.is_moon) + + def test_post_process(self): + side_effect = lambda x:x + post_process_one = mock.Mock(side_effect=side_effect) + post_process_two = mock.Mock(side_effect=side_effect) + + entities = Celestial.objects.all().records(Entity, + post_process_one=PostProcess(post_process_one), + post_process_two=PostProcess(post_process_two)) + + self.assertEqual(len(entities), len(self.celestials)) + self.assertEqual(post_process_one.call_count, len(self.celestials)) + self.assertEqual(post_process_two.call_count, len(self.celestials)) diff --git a/examples/celestials/manage.py b/examples/celestials/manage.py new file mode 100644 index 0000000..7721919 --- /dev/null +++ b/examples/celestials/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/examples/celestials/project/__init__.py b/examples/celestials/project/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/celestials/project/asgi.py b/examples/celestials/project/asgi.py new file mode 100644 index 0000000..2db6c87 --- /dev/null +++ b/examples/celestials/project/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for project project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') + +application = get_asgi_application() diff --git a/examples/celestials/project/settings.py b/examples/celestials/project/settings.py new file mode 100644 index 0000000..11b47ab --- /dev/null +++ b/examples/celestials/project/settings.py @@ -0,0 +1,123 @@ +""" +Django settings for project project. + +Generated by 'django-admin startproject' using Django 5.1.5. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.1/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-sa2)s0st&l*h)3j&#(jk0oo$25uxed3=o=r$)jj76!8163+e5&' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'project.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'project.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/5.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.1/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/examples/celestials/project/urls.py b/examples/celestials/project/urls.py new file mode 100644 index 0000000..6f557a2 --- /dev/null +++ b/examples/celestials/project/urls.py @@ -0,0 +1,22 @@ +""" +URL configuration for project project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.1/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path + +urlpatterns = [ + path('admin/', admin.site.urls), +] diff --git a/examples/celestials/project/wsgi.py b/examples/celestials/project/wsgi.py new file mode 100644 index 0000000..7c2b6aa --- /dev/null +++ b/examples/celestials/project/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for project project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') + +application = get_wsgi_application() diff --git a/examples/celestials/pyproject.toml b/examples/celestials/pyproject.toml new file mode 100644 index 0000000..583dad3 --- /dev/null +++ b/examples/celestials/pyproject.toml @@ -0,0 +1,10 @@ +[project] +name = "celestials" +version = "0.1.0" +description = "Celestial Test App" +readme = "README.md" +requires-python = ">=3.12" +dependencies = ["django>=4", "django-records", "factory_boy"] + +[tool.uv.sources] +django-records = { path = "../.." }