Repository navigation
Expand file tree
/
Copy pathe2e.py
More file actions
2556 lines (2250 loc) · 86.5 KB
/
Copy pathe2e.py
File metadata and controls
2556 lines (2250 loc) · 86.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Cross-platform local E2E environment for the Analog coffee card stack.
This script owns the whole local loop:
docker compose (MSSQL + MailHog) -> analog-core backend -> seed data
-> iOS simulator / Android emulator -> mobile_app via `flutter run`
It is intentionally dependency-free (Python standard library only) so it works
on macOS, Linux and Windows. Use `./e2e <command>` on macOS/Linux and
`e2e.cmd <command>` on Windows. `make <target>` is a thin wrapper for people who
already have GNU make.
See README.md for the quick start and LOCAL-E2E.md for the detailed flow.
"""
from __future__ import annotations
import argparse
import json
import os
import quopri
import re
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
from collections import deque
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple
VERSION = "1.0.0"
MIN_PYTHON = (3, 9)
ROOT = Path(__file__).resolve().parent
# ---------------------------------------------------------------------------
# Console
# ---------------------------------------------------------------------------
class E2EException(RuntimeError):
"""A user-facing error. The CLI prints the message without a traceback."""
class Console:
def __init__(self, color: bool = True, verbose: bool = False) -> None:
self.verbose = verbose
self.color = (
color
and sys.stdout.isatty()
and os.environ.get("NO_COLOR") is None
and os.name != "nt"
)
def _wrap(self, code: str, text: str) -> str:
if not self.color:
return text
return f"\033[{code}m{text}\033[0m"
def log(self, message: str) -> None:
print(f"{self._wrap('1;34', '==>')} {message}", flush=True)
def ok(self, message: str) -> None:
print(f"{self._wrap('1;32', '==>')} {message}", flush=True)
def warn(self, message: str) -> None:
print(f"{self._wrap('1;33', '==>')} {message}", file=sys.stderr, flush=True)
def error(self, message: str) -> None:
print(f"{self._wrap('1;31', '==>')} {message}", file=sys.stderr, flush=True)
def plain(self, message: str = "") -> None:
print(message, flush=True)
VERBOSE = False
# ---------------------------------------------------------------------------
# Small process / text helpers
# ---------------------------------------------------------------------------
def cmdline(cmd: Sequence[Any]) -> str:
return shlex.join([str(part) for part in cmd])
def tail_text(text: str, lines: int = 40) -> str:
return "\n".join(text.splitlines()[-lines:])
def tail_path(path: Path, lines: int = 40) -> str:
try:
with path.open("r", encoding="utf-8", errors="replace") as handle:
return "\n".join(deque(handle, maxlen=lines)).rstrip("\n")
except OSError:
return ""
def run(
cmd: Sequence[Any],
*,
cwd: Optional[Path] = None,
env: Optional[Dict[str, str]] = None,
input: Optional[str] = None,
check: bool = True,
capture: bool = False,
timeout: Optional[float] = None,
log_path: Optional[Path] = None,
) -> subprocess.CompletedProcess:
"""Run a command, optionally capturing output or writing it to a log file."""
argv = [str(part) for part in cmd]
if VERBOSE:
print(f"$ {cmdline(argv)}", file=sys.stderr, flush=True)
log_handle = None
try:
if log_path is not None:
log_path.parent.mkdir(parents=True, exist_ok=True)
log_handle = log_path.open("w", encoding="utf-8", errors="replace")
stdout: Any = log_handle
stderr: Any = subprocess.STDOUT
elif capture:
stdout = subprocess.PIPE
stderr = subprocess.STDOUT
else:
stdout = None
stderr = None
proc = subprocess.run(
argv,
cwd=str(cwd) if cwd is not None else None,
env=env,
input=input,
stdout=stdout,
stderr=stderr,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
)
except FileNotFoundError as exc:
raise E2EException(
f"Command not found: {argv[0]}. Install it and make sure it is on PATH."
) from exc
except subprocess.TimeoutExpired as exc:
raise E2EException(
f"Command timed out after {timeout:g}s: {cmdline(argv)}"
) from exc
finally:
if log_handle is not None:
log_handle.close()
if check and proc.returncode != 0:
detail = ""
if capture and proc.stdout:
detail = "\n" + tail_text(proc.stdout)
elif log_path is not None:
detail = "\n" + tail_path(log_path)
raise E2EException(
f"Command failed (exit {proc.returncode}): {cmdline(argv)}{detail}"
)
return proc
def run_capture(
cmd: Sequence[Any],
*,
cwd: Optional[Path] = None,
env: Optional[Dict[str, str]] = None,
input: Optional[str] = None,
check: bool = True,
timeout: Optional[float] = None,
) -> str:
proc = run(
cmd,
cwd=cwd,
env=env,
input=input,
check=check,
capture=True,
timeout=timeout,
)
return proc.stdout or ""
def require(name: str, hint: Optional[str] = None) -> str:
path = shutil.which(name)
if path:
return path
message = f"Missing required command: {name}"
if hint:
message += f"\n {hint}"
raise E2EException(message)
def command_argv(name: str, *args: Any) -> List[str]:
"""Resolve an executable, working around Windows .bat/.cmd shims (flutter)."""
exe = require(name)
if os.name == "nt" and exe.lower().endswith((".bat", ".cmd")):
return ["cmd.exe", "/d", "/c", exe, *[str(arg) for arg in args]]
return [exe, *[str(arg) for arg in args]]
def which(name: str) -> Optional[str]:
return shutil.which(name)
# ---------------------------------------------------------------------------
# HTTP helpers
# ---------------------------------------------------------------------------
def http_request(
method: str,
url: str,
*,
body: Optional[Any] = None,
headers: Optional[Dict[str, str]] = None,
timeout: float = 5.0,
) -> Tuple[int, bytes]:
data: Optional[bytes] = None
request_headers: Dict[str, str] = dict(headers or {})
if body is not None:
if isinstance(body, (dict, list)):
data = json.dumps(body).encode("utf-8")
request_headers.setdefault("Content-Type", "application/json")
elif isinstance(body, str):
data = body.encode("utf-8")
else:
data = bytes(body)
request = urllib.request.Request(
url, data=data, headers=request_headers, method=method
)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, response.read()
except urllib.error.HTTPError as exc:
return exc.code, exc.read()
except urllib.error.URLError as exc:
raise E2EException(f"HTTP {method} {url} failed: {exc.reason}") from exc
def http_ok(url: str, timeout: float = 2.0) -> bool:
try:
status, _ = http_request("GET", url, timeout=timeout)
return 200 <= status < 500
except Exception:
return False
def http_json(method: str, url: str, *, timeout: float = 5.0) -> Any:
status, payload = http_request(method, url, timeout=timeout)
if status >= 400:
raise E2EException(f"HTTP {method} {url} returned {status}")
return json.loads(payload.decode("utf-8")) if payload else None
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
DEFAULTS: Dict[str, str] = {
# Repositories (relative to this file, or absolute)
"CORE_DIR": "analog-core",
"APP_DIR": "mobile_app",
"CORE_REPO": "https://github.com/AnalogIO/analog-core.git",
"APP_REPO": "https://github.com/AnalogIO/mobile_app.git",
"CORE_REF": "om/magic-link-registration",
"APP_REF": "",
# Backend
"API_PORT": "8080",
"API_BASE_URL": "",
"API_BIND": "0.0.0.0",
"DEEP_LINK_BASE": "analogcoffeecard-dev://cafeanalog.dk/",
"SMTP_HOST": "127.0.0.1",
"SMTP_PORT": "",
# Database
"DB_PORT": "1433",
"DB_BIND": "127.0.0.1",
"DB_USER": "sa",
"DB_PASSWORD": "Your_password123",
"DB_NAME": "master",
"MSSQL_IMAGE": "mcr.microsoft.com/mssql/server:2022-latest",
# MailHog
"MAILHOG_HTTP_PORT": "8025",
"MAILHOG_SMTP_PORT": "1025",
"MAILHOG_BIND": "127.0.0.1",
"MAILHOG_URL": "",
"MAILHOG_IMAGE": "mailhog/mailhog:latest",
# Device
"PLATFORM": "auto",
"DEVICE": "",
"NO_DEVICE": "0",
"SIM_NAME": "iPhone 16 Pro",
"SIM_UDID": "",
"ANDROID_AVD": "",
"ANDROID_SERIAL": "",
# Android emulators reach the host through 10.0.2.2. Set this for a
# physical phone (e.g. http://192.168.1.10:8080).
"ANDROID_API_BASE_URL": "",
"APP_ID": "dk.analogio.analog.dev",
"APP_FLAVOR": "development",
"APP_SCHEME": "analogcoffeecard-dev",
}
ENV_LINE_RE = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$")
def parse_env_text(text: str, source: str = "<config>") -> Dict[str, str]:
"""Parse the small KEY=VALUE subset used by config.env.
No shell expansion is performed on purpose: the same file must be readable
on Windows, macOS and Linux. Quotes are optional; `#` starts a comment.
"""
values: Dict[str, str] = {}
for lineno, raw in enumerate(text.splitlines(), 1):
line = raw.strip()
if not line or line.startswith("#"):
continue
match = ENV_LINE_RE.match(line)
if not match:
raise E2EException(f"{source}:{lineno}: expected KEY=VALUE, got: {raw!r}")
key, raw_value = match.group(1), match.group(2).strip()
if raw_value[:1] in ("'", '"'):
quote = raw_value[0]
if quote == "'":
end = raw_value.find("'", 1)
if end == -1:
raise E2EException(
f"{source}:{lineno}: unterminated quoted value for {key}"
)
value = raw_value[1:end]
rest = raw_value[end + 1 :].strip()
else:
chars: List[str] = []
index = 1
while index < len(raw_value):
char = raw_value[index]
if char == "\\" and index + 1 < len(raw_value):
following = raw_value[index + 1]
if following in ('"', "\\"):
chars.append(following)
index += 2
continue
if char == '"':
break
chars.append(char)
index += 1
if index >= len(raw_value):
raise E2EException(
f"{source}:{lineno}: unterminated quoted value for {key}"
)
value = "".join(chars)
rest = raw_value[index + 1 :].strip()
if rest and not rest.startswith("#"):
raise E2EException(
f"{source}:{lineno}: unexpected text after quoted value: {rest!r}"
)
else:
value = re.sub(r"\s+#.*$", "", raw_value).strip()
values[key] = value
return values
def parse_env_file(path: Path) -> Dict[str, str]:
if not path.exists():
return {}
return parse_env_text(path.read_text(encoding="utf-8"), source=str(path))
def _as_bool(value: str) -> bool:
return value.strip().lower() in ("1", "true", "yes", "on")
def _as_int(name: str, value: str, minimum: int = 1, maximum: int = 65535) -> int:
try:
number = int(value)
except (TypeError, ValueError):
raise E2EException(f"{name} must be an integer, got: {value!r}")
if not minimum <= number <= maximum:
raise E2EException(f"{name} must be between {minimum} and {maximum}, got {number}")
return number
class Config:
def __init__(
self, root: Path, overrides: Optional[Dict[str, str]] = None
) -> None:
self.root = root
values = dict(DEFAULTS)
values.update(parse_env_file(root / "config.env"))
values.update(parse_env_file(root / "config.local.env"))
for key in DEFAULTS:
if key in os.environ:
values[key] = os.environ[key]
if overrides:
values.update({key: str(value) for key, value in overrides.items()})
self.values = values
self.core_dir = self._path("CORE_DIR")
self.app_dir = self._path("APP_DIR")
self.core_repo = self._str("CORE_REPO")
self.app_repo = self._str("APP_REPO")
self.core_ref = self._str("CORE_REF")
self.app_ref = self._str("APP_REF")
self.api_port = _as_int("API_PORT", self._str("API_PORT"))
self.api_bind = self._str("API_BIND")
self.api_base_url = (
self._str("API_BASE_URL") or f"http://localhost:{self.api_port}"
).rstrip("/")
self.deep_link_base = self._str("DEEP_LINK_BASE")
self.db_port = _as_int("DB_PORT", self._str("DB_PORT"))
self.db_bind = self._str("DB_BIND")
self.db_user = self._str("DB_USER")
self.db_password = self._str("DB_PASSWORD")
self.db_name = self._str("DB_NAME")
self.mssql_image = self._str("MSSQL_IMAGE")
self.mailhog_http_port = _as_int(
"MAILHOG_HTTP_PORT", self._str("MAILHOG_HTTP_PORT")
)
self.mailhog_smtp_port = _as_int(
"MAILHOG_SMTP_PORT", self._str("MAILHOG_SMTP_PORT")
)
self.mailhog_bind = self._str("MAILHOG_BIND")
self.mailhog_url = (
self._str("MAILHOG_URL")
or f"http://127.0.0.1:{self.mailhog_http_port}"
).rstrip("/")
self.mailhog_image = self._str("MAILHOG_IMAGE")
self.smtp_host = self._str("SMTP_HOST")
self.smtp_port = _as_int(
"SMTP_PORT", self._str("SMTP_PORT") or str(self.mailhog_smtp_port)
)
self.platform = self._str("PLATFORM").lower() or "auto"
if self.platform not in ("auto", "ios", "android", "none"):
raise E2EException(
"PLATFORM must be one of: auto, ios, android, none "
f"(got {self.platform!r})"
)
self.device = self._str("DEVICE")
self.no_device = _as_bool(self._str("NO_DEVICE"))
self.sim_name = self._str("SIM_NAME")
self.sim_udid = self._str("SIM_UDID")
self.android_avd = self._str("ANDROID_AVD")
self.android_serial = self._str("ANDROID_SERIAL")
self.android_api_base_url = self._str("ANDROID_API_BASE_URL").rstrip("/")
self.app_id = self._str("APP_ID")
self.app_flavor = self._str("APP_FLAVOR")
self.app_scheme = self._str("APP_SCHEME")
self.compose_file = root / "docker-compose.yml"
self.backend_project = self.core_dir / "coffeecard" / "CoffeeCard.WebApi"
self.csproj = self.backend_project / "CoffeeCard.WebApi.csproj"
self.dev_dir = root / ".dev"
self.backend_log = self.dev_dir / "backend.log"
self.backend_build_log = self.dev_dir / "backend-build.log"
self.backend_pid = self.dev_dir / "backend.pid"
self.device_state = self.dev_dir / "device.json"
def _str(self, key: str) -> str:
return str(self.values.get(key, DEFAULTS.get(key, ""))).strip()
def _path(self, key: str) -> Path:
raw = self._str(key)
if not raw:
raise E2EException(f"{key} must not be empty.")
path = Path(raw).expanduser()
if not path.is_absolute():
path = self.root / path
return path.resolve()
@property
def database_connection_string(self) -> str:
return (
f"Server=localhost,{self.db_port};Initial Catalog={self.db_name};"
f"User={self.db_user};Password={self.db_password};"
"TrustServerCertificate=True;"
)
def compose_env(self) -> Dict[str, str]:
env = os.environ.copy()
env.update(
{
"DB_PORT": str(self.db_port),
"DB_BIND": self.db_bind,
"DB_PASSWORD": self.db_password,
"MSSQL_IMAGE": self.mssql_image,
"MAILHOG_SMTP_PORT": str(self.mailhog_smtp_port),
"MAILHOG_HTTP_PORT": str(self.mailhog_http_port),
"MAILHOG_BIND": self.mailhog_bind,
"MAILHOG_IMAGE": self.mailhog_image,
}
)
return env
def describe(self) -> List[Tuple[str, str]]:
password = "*" * len(self.db_password)
return [
("root", str(self.root)),
("core", f"{self.core_dir} ({git_branch(self.core_dir)})"),
("app", f"{self.app_dir} ({git_branch(self.app_dir)})"),
("platform", self.platform),
("device", self.device or self.sim_udid or self.android_serial or "(auto)"),
("api", self.api_base_url),
(
"android api",
self.android_api_base_url
or f"http://10.0.2.2:{self.api_port} (emulator)",
),
("mailhog", self.mailhog_url),
("database", f"localhost:{self.db_port}/{self.db_name}"),
("db password", password),
("app id", self.app_id),
("flavor", self.app_flavor),
("compose", str(self.compose_file)),
("state", str(self.dev_dir)),
]
def git_branch(repo: Path) -> str:
if not (repo / ".git").exists():
return "not a git repo"
proc = run(
["git", "-C", str(repo), "branch", "--show-current"],
check=False,
capture=True,
)
return (proc.stdout or "").strip() or "detached"
# ---------------------------------------------------------------------------
# Docker Compose
# ---------------------------------------------------------------------------
class Docker:
def __init__(self, cfg: Config, con: Console) -> None:
self.cfg = cfg
self.con = con
self._available: Optional[bool] = None
self._docker_exe: Optional[str] = None
@property
def exe(self) -> str:
if self._docker_exe is None:
self._docker_exe = require(
"docker",
"Install Docker Desktop (Windows/macOS) or Docker Engine + the "
"Compose plugin (Linux).",
)
return self._docker_exe
def available(self) -> bool:
if self._available is not None:
return self._available
if not which("docker"):
self._available = False
return False
proc = run([self.exe, "info"], check=False, capture=True, timeout=30)
self._available = proc.returncode == 0
return self._available
def require(self) -> None:
if not self.available():
raise E2EException(
"Docker is not running or not accessible.\n"
" Start Docker Desktop (Windows/macOS) or the Docker daemon "
"(Linux), then retry."
)
def compose_version(self) -> Optional[str]:
if not self.available():
return None
proc = run([self.exe, "compose", "version"], check=False, capture=True)
return (proc.stdout or "").strip() if proc.returncode == 0 else None
def compose(
self,
*args: Any,
check: bool = True,
capture: bool = False,
input: Optional[str] = None,
timeout: Optional[float] = None,
) -> subprocess.CompletedProcess:
self.require()
cmd = [
self.exe,
"compose",
"-f",
str(self.cfg.compose_file),
"--project-directory",
str(self.cfg.root),
*[str(arg) for arg in args],
]
return run(
cmd,
env=self.cfg.compose_env(),
check=check,
capture=capture,
input=input,
timeout=timeout,
)
def up(self) -> None:
self.con.log("Starting MSSQL and MailHog (Docker)...")
try:
self.compose("up", "-d", "mssql", "mailhog", timeout=600)
except E2EException as exc:
legacy_compose = (
self.cfg.core_dir / "coffeecard" / "docker-compose.yml"
)
hint = (
"\n\nIf a previous local stack is still running (for example the "
"old coffeecard compose project), stop it once:\n"
f' docker compose -f "{legacy_compose}" '
f'--project-directory "{legacy_compose.parent}" down\n'
"or remove the old containers directly:\n"
" docker rm -f mssql coffeecard-mailhog-1"
)
raise E2EException(f"{exc}{hint}") from exc
def stop(self) -> None:
self.compose("stop", "mssql", "mailhog", check=False, capture=True)
def down(self, volumes: bool = False) -> None:
args = ["down", "--remove-orphans"]
if volumes:
args.append("--volumes")
self.compose(*args, check=False)
def ps(self) -> str:
proc = self.compose("ps", check=False, capture=True)
return (proc.stdout or "").strip()
# ---------------------------------------------------------------------------
# Database (sqlcmd inside the MSSQL container)
# ---------------------------------------------------------------------------
class Database:
def __init__(self, cfg: Config, docker: Docker, con: Console) -> None:
self.cfg = cfg
self.docker = docker
self.con = con
self._sqlcmd: Optional[str] = None
def _detect_sqlcmd(self) -> Optional[str]:
shell = (
"if [ -x /opt/mssql-tools18/bin/sqlcmd ]; then "
"echo /opt/mssql-tools18/bin/sqlcmd; "
"elif [ -x /opt/mssql-tools/bin/sqlcmd ]; then "
"echo /opt/mssql-tools/bin/sqlcmd; fi"
)
proc = self.docker.compose(
"exec", "-T", "mssql", "sh", "-c", shell, check=False, capture=True
)
if proc.returncode != 0:
return None
for line in (proc.stdout or "").splitlines():
line = line.strip()
if line.startswith("/") and "sqlcmd" in line:
return line
return None
def sqlcmd_bin(self) -> str:
if self._sqlcmd is None:
found = self._detect_sqlcmd()
if not found:
raise E2EException(
"Could not find sqlcmd inside the mssql container. "
"Is the container running?"
)
self._sqlcmd = found
return self._sqlcmd
def sqlcmd(
self,
*args: Any,
input: Optional[str] = None,
check: bool = True,
capture: bool = True,
timeout: Optional[float] = None,
) -> subprocess.CompletedProcess:
cmd = [
"exec",
"-T",
"mssql",
self.sqlcmd_bin(),
"-C",
"-S",
"localhost",
"-U",
self.cfg.db_user,
"-P",
self.cfg.db_password,
"-d",
self.cfg.db_name,
*[str(arg) for arg in args],
]
return self.docker.compose(
*cmd, input=input, check=check, capture=capture, timeout=timeout
)
def wait_ready(self, timeout: int = 120) -> None:
deadline = time.time() + timeout
while time.time() < deadline:
found = self._sqlcmd or self._detect_sqlcmd()
if found:
self._sqlcmd = found
proc = self.sqlcmd("-l", "5", "-Q", "SELECT 1", check=False)
if proc.returncode == 0:
return
time.sleep(1)
raise E2EException(
"MSSQL did not become ready.\n"
" Try: docker compose logs mssql"
)
def run_file(self, path: Path) -> None:
if not path.exists():
raise E2EException(f"SQL file not found: {path}")
text = path.read_text(encoding="utf-8-sig")
proc = self.sqlcmd("-b", input=text, check=False)
if proc.returncode != 0:
raise E2EException(
f"{path.name} failed:\n{tail_text(proc.stdout or '', 40)}"
)
def query(self, sql: str) -> List[List[str]]:
proc = self.sqlcmd(
"-W", "-h", "-1", "-s", "\t", "-Q", sql, check=False
)
if proc.returncode != 0:
raise E2EException(
f"Query failed:\n{tail_text(proc.stdout or '', 40)}"
)
rows: List[List[str]] = []
for line in (proc.stdout or "").splitlines():
if not line.strip():
continue
rows.append([cell.strip() for cell in line.split("\t")])
return rows
def seed(self) -> None:
self.con.log("Seeding database (db/seed.sql)...")
self.run_file(self.cfg.root / "db" / "seed.sql")
counts = self.query(
"SET NOCOUNT ON; "
"SELECT 'programmes', COUNT(*) FROM dbo.Programmes "
"UNION ALL SELECT 'users', COUNT(*) FROM dbo.Users "
"UNION ALL SELECT 'products', COUNT(*) FROM dbo.Products "
"UNION ALL SELECT 'tickets', COUNT(*) FROM dbo.Tickets"
)
for row in counts:
if len(row) >= 2:
self.con.plain(f" {row[0]:<12} {row[1]}")
self.con.ok(
"Seed applied (john@doe.com: 4 unused; "
"many.tickets@analog.local: 70 unused, 120 used, 10 refunded)."
)
def reset(self) -> None:
self.con.log("Removing test accounts and tokens (db/reset.sql)...")
self.run_file(self.cfg.root / "db" / "reset.sql")
self.seed()
def list_users(self) -> str:
rows = self.query(
"SET NOCOUNT ON; "
"SELECT u.Name, u.Email, "
"COALESCE(SUM(CASE WHEN t.Status = 0 THEN 1 ELSE 0 END), 0) "
"FROM dbo.Users u "
"LEFT JOIN dbo.Tickets t ON t.[Owner_Id] = u.Id "
"GROUP BY u.Id, u.Name, u.Email ORDER BY u.Name"
)
return format_table(
["Name", "Email", "Owned tickets"],
rows,
right_align={2},
)
# ---------------------------------------------------------------------------
# MailHog
# ---------------------------------------------------------------------------
def decode_quoted_printable(text: str) -> str:
"""Decode a quoted-printable email body, tolerating already-decoded input."""
if "=" not in text:
return text
try:
raw = quopri.decodestring(text.encode("utf-8", "surrogateescape"))
return raw.decode("utf-8", "replace")
except Exception:
return text
HREF_RE = re.compile(r"""href\s*=\s*["']([^"']+)["']""", re.IGNORECASE)
URL_RE = re.compile(r"""(?:https?|analogcoffeecard[^:\s"']*)://[^\s"'<>]+""", re.IGNORECASE)
def extract_links(text: str) -> List[str]:
links = [match.group(1) for match in HREF_RE.finditer(text)]
links.extend(URL_RE.findall(text))
seen = set()
unique: List[str] = []
for link in links:
link = link.replace("&", "&").strip()
if link not in seen:
seen.add(link)
unique.append(link)
return unique
def magic_link_from_message(message: Dict[str, Any]) -> Optional[str]:
body = (message.get("Content") or {}).get("Body") or ""
text = decode_quoted_printable(body)
for link in extract_links(text):
if "/register/" in link or "/login/auth/" in link:
return link
return None
def message_recipients(message: Dict[str, Any]) -> str:
headers = (message.get("Content") or {}).get("Headers") or {}
recipients = headers.get("To") or []
if isinstance(recipients, str):
recipients = [recipients]
return " ".join(str(item) for item in recipients)
class MailHog:
def __init__(self, cfg: Config, con: Console) -> None:
self.cfg = cfg
self.con = con
def _url(self, path: str) -> str:
return f"{self.cfg.mailhog_url}{path}"
def ok(self) -> bool:
return http_ok(self._url("/api/v2/messages"), timeout=2)
def wait_ready(self, timeout: int = 60) -> None:
deadline = time.time() + timeout
while time.time() < deadline:
if self.ok():
return
time.sleep(1)
raise E2EException(f"MailHog did not become ready at {self.cfg.mailhog_url}.")
def count(self) -> int:
try:
data = http_json("GET", self._url("/api/v2/messages"), timeout=2)
return int((data or {}).get("total", 0))
except Exception:
return 0
def messages(self) -> List[Dict[str, Any]]:
try:
data = http_json("GET", self._url("/api/v2/messages?limit=1000"))
except E2EException:
return []
items = (data or {}).get("items") or []
return sorted(items, key=lambda item: item.get("Created", ""), reverse=True)
def newest_link(self) -> str:
if not self.ok():
raise E2EException(
f"MailHog is not reachable at {self.cfg.mailhog_url}. "
"Run `e2e up` first."
)
for message in self.messages():
link = magic_link_from_message(message)
if link:
return link
raise E2EException(
"No registration or login email found in MailHog. "
"Request a link from the app first."
)
def find_registration_for(
self, email: str, timeout: int = 20
) -> Tuple[Optional[str], Optional[str]]:
if not self.ok():
raise E2EException(
f"MailHog is not reachable at {self.cfg.mailhog_url}."
)
deadline = time.time() + timeout
wanted = email.lower()
while time.time() < deadline:
for message in self.messages():
if wanted not in message_recipients(message).lower():
continue
link = magic_link_from_message(message)
if link and "/register/" in link:
return str(message.get("ID") or ""), link
time.sleep(1)
return None, None
def delete_all(self) -> None:
http_request("DELETE", self._url("/api/v1/messages"))
def delete_message(self, message_id: str) -> None:
if not message_id:
return
encoded = urllib.parse.quote(message_id, safe="")
http_request("DELETE", self._url(f"/api/v1/messages/{encoded}"))
def open_in_browser(self) -> bool:
return webbrowser.open(self.cfg.mailhog_url)
# ---------------------------------------------------------------------------
# Backend process
# ---------------------------------------------------------------------------
class Backend:
MAX_LOG_BYTES = 10 * 1024 * 1024
def __init__(self, cfg: Config, con: Console) -> None:
self.cfg = cfg
self.con = con
self._dll: Optional[Path] = None
def is_up(self) -> bool:
return http_ok(f"{self.cfg.api_base_url}/api/v1/programmes", timeout=2)
def read_pid(self) -> Optional[int]:
try:
raw = self.cfg.backend_pid.read_text(encoding="utf-8").strip()
return int(raw) if raw else None
except (OSError, ValueError):
return None
def _pid_alive(self, pid: int) -> bool:
if os.name == "nt":
proc = run(
["tasklist", "/FI", f"PID eq {pid}", "/NH"],
check=False,
capture=True,
)
output = proc.stdout or ""
return str(pid) in output and "No tasks" not in output
try:
os.kill(pid, 0)
return True
except ProcessLookupError:
return False
except PermissionError:
return True
def listener_pid(self) -> Optional[int]:
port = self.cfg.api_port
if os.name == "nt":
proc = run(["netstat", "-ano", "-p", "tcp"], check=False, capture=True)
for line in (proc.stdout or "").splitlines():
parts = line.split()
if (
len(parts) >= 5
and parts[0].upper() == "TCP"
and parts[1].endswith(f":{port}")
and parts[3].upper() == "LISTENING"
):
try:
return int(parts[-1])
except ValueError:
return None
return None
if which("lsof"):
proc = run(
["lsof", f"-tiTCP:{port}", "-sTCP:LISTEN"],
check=False,
capture=True,
)
for line in (proc.stdout or "").splitlines():
try:
return int(line.strip())
except ValueError:
continue
if which("ss"):
proc = run(["ss", "-ltnp"], check=False, capture=True)
for line in (proc.stdout or "").splitlines():
if f":{port} " in line: