Add the schema, the dependencies and an end-to-end test suite

The schema existed only inside the queries, so a clean clone could not run:
nothing created the tables that database.py and main.py expect, and there was
no declaration of what to install.

- schema.sql: the seven tables, their primary and foreign keys, and the
  administrator the code requires. Reconstructed from the SQL the code issues
  and typed for it: the code reads rows by position (SELECT *), so the column
  order is part of the contract, and users.userid has to be a 4-byte integer
  because message_all() counts rows with pg_column_size(userid)/4.
- scripts/db.py, Makefile, docker-compose.yml: a throwaway PostgreSQL and the
  targets up/schema/seed/run/test/down. Both passwords come from the
  environment (NETFLOX_DB_PASSWORD, NETFLOX_DEMO_PASSWORD); nothing is stored
  in the repository, and schema.sql receives the administrator password
  through a session setting.
- requirements.txt and requirements-dev.txt: psycopg2-binary, plus pytest for
  the suite.
- tests/: 30 end-to-end tests that recreate the schema and drive the real
  functions of database.py. They check the column order and the keys against
  information_schema and walk every main flow. The defects found while mapping
  the code are pinned by test_known_bug_* and xfail instead of fixed, since
  fixing the application was not part of this change. The suite also guards the
  credential fix: database.py must refuse to import without its variable and no
  tracked file may contain the value.
- README.md: the sections shared with the other repositories, with a real
  session.
- The report moved to docs/relatorio-BD.pdf: it had accents and spaces in the
  filename.
