Compare commits
53
Commits
main
..
c3efaa05cb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3efaa05cb | ||
|
|
17f75eccb0 | ||
|
|
6509c6c5d6 | ||
|
|
fcd17b1eba | ||
|
|
d1470ff157 | ||
|
|
c45b1487fd | ||
|
|
3c30c99905 | ||
|
|
542669c135 | ||
|
|
6196e13b3e | ||
|
|
ff7526de23 | ||
|
|
0c6c4365d4 | ||
|
|
add79df3bb | ||
|
|
7e0f9dd51a | ||
|
|
4dc9a1affc | ||
|
|
4544366e2d | ||
|
|
a9603029cd | ||
|
|
0ac7cd0ea7 | ||
|
|
97f795a12b | ||
|
|
33fd8ed58c | ||
|
|
f38429c760 | ||
|
|
fb03e2cc91 | ||
|
|
a19ea572ef | ||
|
|
7c0c3c88c1 | ||
|
|
1e6c31ddbc | ||
|
|
f066508ffe | ||
|
|
1bd5f94092 | ||
|
|
ca89c63015 | ||
|
|
c521ae13f6 | ||
|
|
843b5c1e22 | ||
|
|
c42c96c854 | ||
|
|
a227d20778 | ||
|
|
8b645024b4 | ||
|
|
bf9565989e | ||
|
|
ebeeb84a92 | ||
|
|
73e7d261e4 | ||
|
|
9a8d3f99d9 | ||
|
|
a7caf9c79c | ||
|
|
0141ed8a60 | ||
|
|
8082bf226e | ||
|
|
eb0054aa2b | ||
|
|
97cadfba8a | ||
|
|
98a95f7362 | ||
|
|
19ae3657e7 | ||
|
|
2bc7d6a564 | ||
|
|
efb7a2d4c7 | ||
|
|
5943294ce5 | ||
|
|
2ebc198a24 | ||
|
|
e6e45ac990 | ||
|
|
94cd34bb66 | ||
|
|
c28263970e | ||
|
|
a8f45c59d9 | ||
|
|
d6869f86ea | ||
|
|
8f3ca62d95 |
@@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2020 André Neto and Alexandre Cavadas de Almeida
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@@ -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.
|
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.
|
||||||
|
|
||||||
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.
|
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.
|
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,34 +91,13 @@ make test
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
.venv/bin/python -m pytest -q
|
.venv/bin/python -m pytest -q
|
||||||
....................................................... [100%]
|
...........................xx... [100%]
|
||||||
55 passed in 16.70s
|
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.
|
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.
|
||||||
|
|
||||||
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. `tests/test_injection.py` is the same kind of suite for the SQL: every statement in `database.py` is parameterized now, so a stacked `DROP TABLE`, an apostrophe in `O'Brien` and quotes inside a stored message are all just text. "Known limitations" below lists what was deliberately left alone.
|
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.
|
||||||
|
|
||||||
### 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:
|
|
||||||
|
|
||||||
- the menus index the list they just printed without checking the range, so
|
|
||||||
`article[x - 1]` past the end raises `IndexError`;
|
|
||||||
- `database.my_articles()` / `database.my_history()` read from the keyboard with
|
|
||||||
`input()`, which puts the menu inside the data layer;
|
|
||||||
- `database.message_all()` sizes its `while` loop with
|
|
||||||
`Sum(pg_column_size(userid))/4` instead of `count(*)`, so it stays tied to
|
|
||||||
`users.userid` being a 4-byte `int4` numbered from 1 without gaps;
|
|
||||||
- the client menu in `main.py` keeps its own copy of `USERID`
|
|
||||||
(`USERID = database.USERID`) while the administrator menu reads
|
|
||||||
`database.USERID`, so the two can drift apart.
|
|
||||||
|
|
||||||
The SQL injection that used to be listed here is gone: the 48 statements that
|
|
||||||
interpolated a value are parameterized (`%s` with the value in a tuple), and no
|
|
||||||
identifier comes from input - every table and column name is a literal. The tests in
|
|
||||||
`tests/test_injection.py` fail against the previous version and pass against this one.
|
|
||||||
|
|
||||||
## Structure
|
## Structure
|
||||||
|
|
||||||
@@ -127,8 +106,7 @@ database.py every SQL statement and the connection; reads NETFLOX_DB_
|
|||||||
main.py the menus: menu() -> client() or admin()
|
main.py the menus: menu() -> client() or admin()
|
||||||
schema.sql the relational schema (7 tables, primary and foreign keys) and the minimal seed
|
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
|
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/*.py are the suites
|
tests/conftest.py recreates the schema before every test; tests/test_netflox.py is the suite
|
||||||
(test_netflox.py the flows, test_injection.py the SQL)
|
|
||||||
docker-compose.yml throwaway PostgreSQL (NetfloxFinal, postgres, 127.0.0.1:5432)
|
docker-compose.yml throwaway PostgreSQL (NetfloxFinal, postgres, 127.0.0.1:5432)
|
||||||
Makefile up, schema, seed, run, test, down (plus venv, clean, help)
|
Makefile up, schema, seed, run, test, down (plus venv, clean, help)
|
||||||
requirements.txt psycopg2-binary; requirements-dev.txt adds pytest
|
requirements.txt psycopg2-binary; requirements-dev.txt adds pytest
|
||||||
@@ -139,6 +117,4 @@ encript.jpg image from the original upload; no code or schema reads i
|
|||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT — see [LICENSE](LICENSE). Copyright (c) 2020 **André Neto and
|
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.
|
||||||
Alexandre Cavadas de Almeida**, both named as authors in the course report
|
|
||||||
(`docs/relatorio-BD.pdf`).
|
|
||||||
|
|||||||
+130
-256
@@ -1,8 +1,5 @@
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
import psycopg2
|
import psycopg2
|
||||||
import psycopg2.errors
|
|
||||||
from contextlib import contextmanager
|
|
||||||
|
|
||||||
# Read once, at import time. Never hard-code the password here.
|
# Read once, at import time. Never hard-code the password here.
|
||||||
DB_PASSWORD = os.environ.get("NETFLOX_DB_PASSWORD")
|
DB_PASSWORD = os.environ.get("NETFLOX_DB_PASSWORD")
|
||||||
@@ -12,37 +9,11 @@ if not DB_PASSWORD:
|
|||||||
"password before running (see README.md, Configuration)."
|
"password before running (see README.md, Configuration)."
|
||||||
)
|
)
|
||||||
|
|
||||||
# Account of the last successful log_in(). It used to be created only by
|
global USERID
|
||||||
# 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
|
# MENU
|
||||||
def create_user(name, email, password):
|
def create_user(name, email, password):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
if email.find('@') == -1:
|
if email.find('@') == -1:
|
||||||
@@ -52,22 +23,15 @@ def create_user(name, email, password):
|
|||||||
print("\n\tCan't create accounts under netflox domain")
|
print("\n\tCan't create accounts under netflox domain")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
c.execute(
|
c.execute("INSERT INTO users (nome, email, password, balance) VALUES ('" + name + "','" + email + "','" + password + "',20)")
|
||||||
"INSERT INTO users (nome, email, password, balance)"
|
|
||||||
" VALUES (%s, %s, %s, 20)",
|
|
||||||
(name, email, password),
|
|
||||||
)
|
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
def log_in(email, password):
|
def log_in(email, password):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute(
|
c.execute("SELECT * FROM users WHERE email = '" + email + "' AND password = '" + password + "'")
|
||||||
"SELECT * FROM users WHERE email = %s AND password = %s",
|
|
||||||
(email, password),
|
|
||||||
)
|
|
||||||
results = c.fetchall()
|
results = c.fetchall()
|
||||||
|
|
||||||
global USERID
|
global USERID
|
||||||
@@ -98,49 +62,45 @@ def log_in(email, password):
|
|||||||
|
|
||||||
# MESSAGES CLIENT
|
# MESSAGES CLIENT
|
||||||
def show_unread_messages(userid):
|
def show_unread_messages(userid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute(
|
c.execute("SELECT * FROM messages WHERE users_userid = " + str(userid) + " AND bolread = FALSE")
|
||||||
"SELECT * FROM messages WHERE users_userid = %s AND bolread = FALSE",
|
|
||||||
(userid,),
|
|
||||||
)
|
|
||||||
results = c.fetchall()
|
results = c.fetchall()
|
||||||
|
|
||||||
if results:
|
if results:
|
||||||
y = 0
|
y = 0
|
||||||
print("\r")
|
print("\r")
|
||||||
for i in results:
|
for i in results:
|
||||||
# i[4] is the recipient, i[5] is the sender: the list used to name
|
c.execute("SELECT * FROM users WHERE userid = " + str(i[4]))
|
||||||
# every message after the account that received it.
|
|
||||||
c.execute("SELECT * FROM users WHERE userid = %s", (i[5],))
|
|
||||||
sender = c.fetchall()
|
sender = c.fetchall()
|
||||||
for x in sender:
|
for x in sender:
|
||||||
y += 1
|
y += 1
|
||||||
print("\t" + str(y) + ") Message from " + x[1] + " date: " + str(i[3]))
|
print("\t" + str(y) + ") Message from " + x[1] + " date: " + str(i[3]))
|
||||||
|
|
||||||
print("\t0) Exit")
|
print("\t0) Exit")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
return results
|
return results
|
||||||
|
|
||||||
|
else:
|
||||||
print("\n\tNo new messages\n\t0) Exit")
|
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 []
|
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
def show_read_messages(userid):
|
def show_read_messages(userid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute(
|
c.execute("SELECT * FROM messages WHERE users_userid = " + str(userid) + " AND bolread = TRUE")
|
||||||
"SELECT * FROM messages WHERE users_userid = %s AND bolread = TRUE",
|
|
||||||
(userid,),
|
|
||||||
)
|
|
||||||
messages = c.fetchall()
|
messages = c.fetchall()
|
||||||
|
|
||||||
y = 0
|
y = 0
|
||||||
print("\r")
|
print("\r")
|
||||||
for i in messages:
|
for i in messages:
|
||||||
c.execute("SELECT * FROM users WHERE userid = %s", (i[5],))
|
c.execute("SELECT * FROM users WHERE userid = " + str(i[4]))
|
||||||
sender = c.fetchall()
|
sender = c.fetchall()
|
||||||
for x in sender:
|
for x in sender:
|
||||||
y += 1
|
y += 1
|
||||||
@@ -148,19 +108,21 @@ def show_read_messages(userid):
|
|||||||
|
|
||||||
print("\t0) Exit")
|
print("\t0) Exit")
|
||||||
|
|
||||||
return messages
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
return messages
|
||||||
def read_message(msgid):
|
def read_message(msgid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute("UPDATE messages SET bolread = TRUE WHERE msgid = %s", (msgid,))
|
c.execute("UPDATE messages SET bolread = TRUE WHERE msgid='" + str(msgid) + "'")
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
# MESSAGES ADMIN
|
# MESSAGES ADMIN
|
||||||
def message_all(msg, senderid):
|
def message_all(msg, senderid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute("SELECT userid FROM users")
|
c.execute("SELECT userid FROM users")
|
||||||
@@ -173,11 +135,8 @@ def message_all(msg, senderid):
|
|||||||
while i < size:
|
while i < size:
|
||||||
if results[i][0] != senderid:
|
if results[i][0] != senderid:
|
||||||
c.execute(
|
c.execute(
|
||||||
"INSERT INTO messages"
|
"INSERT INTO messages (message, bolread, users_userid, senderid, data) VALUES ('" + msg + "', FALSE, '" + str(
|
||||||
" (message, bolread, users_userid, senderid, data)"
|
results[i][0]) + "', '" + str(senderid) + "', CURRENT_DATE)")
|
||||||
" VALUES (%s, FALSE, %s, %s, CURRENT_DATE)",
|
|
||||||
(msg, results[i][0], senderid),
|
|
||||||
)
|
|
||||||
i += 1
|
i += 1
|
||||||
|
|
||||||
print("\n\tMessage sent to all")
|
print("\n\tMessage sent to all")
|
||||||
@@ -185,15 +144,12 @@ def message_all(msg, senderid):
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
def message_client(msg, recieverid, senderid):
|
def message_client(msg, recieverid, senderid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute(
|
c.execute(
|
||||||
"INSERT INTO messages"
|
"INSERT INTO messages (message, bolread, users_userid, senderid, data) VALUES ('" + msg + "', FALSE, '" +
|
||||||
" (message, bolread, users_userid, senderid, data)"
|
str(recieverid) + "', '" + str(senderid) + "', CURRENT_DATE)")
|
||||||
" VALUES (%s, FALSE, %s, %s, CURRENT_DATE)",
|
|
||||||
(msg, recieverid, senderid),
|
|
||||||
)
|
|
||||||
|
|
||||||
print("\n\tMessage sent successfully")
|
print("\n\tMessage sent successfully")
|
||||||
|
|
||||||
@@ -202,91 +158,89 @@ def message_client(msg, recieverid, senderid):
|
|||||||
|
|
||||||
# SEARCH ARTICLES
|
# SEARCH ARTICLES
|
||||||
def findby_name(name):
|
def findby_name(name):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles WHERE name like %s", ("%" + name + "%",))
|
|
||||||
movies = c.fetchall()
|
|
||||||
y=0
|
y=0
|
||||||
|
c.execute("SELECT * FROM articles WHERE name like '%" + name + "%'")
|
||||||
|
movies = c.fetchall()
|
||||||
for x in movies:
|
for x in movies:
|
||||||
y=y+1
|
y=y+1
|
||||||
print("\t"+str(y)+") "+x[1])
|
print("\t"+str(y)+") "+x[1])
|
||||||
|
|
||||||
if not movies:
|
if movies:
|
||||||
# An empty list, not the integer 0: main.py indexes whatever comes
|
for i in movies:
|
||||||
# back, and 0 is not indexable.
|
break
|
||||||
|
else:
|
||||||
print("\n---movie name not correct---\n")
|
print("\n---movie name not correct---\n")
|
||||||
|
conn.commit()
|
||||||
return movies
|
conn.close()
|
||||||
|
return (0)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
return(movies)
|
||||||
def findby_director(director):
|
def findby_director(director):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
y = 0
|
y = 0
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute(
|
c.execute("SELECT * FROM articles WHERE director like '%" + director + "%'")
|
||||||
"SELECT * FROM articles WHERE director like %s",
|
|
||||||
("%" + director + "%",),
|
|
||||||
)
|
|
||||||
movies = c.fetchall()
|
movies = c.fetchall()
|
||||||
for x in movies:
|
for x in movies:
|
||||||
y = y + 1
|
y = y + 1
|
||||||
print("\t" + str(y) + ") " + x[1])
|
print("\t" + str(y) + ") " + x[1])
|
||||||
|
|
||||||
if not movies:
|
if movies:
|
||||||
|
for i in movies:
|
||||||
|
break
|
||||||
|
else:
|
||||||
print("\n---movie director name not correct---\n")
|
print("\n---movie director name not correct---\n")
|
||||||
|
conn.commit()
|
||||||
# The success path used to fall off the end of the function and return
|
conn.close()
|
||||||
# None, so main.py never saw the matches it had just printed.
|
return (movies)
|
||||||
return movies
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
def findby_type(type):
|
def findby_type(type):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
y = 0
|
y = 0
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles WHERE type like %s", ("%" + type + "%",))
|
c.execute("SELECT * FROM articles WHERE type like '%" + type + "%'")
|
||||||
movies = c.fetchall()
|
movies = c.fetchall()
|
||||||
for x in movies:
|
for x in movies:
|
||||||
y = y + 1
|
y = y + 1
|
||||||
print("\t" + str(y) + ") " + x[1])
|
print("\t" + str(y) + ") " + x[1])
|
||||||
|
|
||||||
if not movies:
|
if movies:
|
||||||
|
for i in movies:
|
||||||
|
break
|
||||||
|
else:
|
||||||
print("\n---movie type not correct---\n")
|
print("\n---movie type not correct---\n")
|
||||||
|
conn.commit()
|
||||||
# Returning before closing used to leave the session idle in
|
conn.close()
|
||||||
# transaction for good; the empty case returns a list, like findby_name.
|
return (0)
|
||||||
return movies
|
return (movies)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
def findby_actor(actor):
|
def findby_actor(actor):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
j=0
|
j=0
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM actors WHERE name like %s", ("%" + actor + "%",))
|
c.execute("SELECT * FROM actors WHERE name like('%"+actor+"%')")
|
||||||
actors = c.fetchall()
|
actors = c.fetchall()
|
||||||
print("\r")
|
print("\r")
|
||||||
articles = []
|
|
||||||
for x in actors:
|
for x in actors:
|
||||||
actorid=x[0]
|
actorid=x[0]
|
||||||
c.execute(
|
c.execute("SELECT * FROM articles_actors WHERE actors_actorid = '"+str(actorid)+"' ")
|
||||||
"SELECT * FROM articles_actors WHERE actors_actorid = %s",
|
|
||||||
(actorid,),
|
|
||||||
)
|
|
||||||
articles_actors = c.fetchall()
|
articles_actors = c.fetchall()
|
||||||
for y in articles_actors:
|
for y in articles_actors:
|
||||||
j = j + 1
|
j = j + 1
|
||||||
c.execute("SELECT * FROM articles WHERE itemid = %s", (y[0],))
|
c.execute("SELECT * FROM articles WHERE itemid = '"+str(y[0])+"' ")
|
||||||
matched = c.fetchall()
|
articles = c.fetchall()
|
||||||
if matched:
|
print(str("\t"+str(j)+") "+articles[0][1]))
|
||||||
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
|
|
||||||
|
|
||||||
|
return (articles)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
def list_all():
|
def list_all():
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles")
|
c.execute("SELECT * FROM articles")
|
||||||
articles = c.fetchall()
|
articles = c.fetchall()
|
||||||
@@ -301,9 +255,9 @@ def list_all():
|
|||||||
|
|
||||||
return articles
|
return articles
|
||||||
def view_details(itemid):
|
def view_details(itemid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles WHERE itemid = %s", (itemid,))
|
c.execute("SELECT * FROM articles WHERE itemid = '"+str(itemid)+"'")
|
||||||
article = c.fetchall()[0]
|
article = c.fetchall()[0]
|
||||||
print("\n\tTitle: "+str(article[1]))
|
print("\n\tTitle: "+str(article[1]))
|
||||||
print("\tDirector: " + str(article[2]))
|
print("\tDirector: " + str(article[2]))
|
||||||
@@ -315,48 +269,34 @@ def view_details(itemid):
|
|||||||
print("\tTime available: " + str(article[8]) + " days")
|
print("\tTime available: " + str(article[8]) + " days")
|
||||||
print("\tActors: ")
|
print("\tActors: ")
|
||||||
|
|
||||||
c.execute(
|
c.execute("SELECT * FROM articles_actors WHERE articles_itemid = '" + str(itemid) + "'")
|
||||||
"SELECT * FROM articles_actors WHERE articles_itemid = %s", (itemid,)
|
|
||||||
)
|
|
||||||
actors = c.fetchall()
|
actors = c.fetchall()
|
||||||
|
|
||||||
for i in actors:
|
for i in actors:
|
||||||
c.execute("SELECT * FROM actors WHERE actorid = %s", (i[1],))
|
c.execute("SELECT * FROM actors WHERE actorid = '" + str(i[1]) + "'")
|
||||||
actors_name = c.fetchall()[0][1]
|
actors_name = c.fetchall()[0][1]
|
||||||
print("\t\t"+str(actors_name))
|
print("\t\t"+str(actors_name))
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
def purchase(itemid, userid):
|
def purchase(itemid, userid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute("SELECT balance FROM users WHERE userid = %s", (userid,))
|
c.execute("SELECT balance FROM users WHERE userid = '"+str(userid)+"'")
|
||||||
balance = c.fetchall()[0][0]
|
balance = c.fetchall()[0][0]
|
||||||
|
|
||||||
c.execute("SELECT price FROM articles WHERE itemid = %s", (itemid,))
|
c.execute("SELECT price FROM articles WHERE itemid = '" + str(itemid) + "'")
|
||||||
cost = c.fetchall()[0][0]
|
cost = c.fetchall()[0][0]
|
||||||
|
|
||||||
if balance >= cost:
|
if balance >= cost:
|
||||||
new_balance = balance - cost
|
new_balance = balance - cost
|
||||||
# The debit follows the userid argument, not USERID (the account of
|
c.execute("UPDATE users SET balance= '" + str(new_balance) + "' WHERE userid='" + str(USERID) + "'")
|
||||||
# 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 = %s WHERE userid = %s",
|
|
||||||
(new_balance, userid),
|
|
||||||
)
|
|
||||||
|
|
||||||
c.execute(
|
c.execute("SELECT time_available FROM articles WHERE itemid = '" + str(itemid) + "'")
|
||||||
"SELECT time_available FROM articles WHERE itemid = %s", (itemid,)
|
|
||||||
)
|
|
||||||
time_available = c.fetchall()[0][0]
|
time_available = c.fetchall()[0][0]
|
||||||
|
|
||||||
c.execute(
|
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)+"')")
|
||||||
"INSERT INTO rents (purchased_date, end_date, articles_itemid,"
|
|
||||||
" users_userid) VALUES (CURRENT_DATE, CURRENT_DATE + %s, %s, %s)",
|
|
||||||
(int(time_available), itemid, userid),
|
|
||||||
)
|
|
||||||
|
|
||||||
print("\n\tPurchase successful!")
|
print("\n\tPurchase successful!")
|
||||||
print("\tNew balance: "+str(new_balance)+"€")
|
print("\tNew balance: "+str(new_balance)+"€")
|
||||||
@@ -364,9 +304,12 @@ def purchase(itemid, userid):
|
|||||||
else:
|
else:
|
||||||
print("\n\tCan't afford this item")
|
print("\n\tCan't afford this item")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
# ORDER BY
|
# ORDER BY
|
||||||
def order_title():
|
def order_title():
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles ORDER BY name")
|
c.execute("SELECT * FROM articles ORDER BY name")
|
||||||
movies = c.fetchall()
|
movies = c.fetchall()
|
||||||
@@ -381,7 +324,7 @@ def order_title():
|
|||||||
|
|
||||||
return movies
|
return movies
|
||||||
def order_director():
|
def order_director():
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles ORDER BY director")
|
c.execute("SELECT * FROM articles ORDER BY director")
|
||||||
movies = c.fetchall()
|
movies = c.fetchall()
|
||||||
@@ -396,7 +339,7 @@ def order_director():
|
|||||||
|
|
||||||
return movies
|
return movies
|
||||||
def order_year():
|
def order_year():
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles ORDER BY release_year")
|
c.execute("SELECT * FROM articles ORDER BY release_year")
|
||||||
movies = c.fetchall()
|
movies = c.fetchall()
|
||||||
@@ -411,7 +354,7 @@ def order_year():
|
|||||||
|
|
||||||
return movies
|
return movies
|
||||||
def order_imdb():
|
def order_imdb():
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles ORDER BY imbd_rating")
|
c.execute("SELECT * FROM articles ORDER BY imbd_rating")
|
||||||
movies = c.fetchall()
|
movies = c.fetchall()
|
||||||
@@ -426,7 +369,7 @@ def order_imdb():
|
|||||||
|
|
||||||
return movies
|
return movies
|
||||||
def order_genre():
|
def order_genre():
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles ORDER BY genre")
|
c.execute("SELECT * FROM articles ORDER BY genre")
|
||||||
movies = c.fetchall()
|
movies = c.fetchall()
|
||||||
@@ -441,7 +384,7 @@ def order_genre():
|
|||||||
|
|
||||||
return movies
|
return movies
|
||||||
def order_price():
|
def order_price():
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles ORDER BY price")
|
c.execute("SELECT * FROM articles ORDER BY price")
|
||||||
movies = c.fetchall()
|
movies = c.fetchall()
|
||||||
@@ -456,7 +399,7 @@ def order_price():
|
|||||||
|
|
||||||
return movies
|
return movies
|
||||||
def order_type():
|
def order_type():
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT * FROM articles ORDER BY type")
|
c.execute("SELECT * FROM articles ORDER BY type")
|
||||||
movies = c.fetchall()
|
movies = c.fetchall()
|
||||||
@@ -473,14 +416,10 @@ def order_type():
|
|||||||
|
|
||||||
# MY ARTICLES
|
# MY ARTICLES
|
||||||
def my_articles(userid):
|
def my_articles(userid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute(
|
c.execute("SELECT * FROM rents WHERE end_date >= CURRENT_DATE AND users_userid = '" + str(userid) + "' ORDER BY articles_itemid")
|
||||||
"SELECT * FROM rents WHERE end_date >= CURRENT_DATE"
|
|
||||||
" AND users_userid = %s ORDER BY articles_itemid",
|
|
||||||
(userid,),
|
|
||||||
)
|
|
||||||
rents = c.fetchall()
|
rents = c.fetchall()
|
||||||
|
|
||||||
if rents:
|
if rents:
|
||||||
@@ -488,10 +427,7 @@ def my_articles(userid):
|
|||||||
print("\n\tMy articles:\n")
|
print("\n\tMy articles:\n")
|
||||||
for i in rents:
|
for i in rents:
|
||||||
y += 1
|
y += 1
|
||||||
c.execute(
|
c.execute("SELECT * FROM articles WHERE itemid = '" + str(i[3]) + "' ORDER BY itemid")
|
||||||
"SELECT * FROM articles WHERE itemid = %s ORDER BY itemid",
|
|
||||||
(i[3],),
|
|
||||||
)
|
|
||||||
articles = c.fetchall()
|
articles = c.fetchall()
|
||||||
print("\t"+str(articles[0][0])+") "+str(articles[0][1]))
|
print("\t"+str(articles[0][0])+") "+str(articles[0][1]))
|
||||||
|
|
||||||
@@ -503,14 +439,10 @@ def my_articles(userid):
|
|||||||
|
|
||||||
return int(input("\t0) Exit\n\tYour selection: "))
|
return int(input("\t0) Exit\n\tYour selection: "))
|
||||||
def my_history(userid):
|
def my_history(userid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute(
|
c.execute("SELECT * FROM rents WHERE end_date < CURRENT_DATE AND users_userid = '" + str(userid) + "' ORDER BY articles_itemid")
|
||||||
"SELECT * FROM rents WHERE end_date < CURRENT_DATE"
|
|
||||||
" AND users_userid = %s ORDER BY articles_itemid",
|
|
||||||
(userid,),
|
|
||||||
)
|
|
||||||
rents = c.fetchall()
|
rents = c.fetchall()
|
||||||
|
|
||||||
if rents:
|
if rents:
|
||||||
@@ -518,10 +450,7 @@ def my_history(userid):
|
|||||||
print("\n\tMy old articles:\n")
|
print("\n\tMy old articles:\n")
|
||||||
for i in rents:
|
for i in rents:
|
||||||
y += 1
|
y += 1
|
||||||
c.execute(
|
c.execute("SELECT * FROM articles WHERE itemid = '" + str(i[3]) + "' ORDER BY itemid")
|
||||||
"SELECT * FROM articles WHERE itemid = %s ORDER BY itemid",
|
|
||||||
(i[3],),
|
|
||||||
)
|
|
||||||
articles = c.fetchall()
|
articles = c.fetchall()
|
||||||
print("\t" + str(articles[0][1]))
|
print("\t" + str(articles[0][1]))
|
||||||
|
|
||||||
@@ -533,13 +462,10 @@ def my_history(userid):
|
|||||||
|
|
||||||
return int(input("\t0) Exit\n\tYour selection: "))
|
return int(input("\t0) Exit\n\tYour selection: "))
|
||||||
def time_left(itemid, userid):
|
def time_left(itemid, userid):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute(
|
c.execute("SELECT * FROM rents WHERE articles_itemid = "+str(itemid)+" AND users_userid = '"+str(userid)+"'")
|
||||||
"SELECT * FROM rents WHERE articles_itemid = %s AND users_userid = %s",
|
|
||||||
(itemid, userid),
|
|
||||||
)
|
|
||||||
time = c.fetchall()[0][2]
|
time = c.fetchall()[0][2]
|
||||||
|
|
||||||
print("\n\tItem available until "+str(time))
|
print("\n\tItem available until "+str(time))
|
||||||
@@ -549,16 +475,11 @@ def time_left(itemid, userid):
|
|||||||
|
|
||||||
# ADMIN
|
# ADMIN
|
||||||
def add_article(name, director, imbd_rating, genre, price, year, time_available, type):
|
def add_article(name, director, imbd_rating, genre, price, year, time_available, type):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute(
|
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 + "')")
|
||||||
"INSERT INTO articles(name, director, release_year, imbd_rating,"
|
c.execute("SELECT * FROM articles WHERE name = '" + name + "'")
|
||||||
" genre, price, type, time_available)"
|
|
||||||
" VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
|
|
||||||
(name, director, year, imbd_rating, genre, price, type, time_available),
|
|
||||||
)
|
|
||||||
c.execute("SELECT * FROM articles WHERE name = %s", (name,))
|
|
||||||
item_id = c.fetchall()[0][0]
|
item_id = c.fetchall()[0][0]
|
||||||
|
|
||||||
n_actors = int(input("\n\tNumber of actors: "))
|
n_actors = int(input("\n\tNumber of actors: "))
|
||||||
@@ -567,54 +488,42 @@ def add_article(name, director, imbd_rating, genre, price, year, time_available,
|
|||||||
x += 1
|
x += 1
|
||||||
name_actor = str(input("\n\tActor name: "))
|
name_actor = str(input("\n\tActor name: "))
|
||||||
|
|
||||||
c.execute("SELECT * FROM actors WHERE name = %s", (name_actor,))
|
c.execute("SELECT * FROM actors WHERE name ='" + name_actor + "'")
|
||||||
actor = c.fetchall()
|
actor = c.fetchall()
|
||||||
|
|
||||||
if actor:
|
if actor:
|
||||||
c.execute(
|
c.execute("INSERT INTO articles_actors(articles_itemid, actors_actorid) VALUES ('" + str(item_id) + "', '" + str(actor[0][0]) + "' )")
|
||||||
"INSERT INTO articles_actors (articles_itemid, actors_actorid)"
|
|
||||||
" VALUES (%s, %s)",
|
|
||||||
(item_id, actor[0][0]),
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
c.execute("INSERT INTO actors (name) VALUES (%s)", (name_actor,))
|
c.execute("INSERT INTO actors (name) VALUES ('" + name_actor + "')")
|
||||||
c.execute("SELECT * FROM actors WHERE name = %s", (name_actor,))
|
c.execute("SELECT * FROM actors WHERE name ='" + name_actor + "'")
|
||||||
actor_id = c.fetchall()[0][0]
|
actor_id = c.fetchall()[0][0]
|
||||||
c.execute(
|
c.execute("INSERT INTO articles_actors(articles_itemid, actors_actorid) VALUES ('" + str(item_id) + "', '" + str(actor_id) + "')")
|
||||||
"INSERT INTO articles_actors (articles_itemid, actors_actorid)"
|
|
||||||
" VALUES (%s, %s)",
|
|
||||||
(item_id, actor_id),
|
|
||||||
)
|
|
||||||
|
|
||||||
print("\n\tSuccess!")
|
print("\n\tSuccess!")
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
def change_price(n_id, newprice):
|
def change_price(n_id, newprice):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
itemid = n_id
|
itemid = n_id
|
||||||
if isinstance(n_id, str):
|
if isinstance(n_id, str):
|
||||||
c.execute("SELECT itemid FROM articles WHERE name = %s", (n_id,))
|
c.execute("SELECT itemid FROM articles WHERE name = '" + n_id + "'")
|
||||||
n_id = c.fetchall()
|
n_id = c.fetchall()
|
||||||
for i in n_id:
|
for i in n_id:
|
||||||
itemid = i[0]
|
itemid = i[0]
|
||||||
|
|
||||||
c.execute("SELECT price FROM articles WHERE itemid = %s", (itemid,))
|
c.execute("SELECT price FROM articles WHERE itemid = '" + str(itemid) + "'")
|
||||||
result = c.fetchall()
|
result = c.fetchall()
|
||||||
oldprice = 0
|
oldprice = 0
|
||||||
for i in result:
|
for i in result:
|
||||||
oldprice = i[0]
|
oldprice = i[0]
|
||||||
|
|
||||||
|
c.execute("UPDATE articles SET price = '" + str(newprice) + "' WHERE itemid = '" + str(itemid) + "'")
|
||||||
c.execute(
|
c.execute(
|
||||||
"UPDATE articles SET price = %s WHERE itemid = %s", (newprice, itemid)
|
"INSERT INTO pricehistory(old_price, change_date, articles_itemid) VALUES('" + str(oldprice) + "', CURRENT_DATE,'" + str(
|
||||||
)
|
itemid) + "')")
|
||||||
c.execute(
|
|
||||||
"INSERT INTO pricehistory(old_price, change_date, articles_itemid)"
|
|
||||||
" VALUES(%s, CURRENT_DATE, %s)",
|
|
||||||
(oldprice, itemid),
|
|
||||||
)
|
|
||||||
|
|
||||||
print("\n\tPrice updated successfully")
|
print("\n\tPrice updated successfully")
|
||||||
print("\tOld price saved to history")
|
print("\tOld price saved to history")
|
||||||
@@ -622,80 +531,45 @@ def change_price(n_id, newprice):
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
def remove_article(n_id):
|
def remove_article(n_id):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
itemid = n_id
|
itemid = n_id
|
||||||
if isinstance(n_id, str):
|
if isinstance(n_id, str):
|
||||||
c.execute("SELECT itemid FROM articles WHERE name = %s", (n_id,))
|
c.execute("SELECT itemid FROM articles WHERE name = '" + n_id + "'")
|
||||||
n_id = c.fetchall()
|
n_id = c.fetchall()
|
||||||
for i in n_id:
|
for i in n_id:
|
||||||
itemid = i[0]
|
itemid = i[0]
|
||||||
|
|
||||||
c.execute(
|
c.execute("SELECT * FROM rents WHERE articles_itemid = '" + str(itemid) + "' AND CURRENT_DATE < end_date")
|
||||||
"SELECT * FROM rents WHERE articles_itemid = %s"
|
|
||||||
" AND CURRENT_DATE < end_date",
|
|
||||||
(itemid,),
|
|
||||||
)
|
|
||||||
result = c.fetchall()
|
result = c.fetchall()
|
||||||
if result:
|
if result:
|
||||||
print("\n\tCan't remove article because there are user(s) renting it")
|
print("\n\tCan't remove article because there are user(s) renting it")
|
||||||
return
|
else:
|
||||||
|
c.execute("DELETE FROM articles_actors WHERE articles_itemid = '" + str(itemid) + "'")
|
||||||
# The foreign keys block the article through the rents that already ended
|
c.execute("DELETE FROM articles WHERE itemid = '" + str(itemid) + "'")
|
||||||
# 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 = %s", (itemid,)
|
|
||||||
)
|
|
||||||
old_rents = c.fetchall()[0][0]
|
|
||||||
c.execute(
|
|
||||||
"SELECT count(*) FROM pricehistory WHERE articles_itemid = %s", (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 = %s", (itemid,)
|
|
||||||
)
|
|
||||||
c.execute("DELETE FROM articles WHERE itemid = %s", (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
|
|
||||||
|
|
||||||
print("\n\tArticle removed successfully")
|
print("\n\tArticle removed successfully")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
def alter_balance(userid, balance):
|
def alter_balance(userid, balance):
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
c.execute(
|
c.execute("UPDATE users SET balance = '" + str(balance) + "' WHERE userid='" + str(userid) + "'")
|
||||||
"UPDATE users SET balance = %s WHERE userid = %s", (balance, userid)
|
|
||||||
)
|
|
||||||
|
|
||||||
print("\n\tBalance updated successfully")
|
print("\n\tBalance updated successfully")
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
def statistics():
|
def statistics():
|
||||||
with _connection() as conn:
|
conn = psycopg2.connect(f"host=localhost dbname=NetfloxFinal user=postgres password={DB_PASSWORD}")
|
||||||
total=0
|
total=0
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT articles_itemid FROM rents")
|
c.execute("SELECT articles_itemid FROM rents")
|
||||||
rents = c.fetchall()
|
rents = c.fetchall()
|
||||||
for x in rents:
|
for x in rents:
|
||||||
c.execute("SELECT * FROM articles WHERE itemid = %s", (x[0],))
|
c.execute("SELECT * FROM articles WHERE itemid= '"+str(x[0])+"' ")
|
||||||
price=c.fetchall()
|
price=c.fetchall()
|
||||||
for y in price:
|
for y in price:
|
||||||
total=total+y[6]
|
total=total+y[6]
|
||||||
@@ -741,7 +615,7 @@ def statistics():
|
|||||||
c.execute("SELECT * FROM rents WHERE end_date > CURRENT_DATE ")
|
c.execute("SELECT * FROM rents WHERE end_date > CURRENT_DATE ")
|
||||||
rents2 = c.fetchall()
|
rents2 = c.fetchall()
|
||||||
for e in rents2:
|
for e in rents2:
|
||||||
c.execute("SELECT * FROM articles WHERE itemid = %s", (e[3],))
|
c.execute("SELECT * FROM articles WHERE itemid= '"+str(e[3])+"' ")
|
||||||
price2=c.fetchall()
|
price2=c.fetchall()
|
||||||
for d in price2:
|
for d in price2:
|
||||||
total2=total2+d[6]
|
total2=total2+d[6]
|
||||||
|
|||||||
@@ -67,9 +67,6 @@ def client():
|
|||||||
if client_search == '1':
|
if client_search == '1':
|
||||||
client_search_typo=input("\tInsert movie name: ")
|
client_search_typo=input("\tInsert movie name: ")
|
||||||
article=database.findby_name(client_search_typo)
|
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:
|
while (x := int(input("\tYour Selection: "))) != 0:
|
||||||
print("\n\t" + article[x - 1][1])
|
print("\n\t" + article[x - 1][1])
|
||||||
while (client_in := input(article_interface)) != '0':
|
while (client_in := input(article_interface)) != '0':
|
||||||
@@ -86,9 +83,6 @@ def client():
|
|||||||
if client_search == '2':
|
if client_search == '2':
|
||||||
client_search_typo=input("\tInsert movie director: ")
|
client_search_typo=input("\tInsert movie director: ")
|
||||||
article=database.findby_director(client_search_typo)
|
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:
|
while (x := int(input("\tYour Selection: "))) != 0:
|
||||||
print("\n\t" + article[x - 1][1])
|
print("\n\t" + article[x - 1][1])
|
||||||
while (client_in := input(article_interface)) != '0':
|
while (client_in := input(article_interface)) != '0':
|
||||||
@@ -105,9 +99,6 @@ def client():
|
|||||||
if client_search == '3':
|
if client_search == '3':
|
||||||
client_search_typo=input("\tInsert movie type: ")
|
client_search_typo=input("\tInsert movie type: ")
|
||||||
article=database.findby_type(client_search_typo)
|
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:
|
while (x := int(input("\tYour Selection: "))) != 0:
|
||||||
print("\n\t" + article[x - 1][1])
|
print("\n\t" + article[x - 1][1])
|
||||||
while (client_in := input(article_interface)) != '0':
|
while (client_in := input(article_interface)) != '0':
|
||||||
@@ -123,9 +114,6 @@ def client():
|
|||||||
if client_search == '4':
|
if client_search == '4':
|
||||||
client_search_typo=input("\tInsert movie actor: ")
|
client_search_typo=input("\tInsert movie actor: ")
|
||||||
article=database.findby_actor(client_search_typo)
|
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:
|
while (x := int(input("\tYour Selection: "))) != 0:
|
||||||
print("\n\t" + article[x - 1][1])
|
print("\n\t" + article[x - 1][1])
|
||||||
while (client_in := input(article_interface)) != '0':
|
while (client_in := input(article_interface)) != '0':
|
||||||
@@ -280,8 +268,6 @@ def client():
|
|||||||
while (client_input := input(message_interface)) != '0':
|
while (client_input := input(message_interface)) != '0':
|
||||||
if client_input == '1':
|
if client_input == '1':
|
||||||
y = database.show_unread_messages(USERID)
|
y = database.show_unread_messages(USERID)
|
||||||
if not y:
|
|
||||||
continue
|
|
||||||
while (x := int(input("\tYour Selection: "))) != 0:
|
while (x := int(input("\tYour Selection: "))) != 0:
|
||||||
database.read_message(y[x - 1][0])
|
database.read_message(y[x - 1][0])
|
||||||
print("\n\t" + y[x - 1][1])
|
print("\n\t" + y[x - 1][1])
|
||||||
@@ -371,17 +357,9 @@ def admin():
|
|||||||
database.statistics()
|
database.statistics()
|
||||||
|
|
||||||
|
|
||||||
# menu() returns 1 for a client, -1 for an administrator and None when the
|
if menu() != -1:
|
||||||
# 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
|
USERID = database.USERID
|
||||||
client()
|
client()
|
||||||
else:
|
else:
|
||||||
print("\n\tGoodbye")
|
USERID = database.USERID
|
||||||
|
admin()
|
||||||
@@ -1,282 +0,0 @@
|
|||||||
"""Regression tests for the SQL injection that used to be in database.py.
|
|
||||||
|
|
||||||
Every statement in database.py was built by concatenating the value into the
|
|
||||||
SQL text, so anything that reached a search box, a sign-up form or a message
|
|
||||||
body was interpreted as SQL. Every statement is parameterized now (the value
|
|
||||||
travels as a psycopg2 parameter, never as part of the statement) and these tests
|
|
||||||
pin that.
|
|
||||||
|
|
||||||
Each test here fails against the previous, concatenating version of
|
|
||||||
database.py - see README, "Known limitations" and "Tests". The payloads are the
|
|
||||||
usual ones: a stacked `DROP TABLE`, a legitimate apostrophe, and quotes inside
|
|
||||||
the text that is stored and read back.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import ast
|
|
||||||
import builtins
|
|
||||||
import contextlib
|
|
||||||
import os
|
|
||||||
import pathlib
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
import database
|
|
||||||
from scripts import db as dbctl
|
|
||||||
|
|
||||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
|
||||||
ADMIN_EMAIL = dbctl.ADMIN[1]
|
|
||||||
|
|
||||||
# Two statements in one call, and then a comment that swallows the trailing
|
|
||||||
# quote: `LIKE '%'; DROP TABLE users; --%'`.
|
|
||||||
DROP_PAYLOAD = "'; DROP TABLE users; --"
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# helpers (same shape as the ones in test_netflox.py)
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
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 user_id(email: str) -> int:
|
|
||||||
return scalar("SELECT userid FROM users WHERE email = %s", (email,))
|
|
||||||
|
|
||||||
|
|
||||||
def make_client(name="Ana", email="ana@exemplo.pt") -> int:
|
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
def insert_article(name, director, actors=(), **overrides):
|
|
||||||
"""Insert one article (and its cast) with parameterized SQL, for fixtures."""
|
|
||||||
fields = {
|
|
||||||
"release_year": 1995,
|
|
||||||
"imbd_rating": 7.0,
|
|
||||||
"genre": "drama",
|
|
||||||
"price": 1.50,
|
|
||||||
"type": "movie",
|
|
||||||
"time_available": 7,
|
|
||||||
}
|
|
||||||
fields.update(overrides)
|
|
||||||
with raw_cursor() as cur:
|
|
||||||
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, fields["release_year"], fields["imbd_rating"],
|
|
||||||
fields["genre"], fields["price"], fields["type"],
|
|
||||||
fields["time_available"]),
|
|
||||||
)
|
|
||||||
itemid = cur.fetchone()[0]
|
|
||||||
for actor in actors:
|
|
||||||
cur.execute("INSERT INTO actors (name) VALUES (%s) RETURNING actorid",
|
|
||||||
(actor,))
|
|
||||||
cur.execute(
|
|
||||||
"INSERT INTO articles_actors (articles_itemid, actors_actorid)"
|
|
||||||
" VALUES (%s, %s)",
|
|
||||||
(itemid, cur.fetchone()[0]),
|
|
||||||
)
|
|
||||||
return itemid
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# (a) a stacked DROP TABLE is searched as text and changes nothing
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
@pytest.mark.parametrize("search", [
|
|
||||||
"findby_name", "findby_director", "findby_type", "findby_actor",
|
|
||||||
])
|
|
||||||
def test_a_drop_table_payload_is_searched_as_text(capsys, search):
|
|
||||||
"""The payload used to be pasted into the statement, which turned the search
|
|
||||||
into two statements: the SELECT, and `DROP TABLE users`. The SELECT matching
|
|
||||||
`LIKE '%'` also returned every article as if it were a search result.
|
|
||||||
|
|
||||||
Now it is one parameter, the pattern matches nothing (there is no article
|
|
||||||
with that name), and the statement is a search like any other.
|
|
||||||
"""
|
|
||||||
result = getattr(database, search)(DROP_PAYLOAD)
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
# findby_actor returns None when nothing matches; the other three return [].
|
|
||||||
assert result in ([], None)
|
|
||||||
|
|
||||||
# The table is still there, and still has its rows, after the search.
|
|
||||||
assert scalar("SELECT to_regclass('public.users') IS NOT NULL") is True
|
|
||||||
assert scalar("SELECT count(*) FROM users") >= 2
|
|
||||||
assert scalar("SELECT count(*) FROM articles") == 6
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# (b) a legitimate apostrophe is a character, not the end of a literal
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
def test_an_apostrophe_in_a_search_term_is_text(capsys):
|
|
||||||
"""`LIKE '%O'Brien%'` used to be a syntax error (unterminated string)."""
|
|
||||||
insert_article("O'Brien's Ghost", "Ana O'Brien", actors=["Sean O'Brien"])
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
assert [row[1] for row in database.findby_name("O'Brien")] == ["O'Brien's Ghost"]
|
|
||||||
assert [row[1] for row in database.findby_director("O'Brien")] == ["O'Brien's Ghost"]
|
|
||||||
assert [row[1] for row in database.findby_actor("O'Brien")] == ["O'Brien's Ghost"]
|
|
||||||
# findby_type() searches the movie/series column, where an apostrophe can
|
|
||||||
# only appear as a fragment that matches nothing - and it is still a
|
|
||||||
# fragment, not the end of a string literal.
|
|
||||||
assert database.findby_type("movie'") == []
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_apostrophe_in_an_admin_lookup_is_text(capsys):
|
|
||||||
"""change_price()/remove_article() look the article up by name first."""
|
|
||||||
insert_article("O'Brien's Ghost", "Ana O'Brien")
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
database.change_price("O'Brien's Ghost", "2.00")
|
|
||||||
capsys.readouterr()
|
|
||||||
assert scalar("SELECT price FROM articles WHERE name = %s",
|
|
||||||
("O'Brien's Ghost",)) == 2
|
|
||||||
assert scalar("SELECT count(*) FROM pricehistory") == 1
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# (c) quotes in stored text survive a write and a read, unchanged
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
def test_create_user_stores_quotes_exactly(capsys):
|
|
||||||
"""`VALUES ('Ana 'Aspas' Silva', ...)` used to be a syntax error."""
|
|
||||||
name = "Ana 'Aspas' Silva"
|
|
||||||
password = demo_password()
|
|
||||||
|
|
||||||
database.create_user(name, "anasilva@exemplo.pt", password)
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
assert scalar("SELECT nome FROM users WHERE email = %s",
|
|
||||||
("anasilva@exemplo.pt",)) == name
|
|
||||||
assert scalar("SELECT password FROM users WHERE email = %s",
|
|
||||||
("anasilva@exemplo.pt",)) == password
|
|
||||||
# And the account is usable: the same quotes go through log_in().
|
|
||||||
assert database.log_in("anasilva@exemplo.pt", password) == 1
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_message_with_quotes_is_stored_exactly(capsys):
|
|
||||||
client = make_client()
|
|
||||||
admin = user_id(ADMIN_EMAIL)
|
|
||||||
text = "Ele disse 'olá' e \"adeus\" 'a'"
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
database.message_client(text, str(client), str(admin))
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
assert scalar("SELECT message FROM messages WHERE users_userid = %s",
|
|
||||||
(client,)) == text
|
|
||||||
assert scalar("SELECT count(*) FROM messages WHERE senderid = %s",
|
|
||||||
(admin,)) == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_broadcast_with_quotes_is_stored_exactly(capsys):
|
|
||||||
admin = user_id(ADMIN_EMAIL)
|
|
||||||
total_users = scalar("SELECT count(*) FROM users")
|
|
||||||
text = "Aviso: 'manutenção' \"; DROP TABLE messages; --"
|
|
||||||
|
|
||||||
database.message_all(text, admin)
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
assert scalar("SELECT count(*) FROM messages WHERE message = %s",
|
|
||||||
(text,)) == total_users - 1
|
|
||||||
assert scalar("SELECT count(*) FROM messages") == total_users - 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_add_article_stores_quotes_exactly(monkeypatch, capsys):
|
|
||||||
feed_inputs(monkeypatch, ["1", "Sean O'Brien"])
|
|
||||||
|
|
||||||
database.add_article("O'Brien's Ghost", "Ana O'Brien", "7.0", "drama",
|
|
||||||
"1.50", "1995", "7", "movie")
|
|
||||||
capsys.readouterr()
|
|
||||||
|
|
||||||
itemid = scalar("SELECT itemid FROM articles WHERE name = %s",
|
|
||||||
("O'Brien's Ghost",))
|
|
||||||
assert itemid is not None
|
|
||||||
assert scalar("SELECT director FROM articles WHERE itemid = %s",
|
|
||||||
(itemid,)) == "Ana O'Brien"
|
|
||||||
assert scalar("SELECT count(*) FROM actors WHERE name = %s",
|
|
||||||
("Sean O'Brien",)) == 1
|
|
||||||
assert scalar("SELECT count(*) FROM articles_actors WHERE articles_itemid = %s",
|
|
||||||
(itemid,)) == 1
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# the password cannot be commented out or short-circuited
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
@pytest.mark.parametrize("payload", ["' OR '1'='1", "' OR 1=1 --", "x' OR 'a'='a"])
|
|
||||||
def test_the_password_cannot_be_bypassed(capsys, payload):
|
|
||||||
"""`password = '' OR '1'='1'` used to be true for every row, so log_in()
|
|
||||||
handed out the administrator session for any password."""
|
|
||||||
before = database.USERID # a failed login must not move the session
|
|
||||||
assert database.log_in(ADMIN_EMAIL, payload) == 0
|
|
||||||
capsys.readouterr()
|
|
||||||
assert database.USERID == before
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_email_cannot_comment_out_the_password(capsys):
|
|
||||||
"""`email = 'admin@netflox.com' --' AND password = '...'` used to match."""
|
|
||||||
before = database.USERID
|
|
||||||
assert database.log_in("admin@netflox.com' --", "not-the-password") == 0
|
|
||||||
capsys.readouterr()
|
|
||||||
assert database.USERID == before
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# structural guard: no statement may be assembled from parts again
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
def test_no_statement_is_built_by_string_concatenation():
|
|
||||||
"""Every execute() must receive a constant string (plus its parameters).
|
|
||||||
|
|
||||||
This is what the previous version looked like in all 48 interpolated
|
|
||||||
statements: `c.execute("... = '" + value + "'")`, an ast.BinOp as the first
|
|
||||||
argument.
|
|
||||||
"""
|
|
||||||
source = (ROOT / "database.py").read_text(encoding="utf-8")
|
|
||||||
tree = ast.parse(source)
|
|
||||||
|
|
||||||
offenders = []
|
|
||||||
for node in ast.walk(tree):
|
|
||||||
if not isinstance(node, ast.Call):
|
|
||||||
continue
|
|
||||||
func = node.func
|
|
||||||
name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
|
|
||||||
if name != "execute" or not node.args:
|
|
||||||
continue
|
|
||||||
statement = node.args[0]
|
|
||||||
if not (isinstance(statement, ast.Constant) and isinstance(statement.value, str)):
|
|
||||||
offenders.append(ast.get_source_segment(source, statement))
|
|
||||||
|
|
||||||
assert offenders == [], f"statements assembled at runtime: {offenders}"
|
|
||||||
+27
-148
@@ -6,13 +6,12 @@ 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
|
except keyboard input: if the schema does not match what the code expects, these
|
||||||
tests fail.
|
tests fail.
|
||||||
|
|
||||||
Every defect that used to be pinned here by an `xfail` or a `test_known_bug_*`
|
Tests named `test_known_bug_*` and the ones marked `xfail` pin down behaviour
|
||||||
name now has a regression test that fails against the previous code; the last
|
that is wrong in database.py / main.py; they are documentation, not approval
|
||||||
section of this file is that regression suite (see README, "What it is").
|
(see README, "Known limitations").
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import ast
|
|
||||||
import builtins
|
import builtins
|
||||||
import contextlib
|
import contextlib
|
||||||
import datetime
|
import datetime
|
||||||
@@ -319,7 +318,7 @@ def test_message_to_one_client_then_mark_it_read(capsys):
|
|||||||
assert scalar("SELECT bolread FROM messages") is True
|
assert scalar("SELECT bolread FROM messages") is True
|
||||||
read = database.show_read_messages(client)
|
read = database.show_read_messages(client)
|
||||||
assert len(read) == 1 and read[0][1] == "Bem-vindo"
|
assert len(read) == 1 and read[0][1] == "Bem-vindo"
|
||||||
assert database.show_unread_messages(client) == [] # an empty list, not None
|
assert database.show_unread_messages(client) is None # documented quirk
|
||||||
|
|
||||||
|
|
||||||
def test_message_all_reaches_every_user_except_the_sender(capsys):
|
def test_message_all_reaches_every_user_except_the_sender(capsys):
|
||||||
@@ -473,167 +472,47 @@ def test_schema_sql_does_not_carry_the_demo_password():
|
|||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# regressions: every test below used to be an xfail or a `test_known_bug_*`
|
# known bugs, pinned so that they are visible instead of silent
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
def test_findby_director_returns_the_rows_it_printed(capsys):
|
@pytest.mark.xfail(reason="findby_director() has no return on the success path")
|
||||||
"""It printed the matches and fell off the end of the function (None)."""
|
def test_known_bug_findby_director_returns_nothing_on_a_match():
|
||||||
movies = database.findby_director("Christopher Nolan")
|
assert database.findby_director("Christopher Nolan") is not None
|
||||||
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") == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_findby_actor_without_a_match_returns_none():
|
@pytest.mark.xfail(reason="findby_actor() raises UnboundLocalError when no actor matches")
|
||||||
"""It used to raise UnboundLocalError: `articles` was never bound."""
|
def test_known_bug_findby_actor_without_a_match():
|
||||||
assert database.findby_actor("Ninguem Com Este Nome") is None
|
assert database.findby_actor("Ninguem Com Este Nome") is None
|
||||||
|
|
||||||
|
|
||||||
def test_findby_actor_returns_every_article_of_the_actor():
|
def test_known_bug_search_without_matches_breaks_main_py():
|
||||||
"""It used to return whatever `articles` held after the last iteration: only
|
"""findby_name() returns 0, and main.py immediately does article[x - 1][1]."""
|
||||||
the last article of the actor, out of a list that could have several."""
|
assert database.findby_name("zzz-nao-existe") == 0
|
||||||
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_search_without_matches_returns_an_empty_list():
|
def test_known_bug_message_list_labels_a_message_with_the_recipient(capsys):
|
||||||
"""It used to return the integer 0, which main.py then indexed into."""
|
"""show_unread_messages() looks the author up with row[4], which is the
|
||||||
assert database.findby_name("zzz-nao-existe") == []
|
recipient (users_userid); the sender is row[5]. A client therefore sees their
|
||||||
assert database.findby_type("zzz-nao-existe") == []
|
own name as the author of every message."""
|
||||||
|
|
||||||
|
|
||||||
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()
|
client = make_client()
|
||||||
admin = user_id(ADMIN_EMAIL)
|
admin = user_id(ADMIN_EMAIL)
|
||||||
database.message_client("Ola", str(client), str(admin))
|
database.message_client("Ola", str(client), str(admin))
|
||||||
capsys.readouterr()
|
capsys.readouterr()
|
||||||
|
|
||||||
unread = database.show_unread_messages(client)
|
database.show_unread_messages(client)
|
||||||
out = capsys.readouterr().out
|
out = capsys.readouterr().out
|
||||||
assert "Message from Admin" in out
|
assert "Message from Ana" in out # the recipient, not the admin
|
||||||
assert "Message from Ana" not in out
|
assert "Message from Admin" 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_purchase_debits_the_account_it_was_given(capsys):
|
def test_known_bug_purchase_debits_the_last_logged_in_account():
|
||||||
"""It debited USERID (the account of the last log_in), not its argument."""
|
"""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")
|
ana = make_client("Ana", "ana@exemplo.pt")
|
||||||
bruno = make_client("Bruno", "bruno@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)
|
database.purchase(article_id("Pulp Fiction"), bruno)
|
||||||
assert "Purchase successful!" in capsys.readouterr().out
|
|
||||||
|
|
||||||
assert balance_of(bruno) == Decimal("17.50") # 20.00 - 2.50, the buyer
|
assert balance_of(ana) == Decimal("17.50") # Ana paid
|
||||||
assert balance_of(ana) == Decimal("20.00") # the last login, untouched
|
assert balance_of(bruno) == Decimal("20.00")
|
||||||
assert scalar("SELECT count(*) FROM rents WHERE users_userid = %s", (bruno,)) == 1
|
assert scalar("SELECT users_userid FROM rents") == bruno
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|||||||
Reference in New Issue
Block a user