Notes
Why look?
When is a database check worth it? For side effects the response does not show: was the stock reduced, was the cart emptied, was an audit row written? For data the API never returns, like checking a password is stored as a hash, not plain text. For checking integrity after migrations or batch jobs. A simple rule: if the API can show you the same thing, prefer the API; use the database for what it cannot.
- side effects the response does not show: stock reduced? cart emptied? audit row written?
- data the API never returns (password stored as a hash?)
- setting up rare data quickly
- checking data integrity after migrations or batch jobs
- prefer the API when it can show the same thing
ShopRung's tables
ShopRung stores everything in a SQLite database with seven tables. Users, with a password hash and a role. Products, with price in cents and stock. Coupons, with their kind, amount, minimum subtotal and expiry date. Carts and cart items for each user. And orders, with status and every amount in cents, plus order items. Notice the column names use underscores, like total underscore cents, while the API uses total cents. The database and the API are different layers.
users(id, email, name, password_hash, role) products(id, sku, name, category, price_cents, stock) coupons(code, kind, amount, min_subtotal_cents, expires_on) carts(user_id, coupon_code) cart_items(user_id, product_id, quantity) orders(id, user_id, status, ..., total_cents) + order_items
Read-only access
Tests should look at the database, not change it behind the application's back. Use a read only user or connection. ShopRung's SQL console, on the slash sql page or the test SQL endpoint, runs one select query on a read only connection. Ask for the stock of product three: three. Try delete from orders: four hundred, the console runs one select query at a time. Real teams give testers the same kind of read only access.
POST /api/test/sql
{"query": "SELECT stock FROM
products WHERE id = 3"}
→ {"rows": [{"stock": 3}]}
"DELETE FROM orders"
→ 400 select_only
"The console runs one
SELECT query at a time"
also in the browser: /sql A real check
Here is a real test. The db fixture opens ShopRung's database file in read only mode. The test reads the stock of the Bug Hunter's Diary, product three, which starts at three. It adds two to Alice's cart and places the order: two hundred and one. Then it checks the stock is now the old value minus two. Against the normal ShopRung, it passed. The same test then checks the new order row has status placed and the same total as the response.
def test_order_reduces_stock(alice, db):
before = stock(db, 3)
alice.post("/api/cart/items",
json={"productId": 3, "quantity": 2})
r = alice.post("/api/orders", json={})
assert r.status_code == 201
assert stock(db, 3) == before - 2
db = sqlite3.connect(
f"file:{DB}?mode=ro", uri=True) In Java
In Java, JDBC does the same job. Open a connection with read only properties, inside try with resources so it always closes. Use a prepared statement with a question mark placeholder, set the id, execute the query, and read the integer. Always use placeholders, never string concatenation, even in tests: it avoids quoting bugs, and it is the habit that prevents SQL injection in real code.
int stock(long id) throws Exception {
try (var con = DriverManager
.getConnection(DB_URL, ro);
var ps = con.prepareStatement(
"SELECT stock FROM products" +
" WHERE id = ?")) {
ps.setLong(1, id);
var rs = ps.executeQuery();
rs.next(); return rs.getInt(1);
}
} Queries testers use
A few query patterns cover most needs. Joins combine tables, like orders with their items. Group by with having finds broken totals: every order whose items do not add up to its subtotal. Simple where clauses find impossible data, like negative stock. Expected result: zero rows. These integrity checks are especially valuable after migrations and batch jobs, and many teams run them on a schedule.
-- each order's items add up? SELECT o.id FROM orders o JOIN order_items i ON i.order_id = o.id GROUP BY o.id, o.subtotal_cents HAVING SUM(i.price_cents * i.quantity) <> o.subtotal_cents; -- no negative stock SELECT * FROM products WHERE stock < 0;
Trade-offs
Database checks have costs. They couple tests to the schema, so renaming a column breaks tests even when the behaviour is fine. Pointed at the wrong environment, they can read real customer data. Background jobs may not have written yet, so poll with a timeout instead of checking once. And caches mean the database and the API can disagree for a while. Keep SQL in a few helper functions, read only, and on test data only.
- schema changes break tests even when behaviour is fine
- wrong environment = real data
- timing: async jobs may not have written yet (poll)
- caches: DB updated, API still shows old data, or reverse
- keep SQL in a few helpers, read-only, test data only
Common mistakes
Mistakes to avoid. Writing to the database in the middle of a test to fix data, which hides real bugs. Building SQL by string concatenation. Connections that are never closed, which slowly exhausts the pool. The same SQL copied into every test. Checking the database for everything, even what the API shows. And production credentials anywhere in test configuration.
- writing to the DB to "fix" test data mid-test
- SQL by string concatenation
- connections never closed
- SQL copied into every test
- checking the DB instead of the API for everything
- production credentials in test config
Say it like this
In the interview: yes, when the response cannot show the side effect, such as stock, audit rows or hashed passwords. I use a read only connection, parameterised queries kept in a few helpers, and polling for asynchronous writes. For example, my order test checks that stock went down, which caught a bug the response alone completely missed. I also write SQL integrity checks for joins and totals.
- "When the response cannot show
- the side effect: stock, audit
- rows, hashed passwords. I use
- a read-only connection, parameterised queries in a few
- helpers, and poll for async
- writes. For example, an order
- test checks stock went down;
- the response alone missed that bug."