This commit is contained in:
Andre Neto
2026-10-08 14:26:47 +01:00
parent 17f75eccb0
commit c3efaa05cb
12 changed files with 1117 additions and 13 deletions
+13
View File
@@ -0,0 +1,13 @@
# Python
__pycache__/
*.py[cod]
.venv/
venv/
# Local secrets: NETFLOX_DB_PASSWORD / NETFLOX_DEMO_PASSWORD live in the
# environment, never in a file. A .env is loaded by docker compose, so it is
# ignored here to make the accident harder.
.env
# Tooling
.pytest_cache/
+58
View File
@@ -0,0 +1,58 @@
# Netflox - run the app, the database, the schema and the tests.
#
# Two values come from the environment and are never written in this file:
# NETFLOX_DB_PASSWORD password of the throwaway PostgreSQL (compose + app)
# NETFLOX_DEMO_PASSWORD password for the accounts created by `make seed`
# and by the tests (admin@netflox.com, cliente@exemplo.pt)
#
# export NETFLOX_DB_PASSWORD=... NETFLOX_DEMO_PASSWORD=...
# make test
SHELL := /bin/bash
VENV := .venv
PY := $(VENV)/bin/python
PIP := $(VENV)/bin/pip
export NETFLOX_DB_PASSWORD
export NETFLOX_DEMO_PASSWORD
.PHONY: help up down schema seed run test venv clean
help:
@echo "make up start the throwaway PostgreSQL and wait for it"
@echo "make schema drop and recreate the public schema, apply schema.sql"
@echo "make seed reset the rows and insert the demo accounts and catalogue"
@echo "make run run the terminal application (needs a terminal)"
@echo "make test run the pytest suite against the database"
@echo "make down stop the database and delete its volume"
$(VENV)/.deps-ok: requirements.txt requirements-dev.txt
python3 -m venv $(VENV)
$(PIP) install --quiet -r requirements-dev.txt
touch $@
venv: $(VENV)/.deps-ok
up:
@: $${NETFLOX_DB_PASSWORD:?NETFLOX_DB_PASSWORD is not set, see README}
docker compose up -d --wait
schema: up venv
$(PY) scripts/db.py schema
seed: schema
$(PY) scripts/db.py seed
run: up venv
$(PY) main.py
test: up venv
@: $${NETFLOX_DEMO_PASSWORD:?NETFLOX_DEMO_PASSWORD is not set, see README}
$(PY) -m pytest -q
down:
docker compose down -v
clean:
rm -rf $(VENV) .pytest_cache
find . -name __pycache__ -type d -prune -exec rm -rf {} +
+112 -13
View File
@@ -1,21 +1,120 @@
# Netflox
## Configuration
> Terminal application in Python and PostgreSQL that models a video-on-demand shop: accounts with a balance, a catalogue of films and series with their cast, rents with an end date, internal messages and a price history. Project for a Databases course unit.
The PostgreSQL password is **not** stored in the code. `database.py`
reads it once from the environment variable `NETFLOX_DB_PASSWORD`:
## What it is
`main.py` is a menu-driven command line program; `database.py` holds every SQL statement and opens a connection per call. Signing up or logging in is decided by the address: `log_in()` treats any address under `netflox.com` as an **administrator** and every other one as a **client**.
- **Client** - search the catalogue by title, director, type or actor; list everything; order by any column; rent an item (the price is deducted from the balance and `end_date` becomes `CURRENT_DATE + time_available`); list the rentals that are still open and the expired ones; read internal messages.
- **Administrator** - add an article with its cast, change a price (the replaced price is kept in `pricehistory`), remove an article, send a message to every client or to one of them, change a balance, and print statistics.
The data model has seven tables - `users`, `articles`, `actors`, `articles_actors`, `rents`, `messages`, `pricehistory` - and it exists only in `schema.sql`: it was reconstructed from the queries, and no table or column was invented. The code reads rows by position (`SELECT *` followed by `row[1]`, `row[4]`, ...), so the column order in that file is part of the contract.
Some behaviour is broken and was left as it is, because fixing the application was not part of reconstructing its database. The suite pins each case with a test named `test_known_bug_*` or marked `xfail`: `findby_director()` returns nothing when it finds a match; `findby_actor()` raises `UnboundLocalError` when nothing matches; a search with no results returns the integer `0`, which `main.py` then indexes into; `purchase()` deducts the money from the account of the last login instead of the account in its argument; the message list shows the recipient's name as the author; `remove_article()` checks only the rentals that are still open, while the foreign keys also block the older ones; and a few paths never close their connection.
The archive `Projeto_Netflox_Alexandre_Almeida_Andre_Neto.zip` is not tracked any more (it was removed in commit `17f75ec`) because it contained a copy of `database.py` with the database password in clear. If that password was ever used for anything other than a local test database, it has to be rotated. The passwords used now are chosen locally and are not in the repository.
## Requirements
- Python 3.9 or newer, with `pip` (tested on 3.13).
- Docker with the Compose plugin. The application connects to `localhost:5432` and expects the database `NetfloxFinal` with the user `postgres`; `docker-compose.yml` creates exactly that, so nothing in the code has to be patched.
- Permission to talk to the Docker daemon (membership of the `docker` group is the usual way).
- Two values, taken from the environment and never stored in the repository:
- `NETFLOX_DB_PASSWORD` - password of the throwaway PostgreSQL, used by both `docker compose` and the application;
- `NETFLOX_DEMO_PASSWORD` - password given to the accounts that `make seed` and the tests create (`admin@netflox.com` and `cliente@exemplo.pt`).
- Runtime dependency: `psycopg2-binary` (`requirements.txt`). The tests add `pytest` (`requirements-dev.txt`).
## Install / Build
```bash
export NETFLOX_DB_PASSWORD='<your-postgres-password>'
python main.py
# canonical copy on the self-hosted Gitea (aneto/Netflox), mirrored to:
git clone https://github.com/ags-neto/netflox.git
cd netflox
export NETFLOX_DB_PASSWORD='<choose a password>' NETFLOX_DEMO_PASSWORD='<choose a password>'
make up # start the throwaway PostgreSQL on 127.0.0.1:5432 and wait for it
make seed # apply schema.sql, then load the demo accounts and catalogue
```
If the variable is missing or empty the script stops immediately with
a `RuntimeError`; there is no default. Do not commit the value back
into the repository, and see the rotation note in the project issue
tracker if the old password was ever pushed.
`make schema` and `make seed` recreate the `public` schema: they are meant for this throwaway database and discard whatever is in it. `make venv` prepares `.venv` with the dependencies; `make test` and `make run` call it as needed. `make down` stops the container and deletes its volume.
**Note:** `Projeto_Netflox_Alexandre_Almeida_Andre_Neto.zip` was removed from git
tracking because it contained a copy of `database.py` with the old password.
The archive still exists on disk but must not be committed again; regenerate it
without the password if it ever needs to be published.
## Usage
`make run` starts the terminal program; it needs a real terminal, the database running and `NETFLOX_DB_PASSWORD` exported. This is an actual session, logged in as the demo client (`cliente@exemplo.pt`, the password is `$NETFLOX_DEMO_PASSWORD`), listing the catalogue and renting one item:
```text
-- Netflox --
1) Sign Up
2) Log in
0) Exit
Your Selection: 2
Log in
Enter your e-mail: cliente@exemplo.pt
Enter your password:
Welcome Cliente Demo, your balance is 20.00 €
1) Search articles
2) List all articles
3) Order by
4) View my articles
5) My history
6) Messages
0) Exit
Your Selection: 2
1) The Matrix
2) Pulp Fiction
3) The Godfather
4) Interstellar
5) Breaking Bad
6) Stranger Things
Your Selection: 3
The Godfather
1) View details
2) Purchase
0) Exit
Your Selection: 2
Are you sure (y/n): y
Purchase successful!
New balance: 17.00€
```
Logging in as `admin@netflox.com` gives the administrator menu instead (add article, view all, change price, remove article, messages, alter balance, statistics).
## Tests
```bash
export NETFLOX_DB_PASSWORD='...' NETFLOX_DEMO_PASSWORD='...'
make test
```
```text
.venv/bin/python -m pytest -q
...........................xx... [100%]
30 passed, 2 xfailed in 8.87s
```
The suite is end to end and needs the container: before every test `tests/conftest.py` recreates the `public` schema through the same helper the Makefile uses, and the tests then call the real functions of `database.py` - the ones `main.py` calls - against PostgreSQL. Nothing is mocked except the keyboard. It checks the column order and the keys against `information_schema`, then walks the flows: sign up and log in (including the two rejected cases), catalogue search and detail view, ordering, a rent with its balance and end date, the refused rent, current and expired rentals, a message that is read, a broadcast to everybody except the sender, adding an article with a reused actor, a price change with its history, the two removal paths, and the statistics. Three tests guard the credentials: `database.py` must refuse to import without `NETFLOX_DB_PASSWORD`, no connection string may contain a password literal, and no tracked file may contain the value of that variable.
Two tests are marked `xfail` and four are named `test_known_bug_*`: they document the defects listed under "What it is" instead of hiding them. When one of those bugs is fixed, the corresponding test has to change.
## Structure
```text
database.py every SQL statement and the connection; reads NETFLOX_DB_PASSWORD at import
main.py the menus: menu() -> client() or admin()
schema.sql the relational schema (7 tables, primary and foreign keys) and the minimal seed
scripts/db.py applies schema.sql and loads the demo rows; used by make schema/seed and the tests
tests/conftest.py recreates the schema before every test; tests/test_netflox.py is the suite
docker-compose.yml throwaway PostgreSQL (NetfloxFinal, postgres, 127.0.0.1:5432)
Makefile up, schema, seed, run, test, down (plus venv, clean, help)
requirements.txt psycopg2-binary; requirements-dev.txt adds pytest
docs/relatorio-BD.pdf the course report, moved from "RelatórioProjeto-BD-AndréNeto_AlexandreAlmeida_PL2.pdf"
encript.jpg image from the original upload; no code or schema reads it and its bytes are not
embedded in the report (checked), so it was kept instead of deleted
```
## License
Not decided yet: the repository carries no license file, so no license is granted. The author has to choose one before this section can state anything.
+31
View File
@@ -0,0 +1,31 @@
# Throwaway PostgreSQL for the Netflox assignment database.
#
# The database name, user and port match the connection string hard-coded in
# database.py (host=localhost dbname=NetfloxFinal user=postgres), so the
# application and the tests run unmodified.
#
# The password comes from the environment and has no default: `docker compose`
# refuses to start if NETFLOX_DB_PASSWORD is empty, and nothing is committed.
# export NETFLOX_DB_PASSWORD=...
# docker compose up -d --wait
name: netflox
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_DB: NetfloxFinal
POSTGRES_USER: postgres
POSTGRES_PASSWORD: ${NETFLOX_DB_PASSWORD:?set NETFLOX_DB_PASSWORD (see README, Requirements)}
ports:
- "127.0.0.1:5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d NetfloxFinal"]
interval: 2s
timeout: 3s
retries: 30
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
+3
View File
@@ -0,0 +1,3 @@
# Everything needed to run the test suite (make test).
-r requirements.txt
pytest>=8,<9
+5
View File
@@ -0,0 +1,5 @@
# Runtime dependency of database.py (the only third-party import in the code).
# psycopg2-binary ships the libpq it needs, which is what a clone-and-run user
# wants; distributions that prefer to build against a system libpq can install
# psycopg2 instead.
psycopg2-binary>=2.9,<3
+150
View File
@@ -0,0 +1,150 @@
-- Netflox - relational schema.
--
-- Reconstructed from the SQL the application actually issues (database.py,
-- main.py). Every table and column below is read or written by that code and
-- nothing else was added: the application is the specification.
--
-- The application reads rows positionally (`SELECT *` followed by row[1],
-- row[4], ...), so the ORDER of the columns in each CREATE TABLE is part of the
-- contract and must not be changed:
--
-- users userid, nome, email, password, balance
-- articles itemid, name, director, release_year, imbd_rating, genre,
-- price, type, time_available
-- messages msgid, message, bolread, data, users_userid, senderid
-- actors actorid, name
-- articles_actors articles_itemid, actors_actorid
-- rents rentsid, purchased_date, end_date, articles_itemid,
-- users_userid
-- pricehistory pricehistoryid, old_price, change_date, articles_itemid
--
-- Load-bearing typing details:
-- * users.userid is a 4-byte integer. database.py:message_all() counts
-- recipients with `SELECT Sum(pg_column_size(userid))/4 FROM users`; with a
-- bigint (8 bytes per row) it would try to send twice as many messages as
-- there are users.
-- * Date columns are DATE: the code inserts CURRENT_DATE and
-- CURRENT_DATE + time_available.
-- * Money is NUMERIC(x,2): the code subtracts in Python and writes the result
-- back, and statistics() sums prices.
-- * `imbd_rating` keeps the spelling used by database.py (it is a typo, but it
-- is the name in every query).
-- * email and name are deliberately NOT UNIQUE: create_user() performs no
-- duplicate check and log_in() takes the first match, so the tables have to
-- accept what the code accepts. The foreign keys below are what the code
-- really assumes, and they are what makes the delete paths as narrow as they
-- are (see README, "Known limitations").
--
-- Applied by `make schema`, which first recreates the `public` schema
-- (scripts/db.py). The database itself (NetfloxFinal) is created by
-- docker-compose.yml, and the connection parameters are the ones hard-coded in
-- database.py: host=localhost dbname=NetfloxFinal user=postgres.
-- --------------------------------------------------------------------------
-- users: accounts. The email decides the role in log_in(): any address under
-- netflox.com is an administrator, every other one is a client.
-- --------------------------------------------------------------------------
CREATE TABLE users (
userid integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
nome text NOT NULL,
email text NOT NULL,
password text NOT NULL, -- plain text, as the application stores it
balance numeric(8,2) NOT NULL
);
CREATE INDEX users_email_idx ON users (email);
-- --------------------------------------------------------------------------
-- articles: the catalogue. `type` is 'movie' or 'series' (statistics() queries
-- exactly those two literals); price is what a rent costs and time_available is
-- the number of days a rent lasts.
-- --------------------------------------------------------------------------
CREATE TABLE articles (
itemid integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
name text NOT NULL,
director text NOT NULL,
release_year integer NOT NULL,
imbd_rating numeric(3,1) NOT NULL,
genre text NOT NULL,
price numeric(6,2) NOT NULL,
type text NOT NULL,
time_available integer NOT NULL
);
-- --------------------------------------------------------------------------
-- actors + articles_actors: many-to-many between the catalogue and its cast.
-- add_article() reuses an existing actor row instead of duplicating it.
-- --------------------------------------------------------------------------
CREATE TABLE actors (
actorid integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
name text NOT NULL
);
CREATE TABLE articles_actors (
articles_itemid integer NOT NULL REFERENCES articles (itemid),
actors_actorid integer NOT NULL REFERENCES actors (actorid),
PRIMARY KEY (articles_itemid, actors_actorid)
);
CREATE INDEX articles_actors_actor_idx ON articles_actors (actors_actorid);
-- --------------------------------------------------------------------------
-- rents: one row per purchase; end_date is purchased_date + time_available.
-- my_articles() lists the rows with end_date >= CURRENT_DATE and my_history()
-- the ones before it, so an expired rent is kept, not deleted.
-- --------------------------------------------------------------------------
CREATE TABLE rents (
rentsid integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
purchased_date date NOT NULL,
end_date date NOT NULL,
articles_itemid integer NOT NULL REFERENCES articles (itemid),
users_userid integer NOT NULL REFERENCES users (userid)
);
CREATE INDEX rents_user_idx ON rents (users_userid);
CREATE INDEX rents_article_idx ON rents (articles_itemid);
-- --------------------------------------------------------------------------
-- messages: internal mail. users_userid is the recipient, senderid the sender
-- (both are regular userids) and data is the day it was sent.
-- --------------------------------------------------------------------------
CREATE TABLE messages (
msgid integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
message text NOT NULL,
bolread boolean NOT NULL DEFAULT FALSE,
data date NOT NULL,
users_userid integer NOT NULL REFERENCES users (userid),
senderid integer NOT NULL REFERENCES users (userid)
);
CREATE INDEX messages_recipient_idx ON messages (users_userid);
-- --------------------------------------------------------------------------
-- pricehistory: written by change_price() with the price that was replaced.
-- Nothing in the application reads this table back.
-- --------------------------------------------------------------------------
CREATE TABLE pricehistory (
pricehistoryid integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
old_price numeric(6,2) NOT NULL,
change_date date NOT NULL,
articles_itemid integer NOT NULL REFERENCES articles (itemid)
);
CREATE INDEX pricehistory_article_idx ON pricehistory (articles_itemid);
-- --------------------------------------------------------------------------
-- Minimal seed required by the code: one administrator.
--
-- log_in() classifies every address under netflox.com as an administrator, and
-- create_user() refuses to create accounts in that domain, so this row can only
-- be created here. The admin is also what statistics() assumes when it reports
-- "Total number of users" as (number of rows - 1), and message_all() divides by
-- rows, so the table must not be empty.
--
-- The password is not committed: it is read from the session setting
-- `netflox.admin_password`, which `make schema` sets from $NETFLOX_DEMO_PASSWORD.
-- Running this file without that setting fails with
-- ERROR: unrecognized configuration parameter "netflox.admin_password".
-- --------------------------------------------------------------------------
INSERT INTO users (nome, email, password, balance)
VALUES ('Admin', 'admin@netflox.com', current_setting('netflox.admin_password'), 20.00);
View File
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/env python3
"""Database helper for Netflox: applies schema.sql and loads the demo rows.
Used by the Makefile (`make schema`, `make seed`) and by the test suite
(tests/conftest.py), so that the schema and the seed are exercised through the
same path in both places.
Connection parameters are the ones hard-coded in database.py - localhost,
database NetfloxFinal, user postgres - and the password is read from
NETFLOX_DB_PASSWORD. The password for the seeded accounts (the administrator is
required by the code, see schema.sql) is read from NETFLOX_DEMO_PASSWORD; no
credential is stored in the repository.
export NETFLOX_DB_PASSWORD=... NETFLOX_DEMO_PASSWORD=...
python scripts/db.py schema # drop + recreate the public schema, apply schema.sql
python scripts/db.py seed # reset the rows and insert the demo data
python scripts/db.py reset # schema + seed
"""
from __future__ import annotations
import os
import pathlib
import sys
import psycopg2
ROOT = pathlib.Path(__file__).resolve().parent.parent
SCHEMA_FILE = ROOT / "schema.sql"
DB_HOST = "localhost"
DB_NAME = "NetfloxFinal"
DB_USER = "postgres"
# The demo accounts. The administrator must use an address under netflox.com,
# which is how log_in() recognises the role. Both passwords come from
# NETFLOX_DEMO_PASSWORD.
ADMIN = ("Admin", "admin@netflox.com")
DEMO_CLIENT = ("Cliente Demo", "cliente@exemplo.pt")
# (name, director, year, imdb, genre, price, type, days, [actors])
CATALOGUE = [
("The Matrix", "Lana Wachowski", 1999, 8.7, "sci-fi", 3.50, "movie", 7,
["Keanu Reeves", "Laurence Fishburne", "Carrie-Anne Moss"]),
("Pulp Fiction", "Quentin Tarantino", 1994, 8.9, "crime", 2.50, "movie", 7,
["John Travolta", "Samuel L. Jackson", "Uma Thurman"]),
("The Godfather", "Francis Ford Coppola", 1972, 9.2, "crime", 3.00, "movie", 7,
["Marlon Brando", "Al Pacino", "James Caan"]),
("Interstellar", "Christopher Nolan", 2014, 8.6, "sci-fi", 4.00, "movie", 14,
["Matthew McConaughey", "Anne Hathaway"]),
("Breaking Bad", "Vince Gilligan", 2008, 9.5, "drama", 5.00, "series", 30,
["Bryan Cranston", "Aaron Paul", "Anna Gunn"]),
("Stranger Things", "The Duffer Brothers", 2016, 8.7, "sci-fi", 6.00, "series", 30,
["Millie Bobby Brown", "Winona Ryder"]),
]
def _env(name: str, purpose: str) -> str:
value = os.environ.get(name)
if not value:
sys.exit(f"{name} is not set. {purpose}")
return value
def dsn() -> str:
return (
f"host={DB_HOST} dbname={DB_NAME} user={DB_USER} "
f"password={_env('NETFLOX_DB_PASSWORD', 'Export it before touching the database.')}"
)
def connect():
return psycopg2.connect(dsn())
def _assert_throwaway_db(conn) -> None:
"""Refuse to drop anything that is not the throwaway database of this repo."""
with conn.cursor() as cur:
cur.execute("SELECT current_database()")
name = cur.fetchone()[0]
if name != DB_NAME:
sys.exit(f"refusing to work on database {name!r}; expected {DB_NAME!r}")
def _close_other_sessions(conn) -> None:
"""Drop the other connections to this database before recreating the schema.
Needed because database.py leaks connections on a few of its paths: for
example findby_actor() raises before its conn.close() and findby_director()
never closes on the success path. Such a session sits "idle in transaction"
holding a lock on the tables, and DROP SCHEMA would wait for it forever.
"""
with conn.cursor() as cur:
cur.execute(
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity"
" WHERE datname = current_database() AND pid <> pg_backend_pid()"
)
conn.commit()
def apply_schema(conn) -> None:
"""Recreate the public schema and apply schema.sql.
Destructive by design: this database is disposable and the tests need a known
starting point. The administrator password is passed to schema.sql through a
session setting, so that it never appears in the file.
"""
_assert_throwaway_db(conn)
password = _env(
"NETFLOX_DEMO_PASSWORD",
"It is the password for the seeded accounts (schema.sql needs it).",
)
sql_text = SCHEMA_FILE.read_text(encoding="utf-8")
_close_other_sessions(conn)
with conn.cursor() as cur:
cur.execute("DROP SCHEMA IF EXISTS public CASCADE")
cur.execute("CREATE SCHEMA public")
cur.execute("SET netflox.admin_password = %s", (password,))
cur.execute(sql_text)
conn.commit()
def seed(conn) -> None:
"""Reset the rows and insert the demo accounts and catalogue."""
_assert_throwaway_db(conn)
password = _env("NETFLOX_DEMO_PASSWORD", "It is the password for the seeded accounts.")
with conn.cursor() as cur:
cur.execute(
"TRUNCATE users, articles, actors, articles_actors, rents, messages,"
" pricehistory RESTART IDENTITY CASCADE"
)
cur.execute(
"INSERT INTO users (nome, email, password, balance) VALUES (%s, %s, %s, 20.00)",
(*ADMIN, password),
)
cur.execute(
"INSERT INTO users (nome, email, password, balance) VALUES (%s, %s, %s, 20.00)",
(*DEMO_CLIENT, password),
)
for name, director, year, rating, genre, price, kind, days, actors in CATALOGUE:
cur.execute(
"INSERT INTO articles (name, director, release_year, imbd_rating, genre,"
" price, type, time_available) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
" RETURNING itemid",
(name, director, year, rating, genre, price, kind, days),
)
itemid = cur.fetchone()[0]
for actor in actors:
cur.execute(
"INSERT INTO actors (name) VALUES (%s) RETURNING actorid", (actor,)
)
actorid = cur.fetchone()[0]
cur.execute(
"INSERT INTO articles_actors (articles_itemid, actors_actorid)"
" VALUES (%s, %s)",
(itemid, actorid),
)
conn.commit()
def reset(conn) -> None:
apply_schema(conn)
seed(conn)
def main(argv: list[str]) -> int:
action = argv[1] if len(argv) > 1 else ""
if action not in {"schema", "seed", "reset"}:
print(f"usage: {pathlib.Path(argv[0]).name} schema|seed|reset", file=sys.stderr)
return 2
conn = connect()
try:
if action == "schema":
apply_schema(conn)
print(f"schema.sql applied to {DB_NAME}")
elif action == "seed":
seed(conn)
print(f"seed loaded: {len(CATALOGUE)} articles, 2 users")
else:
reset(conn)
print(f"database reset: schema.sql + {len(CATALOGUE)} articles, 2 users")
finally:
conn.close()
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+40
View File
@@ -0,0 +1,40 @@
"""Shared pytest setup for the Netflox suite.
Every test starts from a known database: the `public` schema is recreated and
schema.sql is applied (that is where the administrator required by the code comes
from), then the demo rows are loaded. The database itself is the throwaway
PostgreSQL started by `docker compose` (`make up`).
"""
from __future__ import annotations
import os
import pathlib
import sys
import pytest
ROOT = pathlib.Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from scripts import db as dbctl # noqa: E402
def pytest_configure(config):
for name in ("NETFLOX_DB_PASSWORD", "NETFLOX_DEMO_PASSWORD"):
if not os.environ.get(name):
raise pytest.UsageError(
f"{name} is not set; `make test` exports both, see README (Tests)"
)
@pytest.fixture(autouse=True)
def fresh_database():
"""Recreate the schema and reload the demo rows before every test."""
conn = dbctl.connect()
try:
dbctl.apply_schema(conn)
dbctl.seed(conn)
finally:
conn.close()
yield
+518
View File
@@ -0,0 +1,518 @@
"""End-to-end tests for Netflox.
They run against the throwaway PostgreSQL from `docker compose`, apply schema.sql
through the same helper the Makefile uses (tests/conftest.py), and then drive the
real functions of database.py - the same ones main.py calls. Nothing is mocked
except keyboard input: if the schema does not match what the code expects, these
tests fail.
Tests named `test_known_bug_*` and the ones marked `xfail` pin down behaviour
that is wrong in database.py / main.py; they are documentation, not approval
(see README, "Known limitations").
"""
from __future__ import annotations
import builtins
import contextlib
import datetime
import os
import pathlib
import re
import subprocess
import sys
from decimal import Decimal
import psycopg2.errors
import pytest
import database
from scripts import db as dbctl
ROOT = pathlib.Path(__file__).resolve().parent.parent
ADMIN_EMAIL = dbctl.ADMIN[1]
# The physical column order is part of the application contract: database.py runs
# `SELECT *` and reads rows by position (row[1] is the title, row[4] the balance...).
EXPECTED_COLUMNS = {
"users": ["userid", "nome", "email", "password", "balance"],
"articles": ["itemid", "name", "director", "release_year", "imbd_rating",
"genre", "price", "type", "time_available"],
"actors": ["actorid", "name"],
"articles_actors": ["articles_itemid", "actors_actorid"],
"rents": ["rentsid", "purchased_date", "end_date", "articles_itemid", "users_userid"],
"messages": ["msgid", "message", "bolread", "data", "users_userid", "senderid"],
"pricehistory": ["pricehistoryid", "old_price", "change_date", "articles_itemid"],
}
EXPECTED_FOREIGN_KEYS = {
("messages", "users_userid", "users"),
("messages", "senderid", "users"),
("rents", "articles_itemid", "articles"),
("rents", "users_userid", "users"),
("articles_actors", "articles_itemid", "articles"),
("articles_actors", "actors_actorid", "actors"),
("pricehistory", "articles_itemid", "articles"),
}
# --------------------------------------------------------------------------
# helpers
# --------------------------------------------------------------------------
def demo_password() -> str:
return os.environ["NETFLOX_DEMO_PASSWORD"]
@contextlib.contextmanager
def raw_cursor():
"""A plain connection to the throwaway database, for assertions."""
conn = dbctl.connect()
try:
with conn.cursor() as cur:
yield cur
conn.commit()
finally:
conn.close()
def scalar(sql, params=None):
with raw_cursor() as cur:
cur.execute(sql, params)
row = cur.fetchone()
return row[0] if row else None
def rows(sql, params=None):
with raw_cursor() as cur:
cur.execute(sql, params)
return cur.fetchall()
def user_id(email: str) -> int:
return scalar("SELECT userid FROM users WHERE email = %s", (email,))
def balance_of(userid: int) -> Decimal:
return scalar("SELECT balance FROM users WHERE userid = %s", (userid,))
def article_id(name: str) -> int:
return scalar("SELECT itemid FROM articles WHERE name = %s", (name,))
def today():
return scalar("SELECT CURRENT_DATE")
def make_client(name="Ana", email="ana@exemplo.pt") -> int:
"""Register an account with the application's own code and log it in."""
database.create_user(name, email, demo_password())
assert database.log_in(email, demo_password()) == 1
return database.USERID
def feed_inputs(monkeypatch, values):
queue = list(values)
def fake_input(prompt=""):
if not queue:
raise AssertionError(f"unexpected input() call: {prompt!r}")
return queue.pop(0)
monkeypatch.setattr(builtins, "input", fake_input)
# --------------------------------------------------------------------------
# schema
# --------------------------------------------------------------------------
def test_positional_columns_match_what_the_code_reads():
found: dict[str, list[str]] = {}
for table, column in rows(
"SELECT table_name, column_name FROM information_schema.columns"
" WHERE table_schema = 'public' ORDER BY table_name, ordinal_position"
):
found.setdefault(table, []).append(column)
assert found == EXPECTED_COLUMNS
def test_primary_and_foreign_keys():
primary = {r[0] for r in rows(
"SELECT table_name FROM information_schema.table_constraints"
" WHERE constraint_type = 'PRIMARY KEY' AND table_schema = 'public'")}
assert primary == set(EXPECTED_COLUMNS)
foreign = {(r[0], r[1], r[2]) for r in rows(
"SELECT tc.table_name, kcu.column_name, ccu.table_name"
" FROM information_schema.table_constraints tc"
" JOIN information_schema.key_column_usage kcu"
" ON kcu.constraint_name = tc.constraint_name"
" JOIN information_schema.constraint_column_usage ccu"
" ON ccu.constraint_name = tc.constraint_name"
" WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = 'public'"
" AND ccu.table_schema = 'public'")}
assert foreign == EXPECTED_FOREIGN_KEYS
def test_userid_is_a_4_byte_integer():
"""message_all() counts recipients as Sum(pg_column_size(userid))/4."""
assert scalar(
"SELECT format_type(atttypid, atttypmod) FROM pg_attribute"
" WHERE attrelid = 'users'::regclass AND attname = 'userid'") == "integer"
def test_minimal_seed_has_exactly_one_administrator():
assert scalar("SELECT count(*) FROM users") == 2
assert scalar("SELECT count(*) FROM users WHERE email LIKE '%@netflox.com'") == 1
assert database.log_in(ADMIN_EMAIL, demo_password()) == -1
# --------------------------------------------------------------------------
# accounts
# --------------------------------------------------------------------------
def test_create_user_and_login(capsys):
database.create_user("Ana Silva", "ana@exemplo.pt", "segredo")
assert "Insert a valid email" not in capsys.readouterr().out
assert database.log_in("ana@exemplo.pt", "segredo") == 1
assert "Welcome Ana Silva, your balance is 20.00 €" in capsys.readouterr().out
assert balance_of(database.USERID) == Decimal("20.00")
def test_create_user_rejects_invalid_and_netflox_addresses(capsys):
database.create_user("Sem Arroba", "sem-arroba", "x")
assert "Insert a valid email address" in capsys.readouterr().out
database.create_user("Falso Admin", "root@netflox.com", "x")
assert "Can't create accounts under netflox domain" in capsys.readouterr().out
assert scalar("SELECT count(*) FROM users") == 2 # only the seeded rows
def test_login_rejects_a_wrong_password(capsys):
database.create_user("Ana", "ana@exemplo.pt", "segredo")
assert database.log_in("ana@exemplo.pt", "errado") == 0
assert "Email and password not recognised" in capsys.readouterr().out
# --------------------------------------------------------------------------
# catalogue
# --------------------------------------------------------------------------
def test_list_all_returns_the_seeded_catalogue():
articles = database.list_all()
assert len(articles) == len(dbctl.CATALOGUE)
assert {row[1] for row in articles} == {row[0] for row in dbctl.CATALOGUE}
assert all(len(row) == len(EXPECTED_COLUMNS["articles"]) for row in articles)
def test_findby_name_matches_a_fragment_and_keeps_the_column_order():
movies = database.findby_name("Matr")
assert len(movies) == 1
row = movies[0]
assert row[1] == "The Matrix"
assert row[2] == "Lana Wachowski"
assert row[3] == 1999
assert row[4] == Decimal("8.7")
assert row[5] == "sci-fi"
assert row[6] == Decimal("3.50")
assert row[7] == "movie"
assert row[8] == 7
def test_view_details_prints_every_field_and_the_cast(capsys):
database.view_details(article_id("The Matrix"))
out = capsys.readouterr().out
assert "Title: The Matrix" in out
assert "Director: Lana Wachowski" in out
assert "Year of release: 1999" in out
assert "IMDB rating: 8.7/10" in out
assert "Genre: sci-fi" in out
assert "Type: movie" in out
assert "Price: 3.50€" in out
assert "Time available: 7 days" in out
assert "Keanu Reeves" in out and "Carrie-Anne Moss" in out
def test_order_by_title_and_price():
assert [row[1] for row in database.order_title()] == sorted(
row[0] for row in dbctl.CATALOGUE)
prices = [row[6] for row in database.order_price()]
assert prices == sorted(prices)
# --------------------------------------------------------------------------
# rents
# --------------------------------------------------------------------------
def test_purchase_debits_the_balance_and_creates_a_rent(capsys):
client = make_client()
database.purchase(article_id("The Matrix"), client)
out = capsys.readouterr().out
assert "Purchase successful!" in out
assert "New balance: 16.50€" in out
assert balance_of(client) == Decimal("16.50")
rent = rows("SELECT purchased_date, end_date, articles_itemid, users_userid FROM rents")[0]
assert rent[0] == today()
assert rent[1] == today() + datetime.timedelta(days=7)
assert rent[2] == article_id("The Matrix")
assert rent[3] == client
def test_purchase_without_balance_changes_nothing(capsys):
client = make_client()
database.alter_balance(client, 1)
database.purchase(article_id("The Matrix"), client)
assert "Can't afford this item" in capsys.readouterr().out
assert balance_of(client) == Decimal("1.00")
assert scalar("SELECT count(*) FROM rents") == 0
def test_my_articles_and_time_left(monkeypatch, capsys):
client = make_client()
itemid = article_id("Breaking Bad")
database.purchase(itemid, client)
feed_inputs(monkeypatch, [str(itemid)])
assert database.my_articles(client) == itemid
assert "Breaking Bad" in capsys.readouterr().out
database.time_left(itemid, client)
assert "Item available until" in capsys.readouterr().out
def test_my_history_lists_expired_rents(monkeypatch, capsys):
client = make_client()
itemid = article_id("Pulp Fiction")
database.purchase(itemid, client)
with raw_cursor() as cur:
cur.execute(
"UPDATE rents SET end_date = CURRENT_DATE - 1 WHERE articles_itemid = %s",
(itemid,),
)
feed_inputs(monkeypatch, ["0"])
database.my_history(client)
assert "Pulp Fiction" in capsys.readouterr().out
feed_inputs(monkeypatch, ["0"])
assert database.my_articles(client) == 0 # nothing current any more
# --------------------------------------------------------------------------
# messages
# --------------------------------------------------------------------------
def test_message_to_one_client_then_mark_it_read(capsys):
client = make_client()
admin = user_id(ADMIN_EMAIL)
database.message_client("Bem-vindo", str(client), str(admin))
assert "Message sent successfully" in capsys.readouterr().out
unread = database.show_unread_messages(client)
assert len(unread) == 1
assert unread[0][1] == "Bem-vindo" # message text
assert unread[0][3] == today() # data
assert unread[0][4] == client # recipient
assert unread[0][5] == admin # sender
database.read_message(unread[0][0])
assert scalar("SELECT bolread FROM messages") is True
read = database.show_read_messages(client)
assert len(read) == 1 and read[0][1] == "Bem-vindo"
assert database.show_unread_messages(client) is None # documented quirk
def test_message_all_reaches_every_user_except_the_sender(capsys):
make_client("Ana", "ana@exemplo.pt")
make_client("Bruno", "bruno@exemplo.pt")
admin = user_id(ADMIN_EMAIL)
total_users = scalar("SELECT count(*) FROM users")
database.message_all("Aviso geral", admin)
assert "Message sent to all" in capsys.readouterr().out
# One message per user other than the sender, and the sender receives none.
assert scalar("SELECT count(*) FROM messages") == total_users - 1
assert scalar("SELECT count(DISTINCT users_userid) FROM messages") == total_users - 1
assert scalar("SELECT count(*) FROM messages WHERE senderid = %s", (admin,)) == total_users - 1
assert scalar("SELECT count(*) FROM messages WHERE users_userid = %s", (admin,)) == 0
# --------------------------------------------------------------------------
# admin operations
# --------------------------------------------------------------------------
def test_add_article_reuses_an_existing_actor(monkeypatch, capsys):
feed_inputs(monkeypatch, ["2", "Keanu Reeves", "Nova Atriz"])
database.add_article("Neo", "Lana Wachowski", "7.5", "action", "1.50",
"2025", "10", "movie")
assert "Success!" in capsys.readouterr().out
itemid = article_id("Neo")
assert scalar("SELECT count(*) FROM articles_actors WHERE articles_itemid = %s",
(itemid,)) == 2
assert scalar("SELECT count(*) FROM actors WHERE name = 'Keanu Reeves'") == 1
assert scalar("SELECT count(*) FROM actors WHERE name = 'Nova Atriz'") == 1
assert scalar("SELECT price FROM articles WHERE itemid = %s", (itemid,)) == Decimal("1.50")
def test_change_price_by_name_and_by_id_writes_history(capsys):
itemid = article_id("The Matrix")
database.change_price("The Matrix", "9.99")
assert "Price updated successfully" in capsys.readouterr().out
assert scalar("SELECT price FROM articles WHERE itemid = %s", (itemid,)) == Decimal("9.99")
assert rows("SELECT old_price, change_date, articles_itemid FROM pricehistory") == [
(Decimal("3.50"), today(), itemid)]
database.change_price(itemid, "1.25") # numeric id: skips the name lookup
assert scalar("SELECT price FROM articles WHERE itemid = %s", (itemid,)) == Decimal("1.25")
assert scalar("SELECT count(*) FROM pricehistory") == 2
assert scalar("SELECT max(old_price) FROM pricehistory") == Decimal("9.99")
def test_remove_article_without_rentals_cleans_the_cast(capsys):
with raw_cursor() as cur:
cur.execute(
"INSERT INTO articles (name, director, release_year, imbd_rating, genre,"
" price, type, time_available) VALUES ('Temp','X',2020,5.0,'drama',1.00,"
"'movie',5) RETURNING itemid")
itemid = cur.fetchone()[0]
cur.execute("INSERT INTO actors (name) VALUES ('Temp Actor') RETURNING actorid")
cur.execute("INSERT INTO articles_actors VALUES (%s, %s)", (itemid, cur.fetchone()[0]))
database.remove_article(str(itemid)) # main.py always passes a string
assert "Article removed successfully" in capsys.readouterr().out
assert scalar("SELECT count(*) FROM articles WHERE itemid = %s", (itemid,)) == 0
assert scalar("SELECT count(*) FROM articles_actors WHERE articles_itemid = %s",
(itemid,)) == 0
def test_remove_article_is_refused_while_a_user_is_renting_it(capsys):
client = make_client()
itemid = article_id("Interstellar")
database.purchase(itemid, client)
database.remove_article(str(itemid))
assert "Can't remove article" in capsys.readouterr().out
assert scalar("SELECT count(*) FROM articles WHERE itemid = %s", (itemid,)) == 1
def test_foreign_key_blocks_deleting_an_article_with_rent_history():
"""remove_article() only checks *current* rents, but the DDL does not let the
article disappear behind the older rents that my_history() still needs."""
client = make_client()
itemid = article_id("The Matrix")
database.purchase(itemid, client)
with raw_cursor() as cur:
cur.execute(
"UPDATE rents SET end_date = CURRENT_DATE - 1 WHERE articles_itemid = %s",
(itemid,),
)
assert scalar("SELECT count(*) FROM rents WHERE articles_itemid = %s"
" AND CURRENT_DATE < end_date", (itemid,)) == 0 # code's own check passes
with pytest.raises(psycopg2.errors.ForeignKeyViolation):
with raw_cursor() as cur:
cur.execute("DELETE FROM articles WHERE itemid = %s", (itemid,))
def test_alter_balance_and_statistics(capsys):
client = make_client()
database.alter_balance(client, 50)
assert "Balance updated successfully" in capsys.readouterr().out
assert balance_of(client) == Decimal("50.00")
database.purchase(article_id("Pulp Fiction"), client)
capsys.readouterr()
database.statistics()
out = capsys.readouterr().out
assert "Total spent by all users: 2.50" in out # rents at current prices
# statistics() assumes exactly one administrator and prints the rest.
assert f"Total number of users: {scalar('SELECT count(*) FROM users') - 1}" in out
assert "Total number of articles: 6" in out
assert "Total number of movies: 4" in out
assert "Total number of series: 2" in out
assert "Total spent on movies currently available: 2.50" in out
# "Total spent in movies" is not what the label says: it sums the whole
# catalogue (3.50 + 2.50 + 3.00 + 4.00), not what was spent.
assert "Total spent in movies: 13.00" in out
assert "Total spent in series: 11.00" in out
# --------------------------------------------------------------------------
# credentials
# --------------------------------------------------------------------------
def test_database_refuses_to_start_without_the_password_env_var():
env = {k: v for k, v in os.environ.items() if k != "NETFLOX_DB_PASSWORD"}
proc = subprocess.run([sys.executable, "-c", "import database"],
cwd=ROOT, env=env, capture_output=True, text=True)
assert proc.returncode != 0
assert "NETFLOX_DB_PASSWORD is not set" in proc.stderr
def test_no_connection_string_carries_a_password_literal():
source = (ROOT / "database.py").read_text(encoding="utf-8")
connects = re.findall(r"psycopg2\.connect\((.*?)\)", source)
assert connects, "no psycopg2.connect() found in database.py"
assert all("password={DB_PASSWORD}" in call for call in connects)
assert 'os.environ.get("NETFLOX_DB_PASSWORD")' in source
def test_no_tracked_file_contains_the_database_password():
# safe.directory=* because this runs whatever user drives the container
# (the clone can belong to somebody else, e.g. under sudo).
proc = subprocess.run(
["git", "-c", "safe.directory=*", "grep", "-I", "-l", "-F",
os.environ["NETFLOX_DB_PASSWORD"]],
cwd=ROOT, capture_output=True, text=True)
assert proc.returncode == 1, f"the database password is committed in: {proc.stdout}"
def test_schema_sql_does_not_carry_the_demo_password():
assert os.environ["NETFLOX_DEMO_PASSWORD"] not in (ROOT / "schema.sql").read_text(
encoding="utf-8")
# --------------------------------------------------------------------------
# known bugs, pinned so that they are visible instead of silent
# --------------------------------------------------------------------------
@pytest.mark.xfail(reason="findby_director() has no return on the success path")
def test_known_bug_findby_director_returns_nothing_on_a_match():
assert database.findby_director("Christopher Nolan") is not None
@pytest.mark.xfail(reason="findby_actor() raises UnboundLocalError when no actor matches")
def test_known_bug_findby_actor_without_a_match():
assert database.findby_actor("Ninguem Com Este Nome") is None
def test_known_bug_search_without_matches_breaks_main_py():
"""findby_name() returns 0, and main.py immediately does article[x - 1][1]."""
assert database.findby_name("zzz-nao-existe") == 0
def test_known_bug_message_list_labels_a_message_with_the_recipient(capsys):
"""show_unread_messages() looks the author up with row[4], which is the
recipient (users_userid); the sender is row[5]. A client therefore sees their
own name as the author of every message."""
client = make_client()
admin = user_id(ADMIN_EMAIL)
database.message_client("Ola", str(client), str(admin))
capsys.readouterr()
database.show_unread_messages(client)
out = capsys.readouterr().out
assert "Message from Ana" in out # the recipient, not the admin
assert "Message from Admin" not in out
def test_known_bug_purchase_debits_the_last_logged_in_account():
"""database.py:294 updates the balance WHERE userid = USERID (the global set by
the last log_in), while the rent is inserted for the userid argument."""
ana = make_client("Ana", "ana@exemplo.pt")
bruno = make_client("Bruno", "bruno@exemplo.pt")
assert database.log_in("ana@exemplo.pt", demo_password()) == 1
database.purchase(article_id("Pulp Fiction"), bruno)
assert balance_of(ana) == Decimal("17.50") # Ana paid
assert balance_of(bruno) == Decimal("20.00")
assert scalar("SELECT users_userid FROM rents") == bruno