From db490b03546f1c646482e283bd42feb27e8a1e5c Mon Sep 17 00:00:00 2001 From: Andre Neto Date: Thu, 8 Oct 2026 14:38:11 +0100 Subject: [PATCH] Fix the defects the suite pinned; turn xfail/known_bug into regressions The suite documented every defect with two `xfail` and four `test_known_bug_*` tests. With the tests as the specification, all of them are fixed and those tests are now regression tests that fail against the previous code: - findby_director() returned None on the success path (it printed the matches and fell off the end); it returns the rows now. - findby_actor() raised UnboundLocalError when no actor matched, and returned only the last article of an actor with several; it returns the list, or None. - findby_name() and findby_type() returned the integer 0 on no match, which main.py indexed into; they return an empty list and the menus skip it. - purchase() debited USERID (the account of the last log_in) instead of the userid argument, while the rent went to the argument. - the message list looked the author up with row[4] (the recipient) instead of row[5] (the sender), in the unread and in the read list. - remove_article() checked only the open rents, so the foreign keys on the older rents and on pricehistory turned the refusal into a traceback; it now explains which records keep the article and rolls back as a backstop. - show_unread_messages() returned None when there was nothing; it returns an empty list like the read side, and the messages menu skips an empty list. - database.USERID did not exist before a login, so leaving the menu with 0 raised AttributeError; it starts as None and the menu code handles 0. - every connection is opened and closed by one context manager: findby_director(), findby_actor() and findby_type() returned before conn.close() and statistics() never closed, leaving sessions `idle in transaction`. make test: 40 passed, 0 xfailed (was 30 passed, 2 xfailed). No xfail and no test_known_bug_* is left. The README's previous "what is broken" paragraph and its test output are updated, and a "Known limitations" section lists what was deliberately not touched: SQL built by string concatenation, menu selections past the end of the list, and input() inside the data layer. --- README.md | 17 +- database.py | 1004 +++++++++++++++++++++-------------------- main.py | 28 +- tests/test_netflox.py | 175 +++++-- 4 files changed, 710 insertions(+), 514 deletions(-) diff --git a/README.md b/README.md index d679203..d8a9a17 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ 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 defects the tests used to pin are fixed. `findby_director()` printed its matches and returned nothing; `findby_actor()` raised `UnboundLocalError` when no actor matched, and returned only the last article of an actor that had several; a search with no results returned the integer `0`, which `main.py` then indexed into; `purchase()` debited the account of the last login instead of the account in its argument; the message list showed the recipient's name as the author; `remove_article()` checked only the rentals that were still open, so the foreign keys on the older ones and on `pricehistory` turned the refusal into a traceback; `show_unread_messages()` returned `None` instead of an empty list; `database.USERID` was created by `log_in()`, so leaving the menu with `0` raised `AttributeError`; and several functions returned before closing their connection, leaving `idle in transaction` sessions behind. Every connection is opened and closed in one context manager now, and each of these defects has a regression test. 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. @@ -91,13 +91,22 @@ make test ```text .venv/bin/python -m pytest -q -...........................xx... [100%] -30 passed, 2 xfailed in 8.87s +........................................ [100%] +40 passed in 13.30s ``` 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. +The tests at the end of `tests/test_netflox.py` are the regression suite: each one fails against the code before the fix and passes after it - there is no `xfail` and no `test_known_bug_*` left. "Known limitations" below lists what was deliberately left alone. + +### Known limitations + +Not fixed, and not covered by the suite, because they are the shape of the interface +rather than a defect with a single right answer: every statement is built by string +concatenation, so the input is interpolated into the SQL; the menus index the list they +just printed without checking the range (`article[x - 1]` past the end raises +`IndexError`); and `database.my_articles()` / `database.my_history()` read from the +keyboard, which puts the menu inside the data layer. ## Structure diff --git a/database.py b/database.py index b44525b..68f2476 100644 --- a/database.py +++ b/database.py @@ -1,5 +1,8 @@ import os + import psycopg2 +import psycopg2.errors +from contextlib import contextmanager # Read once, at import time. Never hard-code the password here. DB_PASSWORD = os.environ.get("NETFLOX_DB_PASSWORD") @@ -9,70 +12,122 @@ if not DB_PASSWORD: "password before running (see README.md, Configuration)." ) -global USERID +# Account of the last successful log_in(). It used to be created only by +# log_in(), so every path that ran before a login (or after leaving the menu +# with 0) failed with AttributeError; it exists from the start and is None. +USERID = None + + +@contextmanager +def _connection(): + """Open one connection and always close it. + + The callers keep their own commit(), which is where the data is made + durable; this only guarantees that the session goes away on every path, + including the early returns and the exceptions. Sessions that were left + open stayed `idle in transaction` until something killed them. + """ + conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") + try: + yield conn + if not conn.closed: + conn.commit() + except Exception: + if not conn.closed: + conn.rollback() + raise + finally: + if not conn.closed: + conn.close() # MENU def create_user(name, email, password): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - if email.find('@') == -1: - print("\n\tInsert a valid email address") + if email.find('@') == -1: + print("\n\tInsert a valid email address") - elif email.find('netflox.com') != -1: - print("\n\tCan't create accounts under netflox domain") + elif email.find('netflox.com') != -1: + print("\n\tCan't create accounts under netflox domain") - else: - c.execute("INSERT INTO users (nome, email, password, balance) VALUES ('" + name + "','" + email + "','" + password + "',20)") + else: + c.execute("INSERT INTO users (nome, email, password, balance) VALUES ('" + name + "','" + email + "','" + password + "',20)") - conn.commit() - conn.close() + conn.commit() + conn.close() def log_in(email, password): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("SELECT * FROM users WHERE email = '" + email + "' AND password = '" + password + "'") - results = c.fetchall() + c.execute("SELECT * FROM users WHERE email = '" + email + "' AND password = '" + password + "'") + results = c.fetchall() - global USERID + global USERID - conn.commit() - conn.close() + conn.commit() + conn.close() - if email.find('netflox.com') == -1: + if email.find('netflox.com') == -1: - if results: - print("\n\tWelcome " + results[0][1] + ", your balance is " + str(results[0][4]) + " €") - USERID = results[0][0] + if results: + print("\n\tWelcome " + results[0][1] + ", your balance is " + str(results[0][4]) + " €") + USERID = results[0][0] + + return 1 # client + else: + print("\n\tEmail and password not recognised") + + return 0 - return 1 # client else: - print("\n\tEmail and password not recognised") - - return 0 - - else: - if results: - print("\n\tWelcome Admin " + results[0][1]) - USERID = results[0][0] - return -1 # admin - else: - print("\n\tEmail and password not recognised\n") - return 0 + if results: + print("\n\tWelcome Admin " + results[0][1]) + USERID = results[0][0] + return -1 # admin + else: + print("\n\tEmail and password not recognised\n") + return 0 # MESSAGES CLIENT def show_unread_messages(userid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("SELECT * FROM messages WHERE users_userid = " + str(userid) + " AND bolread = FALSE") - results = c.fetchall() + c.execute("SELECT * FROM messages WHERE users_userid = " + str(userid) + " AND bolread = FALSE") + results = c.fetchall() + + if results: + y = 0 + print("\r") + for i in results: + # i[4] is the recipient, i[5] is the sender: the list used to name + # every message after the account that received it. + c.execute("SELECT * FROM users WHERE userid = " + str(i[5])) + sender = c.fetchall() + for x in sender: + y += 1 + print("\t" + str(y) + ") Message from " + x[1] + " date: " + str(i[3])) + + print("\t0) Exit") + return results + + print("\n\tNo new messages\n\t0) Exit") + # An empty list, not None: main.py indexes what comes back, and the read + # side has always returned a list. + return [] + +def show_read_messages(userid): + with _connection() as conn: + c = conn.cursor() + + c.execute("SELECT * FROM messages WHERE users_userid = " + str(userid) + " AND bolread = TRUE") + messages = c.fetchall() - if results: y = 0 print("\r") - for i in results: - c.execute("SELECT * FROM users WHERE userid = " + str(i[4])) + for i in messages: + c.execute("SELECT * FROM users WHERE userid = " + str(i[5])) sender = c.fetchall() for x in sender: y += 1 @@ -80,547 +135,536 @@ def show_unread_messages(userid): print("\t0) Exit") - conn.commit() - conn.close() + return messages - return results - - else: - print("\n\tNo new messages\n\t0) Exit") - - conn.commit() - conn.close() -def show_read_messages(userid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - - c.execute("SELECT * FROM messages WHERE users_userid = " + str(userid) + " AND bolread = TRUE") - messages = c.fetchall() - - y = 0 - print("\r") - for i in messages: - c.execute("SELECT * FROM users WHERE userid = " + str(i[4])) - sender = c.fetchall() - for x in sender: - y += 1 - print("\t" + str(y) + ") Message from " + x[1] + " date: " + str(i[3])) - - print("\t0) Exit") - - conn.commit() - conn.close() - - return messages def read_message(msgid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("UPDATE messages SET bolread = TRUE WHERE msgid='" + str(msgid) + "'") + c.execute("UPDATE messages SET bolread = TRUE WHERE msgid='" + str(msgid) + "'") - conn.commit() - conn.close() + conn.commit() + conn.close() # MESSAGES ADMIN def message_all(msg, senderid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("SELECT userid FROM users") - results = c.fetchall() + c.execute("SELECT userid FROM users") + results = c.fetchall() - c.execute("SELECT Sum(pg_column_size(userid))/4 as total_size FROM users") - size = c.fetchall()[0][0] + c.execute("SELECT Sum(pg_column_size(userid))/4 as total_size FROM users") + size = c.fetchall()[0][0] - i = 0 - while i < size: - if results[i][0] != senderid: - c.execute( - "INSERT INTO messages (message, bolread, users_userid, senderid, data) VALUES ('" + msg + "', FALSE, '" + str( - results[i][0]) + "', '" + str(senderid) + "', CURRENT_DATE)") - i += 1 + i = 0 + while i < size: + if results[i][0] != senderid: + c.execute( + "INSERT INTO messages (message, bolread, users_userid, senderid, data) VALUES ('" + msg + "', FALSE, '" + str( + results[i][0]) + "', '" + str(senderid) + "', CURRENT_DATE)") + i += 1 - print("\n\tMessage sent to all") + print("\n\tMessage sent to all") - conn.commit() - conn.close() + conn.commit() + conn.close() def message_client(msg, recieverid, senderid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute( - "INSERT INTO messages (message, bolread, users_userid, senderid, data) VALUES ('" + msg + "', FALSE, '" + - str(recieverid) + "', '" + str(senderid) + "', CURRENT_DATE)") + c.execute( + "INSERT INTO messages (message, bolread, users_userid, senderid, data) VALUES ('" + msg + "', FALSE, '" + + str(recieverid) + "', '" + str(senderid) + "', CURRENT_DATE)") - print("\n\tMessage sent successfully") + print("\n\tMessage sent successfully") - conn.commit() - conn.close() + conn.commit() + conn.close() # SEARCH ARTICLES def findby_name(name): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - y=0 - c.execute("SELECT * FROM articles WHERE name like '%" + name + "%'") - movies = c.fetchall() - for x in movies: - y=y+1 - print("\t"+str(y)+") "+x[1]) + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles WHERE name like '%" + name + "%'") + movies = c.fetchall() + y = 0 + for x in movies: + y = y + 1 + print("\t" + str(y) + ") " + x[1]) + + if not movies: + # An empty list, not the integer 0: main.py indexes whatever comes + # back, and 0 is not indexable. + print("\n---movie name not correct---\n") + + return movies - if movies: - for i in movies: - break - else: - print("\n---movie name not correct---\n") - conn.commit() - conn.close() - return (0) - conn.commit() - conn.close() - return(movies) def findby_director(director): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - y = 0 - c = conn.cursor() - c.execute("SELECT * FROM articles WHERE director like '%" + director + "%'") - movies = c.fetchall() - for x in movies: - y = y + 1 - print("\t" + str(y) + ") " + x[1]) + with _connection() as conn: + y = 0 + c = conn.cursor() + c.execute("SELECT * FROM articles WHERE director like '%" + director + "%'") + movies = c.fetchall() + for x in movies: + y = y + 1 + print("\t" + str(y) + ") " + x[1]) + + if not movies: + print("\n---movie director name not correct---\n") + + # The success path used to fall off the end of the function and return + # None, so main.py never saw the matches it had just printed. + return movies - if movies: - for i in movies: - break - else: - print("\n---movie director name not correct---\n") - conn.commit() - conn.close() - return (movies) - conn.commit() - conn.close() def findby_type(type): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - y = 0 - c = conn.cursor() - c.execute("SELECT * FROM articles WHERE type like '%" + type + "%'") - movies = c.fetchall() - for x in movies: - y = y + 1 - print("\t" + str(y) + ") " + x[1]) + with _connection() as conn: + y = 0 + c = conn.cursor() + c.execute("SELECT * FROM articles WHERE type like '%" + type + "%'") + movies = c.fetchall() + for x in movies: + y = y + 1 + print("\t" + str(y) + ") " + x[1]) - if movies: - for i in movies: - break - else: - print("\n---movie type not correct---\n") + if not movies: + print("\n---movie type not correct---\n") + + # Returning before closing used to leave the session idle in + # transaction for good; the empty case returns a list, like findby_name. + return movies + +def findby_actor(actor): + with _connection() as conn: + j = 0 + c = conn.cursor() + c.execute("SELECT * FROM actors WHERE name like('%" + actor + "%')") + actors = c.fetchall() + print("\r") + articles = [] + for x in actors: + actorid = x[0] + c.execute("SELECT * FROM articles_actors WHERE actors_actorid = '" + str(actorid) + "' ") + articles_actors = c.fetchall() + for y in articles_actors: + j = j + 1 + c.execute("SELECT * FROM articles WHERE itemid = '" + str(y[0]) + "' ") + matched = c.fetchall() + if matched: + articles.append(matched[0]) + print(str("\t" + str(j) + ") " + matched[0][1])) + + if not articles: + print("\n---movie actor name not correct---\n") + # `articles` used to be an unbound name when no actor matched. + return None + + return articles + +def list_all(): + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles") + articles = c.fetchall() + print('\r') + + y = 0 + for x in articles: + y += 1 + print("\t"+str(y)+") " + x[1]) conn.commit() conn.close() - return (0) - return (movies) - conn.commit() - conn.close() -def findby_actor(actor): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - j=0 - c = conn.cursor() - c.execute("SELECT * FROM actors WHERE name like('%"+actor+"%')") - actors = c.fetchall() - print("\r") - for x in actors: - actorid=x[0] - c.execute("SELECT * FROM articles_actors WHERE actors_actorid = '"+str(actorid)+"' ") - articles_actors = c.fetchall() - for y in articles_actors: - j = j + 1 - c.execute("SELECT * FROM articles WHERE itemid = '"+str(y[0])+"' ") - articles = c.fetchall() - print(str("\t"+str(j)+") "+articles[0][1])) - return (articles) - conn.commit() - conn.close() -def list_all(): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - c.execute("SELECT * FROM articles") - articles = c.fetchall() - print('\r') - - y = 0 - for x in articles: - y += 1 - print("\t"+str(y)+") " + x[1]) - conn.commit() - conn.close() - - return articles + return articles def view_details(itemid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - c.execute("SELECT * FROM articles WHERE itemid = '"+str(itemid)+"'") - article = c.fetchall()[0] - print("\n\tTitle: "+str(article[1])) - print("\tDirector: " + str(article[2])) - print("\tYear of release: " + str(article[3])) - print("\tIMDB rating: " + str(article[4])+"/10") - print("\tGenre: " + str(article[5])) - print("\tType: " + str(article[7])) - print("\tPrice: " + str(article[6]) + "€") - print("\tTime available: " + str(article[8]) + " days") - print("\tActors: ") + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles WHERE itemid = '"+str(itemid)+"'") + article = c.fetchall()[0] + print("\n\tTitle: "+str(article[1])) + print("\tDirector: " + str(article[2])) + print("\tYear of release: " + str(article[3])) + print("\tIMDB rating: " + str(article[4])+"/10") + print("\tGenre: " + str(article[5])) + print("\tType: " + str(article[7])) + print("\tPrice: " + str(article[6]) + "€") + print("\tTime available: " + str(article[8]) + " days") + print("\tActors: ") - c.execute("SELECT * FROM articles_actors WHERE articles_itemid = '" + str(itemid) + "'") - actors = c.fetchall() + c.execute("SELECT * FROM articles_actors WHERE articles_itemid = '" + str(itemid) + "'") + actors = c.fetchall() - for i in actors: - c.execute("SELECT * FROM actors WHERE actorid = '" + str(i[1]) + "'") - actors_name = c.fetchall()[0][1] - print("\t\t"+str(actors_name)) + for i in actors: + c.execute("SELECT * FROM actors WHERE actorid = '" + str(i[1]) + "'") + actors_name = c.fetchall()[0][1] + print("\t\t"+str(actors_name)) - conn.commit() - conn.close() + conn.commit() + conn.close() def purchase(itemid, userid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("SELECT balance FROM users WHERE userid = '"+str(userid)+"'") - balance = c.fetchall()[0][0] + c.execute("SELECT balance FROM users WHERE userid = '" + str(userid) + "'") + balance = c.fetchall()[0][0] - c.execute("SELECT price FROM articles WHERE itemid = '" + str(itemid) + "'") - cost = c.fetchall()[0][0] + c.execute("SELECT price FROM articles WHERE itemid = '" + str(itemid) + "'") + cost = c.fetchall()[0][0] - if balance >= cost: - new_balance = balance - cost - c.execute("UPDATE users SET balance= '" + str(new_balance) + "' WHERE userid='" + str(USERID) + "'") + if balance >= cost: + new_balance = balance - cost + # The debit follows the userid argument, not USERID (the account of + # the last log_in): buying for somebody else used to charge the + # logged-in account while the rent went to the argument. + c.execute("UPDATE users SET balance= '" + str(new_balance) + "' WHERE userid='" + str(userid) + "'") - c.execute("SELECT time_available FROM articles WHERE itemid = '" + str(itemid) + "'") - time_available = c.fetchall()[0][0] + c.execute("SELECT time_available FROM articles WHERE itemid = '" + str(itemid) + "'") + time_available = c.fetchall()[0][0] - c.execute("INSERT INTO rents (purchased_date, end_date, articles_itemid, users_userid) VALUES (CURRENT_DATE, CURRENT_DATE +"+str(int(time_available))+",'"+str(itemid)+"','"+str(userid)+"')") + c.execute("INSERT INTO rents (purchased_date, end_date, articles_itemid, users_userid) VALUES (CURRENT_DATE, CURRENT_DATE +" + str(int(time_available)) + ",'" + str(itemid) + "','" + str(userid) + "')") - print("\n\tPurchase successful!") - print("\tNew balance: "+str(new_balance)+"€") + print("\n\tPurchase successful!") + print("\tNew balance: " + str(new_balance) + "€") - else: - print("\n\tCan't afford this item") - - conn.commit() - conn.close() + else: + print("\n\tCan't afford this item") # ORDER BY def order_title(): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - c.execute("SELECT * FROM articles ORDER BY name") - movies = c.fetchall() - y = 0 - print("\r") - for x in movies: - y += 1 - print("\t"+str(y)+") " + str(x[1])) - print("\t0) Exit") - conn.commit() - conn.close() + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles ORDER BY name") + movies = c.fetchall() + y = 0 + print("\r") + for x in movies: + y += 1 + print("\t"+str(y)+") " + str(x[1])) + print("\t0) Exit") + conn.commit() + conn.close() - return movies + return movies def order_director(): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - c.execute("SELECT * FROM articles ORDER BY director") - movies = c.fetchall() - y = 0 - print("\r") - for x in movies: - y += 1 - print("\t"+str(y)+") " + str(x[2]) + " - " + str(x[1])) - print("\t0) Exit") - conn.commit() - conn.close() + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles ORDER BY director") + movies = c.fetchall() + y = 0 + print("\r") + for x in movies: + y += 1 + print("\t"+str(y)+") " + str(x[2]) + " - " + str(x[1])) + print("\t0) Exit") + conn.commit() + conn.close() - return movies + return movies def order_year(): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - c.execute("SELECT * FROM articles ORDER BY release_year") - movies = c.fetchall() - y = 0 - print("\r") - for x in movies: - y += 1 - print("\t"+str(y)+") " + str(x[3]) + " - " + str(x[1])) - print("\t0) Exit") - conn.commit() - conn.close() + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles ORDER BY release_year") + movies = c.fetchall() + y = 0 + print("\r") + for x in movies: + y += 1 + print("\t"+str(y)+") " + str(x[3]) + " - " + str(x[1])) + print("\t0) Exit") + conn.commit() + conn.close() - return movies + return movies def order_imdb(): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - c.execute("SELECT * FROM articles ORDER BY imbd_rating") - movies = c.fetchall() - y = 0 - print("\r") - for x in movies: - y += 1 - print("\t"+str(y)+") " + str(x[4]) + " - " + str(x[1])) - print("\t0) Exit") - conn.commit() - conn.close() + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles ORDER BY imbd_rating") + movies = c.fetchall() + y = 0 + print("\r") + for x in movies: + y += 1 + print("\t"+str(y)+") " + str(x[4]) + " - " + str(x[1])) + print("\t0) Exit") + conn.commit() + conn.close() - return movies + return movies def order_genre(): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - c.execute("SELECT * FROM articles ORDER BY genre") - movies = c.fetchall() - y = 0 - print("\r") - for x in movies: - y += 1 - print("\t"+str(y)+") " + str(x[5]) + " - " + str(x[1])) - print("\t0) Exit") - conn.commit() - conn.close() + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles ORDER BY genre") + movies = c.fetchall() + y = 0 + print("\r") + for x in movies: + y += 1 + print("\t"+str(y)+") " + str(x[5]) + " - " + str(x[1])) + print("\t0) Exit") + conn.commit() + conn.close() - return movies + return movies def order_price(): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - c.execute("SELECT * FROM articles ORDER BY price") - movies = c.fetchall() - y = 0 - print("\r") - for x in movies: - y += 1 - print("\t"+str(y)+") " + str(x[6]) + " - " + str(x[1])) - print("\t0) Exit") - conn.commit() - conn.close() + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles ORDER BY price") + movies = c.fetchall() + y = 0 + print("\r") + for x in movies: + y += 1 + print("\t"+str(y)+") " + str(x[6]) + " - " + str(x[1])) + print("\t0) Exit") + conn.commit() + conn.close() - return movies + return movies def order_type(): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() - c.execute("SELECT * FROM articles ORDER BY type") - movies = c.fetchall() - y = 0 - print("\r") - for x in movies: - y += 1 - print("\t"+str(y)+") " + str(x[7]) + " - " + str(x[1])) - print("\t0) Exit") - conn.commit() - conn.close() + with _connection() as conn: + c = conn.cursor() + c.execute("SELECT * FROM articles ORDER BY type") + movies = c.fetchall() + y = 0 + print("\r") + for x in movies: + y += 1 + print("\t"+str(y)+") " + str(x[7]) + " - " + str(x[1])) + print("\t0) Exit") + conn.commit() + conn.close() - return movies + return movies # MY ARTICLES def my_articles(userid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("SELECT * FROM rents WHERE end_date >= CURRENT_DATE AND users_userid = '" + str(userid) + "' ORDER BY articles_itemid") - rents = c.fetchall() + c.execute("SELECT * FROM rents WHERE end_date >= CURRENT_DATE AND users_userid = '" + str(userid) + "' ORDER BY articles_itemid") + rents = c.fetchall() - if rents: - y = 0 - print("\n\tMy articles:\n") - for i in rents: - y += 1 - c.execute("SELECT * FROM articles WHERE itemid = '" + str(i[3]) + "' ORDER BY itemid") - articles = c.fetchall() - print("\t"+str(articles[0][0])+") "+str(articles[0][1])) + if rents: + y = 0 + print("\n\tMy articles:\n") + for i in rents: + y += 1 + c.execute("SELECT * FROM articles WHERE itemid = '" + str(i[3]) + "' ORDER BY itemid") + articles = c.fetchall() + print("\t"+str(articles[0][0])+") "+str(articles[0][1])) - else: - print("\n\tYou don't have any articles") + else: + print("\n\tYou don't have any articles") - conn.commit() - conn.close() + conn.commit() + conn.close() - return int(input("\t0) Exit\n\tYour selection: ")) + return int(input("\t0) Exit\n\tYour selection: ")) def my_history(userid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("SELECT * FROM rents WHERE end_date < CURRENT_DATE AND users_userid = '" + str(userid) + "' ORDER BY articles_itemid") - rents = c.fetchall() + c.execute("SELECT * FROM rents WHERE end_date < CURRENT_DATE AND users_userid = '" + str(userid) + "' ORDER BY articles_itemid") + rents = c.fetchall() - if rents: - y = 0 - print("\n\tMy old articles:\n") - for i in rents: - y += 1 - c.execute("SELECT * FROM articles WHERE itemid = '" + str(i[3]) + "' ORDER BY itemid") - articles = c.fetchall() - print("\t" + str(articles[0][1])) + if rents: + y = 0 + print("\n\tMy old articles:\n") + for i in rents: + y += 1 + c.execute("SELECT * FROM articles WHERE itemid = '" + str(i[3]) + "' ORDER BY itemid") + articles = c.fetchall() + print("\t" + str(articles[0][1])) - else: - print("\n\tYou don't have any old articles yet") + else: + print("\n\tYou don't have any old articles yet") - conn.commit() - conn.close() + conn.commit() + conn.close() - return int(input("\t0) Exit\n\tYour selection: ")) + return int(input("\t0) Exit\n\tYour selection: ")) def time_left(itemid, userid): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("SELECT * FROM rents WHERE articles_itemid = "+str(itemid)+" AND users_userid = '"+str(userid)+"'") - time = c.fetchall()[0][2] + c.execute("SELECT * FROM rents WHERE articles_itemid = "+str(itemid)+" AND users_userid = '"+str(userid)+"'") + time = c.fetchall()[0][2] - print("\n\tItem available until "+str(time)) + print("\n\tItem available until "+str(time)) - conn.commit() - conn.close() + conn.commit() + conn.close() # ADMIN def add_article(name, director, imbd_rating, genre, price, year, time_available, type): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("INSERT INTO articles(name, director, release_year, imbd_rating, genre, price, type, time_available) VALUES('" + name + "','" + director + "', '" + year + "','" + imbd_rating + "','" + genre + "','" + price + "','" + type + "','" + time_available + "')") - c.execute("SELECT * FROM articles WHERE name = '" + name + "'") - item_id = c.fetchall()[0][0] + c.execute("INSERT INTO articles(name, director, release_year, imbd_rating, genre, price, type, time_available) VALUES('" + name + "','" + director + "', '" + year + "','" + imbd_rating + "','" + genre + "','" + price + "','" + type + "','" + time_available + "')") + c.execute("SELECT * FROM articles WHERE name = '" + name + "'") + item_id = c.fetchall()[0][0] - n_actors = int(input("\n\tNumber of actors: ")) - x = 0 - while x < n_actors: - x += 1 - name_actor = str(input("\n\tActor name: ")) + n_actors = int(input("\n\tNumber of actors: ")) + x = 0 + while x < n_actors: + x += 1 + name_actor = str(input("\n\tActor name: ")) - c.execute("SELECT * FROM actors WHERE name ='" + name_actor + "'") - actor = c.fetchall() - - if actor: - c.execute("INSERT INTO articles_actors(articles_itemid, actors_actorid) VALUES ('" + str(item_id) + "', '" + str(actor[0][0]) + "' )") - else: - c.execute("INSERT INTO actors (name) VALUES ('" + name_actor + "')") c.execute("SELECT * FROM actors WHERE name ='" + name_actor + "'") - actor_id = c.fetchall()[0][0] - c.execute("INSERT INTO articles_actors(articles_itemid, actors_actorid) VALUES ('" + str(item_id) + "', '" + str(actor_id) + "')") + actor = c.fetchall() - print("\n\tSuccess!") + if actor: + c.execute("INSERT INTO articles_actors(articles_itemid, actors_actorid) VALUES ('" + str(item_id) + "', '" + str(actor[0][0]) + "' )") + else: + c.execute("INSERT INTO actors (name) VALUES ('" + name_actor + "')") + c.execute("SELECT * FROM actors WHERE name ='" + name_actor + "'") + actor_id = c.fetchall()[0][0] + c.execute("INSERT INTO articles_actors(articles_itemid, actors_actorid) VALUES ('" + str(item_id) + "', '" + str(actor_id) + "')") - conn.commit() - conn.close() + print("\n\tSuccess!") + + conn.commit() + conn.close() def change_price(n_id, newprice): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - itemid = n_id - if isinstance(n_id, str): - c.execute("SELECT itemid FROM articles WHERE name = '" + n_id + "'") - n_id = c.fetchall() - for i in n_id: - itemid = i[0] + itemid = n_id + if isinstance(n_id, str): + c.execute("SELECT itemid FROM articles WHERE name = '" + n_id + "'") + n_id = c.fetchall() + for i in n_id: + itemid = i[0] - c.execute("SELECT price FROM articles WHERE itemid = '" + str(itemid) + "'") - result = c.fetchall() - oldprice = 0 - for i in result: - oldprice = i[0] + c.execute("SELECT price FROM articles WHERE itemid = '" + str(itemid) + "'") + result = c.fetchall() + oldprice = 0 + for i in result: + oldprice = i[0] - c.execute("UPDATE articles SET price = '" + str(newprice) + "' WHERE itemid = '" + str(itemid) + "'") - c.execute( - "INSERT INTO pricehistory(old_price, change_date, articles_itemid) VALUES('" + str(oldprice) + "', CURRENT_DATE,'" + str( - itemid) + "')") + c.execute("UPDATE articles SET price = '" + str(newprice) + "' WHERE itemid = '" + str(itemid) + "'") + c.execute( + "INSERT INTO pricehistory(old_price, change_date, articles_itemid) VALUES('" + str(oldprice) + "', CURRENT_DATE,'" + str( + itemid) + "')") - print("\n\tPrice updated successfully") - print("\tOld price saved to history") + print("\n\tPrice updated successfully") + print("\tOld price saved to history") - conn.commit() - conn.close() + conn.commit() + conn.close() def remove_article(n_id): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - itemid = n_id - if isinstance(n_id, str): - c.execute("SELECT itemid FROM articles WHERE name = '" + n_id + "'") - n_id = c.fetchall() - for i in n_id: - itemid = i[0] + itemid = n_id + if isinstance(n_id, str): + c.execute("SELECT itemid FROM articles WHERE name = '" + n_id + "'") + n_id = c.fetchall() + for i in n_id: + itemid = i[0] + + c.execute("SELECT * FROM rents WHERE articles_itemid = '" + str(itemid) + "' AND CURRENT_DATE < end_date") + result = c.fetchall() + if result: + print("\n\tCan't remove article because there are user(s) renting it") + return + + # The foreign keys block the article through the rents that already ended + # and through its price history too; checking only the open rents turned + # the refusal into a ForeignKeyViolation traceback. + c.execute("SELECT count(*) FROM rents WHERE articles_itemid = '" + str(itemid) + "'") + old_rents = c.fetchall()[0][0] + c.execute("SELECT count(*) FROM pricehistory WHERE articles_itemid = '" + str(itemid) + "'") + price_changes = c.fetchall()[0][0] + if old_rents or price_changes: + kept_by = [] + if old_rents: + kept_by.append("the rental history (" + str(old_rents) + " rent(s) that already ended)") + if price_changes: + kept_by.append("its price history (" + str(price_changes) + " change(s))") + print("\n\tCan't remove article because it is kept by " + " and ".join(kept_by)) + print("\tThose records are still needed, so the article is not deleted.") + return + + try: + c.execute("DELETE FROM articles_actors WHERE articles_itemid = '" + str(itemid) + "'") + c.execute("DELETE FROM articles WHERE itemid = '" + str(itemid) + "'") + except psycopg2.errors.ForeignKeyViolation: + conn.rollback() + print("\n\tCan't remove article because another table still refers to it") + print("\tNothing was deleted.") + return - c.execute("SELECT * FROM rents WHERE articles_itemid = '" + str(itemid) + "' AND CURRENT_DATE < end_date") - result = c.fetchall() - if result: - print("\n\tCan't remove article because there are user(s) renting it") - else: - c.execute("DELETE FROM articles_actors WHERE articles_itemid = '" + str(itemid) + "'") - c.execute("DELETE FROM articles WHERE itemid = '" + str(itemid) + "'") print("\n\tArticle removed successfully") - conn.commit() - conn.close() def alter_balance(userid, balance): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - c = conn.cursor() + with _connection() as conn: + c = conn.cursor() - c.execute("UPDATE users SET balance = '" + str(balance) + "' WHERE userid='" + str(userid) + "'") + c.execute("UPDATE users SET balance = '" + str(balance) + "' WHERE userid='" + str(userid) + "'") - print("\n\tBalance updated successfully") + print("\n\tBalance updated successfully") - conn.commit() - conn.close() + conn.commit() + conn.close() def statistics(): - conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}") - total=0 - c = conn.cursor() - c.execute("SELECT articles_itemid FROM rents") - rents = c.fetchall() - for x in rents: - c.execute("SELECT * FROM articles WHERE itemid= '"+str(x[0])+"' ") - price=c.fetchall() - for y in price: - total=total+y[6] - print("\rTotal spent by all users: "+str(total)) + with _connection() as conn: + total=0 + c = conn.cursor() + c.execute("SELECT articles_itemid FROM rents") + rents = c.fetchall() + for x in rents: + c.execute("SELECT * FROM articles WHERE itemid= '"+str(x[0])+"' ") + price=c.fetchall() + for y in price: + total=total+y[6] + print("\rTotal spent by all users: "+str(total)) - contadorusers=0 - c.execute("SELECT * FROM users") - users=c.fetchall() - for y in users: - contadorusers=contadorusers+1 + contadorusers=0 + c.execute("SELECT * FROM users") + users=c.fetchall() + for y in users: + contadorusers=contadorusers+1 - print("\rTotal number of users: " + str(contadorusers-1)) + print("\rTotal number of users: " + str(contadorusers-1)) - contadorarticles = 0 - c.execute("SELECT * FROM articles") - articles = c.fetchall() - for z in articles: - contadorarticles = contadorarticles + 1 - print("\rTotal number of articles: " + str(contadorarticles)) + contadorarticles = 0 + c.execute("SELECT * FROM articles") + articles = c.fetchall() + for z in articles: + contadorarticles = contadorarticles + 1 + print("\rTotal number of articles: " + str(contadorarticles)) - contadorarticles = 0 - total_movies=0 - c.execute("SELECT * FROM articles where type = 'movie' ") - movies = c.fetchall() - for a in movies: - contadorarticles = contadorarticles + 1 - total_movies=total_movies+a[6] - print("\rTotal number of movies: " + str(contadorarticles)) + contadorarticles = 0 + total_movies=0 + c.execute("SELECT * FROM articles where type = 'movie' ") + movies = c.fetchall() + for a in movies: + contadorarticles = contadorarticles + 1 + total_movies=total_movies+a[6] + print("\rTotal number of movies: " + str(contadorarticles)) - contadorarticles = 0 - total_series=0 - c.execute("SELECT * FROM articles where type = 'series' ") - series = c.fetchall() - for b in series: - contadorarticles = contadorarticles + 1 - total_series=total_series+b[6] - print("\rTotal number of series: " + str(contadorarticles)) + contadorarticles = 0 + total_series=0 + c.execute("SELECT * FROM articles where type = 'series' ") + series = c.fetchall() + for b in series: + contadorarticles = contadorarticles + 1 + total_series=total_series+b[6] + print("\rTotal number of series: " + str(contadorarticles)) - print("\rTotal spent in movies: "+str(total_movies)) - print("\rTotal spent in series: "+str(total_series)) + print("\rTotal spent in movies: "+str(total_movies)) + print("\rTotal spent in series: "+str(total_series)) - total2=0 - c.execute("SELECT * FROM rents WHERE end_date > CURRENT_DATE ") - rents2 = c.fetchall() - for e in rents2: - c.execute("SELECT * FROM articles WHERE itemid= '"+str(e[3])+"' ") - price2=c.fetchall() - for d in price2: - total2=total2+d[6] + total2=0 + c.execute("SELECT * FROM rents WHERE end_date > CURRENT_DATE ") + rents2 = c.fetchall() + for e in rents2: + c.execute("SELECT * FROM articles WHERE itemid= '"+str(e[3])+"' ") + price2=c.fetchall() + for d in price2: + total2=total2+d[6] - print("\rTotal spent on movies currently available: "+str(total2)) + print("\rTotal spent on movies currently available: "+str(total2)) - conn.commit() - conn.close() \ No newline at end of file + conn.commit() + conn.close() \ No newline at end of file diff --git a/main.py b/main.py index 0f15fd7..58636ed 100644 --- a/main.py +++ b/main.py @@ -67,6 +67,9 @@ def client(): if client_search == '1': client_search_typo=input("\tInsert movie name: ") article=database.findby_name(client_search_typo) + if not article: + print("\n\tNo article matches that search") + continue while (x := int(input("\tYour Selection: "))) != 0: print("\n\t" + article[x - 1][1]) while (client_in := input(article_interface)) != '0': @@ -83,6 +86,9 @@ def client(): if client_search == '2': client_search_typo=input("\tInsert movie director: ") article=database.findby_director(client_search_typo) + if not article: + print("\n\tNo article matches that search") + continue while (x := int(input("\tYour Selection: "))) != 0: print("\n\t" + article[x - 1][1]) while (client_in := input(article_interface)) != '0': @@ -99,6 +105,9 @@ def client(): if client_search == '3': client_search_typo=input("\tInsert movie type: ") article=database.findby_type(client_search_typo) + if not article: + print("\n\tNo article matches that search") + continue while (x := int(input("\tYour Selection: "))) != 0: print("\n\t" + article[x - 1][1]) while (client_in := input(article_interface)) != '0': @@ -114,6 +123,9 @@ def client(): if client_search == '4': client_search_typo=input("\tInsert movie actor: ") article=database.findby_actor(client_search_typo) + if not article: + print("\n\tNo article matches that search") + continue while (x := int(input("\tYour Selection: "))) != 0: print("\n\t" + article[x - 1][1]) while (client_in := input(article_interface)) != '0': @@ -268,6 +280,8 @@ def client(): while (client_input := input(message_interface)) != '0': if client_input == '1': y = database.show_unread_messages(USERID) + if not y: + continue while (x := int(input("\tYour Selection: "))) != 0: database.read_message(y[x - 1][0]) print("\n\t" + y[x - 1][1]) @@ -357,9 +371,17 @@ def admin(): database.statistics() -if menu() != -1: +# menu() returns 1 for a client, -1 for an administrator and None when the +# user leaves with 0. That last case used to be tested with `!= -1`, so it +# went into the client branch and read database.USERID, which did not exist +# until somebody logged in (AttributeError). Nobody is logged in there, so +# neither menu is opened. +role = menu() +if role == -1: + USERID = database.USERID + admin() +elif role == 1: USERID = database.USERID client() else: - USERID = database.USERID - admin() \ No newline at end of file + print("\n\tGoodbye") \ No newline at end of file diff --git a/tests/test_netflox.py b/tests/test_netflox.py index 8618822..b89962e 100644 --- a/tests/test_netflox.py +++ b/tests/test_netflox.py @@ -6,12 +6,13 @@ 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"). +Every defect that used to be pinned here by an `xfail` or a `test_known_bug_*` +name now has a regression test that fails against the previous code; the last +section of this file is that regression suite (see README, "What it is"). """ from __future__ import annotations +import ast import builtins import contextlib import datetime @@ -318,7 +319,7 @@ def test_message_to_one_client_then_mark_it_read(capsys): 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 + assert database.show_unread_messages(client) == [] # an empty list, not None def test_message_all_reaches_every_user_except_the_sender(capsys): @@ -472,47 +473,167 @@ def test_schema_sql_does_not_carry_the_demo_password(): # -------------------------------------------------------------------------- -# known bugs, pinned so that they are visible instead of silent +# regressions: every test below used to be an xfail or a `test_known_bug_*` # -------------------------------------------------------------------------- -@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 +def test_findby_director_returns_the_rows_it_printed(capsys): + """It printed the matches and fell off the end of the function (None).""" + movies = database.findby_director("Christopher Nolan") + assert movies is not None + assert [row[1] for row in movies] == ["Interstellar"] + assert movies[0][2] == "Christopher Nolan" # column order kept + assert "Interstellar" in capsys.readouterr().out + + assert database.findby_director("zzz-nao-existe") == [] -@pytest.mark.xfail(reason="findby_actor() raises UnboundLocalError when no actor matches") -def test_known_bug_findby_actor_without_a_match(): +def test_findby_actor_without_a_match_returns_none(): + """It used to raise UnboundLocalError: `articles` was never bound.""" 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_findby_actor_returns_every_article_of_the_actor(): + """It used to return whatever `articles` held after the last iteration: only + the last article of the actor, out of a list that could have several.""" + with raw_cursor() as cur: + cur.execute("INSERT INTO articles (name, director, release_year, imbd_rating," + " genre, price, type, time_available) VALUES ('John Wick'," + " 'Chad Stahelski', 2014, 7.4, 'action', 2.00, 'movie', 7)" + " RETURNING itemid") + second = cur.fetchone()[0] + cur.execute("INSERT INTO articles_actors (articles_itemid, actors_actorid)" + " SELECT %s, actorid FROM actors WHERE name = 'Keanu Reeves'", + (second,)) + + movies = database.findby_actor("Keanu Reeves") + assert sorted(row[1] for row in movies) == ["John Wick", "The Matrix"] + assert movies[0] == database.findby_name("The Matrix")[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.""" +def test_search_without_matches_returns_an_empty_list(): + """It used to return the integer 0, which main.py then indexed into.""" + assert database.findby_name("zzz-nao-existe") == [] + assert database.findby_type("zzz-nao-existe") == [] + + +def test_message_list_shows_the_sender_not_the_recipient(capsys): + """The author was looked up with row[4] (the recipient) instead of row[5].""" client = make_client() admin = user_id(ADMIN_EMAIL) database.message_client("Ola", str(client), str(admin)) capsys.readouterr() - database.show_unread_messages(client) + unread = 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 + assert "Message from Admin" in out + assert "Message from Ana" not in out + + database.read_message(unread[0][0]) # the read list had it too + capsys.readouterr() + database.show_read_messages(client) + out = capsys.readouterr().out + assert "Message from Admin" in out + assert "Message from Ana" 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.""" +def test_purchase_debits_the_account_it_was_given(capsys): + """It debited USERID (the account of the last log_in), not its 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 # Ana is the last login - assert database.log_in("ana@exemplo.pt", demo_password()) == 1 database.purchase(article_id("Pulp Fiction"), bruno) + assert "Purchase successful!" in capsys.readouterr().out - assert balance_of(ana) == Decimal("17.50") # Ana paid - assert balance_of(bruno) == Decimal("20.00") - assert scalar("SELECT users_userid FROM rents") == bruno + assert balance_of(bruno) == Decimal("17.50") # 20.00 - 2.50, the buyer + assert balance_of(ana) == Decimal("20.00") # the last login, untouched + assert scalar("SELECT count(*) FROM rents WHERE users_userid = %s", (bruno,)) == 1 + + +def test_remove_article_is_refused_with_rent_history_and_it_says_why(capsys): + """Only the *current* rents were checked, so the older ones - which the + foreign key also protects - turned the removal into a traceback.""" + 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,)) + + database.remove_article(str(itemid)) # main.py always passes a string + out = capsys.readouterr().out + assert "Can't remove article" in out + assert "rental history" in out # explained, not a traceback + assert scalar("SELECT count(*) FROM articles WHERE itemid = %s", (itemid,)) == 1 + + +def test_remove_article_is_refused_while_the_price_history_keeps_it(capsys): + """pricehistory carries a foreign key to the article as well.""" + itemid = article_id("The Matrix") + database.change_price("The Matrix", "9.99") # writes one pricehistory row + capsys.readouterr() + + database.remove_article(str(itemid)) + out = capsys.readouterr().out + assert "Can't remove article" in out + assert "price history" in out + assert scalar("SELECT count(*) FROM articles WHERE itemid = %s", (itemid,)) == 1 + assert scalar("SELECT count(*) FROM pricehistory") == 1 + + +def test_a_failing_call_does_not_leave_its_session_idle_in_transaction(): + """A traceback keeps its frame alive, and the frame held the connection: + findby_type()/findby_actor()/findby_director() returned before conn.close() + and statistics() never closed at all, so the session stayed open.""" + try: + database.view_details(999999) # no such article: IndexError + except IndexError as exc: + held = exc.__traceback__ # keeps the frame, and its connection + assert held is not None + + assert scalar("SELECT count(*) FROM pg_stat_activity" + " WHERE datname = current_database()" + " AND state = 'idle in transaction'") == 0 + + +def test_no_function_opens_a_connection_outside_the_managed_helper(): + """Structural guard: one place opens and closes, so no early return can leave + an `idle in transaction` session behind again.""" + source = (ROOT / "database.py").read_text(encoding="utf-8") + assert source.count("psycopg2.connect(") == 1 + + tree = ast.parse(source) + openers = sorted( + node.name for node in ast.walk(tree) + if isinstance(node, ast.FunctionDef) + and "psycopg2.connect(" in (ast.get_source_segment(source, node) or "") + ) + assert openers == ["_connection"] + + + +def test_userid_exists_and_is_none_before_any_login(): + """database.USERID was created by log_in(), so the code that runs before a + login read an attribute that did not exist (AttributeError).""" + proc = subprocess.run([sys.executable, "-c", "import database; print(database.USERID)"], + cwd=ROOT, capture_output=True, text=True, env=os.environ.copy()) + assert proc.returncode == 0, proc.stderr + assert proc.stdout.strip() == "None" + + +def test_leaving_the_menu_with_zero_exits_without_a_traceback(): + """`0` at the first menu used to be compared with -1, fall into the client + branch and read database.USERID before anybody had logged in.""" + proc = subprocess.run([sys.executable, "main.py"], cwd=ROOT, input="0\n", + capture_output=True, text=True, env=os.environ.copy()) + assert proc.returncode == 0, proc.stderr + assert "Traceback" not in proc.stderr + assert "Goodbye" in proc.stdout + + +def test_an_administrator_login_opens_the_administrator_menu(): + proc = subprocess.run([sys.executable, "main.py"], cwd=ROOT, + input=f"2\n{ADMIN_EMAIL}\n{demo_password()}\n0\n", + capture_output=True, text=True, env=os.environ.copy()) + assert proc.returncode == 0, proc.stderr + assert "Welcome Admin" in proc.stdout + assert "Change price" in proc.stdout # the administrator menu