Skip to content

Commit

Permalink
tools: add generate_fixtures command
Browse files Browse the repository at this point in the history
  • Loading branch information
mik3y committed Jul 19, 2022
1 parent 18ff8e2 commit 65bf468
Show file tree
Hide file tree
Showing 8 changed files with 22,363 additions and 102,256 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ docs/build
### pykeg
build
dist
test-db.sqlite
9 changes: 9 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
fixtures: export KEGBOT_DATABASE_URL = sqlite:///test-db.sqlite
fixtures: export KEGBOT_BASE_URL = http://fixture.example.com/
fixtures: export KEGBOT_ENV = test
fixtures:
rm -f test-db.sqlite
bin/kegbot generate_fixtures
rm -f test-db.sqlite

.PHONY: fixtures
32 changes: 31 additions & 1 deletion poetry.lock

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

11 changes: 6 additions & 5 deletions pykeg/core/backend_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,25 @@
class BackendsFixtureTestCase(TransactionTestCase):
"""Test backened using fixture (demo) data."""

fixtures = ["testdata/full_demo_site.json"]
fixtures = ["testdata/demo-site.json"]

def test_delete_keg(self):
site = models.KegbotSite.get()
original_stats = site.get_stats()
self.assertEqual(755, original_stats["total_pours"])
self.assertEqual(50, original_stats["total_pours"])

keg = models.Keg.objects.get(pk=2)
keg_stats = keg.get_stats()
keg_drinks = keg.drinks.all()
self.assertEqual(185, len(keg_drinks))
self.assertEqual(16, len(keg_drinks))
keg.cancel()

stats = site.get_stats()
self.assertEqual(755 - 185, stats["total_pours"])
self.assertEqual(
self.assertEqual(34, stats["total_pours"])
self.assertAlmostEqual(
original_stats["total_volume_ml"] - keg_stats["total_volume_ml"],
stats["total_volume_ml"],
places=6,
)


Expand Down
79 changes: 79 additions & 0 deletions pykeg/core/management/commands/generate_fixtures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import datetime
import itertools
import logging

from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from freezegun import freeze_time

from pykeg.core import defaults, models

logger = logging.getLogger(__name__)

FAKE_TIME = "2022-03-04"
FIXTURE_PASSWORD = "!unusable-fixture-user-password"
FIXTURE_OUTPUT_FILENAME = "testdata/demo-site.json"


class Command(BaseCommand):
f"""Generates the file {FIXTURE_OUTPUT_FILENAME} with fake data."""

@freeze_time("2022-03-04")
def handle(self, *args, **options):
if settings.KEGBOT_ENV != "test":
raise ValueError("Can only run this command in test mode!")
call_command("migrate")
self.create_objects()
call_command(
"dumpdata",
"core",
format="json",
indent=2,
output="testdata/demo-site.json",
)

def create_objects(self):
defaults.set_defaults(set_is_setup=True, create_controller=True)
user = models.User.objects.create(
username="admin", email="[email protected]", is_superuser=True, is_staff=True
)
guest_user = models.User.objects.get(username="guest")

# If we call `.set_unusable_password()`, we'll get a new random (unusable)
# password every time this script is run. The password for the fake user
# isn't important either way in tests, so just crib an unusable password here.
# (It's not documented, but Django should treat a prefix of "!" as unusable.)
user.password = FIXTURE_PASSWORD
user.save()
guest_user.password = FIXTURE_PASSWORD
guest_user.save()

producer1 = models.BeverageProducer.objects.create(name="Test Producer 1")
producer2 = models.BeverageProducer.objects.create(name="Test Producer 2")
beverage1 = models.Beverage.objects.create(name="Test Beverage 1", producer=producer1)
beverage2 = models.Beverage.objects.create(name="Test Beverage 2", producer=producer2)

keg1 = models.Keg.start_keg("kegboard.flow0", beverage1)
keg2 = models.Keg.start_keg("kegboard.flow1", beverage2)

users = {"alice": None, "bob": None, "carol": None, "mallory": None}
for username in users.keys():
user = models.User.create_new_user(username=username, email=f"{username}@example.com")
user.password = FIXTURE_PASSWORD
user.activation_key = ""
user.save()
users[username] = user

delay_generator = itertools.cycle([1, 2, 4, 3, 16, 1440])
tick_generator = itertools.cycle([120, 200, 300, 500, 25, 500])
meter_generator = itertools.cycle(["kegboard.flow0", "kegboard.flow0", "kegboard.flow1"])
user_generator = itertools.cycle(users.values())
with freeze_time(FAKE_TIME) as frozen_datetime:
for _ in range(50):
user = next(user_generator)
delay = next(delay_generator)
ticks = next(tick_generator)
meter = next(meter_generator)
models.Drink.record_drink(meter, ticks, username=user.username)
frozen_datetime.tick(delta=datetime.timedelta(minutes=delay))
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ addict = "*"
gevent = "*"
psycopg2 = "*"
future = "^0.18.2"
freezegun = "^1.2.1"

[tool.poetry.dev-dependencies]
black = "*"
Expand Down
Loading

0 comments on commit 65bf468

Please sign in to comment.