Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
944ba204cf | ||
|
|
f57040e136 | ||
|
|
8c6cc148f5 | ||
|
|
0a665ee9ac |
@@ -16,7 +16,7 @@ document of a type. `Primary File` may contain a glob (e.g.
|
|||||||
| PP | Project Plan | docs/project-plan.md | 002 |
|
| PP | Project Plan | docs/project-plan.md | 002 |
|
||||||
| MIL | Milestone / Gateway | docs/milestones/*.md | 009 |
|
| MIL | Milestone / Gateway | docs/milestones/*.md | 009 |
|
||||||
| ADR | Architecture Decision Record | docs/adr/adr-NNNN-*.md | 0004 |
|
| ADR | Architecture Decision Record | docs/adr/adr-NNNN-*.md | 0004 |
|
||||||
| RC | SQA Review Record | docs/sqa/reviews/rc-*.md | 020 |
|
| RC | SQA Review Record | docs/sqa/reviews/rc-*.md | 021 |
|
||||||
| TM | Traceability Matrix | docs/sqa/traceability-matrix.md | 002 |
|
| TM | Traceability Matrix | docs/sqa/traceability-matrix.md | 002 |
|
||||||
| DICT | Domain Dictionary | docs/dictionary.md | 002 |
|
| DICT | Domain Dictionary | docs/dictionary.md | 002 |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# SQA Review Record
|
||||||
|
|
||||||
|
## Metadata
|
||||||
|
| Key | Value |
|
||||||
|
| --- | --- |
|
||||||
|
| ID | RC-020 |
|
||||||
|
| CrossReference | [MIL-006], [QC-PY-001] |
|
||||||
|
|
||||||
|
## Version History
|
||||||
|
| Date | Status | Author | Reviewer | Change | Commit |
|
||||||
|
| --- | --- | --- | --- | --- | --- |
|
||||||
|
| 2026-10-28 | Accepted | Jens Tirsvad Nielsen | AI as stand-in for S02 | Review record, full review of the source and tests of MIL-006 | [f57040e] |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Artifact Under Review
|
||||||
|
|
||||||
|
- Instance reviewed: [MIL-006]
|
||||||
|
- Checklist used: [QC-PY-001] (`QC-PY-001`)
|
||||||
|
- Scope: full review of the source and tests of MIL-006
|
||||||
|
- Language and domain: n/a
|
||||||
|
- Language reviewer: none
|
||||||
|
- Mode: autonomous, not independent (the reviewer is `AI as stand-in for S02`)
|
||||||
|
|
||||||
|
## Checklist Results
|
||||||
|
|
||||||
|
| # | Criterion | Status | Evidence/Notes |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 1 | Packages, modules, functions, variables, classes and constants follow PEP 8 casing (`snake_case`, `PascalCase`, `UPPER_SNAKE`) | Pass | Modules, functions and variables are `snake_case`, classes `PascalCase`, constants `UPPER_SNAKE`; `ruff check` with the N rules passes. |
|
||||||
|
| 2 | Names state purpose in the domain's language; no unexplained abbreviations, no single-letter names outside tiny scopes | Pass | Names state purpose (for example `retry`, `login`, `book_class`, `get_my_bookings`); no single-letter names outside comprehensions. |
|
||||||
|
| 3 | Code is produced by the project's formatter and passes its linter with no unexplained suppressions | Pass | `ruff format` leaves 0 files changed and `ruff check` reports 0 findings; there is no suppression. |
|
||||||
|
| 4 | Every function and method signature is type-annotated, including `-> None` | Pass | Every function and method has annotations (ruff ANN rules pass), including `-> None`. |
|
||||||
|
| 5 | No bare `except:`, no swallowed exceptions; specific exceptions are raised and the cause is kept (`raise ... from`) | Pass | No bare `except`; specific exceptions are caught, and re-raised with `raise ... from` where the cause matters. |
|
||||||
|
| 6 | No mutable default arguments and no shadowed builtins | Pass | No mutable default arguments; no builtin is shadowed (ruff B and A-style checks pass). |
|
||||||
|
| 7 | Files, locks and connections are managed with context managers | Pass | Files and the browser are managed with `with`/`try-finally`; no unmanaged file handle exists. |
|
||||||
|
| 8 | Public modules, classes and functions have docstrings that say what, not how | Pass | Public modules, classes and functions have Doxygen docstrings (`@brief`, `@param`, `@return`). |
|
||||||
|
| 9 | Logging uses `logging`, not `print`; no secrets or personal data in log output | Pass | No print calls; messages go through `logging`. |
|
||||||
|
| 10 | Classes and operations trace to the Design Class Diagram they implement; deviations are recorded | N-A | No Design Class Diagram exists; ADR-0001 records that design artifacts are skipped. Classes follow ADR-0002. |
|
||||||
|
| 11 | Tests exist for new behaviour, are named for the behaviour, and do not depend on order or the network | Pass | 174 unit tests (booking entries, verification, date independence for all seven starting weekdays, command line) need no browser or network; 15 container tests run the adapter against local fixtures; coverage of the non-infrastructure modules is 100%. |
|
||||||
|
| 12 | Type checker runs in strict mode without errors; `Any` is justified in a comment | N-A | No strict type checker is configured; annotations are complete and checked by ruff. |
|
||||||
|
| 13 | Dependencies are declared and pinned in the project's dependency file, none unused | Pass | `pyproject.toml` declares Selenium (runtime) and pytest, pytest-cov, ruff (dev) with lower bounds; none is unused. |
|
||||||
|
| 14 | Each piece of knowledge (a business rule, constant, format, validation or query) is defined in one place; code is merged only where it expresses the same knowledge, not where it merely looks alike | Pass | Each rule, constant and message exists once (constants in `constants.py`, rules in `domain/`). |
|
||||||
|
| 15 | Imports point inward: business-rule modules import no framework, database, UI or delivery-mechanism code, and there are no import cycles | Pass | `domain` and `application` import no Selenium; only `infrastructure` imports it; no import cycle exists. |
|
||||||
|
| 16 | SOLID holds: a class or module has one reason to change; new behaviour is added by extension, not by editing a type test in several places; subclasses honour the contract of their base; protocols are narrow; high-level code depends on protocols or abstract types and receives its implementations | Pass | One reason to change per module; the adapter hides Selenium behind a port; fakes honour the port contract. |
|
||||||
|
| 17 | Source is laid out in the layers and folders of the clean architecture folder structure (`domain`, `application`, `infrastructure`, `presentation` packages under `src/`, and `unit`, `integration` and `e2e` under `tests/`), in `snake_case`, and imports between the layers point inward | Pass | Layout follows `src/snack_and_lift/{domain,application,infrastructure}` and `tests/{unit,integration,e2e}`; there is no presentation layer for a command-line bot (ADR-0002). |
|
||||||
|
| 18 | File and folder names are English, contain no space and no character outside letters, digits, `-`, `_` and `.`, and follow the casing of the language for files | Pass | All file and folder names are English lowercase with `_`, `-` and `.` only. |
|
||||||
|
|
||||||
|
## Overall Verdict
|
||||||
|
|
||||||
|
Go-with-conditions - the code of MIL-006 meets every Mandatory criterion of QC-PY-001 and there is no blocking finding, but part of the gate evidence cannot be produced by the stand-in. Gate criterion 1 (unit tests of the comparison and the mismatch message) is met, and the date independence is tested for every starting weekday (no hardcoded date, no list-position rule). Criteria 2 and 3 (container runs on the live site, including after the admin advances 3 days) are not verified, and criterion 4 is not met: `step-7.png` and `step-8.png` come from a run with an account. The framework forbids the stand-in to enter passwords or register on a third-party site; the admin time controls also need a login. The review is not independent: the AI wrote and reviewed it as stand-in for S02, and S01 can challenge it in the end-of-run summary.
|
||||||
|
|
||||||
|
## Action Items
|
||||||
|
|
||||||
|
| Action | Owner | Due |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Run the bot with your own account (also after advancing the site 3 days as admin) and keep `docs/images/step-7.png` and `step-8.png` | S01 | when S01 has time |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
[MIL-006]: ../../milestones/mil-006-verify-and-time-travel.md
|
||||||
|
[QC-PY-001]: ../../../framework/qc/code/qc-programming-python.md
|
||||||
|
[f57040e]: https://git.tirsystem.com/Tirsvad-Udemy-100-days-of-code/049-snack-and-lift/commit/f57040e136feac01f10d99279038f48992518f43
|
||||||
@@ -40,6 +40,7 @@ Tracks backward and forward links between artifact instances so that the Busines
|
|||||||
| Source and tests of [MIL-003] | Python source code | - | - | [MIL-003], [ADR-0002], [ADR-0003] | - | RC-017 (Go-with-conditions) |
|
| Source and tests of [MIL-003] | Python source code | - | - | [MIL-003], [ADR-0002], [ADR-0003] | - | RC-017 (Go-with-conditions) |
|
||||||
| Source and tests of [MIL-004] | Python source code | - | - | [MIL-004], [ADR-0002] | - | RC-018 (Go-with-conditions) |
|
| Source and tests of [MIL-004] | Python source code | - | - | [MIL-004], [ADR-0002] | - | RC-018 (Go-with-conditions) |
|
||||||
| Source and tests of [MIL-005] | Python source code | - | - | [MIL-005], [ADR-0002] | - | RC-019 (Go-with-conditions) |
|
| Source and tests of [MIL-005] | Python source code | - | - | [MIL-005], [ADR-0002] | - | RC-019 (Go-with-conditions) |
|
||||||
|
| Source and tests of [MIL-006] | Python source code | - | - | [MIL-006], [ADR-0002] | - | RC-020 (Go-with-conditions) |
|
||||||
|
|
||||||
## Concern Coverage
|
## Concern Coverage
|
||||||
|
|
||||||
|
|||||||
@@ -1,66 +1,82 @@
|
|||||||
"""@file ports.py
|
"""@file ports.py
|
||||||
@brief The ports the use cases need from the outside world.
|
@brief The ports the use cases need from the outside world.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Protocol
|
from typing import Protocol
|
||||||
|
|
||||||
from snack_and_lift.domain.models import ClassCard
|
from snack_and_lift.domain.booking_entry import BookingEntry
|
||||||
|
from snack_and_lift.domain.models import ClassCard
|
||||||
|
|
||||||
class GymPort(Protocol):
|
|
||||||
"""@brief The gym site as the use cases see it."""
|
class GymPort(Protocol):
|
||||||
|
"""@brief The gym site as the use cases see it."""
|
||||||
def open_site(self) -> None:
|
|
||||||
"""@brief Open the home page and wait until it is ready.
|
def open_site(self) -> None:
|
||||||
|
"""@brief Open the home page and wait until it is ready.
|
||||||
@exception GymError The page did not load.
|
|
||||||
"""
|
@exception GymError The page did not load.
|
||||||
...
|
"""
|
||||||
|
...
|
||||||
def log_in(self, email: str, password: str) -> None:
|
|
||||||
"""@brief Log in and wait until the class schedule is shown.
|
def log_in(self, email: str, password: str) -> None:
|
||||||
|
"""@brief Log in and wait until the class schedule is shown.
|
||||||
@param email The account e-mail.
|
|
||||||
@param password The account password.
|
@param email The account e-mail.
|
||||||
@exception LoginFailedError The site refused the login.
|
@param password The account password.
|
||||||
@exception GymError The page did not behave as expected.
|
@exception LoginFailedError The site refused the login.
|
||||||
"""
|
@exception GymError The page did not behave as expected.
|
||||||
...
|
"""
|
||||||
|
...
|
||||||
def list_class_cards(self) -> list[ClassCard]:
|
|
||||||
"""@brief Read every class card of the schedule, in page order.
|
def list_class_cards(self) -> list[ClassCard]:
|
||||||
|
"""@brief Read every class card of the schedule, in page order.
|
||||||
@return The classes, each with the day of its group.
|
|
||||||
@exception GymError The schedule could not be read.
|
@return The classes, each with the day of its group.
|
||||||
"""
|
@exception GymError The schedule could not be read.
|
||||||
...
|
"""
|
||||||
|
...
|
||||||
def press_class_button(self, card_id: str) -> str:
|
|
||||||
"""@brief Click the button of a class and wait until the request has finished.
|
def press_class_button(self, card_id: str) -> str:
|
||||||
|
"""@brief Click the button of a class and wait until the request has finished.
|
||||||
@param card_id The id of the card without its prefix.
|
|
||||||
@return The new text of the button.
|
@param card_id The id of the card without its prefix.
|
||||||
@exception GymError The site shows an error for the class (the message is its text)
|
@return The new text of the button.
|
||||||
or nothing settled in time.
|
@exception GymError The site shows an error for the class (the message is its text)
|
||||||
"""
|
or nothing settled in time.
|
||||||
...
|
"""
|
||||||
|
...
|
||||||
def save_text_screenshot(self, text: str, path: Path) -> None:
|
|
||||||
"""@brief Save an image of console text.
|
def open_my_bookings(self) -> None:
|
||||||
|
"""@brief Open the My Bookings page and wait until it is shown.
|
||||||
@param text The lines to draw, in a dark monospace style.
|
|
||||||
@param path The PNG file to write; its folders are created.
|
@exception GymError The page did not load.
|
||||||
"""
|
"""
|
||||||
...
|
...
|
||||||
|
|
||||||
def save_screenshot(self, path: Path) -> None:
|
def list_my_bookings(self) -> list[BookingEntry]:
|
||||||
"""@brief Save a screenshot of the current page.
|
"""@brief Read every confirmed booking and waitlist entry of the My Bookings page.
|
||||||
|
|
||||||
@param path The PNG file to write; its folders are created.
|
@return The entries, confirmed ones first; empty when the page shows its empty state.
|
||||||
"""
|
@exception GymError The page shows an error (the message is its text) or did not settle.
|
||||||
...
|
"""
|
||||||
|
...
|
||||||
def close(self) -> None:
|
|
||||||
"""@brief Close the browser."""
|
def save_text_screenshot(self, text: str, path: Path) -> None:
|
||||||
...
|
"""@brief Save an image of console text.
|
||||||
|
|
||||||
|
@param text The lines to draw, in a dark monospace style.
|
||||||
|
@param path The PNG file to write; its folders are created.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def save_screenshot(self, path: Path) -> None:
|
||||||
|
"""@brief Save a screenshot of the current page.
|
||||||
|
|
||||||
|
@param path The PNG file to write; its folders are created.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
"""@brief Close the browser."""
|
||||||
|
...
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""@file verification.py
|
||||||
|
@brief Lecture steps 7 and 8: check the bookings on the My Bookings page.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from snack_and_lift import constants
|
||||||
|
from snack_and_lift.application.ports import GymPort
|
||||||
|
from snack_and_lift.domain.booking_entry import BookingEntry, is_target_entry
|
||||||
|
from snack_and_lift.domain.errors import NoBookingsFoundError
|
||||||
|
from snack_and_lift.domain.models import ClassResult
|
||||||
|
from snack_and_lift.domain.verification import VerificationResult, build_verification
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def get_my_bookings(gym: GymPort) -> list[BookingEntry]:
|
||||||
|
"""@brief Open the My Bookings page and read all its entries.
|
||||||
|
|
||||||
|
@param gym The gym site.
|
||||||
|
@return Every confirmed booking and waitlist entry, not only the target classes.
|
||||||
|
@exception NoBookingsFoundError The page shows no entry at all.
|
||||||
|
@exception GymError The page could not be opened or read.
|
||||||
|
"""
|
||||||
|
gym.open_my_bookings()
|
||||||
|
entries = gym.list_my_bookings()
|
||||||
|
if not entries:
|
||||||
|
raise NoBookingsFoundError(constants.MESSAGE_NO_BOOKINGS_FOUND)
|
||||||
|
return entries
|
||||||
|
|
||||||
|
|
||||||
|
def verify_bookings(gym: GymPort, results: Sequence[ClassResult]) -> VerificationResult:
|
||||||
|
"""@brief Compare what the bot booked with the My Bookings page.
|
||||||
|
|
||||||
|
The page is not opened when the bot handled no class.
|
||||||
|
|
||||||
|
@param gym The gym site.
|
||||||
|
@param results What happened to each class.
|
||||||
|
@return The comparison of the expected entries with the Tuesday and Thursday 6pm entries.
|
||||||
|
@exception NoBookingsFoundError Classes were handled but the page shows no entry.
|
||||||
|
@exception GymError The page could not be opened or read.
|
||||||
|
"""
|
||||||
|
if not results:
|
||||||
|
return build_verification(results, [])
|
||||||
|
entries = [entry for entry in get_my_bookings(gym) if is_target_entry(entry)]
|
||||||
|
return build_verification(results, entries)
|
||||||
+222
-209
@@ -1,209 +1,222 @@
|
|||||||
"""@file cli.py
|
"""@file cli.py
|
||||||
@brief Command-line entry point (the composition root of the bot).
|
@brief Command-line entry point (the composition root of the bot).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
from collections.abc import Callable, Sequence
|
from collections.abc import Callable, Sequence
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from snack_and_lift import constants
|
from snack_and_lift import constants
|
||||||
from snack_and_lift.application.booking import book_next_tuesday, book_target_classes
|
from snack_and_lift.application.booking import book_next_tuesday, book_target_classes
|
||||||
from snack_and_lift.application.credentials import Credentials, load_credentials
|
from snack_and_lift.application.credentials import Credentials, load_credentials
|
||||||
from snack_and_lift.application.ports import GymPort
|
from snack_and_lift.application.ports import GymPort
|
||||||
from snack_and_lift.application.session import login
|
from snack_and_lift.application.session import login
|
||||||
from snack_and_lift.domain.errors import GymError, LoginFailedError, MissingCredentialsError
|
from snack_and_lift.application.verification import verify_bookings
|
||||||
from snack_and_lift.domain.models import ClassResult
|
from snack_and_lift.domain.errors import GymError, LoginFailedError, MissingCredentialsError
|
||||||
from snack_and_lift.domain.report import format_detail_list, format_summary
|
from snack_and_lift.domain.models import ClassResult
|
||||||
from snack_and_lift.infrastructure.browser import create_driver, default_profile_dir
|
from snack_and_lift.domain.report import format_detail_list, format_summary
|
||||||
from snack_and_lift.infrastructure.console_recorder import ConsoleRecorder
|
from snack_and_lift.domain.verification import format_verification
|
||||||
from snack_and_lift.infrastructure.selenium_gym import SeleniumGym
|
from snack_and_lift.infrastructure.browser import create_driver, default_profile_dir
|
||||||
|
from snack_and_lift.infrastructure.console_recorder import ConsoleRecorder
|
||||||
## Builds the gym site from (headless, profile folder, keep open).
|
from snack_and_lift.infrastructure.selenium_gym import SeleniumGym
|
||||||
GymFactory = Callable[[bool, Path, bool], GymPort]
|
|
||||||
|
## Builds the gym site from (headless, profile folder, keep open).
|
||||||
logger = logging.getLogger(__name__)
|
GymFactory = Callable[[bool, Path, bool], GymPort]
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
def selenium_gym_factory(headless: bool, profile_dir: Path, keep_open: bool) -> GymPort:
|
|
||||||
"""@brief Start Chrome and wrap it as the gym site.
|
|
||||||
|
def selenium_gym_factory(headless: bool, profile_dir: Path, keep_open: bool) -> GymPort:
|
||||||
@param headless True to run without a window.
|
"""@brief Start Chrome and wrap it as the gym site.
|
||||||
@param profile_dir The Chrome user data folder.
|
|
||||||
@param keep_open True to leave the browser open when the program ends.
|
@param headless True to run without a window.
|
||||||
@return The gym site.
|
@param profile_dir The Chrome user data folder.
|
||||||
"""
|
@param keep_open True to leave the browser open when the program ends.
|
||||||
return SeleniumGym(create_driver(headless, profile_dir, keep_open))
|
@return The gym site.
|
||||||
|
"""
|
||||||
|
return SeleniumGym(create_driver(headless, profile_dir, keep_open))
|
||||||
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
|
||||||
"""@brief Read the command line.
|
|
||||||
|
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
||||||
@param argv Arguments without the program name; None reads `sys.argv`.
|
"""@brief Read the command line.
|
||||||
@return The parsed options; `keep_open` is True unless `--headless` is given.
|
|
||||||
"""
|
@param argv Arguments without the program name; None reads `sys.argv`.
|
||||||
parser = argparse.ArgumentParser(
|
@return The parsed options; `keep_open` is True unless `--headless` is given.
|
||||||
prog="snack-and-lift",
|
"""
|
||||||
description="Books the Tuesday and Thursday 6pm classes at the Snack and Lift gym.",
|
parser = argparse.ArgumentParser(
|
||||||
)
|
prog="snack-and-lift",
|
||||||
parser.add_argument(
|
description="Books the Tuesday and Thursday 6pm classes at the Snack and Lift gym.",
|
||||||
"--headless",
|
epilog=(
|
||||||
action="store_true",
|
"exit codes: 0 done, 1 a step failed, 2 credentials missing, "
|
||||||
help="run Chrome without a window (the Docker image does this)",
|
"3 the My Bookings page does not match the bookings made"
|
||||||
)
|
),
|
||||||
parser.add_argument(
|
)
|
||||||
"--keep-open",
|
parser.add_argument(
|
||||||
action="store_true",
|
"--headless",
|
||||||
default=None,
|
action="store_true",
|
||||||
help="leave the browser open at the end (default when not headless)",
|
help="run Chrome without a window (the Docker image does this)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--profile-dir",
|
"--keep-open",
|
||||||
type=Path,
|
action="store_true",
|
||||||
default=None,
|
default=None,
|
||||||
help="Chrome profile folder (default: ./chrome_profile)",
|
help="leave the browser open at the end (default when not headless)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--screenshot-dir",
|
"--profile-dir",
|
||||||
type=Path,
|
type=Path,
|
||||||
default=None,
|
default=None,
|
||||||
help="save a screenshot after each step into this folder",
|
help="Chrome profile folder (default: ./chrome_profile)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--first-tuesday-only",
|
"--screenshot-dir",
|
||||||
action="store_true",
|
type=Path,
|
||||||
help="book only the next Tuesday 6pm class (lecture steps 3 and 4)",
|
default=None,
|
||||||
)
|
help="save a screenshot after each step into this folder",
|
||||||
args = parser.parse_args(argv)
|
)
|
||||||
if args.keep_open is None:
|
parser.add_argument(
|
||||||
args.keep_open = not args.headless
|
"--first-tuesday-only",
|
||||||
if args.profile_dir is None:
|
action="store_true",
|
||||||
args.profile_dir = default_profile_dir()
|
help="book only the next Tuesday 6pm class (lecture steps 3 and 4); skips the verification",
|
||||||
return args
|
)
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
if args.keep_open is None:
|
||||||
def _use_utf8_output() -> None:
|
args.keep_open = not args.headless
|
||||||
"""@brief Make stdout UTF-8 so the check mark of the messages prints on Windows."""
|
if args.profile_dir is None:
|
||||||
reconfigure = getattr(sys.stdout, "reconfigure", None)
|
args.profile_dir = default_profile_dir()
|
||||||
if reconfigure is not None:
|
return args
|
||||||
reconfigure(encoding="utf-8")
|
|
||||||
|
|
||||||
|
def _use_utf8_output() -> None:
|
||||||
def _save_step(gym: GymPort, screenshot_dir: Path | None, name: str) -> None:
|
"""@brief Make stdout UTF-8 so the check mark of the messages prints on Windows."""
|
||||||
"""@brief Save a screenshot when a folder was asked for.
|
reconfigure = getattr(sys.stdout, "reconfigure", None)
|
||||||
|
if reconfigure is not None:
|
||||||
@param gym The gym site.
|
reconfigure(encoding="utf-8")
|
||||||
@param screenshot_dir The folder, or None for no screenshots.
|
|
||||||
@param name The file name.
|
|
||||||
"""
|
def _save_step(gym: GymPort, screenshot_dir: Path | None, name: str) -> None:
|
||||||
if screenshot_dir is not None:
|
"""@brief Save a screenshot when a folder was asked for.
|
||||||
gym.save_screenshot(screenshot_dir / name)
|
|
||||||
|
@param gym The gym site.
|
||||||
|
@param screenshot_dir The folder, or None for no screenshots.
|
||||||
def _save_console(gym: GymPort, screenshot_dir: Path | None, text: str, name: str) -> None:
|
@param name The file name.
|
||||||
"""@brief Save console text as an image when a folder was asked for.
|
"""
|
||||||
|
if screenshot_dir is not None:
|
||||||
@param gym The gym site.
|
gym.save_screenshot(screenshot_dir / name)
|
||||||
@param screenshot_dir The folder, or None for no screenshots.
|
|
||||||
@param text The console text to draw.
|
|
||||||
@param name The file name.
|
def _save_console(gym: GymPort, screenshot_dir: Path | None, text: str, name: str) -> None:
|
||||||
"""
|
"""@brief Save console text as an image when a folder was asked for.
|
||||||
if screenshot_dir is not None:
|
|
||||||
gym.save_text_screenshot(text, screenshot_dir / name)
|
@param gym The gym site.
|
||||||
|
@param screenshot_dir The folder, or None for no screenshots.
|
||||||
|
@param text The console text to draw.
|
||||||
def _run(
|
@param name The file name.
|
||||||
gym: GymPort, args: argparse.Namespace, recorder: ConsoleRecorder, credentials: Credentials
|
"""
|
||||||
) -> None:
|
if screenshot_dir is not None:
|
||||||
"""@brief Open the site, log in and book the classes, saving the step images.
|
gym.save_text_screenshot(text, screenshot_dir / name)
|
||||||
|
|
||||||
Books every Tuesday and Thursday 6pm class and logs the summary and the detailed list;
|
|
||||||
with `--first-tuesday-only` it books the next Tuesday class only.
|
def _run(
|
||||||
|
gym: GymPort, args: argparse.Namespace, recorder: ConsoleRecorder, credentials: Credentials
|
||||||
|
) -> bool:
|
||||||
@param gym The gym site.
|
"""@brief Open the site, log in, book the classes and verify them, saving the step images.
|
||||||
@param args The parsed options.
|
|
||||||
@param recorder The recorded console lines, drawn for step 4.
|
Books every Tuesday and Thursday 6pm class, logs the summary and the detailed list and
|
||||||
@param credentials The account to log in with.
|
verifies the bookings on the My Bookings page; with `--first-tuesday-only` it books the
|
||||||
@exception GymError A step failed.
|
next Tuesday class only and does not verify.
|
||||||
"""
|
|
||||||
gym.open_site()
|
@param gym The gym site.
|
||||||
_save_step(gym, args.screenshot_dir, "step-1.png")
|
@param args The parsed options.
|
||||||
login(gym, credentials)
|
@param recorder The recorded console lines, drawn for step 4.
|
||||||
_save_step(gym, args.screenshot_dir, "step-2.png")
|
@param credentials The account to log in with.
|
||||||
if args.first_tuesday_only:
|
@return False when the My Bookings page does not match the bookings made, else True.
|
||||||
book_next_tuesday(gym)
|
@exception GymError A step failed.
|
||||||
_save_step(gym, args.screenshot_dir, constants.SCREENSHOT_STEP_3)
|
"""
|
||||||
_save_console(gym, args.screenshot_dir, recorder.text, constants.SCREENSHOT_STEP_4)
|
gym.open_site()
|
||||||
return
|
_save_step(gym, args.screenshot_dir, "step-1.png")
|
||||||
window_saved = False
|
login(gym, credentials)
|
||||||
|
_save_step(gym, args.screenshot_dir, "step-2.png")
|
||||||
def save_window_once(_: ClassResult) -> None:
|
if args.first_tuesday_only:
|
||||||
nonlocal window_saved
|
book_next_tuesday(gym)
|
||||||
if not window_saved:
|
_save_step(gym, args.screenshot_dir, constants.SCREENSHOT_STEP_3)
|
||||||
_save_step(gym, args.screenshot_dir, constants.SCREENSHOT_STEP_3)
|
_save_console(gym, args.screenshot_dir, recorder.text, constants.SCREENSHOT_STEP_4)
|
||||||
window_saved = True
|
return True
|
||||||
|
window_saved = False
|
||||||
results = book_target_classes(gym, save_window_once)
|
|
||||||
if not window_saved:
|
def save_window_once(_: ClassResult) -> None:
|
||||||
_save_step(gym, args.screenshot_dir, constants.SCREENSHOT_STEP_3)
|
nonlocal window_saved
|
||||||
_save_console(gym, args.screenshot_dir, recorder.text, constants.SCREENSHOT_STEP_4)
|
if not window_saved:
|
||||||
summary = format_summary(results)
|
_save_step(gym, args.screenshot_dir, constants.SCREENSHOT_STEP_3)
|
||||||
logger.info("%s", summary)
|
window_saved = True
|
||||||
_save_console(gym, args.screenshot_dir, summary, constants.SCREENSHOT_STEP_5)
|
|
||||||
detail = format_detail_list(results)
|
results = book_target_classes(gym, save_window_once)
|
||||||
logger.info("%s", detail)
|
if not window_saved:
|
||||||
_save_console(gym, args.screenshot_dir, f"{summary}\n{detail}", constants.SCREENSHOT_STEP_6)
|
_save_step(gym, args.screenshot_dir, constants.SCREENSHOT_STEP_3)
|
||||||
|
_save_console(gym, args.screenshot_dir, recorder.text, constants.SCREENSHOT_STEP_4)
|
||||||
|
summary = format_summary(results)
|
||||||
def main(
|
logger.info("%s", summary)
|
||||||
argv: Sequence[str] | None = None,
|
_save_console(gym, args.screenshot_dir, summary, constants.SCREENSHOT_STEP_5)
|
||||||
gym_factory: GymFactory = selenium_gym_factory,
|
detail = format_detail_list(results)
|
||||||
) -> int:
|
logger.info("%s", detail)
|
||||||
"""@brief Start the bot: open the site, log in and book the next Tuesday 6pm class.
|
_save_console(gym, args.screenshot_dir, f"{summary}\n{detail}", constants.SCREENSHOT_STEP_6)
|
||||||
|
verification = verify_bookings(gym, results)
|
||||||
@param argv Arguments without the program name; None reads `sys.argv`.
|
_save_step(gym, args.screenshot_dir, constants.SCREENSHOT_STEP_7)
|
||||||
@param gym_factory Builds the gym site; tests pass a fake.
|
verification_text = format_verification(verification)
|
||||||
@return Process exit code: 0 done, 1 a step failed, 2 credentials missing.
|
logger.info("%s", verification_text)
|
||||||
"""
|
_save_console(gym, args.screenshot_dir, verification_text, constants.SCREENSHOT_STEP_8)
|
||||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
return verification.is_success
|
||||||
root = logging.getLogger()
|
|
||||||
root.setLevel(logging.INFO)
|
|
||||||
recorder = ConsoleRecorder()
|
def main(
|
||||||
root.addHandler(recorder)
|
argv: Sequence[str] | None = None,
|
||||||
try:
|
gym_factory: GymFactory = selenium_gym_factory,
|
||||||
return _main(argv, gym_factory, recorder)
|
) -> int:
|
||||||
finally:
|
"""@brief Start the bot: open the site, log in and book the next Tuesday 6pm class.
|
||||||
root.removeHandler(recorder)
|
|
||||||
|
@param argv Arguments without the program name; None reads `sys.argv`.
|
||||||
|
@param gym_factory Builds the gym site; tests pass a fake.
|
||||||
def _main(argv: Sequence[str] | None, gym_factory: GymFactory, recorder: ConsoleRecorder) -> int:
|
@return Process exit code: 0 done, 1 a step failed, 2 credentials missing, 3 mismatch.
|
||||||
"""@brief The body of `main`, run while the recorder is attached.
|
"""
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||||
@param argv Arguments without the program name.
|
root = logging.getLogger()
|
||||||
@param gym_factory Builds the gym site.
|
root.setLevel(logging.INFO)
|
||||||
@param recorder The console recorder.
|
recorder = ConsoleRecorder()
|
||||||
@return Process exit code.
|
root.addHandler(recorder)
|
||||||
"""
|
try:
|
||||||
_use_utf8_output()
|
return _main(argv, gym_factory, recorder)
|
||||||
args = parse_args(argv)
|
finally:
|
||||||
try:
|
root.removeHandler(recorder)
|
||||||
credentials = load_credentials(os.environ)
|
|
||||||
except MissingCredentialsError as error:
|
|
||||||
logger.error("%s", error)
|
def _main(argv: Sequence[str] | None, gym_factory: GymFactory, recorder: ConsoleRecorder) -> int:
|
||||||
return 2
|
"""@brief The body of `main`, run while the recorder is attached.
|
||||||
gym = gym_factory(args.headless, args.profile_dir, args.keep_open)
|
|
||||||
try:
|
@param argv Arguments without the program name.
|
||||||
_run(gym, args, recorder, credentials)
|
@param gym_factory Builds the gym site.
|
||||||
except LoginFailedError as error:
|
@param recorder The console recorder.
|
||||||
logger.error("Login failed: %s", error)
|
@return Process exit code.
|
||||||
return 1
|
"""
|
||||||
except GymError as error:
|
_use_utf8_output()
|
||||||
logger.error("Failed: %s", error)
|
args = parse_args(argv)
|
||||||
return 1
|
try:
|
||||||
finally:
|
credentials = load_credentials(os.environ)
|
||||||
if not args.keep_open:
|
except MissingCredentialsError as error:
|
||||||
gym.close()
|
logger.error("%s", error)
|
||||||
return 0
|
return 2
|
||||||
|
gym = gym_factory(args.headless, args.profile_dir, args.keep_open)
|
||||||
|
try:
|
||||||
|
verified = _run(gym, args, recorder, credentials)
|
||||||
|
except LoginFailedError as error:
|
||||||
|
logger.error("Login failed: %s", error)
|
||||||
|
return 1
|
||||||
|
except GymError as error:
|
||||||
|
logger.error("Failed: %s", error)
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
if not args.keep_open:
|
||||||
|
gym.close()
|
||||||
|
return 0 if verified else constants.EXIT_VERIFICATION_MISMATCH
|
||||||
|
|||||||
@@ -152,3 +152,54 @@ CONSOLE_PAGE_TEMPLATE: Final[str] = (
|
|||||||
|
|
||||||
## Prefix of the `data:` URL that carries the console page.
|
## Prefix of the `data:` URL that carries the console page.
|
||||||
CONSOLE_PAGE_URL_PREFIX: Final[str] = "data:text/html;charset=utf-8,"
|
CONSOLE_PAGE_URL_PREFIX: Final[str] = "data:text/html;charset=utf-8,"
|
||||||
|
|
||||||
|
## File names of the screenshots of lecture steps 7 and 8.
|
||||||
|
SCREENSHOT_STEP_7: Final[str] = "step-7.png"
|
||||||
|
SCREENSHOT_STEP_8: Final[str] = "step-8.png"
|
||||||
|
|
||||||
|
## Process exit code when the My Bookings page does not match what the bot did.
|
||||||
|
EXIT_VERIFICATION_MISMATCH: Final[int] = 3
|
||||||
|
|
||||||
|
## Id of the navigation link that opens the My Bookings page.
|
||||||
|
MY_BOOKINGS_LINK_ID: Final[str] = "my-bookings-link"
|
||||||
|
|
||||||
|
## Id of the My Bookings page, shown after its bookings were loaded.
|
||||||
|
MY_BOOKINGS_PAGE_ID: Final[str] = "my-bookings-page"
|
||||||
|
|
||||||
|
## Id of the element shown when the account has no booking and no waitlist entry.
|
||||||
|
EMPTY_BOOKINGS_STATE_ID: Final[str] = "empty-bookings-state"
|
||||||
|
|
||||||
|
## CSS selectors of the confirmed booking cards and the waitlist cards.
|
||||||
|
BOOKING_CARD_CSS: Final[str] = "#confirmed-bookings-section div[id^='booking-card-']"
|
||||||
|
WAITLIST_CARD_CSS: Final[str] = "#waitlist-section div[id^='waitlist-card-']"
|
||||||
|
|
||||||
|
## Prefixes of the element ids of a booking card and of a waitlist card.
|
||||||
|
BOOKING_CARD_ID_PREFIX: Final[str] = "booking-card-"
|
||||||
|
BOOKING_NAME_ID_PREFIX: Final[str] = "booking-class-name-"
|
||||||
|
WAITLIST_CARD_ID_PREFIX: Final[str] = "waitlist-card-"
|
||||||
|
WAITLIST_NAME_ID_PREFIX: Final[str] = "waitlist-class-name-"
|
||||||
|
|
||||||
|
## XPath, relative to a card, of the paragraph "When: Tue, Aug 12, 6:00 PM".
|
||||||
|
WHEN_XPATH: Final[str] = ".//p[strong[starts-with(normalize-space(), 'When:')]]"
|
||||||
|
|
||||||
|
## Prefix of the date and time text of a booking card.
|
||||||
|
WHEN_TEXT_PREFIX: Final[str] = "When:"
|
||||||
|
|
||||||
|
## Suffix the My Bookings page adds to the name of a waitlist entry.
|
||||||
|
WAITLIST_NAME_SUFFIX: Final[str] = " (Waitlist)"
|
||||||
|
|
||||||
|
## Message of the error raised when the My Bookings page shows no booking at all.
|
||||||
|
MESSAGE_NO_BOOKINGS_FOUND: Final[str] = "The My Bookings page shows no booking or waitlist entry"
|
||||||
|
|
||||||
|
## Lines of the verification on the My Bookings page (lecture steps 7 and 8).
|
||||||
|
VERIFY_TITLE: Final[str] = "--- VERIFYING ON MY BOOKINGS PAGE ---"
|
||||||
|
VERIFY_LINE_VERIFIED: Final[str] = " ✓ Verified: {name}"
|
||||||
|
VERIFY_RESULT_TITLE: Final[str] = "--- VERIFICATION RESULT ---"
|
||||||
|
VERIFY_EXPECTED: Final[str] = "Expected: {count} {noun}"
|
||||||
|
VERIFY_FOUND: Final[str] = "Found: {count} {noun}"
|
||||||
|
VERIFY_NOUN_SINGULAR: Final[str] = "booking"
|
||||||
|
VERIFY_NOUN_PLURAL: Final[str] = "bookings"
|
||||||
|
VERIFY_SUCCESS: Final[str] = "✅ SUCCESS: All bookings verified!"
|
||||||
|
VERIFY_MISMATCH: Final[str] = "❌ MISMATCH: Missing {count} bookings"
|
||||||
|
VERIFY_LINE_MISSING: Final[str] = " ✗ Missing: {entry}"
|
||||||
|
VERIFY_LINE_UNEXPECTED: Final[str] = " ? Unexpected: {entry}"
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""@file booking_entry.py
|
||||||
|
@brief One entry of the My Bookings page: a confirmed booking or a waitlist entry.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from snack_and_lift import constants
|
||||||
|
from snack_and_lift.domain.day_label import parse_day_label
|
||||||
|
from snack_and_lift.domain.errors import PageFormatError
|
||||||
|
from snack_and_lift.domain.rules import parse_time
|
||||||
|
|
||||||
|
_WHEN = re.compile(r"(?P<date>[A-Z][a-z]{2}, [A-Z][a-z]{2} \d{1,2}), (?P<time>.+)")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class BookingEntry:
|
||||||
|
"""@brief A booking or waitlist entry, as read from the My Bookings page.
|
||||||
|
|
||||||
|
`name` is the class name WITHOUT the ` (Waitlist)` suffix the page adds to a waitlist
|
||||||
|
entry; `waitlisted` carries that fact. `when_text` is the page text without the
|
||||||
|
`When:` prefix, for example `Tue, Aug 12, 6:00 PM`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
when_text: str
|
||||||
|
waitlisted: bool
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_page(cls, heading: str, when_text: str, waitlisted: bool) -> "BookingEntry":
|
||||||
|
"""@brief Build an entry from the texts of its card.
|
||||||
|
|
||||||
|
@param heading The class name as the page shows it, possibly with the waitlist suffix.
|
||||||
|
@param when_text The date and time paragraph, with or without the `When:` prefix.
|
||||||
|
@param waitlisted True for a card of the waitlist section.
|
||||||
|
@return The entry, with the suffix and the prefix removed.
|
||||||
|
"""
|
||||||
|
name = heading.strip().removesuffix(constants.WAITLIST_NAME_SUFFIX.strip()).strip()
|
||||||
|
when = when_text.strip().removeprefix(constants.WHEN_TEXT_PREFIX).strip()
|
||||||
|
return cls(name, when, waitlisted)
|
||||||
|
|
||||||
|
def _split_when(self) -> tuple[str, str]:
|
||||||
|
"""@brief Split the date text from the time text.
|
||||||
|
|
||||||
|
@return The date text (`Tue, Aug 12`) and the time text (`6:00 PM`).
|
||||||
|
@exception PageFormatError The text has no date and time.
|
||||||
|
"""
|
||||||
|
match = _WHEN.fullmatch(self.when_text)
|
||||||
|
if match is None:
|
||||||
|
raise PageFormatError(f"Unexpected booking date and time: {self.when_text!r}")
|
||||||
|
return match["date"], match["time"]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def weekday(self) -> str:
|
||||||
|
"""@brief The weekday of the entry (`Tue`).
|
||||||
|
|
||||||
|
@exception PageFormatError The date and time text is not valid.
|
||||||
|
"""
|
||||||
|
return parse_day_label(self._split_when()[0])[0]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def date_text(self) -> str:
|
||||||
|
"""@brief The date of the entry (`Tue, Aug 12`), comparable with a class card's date.
|
||||||
|
|
||||||
|
@exception PageFormatError The date and time text is not valid.
|
||||||
|
"""
|
||||||
|
return parse_day_label(self._split_when()[0])[1]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def time(self) -> tuple[int, int]:
|
||||||
|
"""@brief The hour (0-23) and the minute of the entry.
|
||||||
|
|
||||||
|
@exception PageFormatError The date and time text is not valid.
|
||||||
|
"""
|
||||||
|
return parse_time(self._split_when()[1])
|
||||||
|
|
||||||
|
|
||||||
|
def is_target_entry(entry: BookingEntry) -> bool:
|
||||||
|
"""@brief Tell whether the entry is a class the bot books: a target weekday at the target time.
|
||||||
|
|
||||||
|
@param entry The entry.
|
||||||
|
@return True for Tuesday or Thursday at `TARGET_HOUR`:`TARGET_MINUTE`.
|
||||||
|
@exception PageFormatError The date and time text is not valid.
|
||||||
|
"""
|
||||||
|
return entry.weekday in constants.TARGET_WEEKDAYS and entry.time == (
|
||||||
|
constants.TARGET_HOUR,
|
||||||
|
constants.TARGET_MINUTE,
|
||||||
|
)
|
||||||
@@ -21,3 +21,11 @@ class UnknownButtonError(GymError):
|
|||||||
|
|
||||||
class PageFormatError(GymError):
|
class PageFormatError(GymError):
|
||||||
"""@brief A text read from the page (a day label or a time) has an unexpected format."""
|
"""@brief A text read from the page (a day label or a time) has an unexpected format."""
|
||||||
|
|
||||||
|
|
||||||
|
class NoBookingsFoundError(GymError):
|
||||||
|
"""@brief The My Bookings page shows no booking where the bot expects some.
|
||||||
|
|
||||||
|
The project's counterpart of Selenium's `NoSuchElementException`, which the lecture asks
|
||||||
|
the student to raise when the bookings that should be there are missing.
|
||||||
|
"""
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""@file verification.py
|
||||||
|
@brief Lecture steps 7 and 8: compare what the bot did with the My Bookings page.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from snack_and_lift import constants
|
||||||
|
from snack_and_lift.domain.booking_entry import BookingEntry
|
||||||
|
from snack_and_lift.domain.models import ClassResult, Outcome
|
||||||
|
|
||||||
|
_WAITLISTED_OUTCOMES = (Outcome.NEW_WAITLIST, Outcome.ALREADY_WAITLISTED)
|
||||||
|
|
||||||
|
## An entry is identified by its class name, its date text and whether it is waitlisted.
|
||||||
|
_Key = tuple[str, str, bool]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class VerificationResult:
|
||||||
|
"""@brief What the My Bookings page shows compared with what the bot did.
|
||||||
|
|
||||||
|
`verified`, `missing` and `unexpected` hold display names, with the waitlist suffix for a
|
||||||
|
waitlist entry; `missing` and `unexpected` also say the day (`Spin Class on Tue, Aug 12`).
|
||||||
|
"""
|
||||||
|
|
||||||
|
expected: int
|
||||||
|
found: int
|
||||||
|
verified: list[str]
|
||||||
|
missing: list[str]
|
||||||
|
unexpected: list[str]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_success(self) -> bool:
|
||||||
|
"""@brief True when every expected entry was found and nothing else was."""
|
||||||
|
return self.expected == self.found and not self.missing and not self.unexpected
|
||||||
|
|
||||||
|
|
||||||
|
def _display_name(name: str, waitlisted: bool) -> str:
|
||||||
|
"""@brief The name as the page shows it."""
|
||||||
|
return name + constants.WAITLIST_NAME_SUFFIX if waitlisted else name
|
||||||
|
|
||||||
|
|
||||||
|
def _expected_keys(results: Sequence[ClassResult]) -> list[_Key]:
|
||||||
|
"""@brief The entries the bot's results say must be on the page."""
|
||||||
|
return [(r.card.name, r.card.date_text, r.outcome in _WAITLISTED_OUTCOMES) for r in results]
|
||||||
|
|
||||||
|
|
||||||
|
def _entry_keys(entries: Sequence[BookingEntry]) -> list[_Key]:
|
||||||
|
"""@brief The identity of each entry found on the page."""
|
||||||
|
return [(e.name, e.date_text, e.waitlisted) for e in entries]
|
||||||
|
|
||||||
|
|
||||||
|
def _describe(key: _Key) -> str:
|
||||||
|
"""@brief Write an entry for the missing and unexpected lines."""
|
||||||
|
name, day, waitlisted = key
|
||||||
|
return f"{_display_name(name, waitlisted)} on {day}"
|
||||||
|
|
||||||
|
|
||||||
|
def build_verification(
|
||||||
|
results: Sequence[ClassResult], entries: Sequence[BookingEntry]
|
||||||
|
) -> VerificationResult:
|
||||||
|
"""@brief Compare the results of the booking with the target entries of the page.
|
||||||
|
|
||||||
|
@param results What happened to each class; waitlisted when the outcome is a waitlist one.
|
||||||
|
@param entries The Tuesday and Thursday 6pm entries found on the page.
|
||||||
|
@return The comparison; the counts are the numbers of results and of entries.
|
||||||
|
@exception PageFormatError An entry or a card has no valid date.
|
||||||
|
"""
|
||||||
|
expected = _expected_keys(results)
|
||||||
|
remaining = Counter(_entry_keys(entries))
|
||||||
|
verified: list[str] = []
|
||||||
|
missing: list[str] = []
|
||||||
|
for key in expected:
|
||||||
|
if remaining[key] > 0:
|
||||||
|
remaining[key] -= 1
|
||||||
|
verified.append(_display_name(key[0], key[2]))
|
||||||
|
else:
|
||||||
|
missing.append(_describe(key))
|
||||||
|
unexpected = [_describe(key) for key in remaining.elements()]
|
||||||
|
return VerificationResult(len(expected), len(entries), verified, missing, unexpected)
|
||||||
|
|
||||||
|
|
||||||
|
def _count_text(template: str, count: int) -> str:
|
||||||
|
"""@brief Write a count with `booking` in the singular for 1."""
|
||||||
|
noun = constants.VERIFY_NOUN_SINGULAR if count == 1 else constants.VERIFY_NOUN_PLURAL
|
||||||
|
return template.format(count=count, noun=noun)
|
||||||
|
|
||||||
|
|
||||||
|
def format_verification(result: VerificationResult) -> str:
|
||||||
|
"""@brief Write the verification block.
|
||||||
|
|
||||||
|
@param result The comparison.
|
||||||
|
@return The block, starting with `--- VERIFYING ON MY BOOKINGS PAGE ---`.
|
||||||
|
"""
|
||||||
|
lines = [constants.VERIFY_TITLE]
|
||||||
|
lines.extend(constants.VERIFY_LINE_VERIFIED.format(name=name) for name in result.verified)
|
||||||
|
lines.append("")
|
||||||
|
lines.append(constants.VERIFY_RESULT_TITLE)
|
||||||
|
lines.append(_count_text(constants.VERIFY_EXPECTED, result.expected))
|
||||||
|
lines.append(_count_text(constants.VERIFY_FOUND, result.found))
|
||||||
|
if result.is_success:
|
||||||
|
lines.append(constants.VERIFY_SUCCESS)
|
||||||
|
return "\n".join(lines)
|
||||||
|
lines.append(constants.VERIFY_MISMATCH.format(count=result.expected - result.found))
|
||||||
|
lines.extend(constants.VERIFY_LINE_MISSING.format(entry=text) for text in result.missing)
|
||||||
|
lines.extend(constants.VERIFY_LINE_UNEXPECTED.format(entry=text) for text in result.unexpected)
|
||||||
|
return "\n".join(lines)
|
||||||
@@ -1,194 +1,255 @@
|
|||||||
"""@file selenium_gym.py
|
"""@file selenium_gym.py
|
||||||
@brief The Selenium adapter of the GymPort.
|
@brief The Selenium adapter of the GymPort.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import functools
|
import functools
|
||||||
import html
|
import html
|
||||||
import logging
|
import logging
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from string import Template
|
from string import Template
|
||||||
from typing import Concatenate, Literal
|
from typing import Concatenate, Literal
|
||||||
|
|
||||||
from selenium.common.exceptions import (
|
from selenium.common.exceptions import (
|
||||||
ElementClickInterceptedException,
|
ElementClickInterceptedException,
|
||||||
NoSuchElementException,
|
NoSuchElementException,
|
||||||
StaleElementReferenceException,
|
StaleElementReferenceException,
|
||||||
TimeoutException,
|
TimeoutException,
|
||||||
)
|
)
|
||||||
from selenium.webdriver.common.by import By
|
from selenium.webdriver.common.by import By
|
||||||
from selenium.webdriver.remote.webdriver import WebDriver
|
from selenium.webdriver.remote.webdriver import WebDriver
|
||||||
from selenium.webdriver.remote.webelement import WebElement
|
from selenium.webdriver.remote.webelement import WebElement
|
||||||
from selenium.webdriver.support import expected_conditions as ec
|
from selenium.webdriver.support import expected_conditions as ec
|
||||||
from selenium.webdriver.support.ui import WebDriverWait
|
from selenium.webdriver.support.ui import WebDriverWait
|
||||||
|
|
||||||
from snack_and_lift import constants
|
from snack_and_lift import constants
|
||||||
from snack_and_lift.domain.errors import GymError, LoginFailedError
|
from snack_and_lift.domain.booking_entry import BookingEntry
|
||||||
from snack_and_lift.domain.models import ButtonState, ClassCard
|
from snack_and_lift.domain.errors import GymError, LoginFailedError
|
||||||
|
from snack_and_lift.domain.models import ButtonState, ClassCard
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
_SELENIUM_ERRORS = (
|
|
||||||
TimeoutException,
|
_SELENIUM_ERRORS = (
|
||||||
NoSuchElementException,
|
TimeoutException,
|
||||||
StaleElementReferenceException,
|
NoSuchElementException,
|
||||||
ElementClickInterceptedException,
|
StaleElementReferenceException,
|
||||||
)
|
ElementClickInterceptedException,
|
||||||
|
)
|
||||||
|
|
||||||
def _translate_errors[S, **P, R](
|
|
||||||
method: Callable[Concatenate[S, P], R],
|
def _translate_errors[S, **P, R](
|
||||||
) -> Callable[Concatenate[S, P], R]:
|
method: Callable[Concatenate[S, P], R],
|
||||||
"""@brief Turn Selenium errors of a method into GymError.
|
) -> Callable[Concatenate[S, P], R]:
|
||||||
|
"""@brief Turn Selenium errors of a method into GymError.
|
||||||
@param method The adapter method to wrap.
|
|
||||||
@return The wrapped method.
|
@param method The adapter method to wrap.
|
||||||
"""
|
@return The wrapped method.
|
||||||
|
"""
|
||||||
@functools.wraps(method)
|
|
||||||
def wrapper(self: S, *args: P.args, **kwargs: P.kwargs) -> R:
|
@functools.wraps(method)
|
||||||
try:
|
def wrapper(self: S, *args: P.args, **kwargs: P.kwargs) -> R:
|
||||||
return method(self, *args, **kwargs)
|
try:
|
||||||
except _SELENIUM_ERRORS as error:
|
return method(self, *args, **kwargs)
|
||||||
raise GymError(f"{method.__name__} failed: {type(error).__name__}") from error
|
except _SELENIUM_ERRORS as error:
|
||||||
|
raise GymError(f"{method.__name__} failed: {type(error).__name__}") from error
|
||||||
return wrapper
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
class SeleniumGym:
|
|
||||||
"""@brief The gym site driven by a Selenium WebDriver."""
|
class SeleniumGym:
|
||||||
|
"""@brief The gym site driven by a Selenium WebDriver."""
|
||||||
def __init__(self, driver: WebDriver, base_url: str = constants.GYM_URL) -> None:
|
|
||||||
"""@brief Wrap a driver.
|
def __init__(self, driver: WebDriver, base_url: str = constants.GYM_URL) -> None:
|
||||||
|
"""@brief Wrap a driver.
|
||||||
@param driver A running WebDriver.
|
|
||||||
@param base_url The address of the home page.
|
@param driver A running WebDriver.
|
||||||
"""
|
@param base_url The address of the home page.
|
||||||
self._driver = driver
|
"""
|
||||||
self._base_url = base_url
|
self._driver = driver
|
||||||
self._wait = WebDriverWait(driver, constants.WAIT_TIMEOUT_SECONDS)
|
self._base_url = base_url
|
||||||
|
self._wait = WebDriverWait(driver, constants.WAIT_TIMEOUT_SECONDS)
|
||||||
@_translate_errors
|
|
||||||
def open_site(self) -> None:
|
@_translate_errors
|
||||||
"""@brief Open the home page and wait for the login button.
|
def open_site(self) -> None:
|
||||||
|
"""@brief Open the home page and wait for the login button.
|
||||||
@exception GymError The page did not load.
|
|
||||||
"""
|
@exception GymError The page did not load.
|
||||||
self._driver.get(self._base_url)
|
"""
|
||||||
self._wait.until(ec.presence_of_element_located((By.ID, constants.NAV_LOGIN_BUTTON_ID)))
|
self._driver.get(self._base_url)
|
||||||
|
self._wait.until(ec.presence_of_element_located((By.ID, constants.NAV_LOGIN_BUTTON_ID)))
|
||||||
@_translate_errors
|
|
||||||
def log_in(self, email: str, password: str) -> None:
|
@_translate_errors
|
||||||
"""@brief Fill in the login form and wait for the schedule or an error.
|
def log_in(self, email: str, password: str) -> None:
|
||||||
|
"""@brief Fill in the login form and wait for the schedule or an error.
|
||||||
@param email The account e-mail.
|
|
||||||
@param password The account password.
|
@param email The account e-mail.
|
||||||
@exception LoginFailedError The site shows a login error.
|
@param password The account password.
|
||||||
@exception GymError The page did not behave as expected.
|
@exception LoginFailedError The site shows a login error.
|
||||||
"""
|
@exception GymError The page did not behave as expected.
|
||||||
self._wait.until(ec.element_to_be_clickable((By.ID, constants.NAV_LOGIN_BUTTON_ID))).click()
|
"""
|
||||||
self._wait.until(
|
self._wait.until(ec.element_to_be_clickable((By.ID, constants.NAV_LOGIN_BUTTON_ID))).click()
|
||||||
ec.presence_of_element_located((By.ID, constants.LOGIN_EMAIL_INPUT_ID))
|
self._wait.until(
|
||||||
).send_keys(email)
|
ec.presence_of_element_located((By.ID, constants.LOGIN_EMAIL_INPUT_ID))
|
||||||
self._driver.find_element(By.ID, constants.LOGIN_PASSWORD_INPUT_ID).send_keys(password)
|
).send_keys(email)
|
||||||
self._driver.find_element(By.ID, constants.LOGIN_SUBMIT_BUTTON_ID).click()
|
self._driver.find_element(By.ID, constants.LOGIN_PASSWORD_INPUT_ID).send_keys(password)
|
||||||
self._wait.until(
|
self._driver.find_element(By.ID, constants.LOGIN_SUBMIT_BUTTON_ID).click()
|
||||||
ec.any_of(
|
self._wait.until(
|
||||||
ec.presence_of_element_located((By.ID, constants.SCHEDULE_PAGE_ID)),
|
ec.any_of(
|
||||||
ec.presence_of_element_located((By.ID, constants.ERROR_MESSAGE_ID)),
|
ec.presence_of_element_located((By.ID, constants.SCHEDULE_PAGE_ID)),
|
||||||
)
|
ec.presence_of_element_located((By.ID, constants.ERROR_MESSAGE_ID)),
|
||||||
)
|
)
|
||||||
errors = self._driver.find_elements(By.ID, constants.ERROR_MESSAGE_ID)
|
)
|
||||||
if errors:
|
errors = self._driver.find_elements(By.ID, constants.ERROR_MESSAGE_ID)
|
||||||
raise LoginFailedError(errors[0].text)
|
if errors:
|
||||||
|
raise LoginFailedError(errors[0].text)
|
||||||
@_translate_errors
|
|
||||||
def list_class_cards(self) -> list[ClassCard]:
|
@_translate_errors
|
||||||
"""@brief Read every class card; the day comes from the ancestor day group.
|
def list_class_cards(self) -> list[ClassCard]:
|
||||||
|
"""@brief Read every class card; the day comes from the ancestor day group.
|
||||||
@return The classes in page order.
|
|
||||||
@exception GymError The schedule could not be read.
|
@return The classes in page order.
|
||||||
"""
|
@exception GymError The schedule could not be read.
|
||||||
self._wait.until(
|
"""
|
||||||
ec.presence_of_element_located((By.CSS_SELECTOR, constants.CLASS_CARD_CSS))
|
self._wait.until(
|
||||||
)
|
ec.presence_of_element_located((By.CSS_SELECTOR, constants.CLASS_CARD_CSS))
|
||||||
elements = self._driver.find_elements(By.CSS_SELECTOR, constants.CLASS_CARD_CSS)
|
)
|
||||||
return [self._read_card(element) for element in elements]
|
elements = self._driver.find_elements(By.CSS_SELECTOR, constants.CLASS_CARD_CSS)
|
||||||
|
return [self._read_card(element) for element in elements]
|
||||||
def _read_card(self, element: WebElement) -> ClassCard:
|
|
||||||
"""@brief Turn one card element into plain data.
|
def _read_card(self, element: WebElement) -> ClassCard:
|
||||||
|
"""@brief Turn one card element into plain data.
|
||||||
@param element The card.
|
|
||||||
@return The class.
|
@param element The card.
|
||||||
"""
|
@return The class.
|
||||||
card_id = (element.get_attribute("id") or "").removeprefix(constants.CLASS_CARD_ID_PREFIX)
|
"""
|
||||||
buttons = element.find_elements(By.ID, constants.BOOK_BUTTON_ID_PREFIX + card_id)
|
card_id = (element.get_attribute("id") or "").removeprefix(constants.CLASS_CARD_ID_PREFIX)
|
||||||
labels = element.find_elements(By.ID, constants.COMPLETED_LABEL_ID_PREFIX + card_id)
|
buttons = element.find_elements(By.ID, constants.BOOK_BUTTON_ID_PREFIX + card_id)
|
||||||
control = (buttons or labels or [None])[0]
|
labels = element.find_elements(By.ID, constants.COMPLETED_LABEL_ID_PREFIX + card_id)
|
||||||
return ClassCard(
|
control = (buttons or labels or [None])[0]
|
||||||
card_id=card_id,
|
return ClassCard(
|
||||||
name=element.find_element(By.ID, constants.CLASS_NAME_ID_PREFIX + card_id).text,
|
card_id=card_id,
|
||||||
day_label=element.find_element(By.XPATH, constants.DAY_TITLE_XPATH).text,
|
name=element.find_element(By.ID, constants.CLASS_NAME_ID_PREFIX + card_id).text,
|
||||||
time_text=element.find_element(By.ID, constants.CLASS_TIME_ID_PREFIX + card_id).text,
|
day_label=element.find_element(By.XPATH, constants.DAY_TITLE_XPATH).text,
|
||||||
button_text=control.text if control is not None else "",
|
time_text=element.find_element(By.ID, constants.CLASS_TIME_ID_PREFIX + card_id).text,
|
||||||
)
|
button_text=control.text if control is not None else "",
|
||||||
|
)
|
||||||
@_translate_errors
|
|
||||||
def press_class_button(self, card_id: str) -> str:
|
@_translate_errors
|
||||||
"""@brief Scroll to the button, click it and wait for the result or the error box.
|
def press_class_button(self, card_id: str) -> str:
|
||||||
|
"""@brief Scroll to the button, click it and wait for the result or the error box.
|
||||||
@param card_id The id of the card without its prefix.
|
|
||||||
@return The new text of the button.
|
@param card_id The id of the card without its prefix.
|
||||||
@exception GymError The site shows an error for the class, or nothing settled in time.
|
@return The new text of the button.
|
||||||
"""
|
@exception GymError The site shows an error for the class, or nothing settled in time.
|
||||||
button_id = constants.BOOK_BUTTON_ID_PREFIX + card_id
|
"""
|
||||||
button = self._wait.until(ec.presence_of_element_located((By.ID, button_id)))
|
button_id = constants.BOOK_BUTTON_ID_PREFIX + card_id
|
||||||
self._driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
|
button = self._wait.until(ec.presence_of_element_located((By.ID, button_id)))
|
||||||
before = button.text
|
self._driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
|
||||||
self._wait.until(ec.element_to_be_clickable((By.ID, button_id))).click()
|
before = button.text
|
||||||
|
self._wait.until(ec.element_to_be_clickable((By.ID, button_id))).click()
|
||||||
def settled(driver: WebDriver) -> tuple[str, str] | Literal[False]:
|
|
||||||
errors = driver.find_elements(By.ID, constants.CLASS_ERROR_ID_PREFIX + card_id)
|
def settled(driver: WebDriver) -> tuple[str, str] | Literal[False]:
|
||||||
text = driver.find_element(By.ID, button_id).text
|
errors = driver.find_elements(By.ID, constants.CLASS_ERROR_ID_PREFIX + card_id)
|
||||||
if errors:
|
text = driver.find_element(By.ID, button_id).text
|
||||||
return text, errors[0].text or "class error"
|
if errors:
|
||||||
if text != before and ButtonState.from_text(text) is not ButtonState.BUSY:
|
return text, errors[0].text or "class error"
|
||||||
return text, ""
|
if text != before and ButtonState.from_text(text) is not ButtonState.BUSY:
|
||||||
return False
|
return text, ""
|
||||||
|
return False
|
||||||
text, error = self._wait.until(settled)
|
|
||||||
if error:
|
text, error = self._wait.until(settled)
|
||||||
raise GymError(error)
|
if error:
|
||||||
return text
|
raise GymError(error)
|
||||||
|
return text
|
||||||
@_translate_errors
|
|
||||||
def save_text_screenshot(self, text: str, path: Path) -> None:
|
@_translate_errors
|
||||||
"""@brief Draw console text in a temporary tab and save a screenshot of it.
|
def open_my_bookings(self) -> None:
|
||||||
|
"""@brief Click the My Bookings link and wait for the page.
|
||||||
A tab is used so that the schedule page keeps its state.
|
|
||||||
|
@exception GymError The page did not load.
|
||||||
@param text The lines to draw.
|
"""
|
||||||
@param path The PNG file to write; its folders are created.
|
self._wait.until(ec.element_to_be_clickable((By.ID, constants.MY_BOOKINGS_LINK_ID))).click()
|
||||||
"""
|
self._wait.until(ec.presence_of_element_located((By.ID, constants.MY_BOOKINGS_PAGE_ID)))
|
||||||
page = Template(constants.CONSOLE_PAGE_TEMPLATE).substitute(text=html.escape(text))
|
|
||||||
original = self._driver.current_window_handle
|
@_translate_errors
|
||||||
self._driver.switch_to.new_window("tab")
|
def list_my_bookings(self) -> list[BookingEntry]:
|
||||||
try:
|
"""@brief Wait for the bookings to load, then read the confirmed and waitlist cards.
|
||||||
self._driver.get(constants.CONSOLE_PAGE_URL_PREFIX + urllib.parse.quote(page))
|
|
||||||
self.save_screenshot(path)
|
@return The entries, confirmed ones first; empty when the page shows its empty state.
|
||||||
finally:
|
@exception GymError The page shows an error box, or nothing was shown in time.
|
||||||
self._driver.close()
|
"""
|
||||||
self._driver.switch_to.window(original)
|
self._wait.until(
|
||||||
|
ec.any_of(
|
||||||
def save_screenshot(self, path: Path) -> None:
|
ec.presence_of_element_located((By.CSS_SELECTOR, constants.BOOKING_CARD_CSS)),
|
||||||
"""@brief Save a screenshot of the current page.
|
ec.presence_of_element_located((By.CSS_SELECTOR, constants.WAITLIST_CARD_CSS)),
|
||||||
|
ec.presence_of_element_located((By.ID, constants.EMPTY_BOOKINGS_STATE_ID)),
|
||||||
@param path The PNG file to write; its folders are created.
|
ec.presence_of_element_located((By.ID, constants.ERROR_MESSAGE_ID)),
|
||||||
"""
|
)
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
)
|
||||||
self._driver.save_screenshot(str(path))
|
errors = self._driver.find_elements(By.ID, constants.ERROR_MESSAGE_ID)
|
||||||
|
if errors:
|
||||||
def close(self) -> None:
|
raise GymError(errors[0].text or "My Bookings error")
|
||||||
"""@brief Quit the browser."""
|
confirmed = self._driver.find_elements(By.CSS_SELECTOR, constants.BOOKING_CARD_CSS)
|
||||||
self._driver.quit()
|
waitlist = self._driver.find_elements(By.CSS_SELECTOR, constants.WAITLIST_CARD_CSS)
|
||||||
|
return [
|
||||||
|
self._read_entry(
|
||||||
|
element, constants.BOOKING_CARD_ID_PREFIX, constants.BOOKING_NAME_ID_PREFIX, False
|
||||||
|
)
|
||||||
|
for element in confirmed
|
||||||
|
] + [
|
||||||
|
self._read_entry(
|
||||||
|
element, constants.WAITLIST_CARD_ID_PREFIX, constants.WAITLIST_NAME_ID_PREFIX, True
|
||||||
|
)
|
||||||
|
for element in waitlist
|
||||||
|
]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _read_entry(
|
||||||
|
element: WebElement, card_prefix: str, name_prefix: str, waitlisted: bool
|
||||||
|
) -> BookingEntry:
|
||||||
|
"""@brief Turn one booking or waitlist card into plain data.
|
||||||
|
|
||||||
|
@param element The card.
|
||||||
|
@param card_prefix The prefix of the card id.
|
||||||
|
@param name_prefix The prefix of the id of the card's heading.
|
||||||
|
@param waitlisted True for a card of the waitlist section.
|
||||||
|
@return The entry.
|
||||||
|
"""
|
||||||
|
card_id = (element.get_attribute("id") or "").removeprefix(card_prefix)
|
||||||
|
return BookingEntry.from_page(
|
||||||
|
heading=element.find_element(By.ID, name_prefix + card_id).text,
|
||||||
|
when_text=element.find_element(By.XPATH, constants.WHEN_XPATH).text,
|
||||||
|
waitlisted=waitlisted,
|
||||||
|
)
|
||||||
|
|
||||||
|
@_translate_errors
|
||||||
|
def save_text_screenshot(self, text: str, path: Path) -> None:
|
||||||
|
"""@brief Draw console text in a temporary tab and save a screenshot of it.
|
||||||
|
|
||||||
|
A tab is used so that the schedule page keeps its state.
|
||||||
|
|
||||||
|
@param text The lines to draw.
|
||||||
|
@param path The PNG file to write; its folders are created.
|
||||||
|
"""
|
||||||
|
page = Template(constants.CONSOLE_PAGE_TEMPLATE).substitute(text=html.escape(text))
|
||||||
|
original = self._driver.current_window_handle
|
||||||
|
self._driver.switch_to.new_window("tab")
|
||||||
|
try:
|
||||||
|
self._driver.get(constants.CONSOLE_PAGE_URL_PREFIX + urllib.parse.quote(page))
|
||||||
|
self.save_screenshot(path)
|
||||||
|
finally:
|
||||||
|
self._driver.close()
|
||||||
|
self._driver.switch_to.window(original)
|
||||||
|
|
||||||
|
def save_screenshot(self, path: Path) -> None:
|
||||||
|
"""@brief Save a screenshot of the current page.
|
||||||
|
|
||||||
|
@param path The PNG file to write; its folders are created.
|
||||||
|
"""
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._driver.save_screenshot(str(path))
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
"""@brief Quit the browser."""
|
||||||
|
self._driver.quit()
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta charset="utf-8"><title>Fixture gym my bookings</title></head>
|
||||||
|
<body>
|
||||||
|
<nav><a id="my-bookings-link" href="my_bookings.html">My Bookings</a></nav>
|
||||||
|
<div id="my-bookings-page" data-bookings-count="0" data-waitlist-count="0" data-loading="true">
|
||||||
|
<h1>My Bookings</h1>
|
||||||
|
<p id="loading-placeholder">Loading your bookings...</p>
|
||||||
|
<div id="content"></div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
// Imitates the site: a loading text, then the page for the state in the query
|
||||||
|
// (?state=empty or ?state=error; anything else shows two bookings and a waitlist entry).
|
||||||
|
const state = new URLSearchParams(window.location.search).get("state");
|
||||||
|
// The nav link keeps the state, so opening the page from here shows the same state again.
|
||||||
|
document.getElementById("my-bookings-link").href = "my_bookings.html" + window.location.search;
|
||||||
|
const page = document.getElementById("my-bookings-page");
|
||||||
|
const content = document.getElementById("content");
|
||||||
|
setTimeout(function () {
|
||||||
|
document.getElementById("loading-placeholder").remove();
|
||||||
|
page.dataset.loading = "false";
|
||||||
|
if (state === "error") {
|
||||||
|
content.innerHTML = '<div id="error-message">Failed to load bookings</div>';
|
||||||
|
} else if (state === "empty") {
|
||||||
|
content.innerHTML = '<div id="empty-bookings-state">You have no bookings yet</div>';
|
||||||
|
} else {
|
||||||
|
page.dataset.bookingsCount = "2";
|
||||||
|
page.dataset.waitlistCount = "1";
|
||||||
|
content.innerHTML =
|
||||||
|
'<div id="confirmed-bookings-section">' +
|
||||||
|
'<div id="booking-card-11" data-booking-status="confirmed">' +
|
||||||
|
'<h3 id="booking-class-name-11">Spin Class</h3>' +
|
||||||
|
'<p><strong>When:</strong> Tue, Aug 12, 6:00 PM</p></div>' +
|
||||||
|
'<div id="booking-card-12" data-booking-status="confirmed">' +
|
||||||
|
'<h3 id="booking-class-name-12">Yoga Class</h3>' +
|
||||||
|
'<p><strong>When:</strong> Wed, Aug 13, 7:00 AM</p></div>' +
|
||||||
|
'</div>' +
|
||||||
|
'<div id="waitlist-section">' +
|
||||||
|
'<div id="waitlist-card-21" data-booking-status="waitlisted">' +
|
||||||
|
'<h3 id="waitlist-class-name-21">HIIT Class (Waitlist)</h3>' +
|
||||||
|
'<p><strong>When:</strong> Thu, Aug 14, 6:00 PM</p></div>' +
|
||||||
|
'</div>';
|
||||||
|
}
|
||||||
|
}, 200);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head><meta charset="utf-8"><title>Fixture gym schedule</title></head>
|
<head><meta charset="utf-8"><title>Fixture gym schedule</title></head>
|
||||||
<body>
|
<body>
|
||||||
|
<nav><a id="my-bookings-link" href="my_bookings.html">My Bookings</a></nav>
|
||||||
<div id="schedule-page">
|
<div id="schedule-page">
|
||||||
<h1>Class Schedule (Today: Wed, Aug 13)</h1>
|
<h1>Class Schedule (Today: Wed, Aug 13)</h1>
|
||||||
<select id="day-filter"><option>Next 7 Days</option></select>
|
<select id="day-filter"><option>Next 7 Days</option></select>
|
||||||
|
|||||||
@@ -3,13 +3,15 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from collections.abc import Iterator
|
from collections.abc import Callable, Iterator
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from snack_and_lift.application.booking import book_target_classes
|
from snack_and_lift.application.booking import book_target_classes
|
||||||
from snack_and_lift.domain.errors import GymError, LoginFailedError
|
from snack_and_lift.application.verification import get_my_bookings
|
||||||
|
from snack_and_lift.domain.booking_entry import BookingEntry
|
||||||
|
from snack_and_lift.domain.errors import GymError, LoginFailedError, NoBookingsFoundError
|
||||||
from snack_and_lift.domain.models import Outcome
|
from snack_and_lift.domain.models import Outcome
|
||||||
from snack_and_lift.infrastructure.browser import create_driver
|
from snack_and_lift.infrastructure.browser import create_driver
|
||||||
from snack_and_lift.infrastructure.selenium_gym import SeleniumGym
|
from snack_and_lift.infrastructure.selenium_gym import SeleniumGym
|
||||||
@@ -126,3 +128,63 @@ def test_book_target_classes_books_every_tuesday_and_thursday_class(
|
|||||||
("201", Outcome.ALREADY_WAITLISTED),
|
("201", Outcome.ALREADY_WAITLISTED),
|
||||||
("302", Outcome.NEW_BOOKING),
|
("302", Outcome.NEW_BOOKING),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
FIXTURE_MY_BOOKINGS = (Path(__file__).parent / "fixtures" / "my_bookings.html").as_uri()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def open_my_bookings_page(tmp_path: Path) -> Iterator[Callable[[str], SeleniumGym]]:
|
||||||
|
"""@brief Opens the My Bookings fixture in the given state (a query such as `?state=empty`)."""
|
||||||
|
driver = create_driver(headless=True, profile_dir=tmp_path / "profile", keep_open=False)
|
||||||
|
|
||||||
|
def open_page(query: str = "") -> SeleniumGym:
|
||||||
|
driver.get(FIXTURE_MY_BOOKINGS + query)
|
||||||
|
return SeleniumGym(driver, base_url=FIXTURE_MY_BOOKINGS)
|
||||||
|
|
||||||
|
try:
|
||||||
|
yield open_page
|
||||||
|
finally:
|
||||||
|
driver.quit()
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_my_bookings_follows_the_nav_link(schedule_gym: SeleniumGym) -> None:
|
||||||
|
schedule_gym.open_my_bookings()
|
||||||
|
|
||||||
|
assert [entry.name for entry in schedule_gym.list_my_bookings()] == [
|
||||||
|
"Spin Class",
|
||||||
|
"Yoga Class",
|
||||||
|
"HIIT Class",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_my_bookings_reads_confirmed_and_waitlist_entries(
|
||||||
|
open_my_bookings_page: Callable[[str], SeleniumGym],
|
||||||
|
) -> None:
|
||||||
|
entries = open_my_bookings_page("").list_my_bookings()
|
||||||
|
|
||||||
|
assert entries == [
|
||||||
|
BookingEntry("Spin Class", "Tue, Aug 12, 6:00 PM", False),
|
||||||
|
BookingEntry("Yoga Class", "Wed, Aug 13, 7:00 AM", False),
|
||||||
|
BookingEntry("HIIT Class", "Thu, Aug 14, 6:00 PM", True),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_my_bookings_returns_nothing_for_the_empty_state(
|
||||||
|
open_my_bookings_page: Callable[[str], SeleniumGym],
|
||||||
|
) -> None:
|
||||||
|
assert open_my_bookings_page("?state=empty").list_my_bookings() == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_my_bookings_raises_for_the_empty_state(
|
||||||
|
open_my_bookings_page: Callable[[str], SeleniumGym],
|
||||||
|
) -> None:
|
||||||
|
with pytest.raises(NoBookingsFoundError):
|
||||||
|
get_my_bookings(open_my_bookings_page("?state=empty"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_my_bookings_raises_with_the_text_of_the_error_box(
|
||||||
|
open_my_bookings_page: Callable[[str], SeleniumGym],
|
||||||
|
) -> None:
|
||||||
|
with pytest.raises(GymError, match="Failed to load bookings"):
|
||||||
|
open_my_bookings_page("?state=error").list_my_bookings()
|
||||||
|
|||||||
+40
-2
@@ -5,8 +5,9 @@
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from snack_and_lift import constants
|
from snack_and_lift import constants
|
||||||
|
from snack_and_lift.domain.booking_entry import BookingEntry
|
||||||
from snack_and_lift.domain.errors import GymError, LoginFailedError
|
from snack_and_lift.domain.errors import GymError, LoginFailedError
|
||||||
from snack_and_lift.domain.models import ClassCard
|
from snack_and_lift.domain.models import ButtonState, ClassCard
|
||||||
|
|
||||||
_PRESS_RESULTS = {
|
_PRESS_RESULTS = {
|
||||||
constants.BUTTON_TEXT_BOOK: constants.BUTTON_TEXT_BOOKED,
|
constants.BUTTON_TEXT_BOOK: constants.BUTTON_TEXT_BOOKED,
|
||||||
@@ -14,8 +15,29 @@ _PRESS_RESULTS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
_WAITLISTED_BY_STATE = {
|
||||||
|
ButtonState.BOOK: False,
|
||||||
|
ButtonState.BOOKED: False,
|
||||||
|
ButtonState.JOIN_WAITLIST: True,
|
||||||
|
ButtonState.WAITLISTED: True,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _entry_of(card: ClassCard) -> BookingEntry | None:
|
||||||
|
"""@brief The My Bookings entry that a card ends in, or None when it is not booked."""
|
||||||
|
flag = _WAITLISTED_BY_STATE.get(card.state)
|
||||||
|
if flag is None:
|
||||||
|
return None
|
||||||
|
time_text = card.time_text.removeprefix(constants.TIME_TEXT_PREFIX).strip()
|
||||||
|
return BookingEntry(card.name, f"{card.date_text}, {time_text}", flag)
|
||||||
|
|
||||||
|
|
||||||
class FakeGym:
|
class FakeGym:
|
||||||
"""@brief Records the calls; can refuse the login, serve cards and fail a click."""
|
"""@brief Records the calls; can refuse the login, serve cards and fail a click.
|
||||||
|
|
||||||
|
Unless `bookings` is given, the My Bookings page shows every card that is, or by the
|
||||||
|
click becomes, booked or waitlisted.
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -23,11 +45,15 @@ class FakeGym:
|
|||||||
cards: list[ClassCard] | None = None,
|
cards: list[ClassCard] | None = None,
|
||||||
press_result: str | None = None,
|
press_result: str | None = None,
|
||||||
press_error: str | None = None,
|
press_error: str | None = None,
|
||||||
|
bookings: list[BookingEntry] | None = None,
|
||||||
|
bookings_error: str | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.login_error = login_error
|
self.login_error = login_error
|
||||||
self.cards = cards or []
|
self.cards = cards or []
|
||||||
self.press_result = press_result
|
self.press_result = press_result
|
||||||
self.press_error = press_error
|
self.press_error = press_error
|
||||||
|
self.bookings = bookings
|
||||||
|
self.bookings_error = bookings_error
|
||||||
self.calls: list[str] = []
|
self.calls: list[str] = []
|
||||||
self.logins: list[tuple[str, str]] = []
|
self.logins: list[tuple[str, str]] = []
|
||||||
self.screenshots: list[Path] = []
|
self.screenshots: list[Path] = []
|
||||||
@@ -58,6 +84,18 @@ class FakeGym:
|
|||||||
card = next(card for card in self.cards if card.card_id == card_id)
|
card = next(card for card in self.cards if card.card_id == card_id)
|
||||||
return _PRESS_RESULTS[card.button_text]
|
return _PRESS_RESULTS[card.button_text]
|
||||||
|
|
||||||
|
def open_my_bookings(self) -> None:
|
||||||
|
self.calls.append("open_my_bookings")
|
||||||
|
|
||||||
|
def list_my_bookings(self) -> list[BookingEntry]:
|
||||||
|
self.calls.append("list_my_bookings")
|
||||||
|
if self.bookings_error is not None:
|
||||||
|
raise GymError(self.bookings_error)
|
||||||
|
if self.bookings is not None:
|
||||||
|
return list(self.bookings)
|
||||||
|
entries = (_entry_of(card) for card in self.cards)
|
||||||
|
return [entry for entry in entries if entry is not None]
|
||||||
|
|
||||||
def save_text_screenshot(self, text: str, path: Path) -> None:
|
def save_text_screenshot(self, text: str, path: Path) -> None:
|
||||||
self.calls.append("save_text_screenshot")
|
self.calls.append("save_text_screenshot")
|
||||||
self.text_screenshots.append((text, path))
|
self.text_screenshots.append((text, path))
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"""@file test_application_verification.py
|
||||||
|
@brief Reading the My Bookings page and verifying the bookings, against a fake gym.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from tests.unit.fakes import FakeGym
|
||||||
|
from tests.unit.test_booking_entry import make_entry
|
||||||
|
from tests.unit.test_models import make_card
|
||||||
|
|
||||||
|
from snack_and_lift.application.booking import book_target_classes
|
||||||
|
from snack_and_lift.application.verification import get_my_bookings, verify_bookings
|
||||||
|
from snack_and_lift.domain.errors import GymError, NoBookingsFoundError
|
||||||
|
from snack_and_lift.domain.models import ClassResult, Outcome
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_my_bookings_opens_the_page_and_returns_all_entries() -> None:
|
||||||
|
entries = [make_entry("Wed, Aug 13, 7:00 AM"), make_entry(waitlisted=True)]
|
||||||
|
gym = FakeGym(bookings=entries)
|
||||||
|
|
||||||
|
assert get_my_bookings(gym) == entries
|
||||||
|
assert gym.calls == ["open_my_bookings", "list_my_bookings"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_my_bookings_raises_when_the_page_has_no_entry() -> None:
|
||||||
|
with pytest.raises(NoBookingsFoundError):
|
||||||
|
get_my_bookings(FakeGym(bookings=[]))
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_my_bookings_propagates_the_page_error() -> None:
|
||||||
|
with pytest.raises(GymError, match="Failed to load"):
|
||||||
|
get_my_bookings(FakeGym(bookings_error="Failed to load bookings"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_bookings_succeeds_for_the_booked_classes() -> None:
|
||||||
|
gym = FakeGym(
|
||||||
|
cards=[
|
||||||
|
make_card("Tue, Aug 12", card_id="1"),
|
||||||
|
make_card("Thu, Aug 14", card_id="2", button_text="Join Waitlist"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
results = book_target_classes(gym)
|
||||||
|
|
||||||
|
verification = verify_bookings(gym, results)
|
||||||
|
|
||||||
|
assert verification.is_success
|
||||||
|
assert verification.verified == ["Spin Class", "Spin Class (Waitlist)"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_bookings_ignores_entries_that_are_not_target_classes() -> None:
|
||||||
|
gym = FakeGym(bookings=[make_entry(), make_entry("Wed, Aug 13, 6:00 PM")])
|
||||||
|
results = [ClassResult(make_card("Tue, Aug 12"), Outcome.NEW_BOOKING)]
|
||||||
|
|
||||||
|
assert verify_bookings(gym, results).is_success
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_bookings_reports_a_missing_booking() -> None:
|
||||||
|
gym = FakeGym(bookings=[make_entry("Wed, Aug 13, 7:00 AM")])
|
||||||
|
results = [ClassResult(make_card("Tue, Aug 12"), Outcome.NEW_BOOKING)]
|
||||||
|
|
||||||
|
verification = verify_bookings(gym, results)
|
||||||
|
|
||||||
|
assert not verification.is_success
|
||||||
|
assert verification.missing == ["Spin Class on Tue, Aug 12"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_bookings_raises_when_classes_were_booked_but_the_page_is_empty() -> None:
|
||||||
|
gym = FakeGym(bookings=[])
|
||||||
|
results = [ClassResult(make_card("Tue, Aug 12"), Outcome.NEW_BOOKING)]
|
||||||
|
|
||||||
|
with pytest.raises(NoBookingsFoundError):
|
||||||
|
verify_bookings(gym, results)
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_bookings_skips_the_page_when_nothing_is_expected() -> None:
|
||||||
|
gym = FakeGym()
|
||||||
|
|
||||||
|
verification = verify_bookings(gym, [])
|
||||||
|
|
||||||
|
assert verification.is_success
|
||||||
|
assert verification.expected == 0
|
||||||
|
assert gym.calls == []
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""@file test_booking_entry.py
|
||||||
|
@brief The entries of the My Bookings page: parsing and the target test.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import dataclasses
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from snack_and_lift.domain.booking_entry import BookingEntry, is_target_entry
|
||||||
|
from snack_and_lift.domain.errors import GymError, NoBookingsFoundError, PageFormatError
|
||||||
|
|
||||||
|
|
||||||
|
def make_entry(
|
||||||
|
when_text: str = "Tue, Aug 12, 6:00 PM", name: str = "Spin Class", waitlisted: bool = False
|
||||||
|
) -> BookingEntry:
|
||||||
|
return BookingEntry(name, when_text, waitlisted)
|
||||||
|
|
||||||
|
|
||||||
|
def test_entry_derives_weekday_date_and_time() -> None:
|
||||||
|
entry = make_entry("Thu, Aug 14, 6:00 PM")
|
||||||
|
|
||||||
|
assert entry.weekday == "Thu"
|
||||||
|
assert entry.date_text == "Thu, Aug 14"
|
||||||
|
assert entry.time == (18, 0)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"when_text", ["", "Someday", "Tue, Aug 12", "Tue, Aug 12, noon", "6:00 PM"]
|
||||||
|
)
|
||||||
|
def test_entry_with_bad_when_text_raises(when_text: str) -> None:
|
||||||
|
with pytest.raises(PageFormatError):
|
||||||
|
is_target_entry(make_entry(when_text))
|
||||||
|
|
||||||
|
|
||||||
|
def test_from_page_removes_the_waitlist_suffix_and_the_when_prefix() -> None:
|
||||||
|
entry = BookingEntry.from_page("Spin Class (Waitlist)", "When: Tue, Aug 12, 6:00 PM", True)
|
||||||
|
|
||||||
|
assert entry == BookingEntry("Spin Class", "Tue, Aug 12, 6:00 PM", True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_from_page_keeps_a_plain_name() -> None:
|
||||||
|
assert BookingEntry.from_page("Spin Class", "Tue, Aug 12, 6:00 PM", False).name == "Spin Class"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("when_text", "expected"),
|
||||||
|
[
|
||||||
|
("Tue, Aug 12, 6:00 PM", True),
|
||||||
|
("Thu, Aug 14, 6:00 PM", True),
|
||||||
|
("Wed, Aug 13, 6:00 PM", False),
|
||||||
|
("Tue, Aug 12, 6:00 AM", False),
|
||||||
|
("Thu, Aug 14, 6:30 PM", False),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_is_target_entry(when_text: str, expected: bool) -> None:
|
||||||
|
assert is_target_entry(make_entry(when_text)) is expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_entry_is_immutable() -> None:
|
||||||
|
with pytest.raises(dataclasses.FrozenInstanceError):
|
||||||
|
make_entry().name = "Other" # type: ignore[misc]
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_bookings_found_is_a_gym_error() -> None:
|
||||||
|
assert issubclass(NoBookingsFoundError, GymError)
|
||||||
+51
-2
@@ -7,6 +7,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from tests.unit.fakes import FakeGym
|
from tests.unit.fakes import FakeGym
|
||||||
|
from tests.unit.test_booking_entry import make_entry
|
||||||
from tests.unit.test_models import make_card
|
from tests.unit.test_models import make_card
|
||||||
|
|
||||||
from snack_and_lift import constants
|
from snack_and_lift import constants
|
||||||
@@ -67,11 +68,13 @@ def test_main_saves_both_screenshots_on_success(tmp_path: Path) -> None:
|
|||||||
tmp_path / "step-1.png",
|
tmp_path / "step-1.png",
|
||||||
tmp_path / "step-2.png",
|
tmp_path / "step-2.png",
|
||||||
tmp_path / "step-3.png",
|
tmp_path / "step-3.png",
|
||||||
|
tmp_path / "step-7.png",
|
||||||
]
|
]
|
||||||
assert [path for _, path in gym.text_screenshots] == [
|
assert [path for _, path in gym.text_screenshots] == [
|
||||||
tmp_path / "step-4.png",
|
tmp_path / "step-4.png",
|
||||||
tmp_path / "step-5.png",
|
tmp_path / "step-5.png",
|
||||||
tmp_path / "step-6.png",
|
tmp_path / "step-6.png",
|
||||||
|
tmp_path / "step-8.png",
|
||||||
]
|
]
|
||||||
assert gym.calls == [
|
assert gym.calls == [
|
||||||
"open_site",
|
"open_site",
|
||||||
@@ -83,6 +86,8 @@ def test_main_saves_both_screenshots_on_success(tmp_path: Path) -> None:
|
|||||||
"save_text_screenshot",
|
"save_text_screenshot",
|
||||||
"save_text_screenshot",
|
"save_text_screenshot",
|
||||||
"save_text_screenshot",
|
"save_text_screenshot",
|
||||||
|
"save_screenshot",
|
||||||
|
"save_text_screenshot",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -140,15 +145,57 @@ def test_main_saves_step_3_after_the_first_class_and_the_report_images(tmp_path:
|
|||||||
"save_text_screenshot",
|
"save_text_screenshot",
|
||||||
"save_text_screenshot",
|
"save_text_screenshot",
|
||||||
"save_text_screenshot",
|
"save_text_screenshot",
|
||||||
|
"open_my_bookings",
|
||||||
|
"list_my_bookings",
|
||||||
|
"save_screenshot",
|
||||||
|
"save_text_screenshot",
|
||||||
]
|
]
|
||||||
assert gym.screenshots[-1] == tmp_path / "step-3.png"
|
assert gym.screenshots[-2:] == [tmp_path / "step-3.png", tmp_path / "step-7.png"]
|
||||||
(_, _), (step_5, _), (step_6, _) = gym.text_screenshots
|
(_, _), (step_5, _), (step_6, _), (step_8, step_8_path) = gym.text_screenshots
|
||||||
|
assert step_8_path == tmp_path / "step-8.png"
|
||||||
|
assert step_8.startswith("--- VERIFYING ON MY BOOKINGS PAGE ---")
|
||||||
|
assert step_8.endswith("✅ SUCCESS: All bookings verified!")
|
||||||
assert step_5.startswith("--- BOOKING SUMMARY ---\nNew bookings: 2")
|
assert step_5.startswith("--- BOOKING SUMMARY ---\nNew bookings: 2")
|
||||||
assert "--- DETAILED CLASS LIST ---" not in step_5
|
assert "--- DETAILED CLASS LIST ---" not in step_5
|
||||||
assert step_6.startswith(step_5)
|
assert step_6.startswith(step_5)
|
||||||
assert "--- DETAILED CLASS LIST ---\n • [New Booking] Spin Class on Thu, Aug 14" in step_6
|
assert "--- DETAILED CLASS LIST ---\n • [New Booking] Spin Class on Thu, Aug 14" in step_6
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("credentials_env")
|
||||||
|
def test_main_logs_the_verification_and_returns_0_on_success(
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
) -> None:
|
||||||
|
gym = FakeGym(cards=[make_card("Tue, Aug 19")])
|
||||||
|
|
||||||
|
with caplog.at_level(logging.INFO):
|
||||||
|
assert main([], lambda *_: gym) == 0
|
||||||
|
|
||||||
|
assert "--- VERIFYING ON MY BOOKINGS PAGE ---\n ✓ Verified: Spin Class" in caplog.text
|
||||||
|
assert "Expected: 1 booking\nFound: 1 booking\n✅ SUCCESS" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("credentials_env")
|
||||||
|
def test_main_returns_3_on_a_mismatch(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||||
|
gym = FakeGym(cards=[make_card("Tue, Aug 19")], bookings=[make_entry("Wed, Aug 20, 7:00 AM")])
|
||||||
|
|
||||||
|
with caplog.at_level(logging.INFO):
|
||||||
|
code = main(["--headless", "--screenshot-dir", str(tmp_path)], lambda *_: gym)
|
||||||
|
|
||||||
|
assert code == 3
|
||||||
|
assert "❌ MISMATCH: Missing 1 bookings" in caplog.text
|
||||||
|
assert " ✗ Missing: Spin Class on Tue, Aug 19" in caplog.text
|
||||||
|
assert gym.screenshots[-1] == tmp_path / "step-7.png"
|
||||||
|
assert gym.text_screenshots[-1][1] == tmp_path / "step-8.png"
|
||||||
|
assert gym.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("credentials_env")
|
||||||
|
def test_main_returns_1_when_the_bookings_page_is_empty() -> None:
|
||||||
|
gym = FakeGym(cards=[make_card("Tue, Aug 19")], bookings=[])
|
||||||
|
|
||||||
|
assert main([], lambda *_: gym) == 1
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.usefixtures("credentials_env")
|
@pytest.mark.usefixtures("credentials_env")
|
||||||
def test_main_logs_an_empty_report_without_target_classes(
|
def test_main_logs_an_empty_report_without_target_classes(
|
||||||
caplog: pytest.LogCaptureFixture,
|
caplog: pytest.LogCaptureFixture,
|
||||||
@@ -176,6 +223,8 @@ def test_main_first_tuesday_only_books_one_class_and_no_report(
|
|||||||
assert code == 0
|
assert code == 0
|
||||||
assert gym.pressed == ["2"]
|
assert gym.pressed == ["2"]
|
||||||
assert "BOOKING SUMMARY" not in caplog.text
|
assert "BOOKING SUMMARY" not in caplog.text
|
||||||
|
assert "VERIFYING" not in caplog.text
|
||||||
|
assert "open_my_bookings" not in gym.calls
|
||||||
assert [path.name for path in gym.screenshots] == ["step-1.png", "step-2.png", "step-3.png"]
|
assert [path.name for path in gym.screenshots] == ["step-1.png", "step-2.png", "step-3.png"]
|
||||||
assert [path.name for _, path in gym.text_screenshots] == ["step-4.png"]
|
assert [path.name for _, path in gym.text_screenshots] == ["step-4.png"]
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""@file test_date_independence.py
|
||||||
|
@brief The bot picks classes by weekday and time only, whatever the first visible day is.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import date, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from tests.unit.fakes import FakeGym
|
||||||
|
|
||||||
|
from snack_and_lift.application.booking import book_target_classes
|
||||||
|
from snack_and_lift.application.verification import verify_bookings
|
||||||
|
from snack_and_lift.domain.models import ClassCard
|
||||||
|
from snack_and_lift.domain.rules import find_target_classes
|
||||||
|
|
||||||
|
## A Monday; the schedules below start on this day plus an offset, so every weekday occurs.
|
||||||
|
_A_MONDAY = date(2025, 8, 11)
|
||||||
|
_DAYS_SHOWN = 8
|
||||||
|
_TUESDAY, _THURSDAY = 1, 3
|
||||||
|
_TIMES = (
|
||||||
|
("Time: 6:00 AM", "Book Class"),
|
||||||
|
("Time: 6:00 PM", "Book Class"),
|
||||||
|
("Time: 7:00 PM", "Book Class"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _day_text(day: date) -> str:
|
||||||
|
return f"{day:%a}, {day:%b} {day.day}"
|
||||||
|
|
||||||
|
|
||||||
|
def _label(index: int, day: date) -> str:
|
||||||
|
if index == 0:
|
||||||
|
return f"Today ({_day_text(day)})"
|
||||||
|
if index == 1:
|
||||||
|
return f"Tomorrow ({_day_text(day)})"
|
||||||
|
return _day_text(day)
|
||||||
|
|
||||||
|
|
||||||
|
def make_schedule(start_offset: int) -> tuple[list[ClassCard], set[str]]:
|
||||||
|
"""@brief Cards of 8 days from a start weekday, and the ids of the Tue/Thu 6pm ones."""
|
||||||
|
cards: list[ClassCard] = []
|
||||||
|
wanted: set[str] = set()
|
||||||
|
for index in range(_DAYS_SHOWN):
|
||||||
|
day = _A_MONDAY + timedelta(days=start_offset + index)
|
||||||
|
for slot, (time_text, button) in enumerate(_TIMES):
|
||||||
|
card_id = f"{index}{slot}"
|
||||||
|
cards.append(ClassCard(card_id, "Spin Class", _label(index, day), time_text, button))
|
||||||
|
if day.weekday() in (_TUESDAY, _THURSDAY) and slot == 1:
|
||||||
|
wanted.add(card_id)
|
||||||
|
return cards, wanted
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("start_offset", range(7))
|
||||||
|
def test_find_target_classes_for_every_starting_weekday(start_offset: int) -> None:
|
||||||
|
cards, wanted = make_schedule(start_offset)
|
||||||
|
|
||||||
|
assert {card.card_id for card in find_target_classes(cards)} == wanted
|
||||||
|
assert wanted
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("start_offset", range(7))
|
||||||
|
def test_booking_and_verification_for_every_starting_weekday(start_offset: int) -> None:
|
||||||
|
cards, wanted = make_schedule(start_offset)
|
||||||
|
gym = FakeGym(cards=cards)
|
||||||
|
|
||||||
|
results = book_target_classes(gym)
|
||||||
|
|
||||||
|
assert set(gym.pressed) == wanted
|
||||||
|
assert len(gym.pressed) == len(wanted)
|
||||||
|
assert verify_bookings(gym, results).is_success
|
||||||
|
|
||||||
|
|
||||||
|
def test_schedule_whose_first_visible_day_is_a_thursday_includes_today() -> None:
|
||||||
|
cards, _ = make_schedule(3)
|
||||||
|
assert cards[0].day_label.startswith("Today (Thu,")
|
||||||
|
|
||||||
|
chosen = find_target_classes(cards)
|
||||||
|
|
||||||
|
assert [card.weekday for card in chosen] == ["Thu", "Tue", "Thu"]
|
||||||
|
assert chosen[0].card_id == "01"
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_order_does_not_change_which_classes_are_chosen() -> None:
|
||||||
|
cards, wanted = make_schedule(2)
|
||||||
|
|
||||||
|
chosen = find_target_classes(list(reversed(cards)))
|
||||||
|
|
||||||
|
assert {card.card_id for card in chosen} == wanted
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""@file test_verification.py
|
||||||
|
@brief The comparison of the bot's results with the My Bookings page, and its text.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from tests.unit.test_booking_entry import make_entry
|
||||||
|
from tests.unit.test_models import make_card
|
||||||
|
|
||||||
|
from snack_and_lift.domain.models import ClassResult, Outcome
|
||||||
|
from snack_and_lift.domain.verification import build_verification, format_verification
|
||||||
|
|
||||||
|
BOOKED = ClassResult(make_card("Tue, Aug 12"), Outcome.NEW_BOOKING)
|
||||||
|
WAITLISTED = ClassResult(make_card("Thu, Aug 14", card_id="2"), Outcome.NEW_WAITLIST)
|
||||||
|
|
||||||
|
|
||||||
|
def test_everything_found_is_a_success() -> None:
|
||||||
|
result = build_verification(
|
||||||
|
[BOOKED, WAITLISTED],
|
||||||
|
[make_entry("Tue, Aug 12, 6:00 PM"), make_entry("Thu, Aug 14, 6:00 PM", waitlisted=True)],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.is_success
|
||||||
|
assert result.verified == ["Spin Class", "Spin Class (Waitlist)"]
|
||||||
|
assert (result.expected, result.found) == (2, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_success_text_is_exact() -> None:
|
||||||
|
result = build_verification(
|
||||||
|
[BOOKED, WAITLISTED],
|
||||||
|
[make_entry("Tue, Aug 12, 6:00 PM"), make_entry("Thu, Aug 14, 6:00 PM", waitlisted=True)],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert format_verification(result) == (
|
||||||
|
"--- VERIFYING ON MY BOOKINGS PAGE ---\n"
|
||||||
|
" ✓ Verified: Spin Class\n"
|
||||||
|
" ✓ Verified: Spin Class (Waitlist)\n"
|
||||||
|
"\n"
|
||||||
|
"--- VERIFICATION RESULT ---\n"
|
||||||
|
"Expected: 2 bookings\n"
|
||||||
|
"Found: 2 bookings\n"
|
||||||
|
"✅ SUCCESS: All bookings verified!"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_one_booking_is_singular() -> None:
|
||||||
|
text = format_verification(build_verification([BOOKED], [make_entry("Tue, Aug 12, 6:00 PM")]))
|
||||||
|
|
||||||
|
assert "Expected: 1 booking\nFound: 1 booking\n" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_entry_is_a_mismatch_with_a_line() -> None:
|
||||||
|
result = build_verification([BOOKED, WAITLISTED], [make_entry("Tue, Aug 12, 6:00 PM")])
|
||||||
|
|
||||||
|
text = format_verification(result)
|
||||||
|
|
||||||
|
assert not result.is_success
|
||||||
|
assert result.missing == ["Spin Class (Waitlist) on Thu, Aug 14"]
|
||||||
|
assert "Expected: 2 bookings\nFound: 1 booking\n❌ MISMATCH: Missing 1 bookings" in text
|
||||||
|
assert text.endswith(" ✗ Missing: Spin Class (Waitlist) on Thu, Aug 14")
|
||||||
|
|
||||||
|
|
||||||
|
def test_unexpected_entry_gives_a_negative_missing_count() -> None:
|
||||||
|
result = build_verification(
|
||||||
|
[BOOKED], [make_entry("Tue, Aug 12, 6:00 PM"), make_entry("Thu, Aug 14, 6:00 PM")]
|
||||||
|
)
|
||||||
|
|
||||||
|
text = format_verification(result)
|
||||||
|
|
||||||
|
assert result.unexpected == ["Spin Class on Thu, Aug 14"]
|
||||||
|
assert "❌ MISMATCH: Missing -1 bookings" in text
|
||||||
|
assert text.endswith(" ? Unexpected: Spin Class on Thu, Aug 14")
|
||||||
|
|
||||||
|
|
||||||
|
def test_waitlist_flag_must_match() -> None:
|
||||||
|
result = build_verification([BOOKED], [make_entry("Tue, Aug 12, 6:00 PM", waitlisted=True)])
|
||||||
|
|
||||||
|
assert result.missing == ["Spin Class on Tue, Aug 12"]
|
||||||
|
assert result.unexpected == ["Spin Class (Waitlist) on Tue, Aug 12"]
|
||||||
|
assert "Missing 0 bookings" in format_verification(result)
|
||||||
|
|
||||||
|
|
||||||
|
def test_date_must_match() -> None:
|
||||||
|
result = build_verification([BOOKED], [make_entry("Tue, Aug 19, 6:00 PM")])
|
||||||
|
|
||||||
|
assert not result.is_success
|
||||||
|
|
||||||
|
|
||||||
|
def test_already_waitlisted_is_expected_as_waitlist() -> None:
|
||||||
|
results = [ClassResult(make_card("Thu, Aug 14"), Outcome.ALREADY_WAITLISTED)]
|
||||||
|
|
||||||
|
assert build_verification(
|
||||||
|
results, [make_entry("Thu, Aug 14, 6:00 PM", waitlisted=True)]
|
||||||
|
).is_success
|
||||||
|
|
||||||
|
|
||||||
|
def test_nothing_expected_and_nothing_found_is_a_success() -> None:
|
||||||
|
result = build_verification([], [])
|
||||||
|
|
||||||
|
assert result.is_success
|
||||||
|
assert "Expected: 0 bookings\nFound: 0 bookings\n✅ SUCCESS" in format_verification(result)
|
||||||
|
|
||||||
|
|
||||||
|
def test_same_class_twice_is_matched_one_to_one() -> None:
|
||||||
|
result = build_verification([BOOKED, BOOKED], [make_entry("Tue, Aug 12, 6:00 PM")])
|
||||||
|
|
||||||
|
assert result.verified == ["Spin Class"]
|
||||||
|
assert result.missing == ["Spin Class on Tue, Aug 12"]
|
||||||
Reference in New Issue
Block a user