feat: implement Fil-A-Management Django MVP
This commit is contained in:
commit
1127e7ecf4
66 files changed
+3774
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,143 @@
|
||||
import http.cookiejar
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from .support import ROOT, clean_environment
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
def prepare_database(directory):
|
||||
directory = Path(directory)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
password = secrets.token_urlsafe(24)
|
||||
env = clean_environment() | {
|
||||
"FAM_DATA_DIR": str(directory / "data"),
|
||||
"DJANGO_SECRET_KEY": secrets.token_urlsafe(64),
|
||||
"DJANGO_COOKIE_SECURE": "0",
|
||||
"DJANGO_ALLOWED_HOSTS": "127.0.0.1,localhost",
|
||||
"FAM_TEST_PASSWORD": password,
|
||||
}
|
||||
|
||||
def manage(*args):
|
||||
result = subprocess.run(
|
||||
[sys.executable, "manage.py", *args],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stdout + result.stderr)
|
||||
return result.stdout
|
||||
|
||||
manage("migrate", "--noinput")
|
||||
manage("seed_catalog")
|
||||
manage("collectstatic", "--noinput", "--verbosity", "0")
|
||||
manage(
|
||||
"shell",
|
||||
"-c",
|
||||
"import os; from django.contrib.auth import get_user_model; U=get_user_model(); U.objects.create_user('synthetic-one',password=os.environ['FAM_TEST_PASSWORD']); U.objects.create_user('synthetic-two',password=os.environ['FAM_TEST_PASSWORD'])",
|
||||
)
|
||||
return env, password, manage
|
||||
|
||||
|
||||
class LiveServer:
|
||||
def __init__(self, env, directory):
|
||||
self.env = env
|
||||
self.port = free_port()
|
||||
self.url = f"http://127.0.0.1:{self.port}"
|
||||
self.log = Path(directory) / "http-server.log"
|
||||
self.process = None
|
||||
self.handle = None
|
||||
|
||||
def start(self):
|
||||
self.handle = self.log.open("a")
|
||||
executable = str(Path(sys.executable).with_name("gunicorn"))
|
||||
self.process = subprocess.Popen(
|
||||
[
|
||||
executable,
|
||||
"config.wsgi:application",
|
||||
"--bind",
|
||||
f"127.0.0.1:{self.port}",
|
||||
"--workers",
|
||||
"1",
|
||||
"--worker-class",
|
||||
"gthread",
|
||||
"--threads",
|
||||
"4",
|
||||
"--no-control-socket",
|
||||
"--forwarded-allow-ips=",
|
||||
],
|
||||
cwd=ROOT,
|
||||
env=self.env,
|
||||
stdout=self.handle,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
for _ in range(100):
|
||||
try:
|
||||
with urllib.request.urlopen(self.url + "/healthz/", timeout=1) as response:
|
||||
if json.load(response) == {"status": "ok"}:
|
||||
return
|
||||
except (OSError, ValueError):
|
||||
if self.process.poll() is not None:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
self.stop()
|
||||
raise RuntimeError(self.log.read_text())
|
||||
|
||||
def stop(self):
|
||||
if self.process and self.process.poll() is None:
|
||||
self.process.terminate()
|
||||
try:
|
||||
self.process.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.process.kill()
|
||||
self.process.wait(timeout=5)
|
||||
if self.handle:
|
||||
self.handle.close()
|
||||
|
||||
|
||||
class WebSession:
|
||||
def __init__(self, base):
|
||||
self.base = base
|
||||
self.cookies = http.cookiejar.CookieJar()
|
||||
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookies))
|
||||
|
||||
def request(self, path, data=None):
|
||||
body = urllib.parse.urlencode(data).encode() if data is not None else None
|
||||
try:
|
||||
response = self.opener.open(self.base + path, body, timeout=10)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
return response.status, response.read().decode(), response.headers, response.url
|
||||
|
||||
def get(self, path):
|
||||
return self.request(path)
|
||||
|
||||
def post(self, path, data):
|
||||
status, html, _, _ = self.get(path)
|
||||
if status != 200:
|
||||
raise AssertionError(f"GET {path}: {status}")
|
||||
token = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"', html).group(1)
|
||||
return self.request(path, data | {"csrfmiddlewaretoken": token})
|
||||
|
||||
def login(self, username, password):
|
||||
status, _, _, url = self.post("/anmelden/", {"username": username, "password": password})
|
||||
if status != 200 or not url.endswith("/bestand/"):
|
||||
raise AssertionError("Synthetic HTTP login failed")
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Disposable UI fixture with synthetic accounts. Never use against real data."""
|
||||
|
||||
import json
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .http_support import LiveServer, prepare_database
|
||||
|
||||
|
||||
def main():
|
||||
directory = Path(sys.argv[1]).resolve()
|
||||
if (directory / "data").exists():
|
||||
raise SystemExit("Bitte ein neues, leeres Demo-Verzeichnis verwenden.")
|
||||
env, _, manage = prepare_database(directory)
|
||||
metadata = directory / "browser.json"
|
||||
env["FAM_SESSION_PATH"] = str(metadata)
|
||||
manage(
|
||||
"shell",
|
||||
"-c",
|
||||
"import os,json; from pathlib import Path; from django.contrib.auth import get_user_model; from django.test import Client; from filament.models import Variant,InventoryItem,OrderItem,Printer; from filament.services import add_quantity; a=get_user_model().objects.get(username='synthetic-one'); b=get_user_model().objects.get(username='synthetic-two'); vs=list(Variant.objects.filter(spool_type='spool')); [add_quantity(InventoryItem,a,v,n+1) for n,v in enumerate(vs[:3])]; add_quantity(OrderItem,a,vs[0],2); add_quantity(OrderItem,b,vs[0],1); Printer.objects.create(owner=a,manufacturer='Bambu Lab',model='P1S',name='Werkstatt'); c=Client(); c.force_login(a); Path(os.environ['FAM_SESSION_PATH']).write_text(json.dumps({'sessionid':c.cookies['sessionid'].value}))",
|
||||
)
|
||||
server = LiveServer(env, directory)
|
||||
|
||||
def stop(*_):
|
||||
server.stop()
|
||||
raise SystemExit(0)
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
try:
|
||||
server.start()
|
||||
state = json.loads(metadata.read_text()) | {"url": server.url}
|
||||
metadata.write_text(json.dumps(state))
|
||||
metadata.chmod(0o600)
|
||||
print(f"FAM_DEMO_READY {server.url} · synthetic fixture {directory}", flush=True)
|
||||
while True:
|
||||
time.sleep(1)
|
||||
finally:
|
||||
server.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Synthetic, isolated fixtures. Never access production Docker containers or data."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def clean_environment():
|
||||
env = os.environ.copy()
|
||||
for name in (
|
||||
"PYTHONPATH",
|
||||
"VIRTUAL_ENV",
|
||||
"DJANGO_SETTINGS_MODULE",
|
||||
"DJANGO_SECRET_KEY",
|
||||
"DJANGO_SECRET_KEY_FILE",
|
||||
"GIT_DIR",
|
||||
"GIT_WORK_TREE",
|
||||
):
|
||||
env.pop(name, None)
|
||||
return env
|
||||
|
||||
|
||||
def git_fixture(directory):
|
||||
repo = directory / "repository"
|
||||
repo.mkdir()
|
||||
paths = (
|
||||
subprocess.check_output(
|
||||
["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], cwd=ROOT
|
||||
)
|
||||
.decode()
|
||||
.split("\0")
|
||||
)
|
||||
for name in paths:
|
||||
if not name:
|
||||
continue
|
||||
source, destination = ROOT / name, repo / name
|
||||
if source.is_file():
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source, destination)
|
||||
|
||||
def git(*args):
|
||||
return (
|
||||
subprocess.check_output(
|
||||
[
|
||||
"git",
|
||||
"-c",
|
||||
"user.name=FAM Synthetic Test",
|
||||
"-c",
|
||||
"user.email=test@example.invalid",
|
||||
*args,
|
||||
],
|
||||
cwd=repo,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
.decode()
|
||||
.strip()
|
||||
)
|
||||
|
||||
git("init", "-b", "main")
|
||||
(repo / "revision-marker.txt").write_text("first")
|
||||
git("add", ".")
|
||||
git("commit", "-m", "Synthetic revision one")
|
||||
first = git("rev-parse", "HEAD")
|
||||
git("tag", "mvp-test")
|
||||
(repo / "revision-marker.txt").write_text("second")
|
||||
git("add", "revision-marker.txt")
|
||||
git("commit", "-m", "Synthetic revision two")
|
||||
second = git("rev-parse", "HEAD")
|
||||
return repo, first, second
|
||||
@@ -0,0 +1,92 @@
|
||||
import secrets
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from .support import ROOT, clean_environment, git_fixture
|
||||
|
||||
|
||||
class BootstrapTests(unittest.TestCase):
|
||||
def test_real_git_start_tag_restart_and_commit_switch_preserve_database(self):
|
||||
start = ROOT / "start.sh"
|
||||
self.assertTrue(start.is_file(), "Git-basierter Start fehlt")
|
||||
with tempfile.TemporaryDirectory(prefix="fam-bootstrap-") as directory:
|
||||
directory = Path(directory)
|
||||
repo, first, second = git_fixture(directory)
|
||||
bundle = directory / "repository.bundle"
|
||||
subprocess.run(
|
||||
["git", "bundle", "create", str(bundle), "--all"],
|
||||
cwd=repo,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
env = clean_environment() | {
|
||||
"GIT_REPO_URL": bundle.as_uri(),
|
||||
"GIT_REVISION": "mvp-test",
|
||||
"FAM_ALLOW_LOCAL_GIT": "1",
|
||||
"FAM_RUNTIME_DIR": str(directory / "runtime"),
|
||||
"FAM_DATA_DIR": str(directory / "data"),
|
||||
"FAM_GIT_HELPERS": str(ROOT / "docker"),
|
||||
"SEED_CATALOG": "1",
|
||||
"DJANGO_COOKIE_SECURE": "0",
|
||||
"FAM_TEST_PASSWORD": secrets.token_urlsafe(24),
|
||||
}
|
||||
|
||||
def boot(code):
|
||||
result = subprocess.run(
|
||||
["sh", str(start), "python", "manage.py", "shell", "-c", code],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=180,
|
||||
)
|
||||
if result.returncode:
|
||||
self.fail(result.stdout + result.stderr)
|
||||
return result.stdout
|
||||
|
||||
boot(
|
||||
"import os; from django.contrib.auth import get_user_model; from filament.models import Variant,InventoryItem,OrderItem,Printer; from filament.services import add_quantity; U=get_user_model(); a=U.objects.create_user('synthetic-one',password=os.environ['FAM_TEST_PASSWORD']); b=U.objects.create_user('synthetic-two',password=os.environ['FAM_TEST_PASSWORD']); v=Variant.objects.filter(spool_type='spool').first(); add_quantity(InventoryItem,a,v,2); add_quantity(InventoryItem,a,v,1); add_quantity(OrderItem,a,v,2); add_quantity(OrderItem,b,v,1); Printer.objects.create(owner=a,manufacturer='Test',model='Synthetic'); print('CREATED_SYNTHETIC_DATA')"
|
||||
)
|
||||
secret = (directory / "data/secret.key").read_bytes()
|
||||
verify = "from filament.models import InventoryItem,OrderItem,Printer; from django.db.models import Sum; print('PERSISTENCE='+str((InventoryItem.objects.get().quantity,OrderItem.objects.aggregate(n=Sum('quantity'))['n'],Printer.objects.count())))"
|
||||
self.assertIn("PERSISTENCE=(3, 3, 1)", boot(verify))
|
||||
self.assertEqual(
|
||||
subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=directory / "runtime/app")
|
||||
.decode()
|
||||
.strip(),
|
||||
first,
|
||||
)
|
||||
env["GIT_REVISION"] = second
|
||||
self.assertIn("PERSISTENCE=(3, 3, 1)", boot(verify))
|
||||
self.assertEqual(
|
||||
subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=directory / "runtime/app")
|
||||
.decode()
|
||||
.strip(),
|
||||
second,
|
||||
)
|
||||
env["GIT_REVISION"] = "main"
|
||||
self.assertIn("PERSISTENCE=(3, 3, 1)", boot(verify))
|
||||
self.assertEqual((directory / "data/secret.key").read_bytes(), secret)
|
||||
boot(
|
||||
"from django.core.management import call_command; call_command('backup_sqlite', '"
|
||||
+ str(directory / "data/snapshot.sqlite3")
|
||||
+ "')"
|
||||
)
|
||||
self.assertTrue((directory / "data/snapshot.sqlite3").is_file())
|
||||
print(
|
||||
"Bootstrap: tag, repeated start, commit, branch, persistent data and backup verified."
|
||||
)
|
||||
|
||||
def test_credential_bearing_urls_fail_without_printing_credentials(self):
|
||||
self.assertTrue((ROOT / "start.sh").is_file())
|
||||
marker = secrets.token_hex(16)
|
||||
env = clean_environment() | {
|
||||
"GIT_REPO_URL": f"https://user:{marker}@example.invalid/repo.git"
|
||||
}
|
||||
result = subprocess.run(
|
||||
["sh", str(ROOT / "start.sh")], env=env, capture_output=True, text=True, timeout=20
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertNotIn(marker, result.stdout + result.stderr)
|
||||
self.assertIn("Zugangsdaten", result.stderr)
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Opt-in REAL Docker acceptance. Only uniquely named synthetic resources are touched."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from .support import ROOT, git_fixture
|
||||
|
||||
|
||||
@unittest.skipUnless(
|
||||
os.environ.get("FAM_TEST_DOCKER") == "1",
|
||||
"Real Docker check: set FAM_TEST_DOCKER=1 on an authorized development Docker host",
|
||||
)
|
||||
class ContainerPersistenceTests(unittest.TestCase):
|
||||
def test_container_restart_and_revision_recreation_preserve_volume(self):
|
||||
name = "fam-mvp-test-" + uuid.uuid4().hex[:12]
|
||||
volume, image = name + "-data", name + ":local"
|
||||
|
||||
def docker(*args, timeout=120):
|
||||
result = subprocess.run(
|
||||
["docker", *args], cwd=ROOT, text=True, capture_output=True, timeout=timeout
|
||||
)
|
||||
if result.returncode:
|
||||
self.fail(result.stdout + result.stderr)
|
||||
return result.stdout.strip()
|
||||
|
||||
# Do not silently skip an explicitly requested check if the daemon is unavailable.
|
||||
docker("info", "--format", "{{.ServerVersion}}")
|
||||
with tempfile.TemporaryDirectory(prefix="fam-container-") as directory:
|
||||
directory = Path(directory)
|
||||
repo, first, second = git_fixture(directory)
|
||||
bundle = directory / "repository.bundle"
|
||||
subprocess.run(
|
||||
["git", "bundle", "create", str(bundle), "--all"],
|
||||
cwd=repo,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
docker("build", "--tag", image, ".", timeout=600)
|
||||
try:
|
||||
docker("volume", "create", volume)
|
||||
|
||||
def start(revision):
|
||||
docker(
|
||||
"run",
|
||||
"--detach",
|
||||
"--name",
|
||||
name,
|
||||
"--security-opt",
|
||||
"no-new-privileges:true",
|
||||
"--env",
|
||||
"GIT_REPO_URL=file:///fixtures/repository.bundle",
|
||||
"--env",
|
||||
"FAM_ALLOW_LOCAL_GIT=1",
|
||||
"--env",
|
||||
"GIT_REVISION=" + revision,
|
||||
"--env",
|
||||
"SEED_CATALOG=1",
|
||||
"--env",
|
||||
"DJANGO_COOKIE_SECURE=0",
|
||||
"--mount",
|
||||
"type=volume,source=" + volume + ",target=/data",
|
||||
"--mount",
|
||||
"type=bind,source="
|
||||
+ str(bundle)
|
||||
+ ",target=/fixtures/repository.bundle,readonly",
|
||||
image,
|
||||
)
|
||||
|
||||
def ready():
|
||||
for _ in range(150):
|
||||
state = docker(
|
||||
"inspect",
|
||||
"--format",
|
||||
"{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{end}}",
|
||||
name,
|
||||
)
|
||||
if state == "running healthy":
|
||||
return
|
||||
if state.startswith("exited"):
|
||||
break
|
||||
time.sleep(2)
|
||||
self.fail("Synthetic container not healthy: " + docker("logs", name))
|
||||
|
||||
def manage(code):
|
||||
return docker(
|
||||
"exec",
|
||||
"--user",
|
||||
"fam",
|
||||
name,
|
||||
"/opt/fam/venv/bin/python",
|
||||
"/opt/fam/app/manage.py",
|
||||
"shell",
|
||||
"-c",
|
||||
code,
|
||||
)
|
||||
|
||||
start(first)
|
||||
ready()
|
||||
manage(
|
||||
"import secrets; from django.contrib.auth import get_user_model; from filament.models import Variant,InventoryItem,OrderItem; from filament.services import add_quantity; U=get_user_model(); a=U.objects.create_user('synthetic-one',password=secrets.token_urlsafe(24)); b=U.objects.create_user('synthetic-two',password=secrets.token_urlsafe(24)); v=Variant.objects.first(); add_quantity(InventoryItem,a,v,2); add_quantity(InventoryItem,a,v,1); add_quantity(OrderItem,a,v,2); add_quantity(OrderItem,b,v,1)"
|
||||
)
|
||||
check = "from filament.models import InventoryItem,OrderItem; from django.db.models import Sum; assert InventoryItem.objects.get().quantity==3; assert OrderItem.objects.aggregate(n=Sum('quantity'))['n']==3; print('PERSISTENCE_OK')"
|
||||
self.assertIn("PERSISTENCE_OK", manage(check))
|
||||
docker("restart", name)
|
||||
ready()
|
||||
self.assertIn("PERSISTENCE_OK", manage(check))
|
||||
docker("rm", "--force", name)
|
||||
start(second)
|
||||
ready()
|
||||
self.assertIn("PERSISTENCE_OK", manage(check))
|
||||
self.assertEqual(
|
||||
docker(
|
||||
"exec",
|
||||
"--user",
|
||||
"fam",
|
||||
name,
|
||||
"git",
|
||||
"-C",
|
||||
"/opt/fam/app",
|
||||
"rev-parse",
|
||||
"HEAD",
|
||||
),
|
||||
second,
|
||||
)
|
||||
manage(
|
||||
"from pathlib import Path; rows=[p for p in Path('/proc').glob('[0-9]*') if any(a.endswith(b'/gunicorn') for a in (p/'cmdline').read_bytes().split(bytes([0])))]; assert rows; assert all('Uid:\t10001\t10001\t10001\t10001' in (p/'status').read_text() for p in rows); print('UNPRIVILEGED_SERVER_OK')"
|
||||
)
|
||||
print(
|
||||
"REAL Docker: image build, two accounts, container restart, revision recreation and named-volume persistence verified."
|
||||
)
|
||||
finally:
|
||||
# Exact, random test resources only. No compose down, daemon cleanup or existing services.
|
||||
subprocess.run(["docker", "rm", "--force", name], capture_output=True)
|
||||
subprocess.run(["docker", "volume", "rm", volume], capture_output=True)
|
||||
subprocess.run(["docker", "image", "rm", image], capture_output=True)
|
||||
@@ -0,0 +1,83 @@
|
||||
import re
|
||||
import tempfile
|
||||
import unittest
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from .http_support import LiveServer, WebSession, prepare_database
|
||||
|
||||
|
||||
class RealHTTPTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory(prefix="fam-http-")
|
||||
self.env, self.password, self.manage = prepare_database(self.directory.name)
|
||||
self.server = LiveServer(self.env, self.directory.name)
|
||||
self.server.start()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.addCleanup(self.server.stop)
|
||||
self.alice = WebSession(self.server.url)
|
||||
self.bob = WebSession(self.server.url)
|
||||
self.alice.login("synthetic-one", self.password)
|
||||
self.bob.login("synthetic-two", self.password)
|
||||
|
||||
def selection(self, quantity=1, spool="spool"):
|
||||
# IDs are discovered from actual rendered forms, not guessed from seed ordering.
|
||||
html = self.alice.get("/bestand/hinzufuegen/")[1]
|
||||
manufacturer = re.search(r'<option value="(\d+)"', html).group(1)
|
||||
html = self.alice.post(
|
||||
"/bestand/hinzufuegen/", {"manufacturer": manufacturer, "action": "filter"}
|
||||
)[1]
|
||||
product = re.search(
|
||||
r'<select name="product_type".*?<option value="(\d+)"', html, re.S
|
||||
).group(1)
|
||||
html = self.alice.post(
|
||||
"/bestand/hinzufuegen/",
|
||||
{"manufacturer": manufacturer, "product_type": product, "action": "filter"},
|
||||
)[1]
|
||||
color = re.search(r'<select name="color".*?<option value="(\d+)"', html, re.S).group(1)
|
||||
return {
|
||||
"manufacturer": manufacturer,
|
||||
"product_type": product,
|
||||
"color": color,
|
||||
"spool_type": spool,
|
||||
"quantity": quantity,
|
||||
}
|
||||
|
||||
def test_two_accounts_privacy_shared_totals_static_and_server_restart(self):
|
||||
payload = self.selection(2)
|
||||
self.assertEqual(self.alice.post("/bestand/hinzufuegen/", payload)[0], 200)
|
||||
self.alice.post("/bestand/hinzufuegen/", payload | {"quantity": 1})
|
||||
html = self.alice.get("/bestand/")[1]
|
||||
self.assertIn('class="quantity">3</td>', html)
|
||||
edit_url = re.search(r'href="(/bestand/\d+/bearbeiten/)"', html).group(1)
|
||||
self.assertEqual(self.bob.get(edit_url)[0], 404)
|
||||
self.assertNotIn('class="quantity">3</td>', self.bob.get("/bestand/")[1])
|
||||
self.alice.post("/bestellung/hinzufuegen/", payload)
|
||||
self.bob.post("/bestellung/hinzufuegen/", payload | {"quantity": 1})
|
||||
html = self.bob.get("/bestellung/")[1]
|
||||
self.assertIn('class="quantity">3</td>', html)
|
||||
self.assertIn("synthetic-one: <strong>2</strong>", html)
|
||||
self.assertIn("synthetic-two: <strong>1</strong>", html)
|
||||
css = re.search(r'href="(/static/[^"]+\.css)"', html).group(1)
|
||||
self.assertEqual(self.alice.get(css)[0], 200)
|
||||
self.assertIn("text/css", self.alice.get(css)[2]["Content-Type"])
|
||||
self.server.stop()
|
||||
self.server.start()
|
||||
self.assertIn('class="quantity">3</td>', self.alice.get("/bestand/")[1])
|
||||
self.assertIn('class="quantity">3</td>', self.bob.get("/bestellung/")[1])
|
||||
print(
|
||||
"HTTP: separate logins, private stock, 2+1 aggregation, CSS and Gunicorn restart verified."
|
||||
)
|
||||
|
||||
def test_parallel_additions_do_not_lose_quantities(self):
|
||||
payload = self.selection()
|
||||
clients = [WebSession(self.server.url) for _ in range(6)]
|
||||
for client in clients:
|
||||
client.login("synthetic-one", self.password)
|
||||
|
||||
def add(client):
|
||||
return client.post("/bestand/hinzufuegen/", payload)[0]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=6) as pool:
|
||||
self.assertEqual(list(pool.map(add, clients)), [200] * 6)
|
||||
self.assertIn('class="quantity">6</td>', self.alice.get("/bestand/")[1])
|
||||
print("HTTP: six simultaneous additions, one position, quantity six verified.")
|
||||
Reference in new issue
Block a user