feat: examples and tests

This commit is contained in:
Gabor Körber 2025-01-23 14:34:20 +01:00
parent e539aaf158
commit de7c4a69e8
14 changed files with 456 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# Celestials Test Database
The galaxy.Stars helper class can create a sun system as test data.

View File

View File

@ -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'

View File

@ -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

View File

@ -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'),
]

View File

@ -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()

View File

@ -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))

View File

@ -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()

View File

View File

@ -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()

View File

@ -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'

View File

@ -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),
]

View File

@ -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()

View File

@ -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 = "../.." }