QA and Test Automation · Lab 4 of 35
Your first Java test project: Maven, JUnit 5 and a first API check
Install JDK 21 and Maven, build a test project from an empty folder, code ShopRung's coupon and shipping rules in cents, cover every boundary with parameterized JUnit 5 tests, solve four SDET interview programs with tests, and write a first API check of the running shop.
⏱ 75 minBeginner💸 Free8 stepsJava + Python
Java 21 (Temurin or OpenJDK)Maven 3.9JUnit 5.11java.net.http.HttpClientShopRungPython 3.12 + pytest (second path)
Overview video
What you will build
A real Maven test project, written line by line from an empty folder, with 40 passing tests in three classes:
PricingTest: ShopRung's money rules (SAVE10, FLAT5, the expired WELCOME15, free shipping from $75.00, rounding half a cent up), coded in whole cents and tested on every boundary with@ParameterizedTestand@CsvSource,assertAllandassertThrows.PuzzlesTest: the four programs SDET interviews ask for most (reverse the words, find duplicates with aMap, palindrome, count characters), each with tests for the edge cases interviewers look for.ShopRungApiTest: your first black-box check of the running shop over HTTP, using only the JDK. It skips itself cleanly when ShopRung is not running, and it catches a real ShopRung bug when you switch that bug on.
Prefer Python? Switch to Python at the top of the steps: the same project, test for test, with pytest.
Before you start
- Java basics: classes, methods,
ifand loops. New to Java? Watch Java for testers first. Maven and JUnit 5 explains the ideas this lab puts into practice. - ShopRung installed, as in lab 1 setup. You need it running from step 7.
- You have done Test cases for a checkout: this lab automates some of the same boundaries.
- A code editor: IntelliJ IDEA (the free version is enough) or VS Code with the Extension Pack for Java. Every step also works with just a terminal.
Setup
S1Install Java 21 (the JDK)
The JDK (Java Development Kit) has the compiler javac and the java command. Java 21 is a long-term support release, which most companies use for test projects. Temurin is a free, open-source build of it.
macOS: Homebrew installs Temurin 21 where macOS looks for Java, and the JAVA_HOME line tells Maven to use it. Linux: the line below is for Ubuntu and Debian (Fedora: sudo dnf install java-21-openjdk-devel). If you use SDKMAN, run sdk list java, pick the newest 21.x line that ends in -tem, and sdk install java with that id. Windows: after the install, open a new terminal so it finds java.
brew install --cask temurin@21
echo 'export JAVA_HOME=$(/usr/libexec/java_home -v 21)' >> ~/.zshrc
source ~/.zshrc
java -versionsudo apt update
sudo apt install -y openjdk-21-jdk
java -versionwinget install EclipseAdoptium.Temurin.21.JDK
# open a new terminal, then:
java -version openjdk version "21.0.9" 2025-10-21 LTS OpenJDK Runtime Environment Temurin-21.0.9+10 (build 21.0.9+10-LTS) OpenJDK 64-Bit Server VM Temurin-21.0.9+10 (build 21.0.9+10-LTS, mixed mode, sharing)
S2Install Maven
Maven builds Java projects: it downloads the libraries your pom.xml asks for (like JUnit), compiles your code and runs your tests. Any Maven from 3.8 works for this lab.
Windows has no one-line installer for Maven, so the commands download the official zip, unzip it to C:\tools, and add its bin folder to your PATH. Open a new terminal afterwards. (If you have Scoop or Chocolatey, scoop install maven or choco install maven also work.)
brew install maven
mvn -vsudo apt install -y maven
mvn -vInvoke-WebRequest https://archive.apache.org/dist/maven/maven-3/3.9.11/binaries/apache-maven-3.9.11-bin.zip -OutFile maven.zip
Expand-Archive maven.zip -DestinationPath C:\tools
[Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";C:\tools\apache-maven-3.9.11\bin", "User")
# open a new terminal, then:
mvn -v Apache Maven 3.9.11 (3e54c93a704957b63ee3494413a2b544fd3d825b) Maven home: ... Java version: 21.0.9, vendor: Eclipse Adoptium, runtime: ...
S3Check Maven uses Java 21
Look at the Java version: line of mvn -v. It must start with 21. If it shows another version (Homebrew's Maven brings its own newest Java), JAVA_HOME is not set in this terminal: on macOS run source ~/.zshrc and check echo $JAVA_HOME prints a path with 21 in it.
S4Python path only: Python 3.12 or newer
Only if you take the Python path. Install Python from python.org (Windows and macOS) or your package manager, then check the version. On Windows, use py where the steps say python3.
python3 --versionpython3 --versionpy --version Python 3.12.x (or newer)
Create the Maven project
An empty project that Maven can build: the standard folders and a pom.xml.
Maven expects a fixed layout, and every Java team uses it: src/main/java for the code, src/test/java for the tests, and pom.xml (the Project Object Model) at the top. Folders follow the package name, so dev.algorung.shop lives in dev/algorung/shop.
Make the folders. Open a terminal where you keep your labs (for example ~/qa-labs) and run the command for your system:
# macOS and Linux
mkdir -p shoprung-tests/src/main/java/dev/algorung/shop shoprung-tests/src/test/java/dev/algorung/shop
cd shoprung-tests
# Windows PowerShell
mkdir shoprung-tests\src\main\java\dev\algorung\shop, shoprung-tests\src\test\java\dev\algorung\shop
cd shoprung-tests
Now create pom.xml in the shoprung-tests folder with the content below. You could generate a project with mvn archetype:generate, but writing it yourself once means you know what every line does. Then run mvn test. The first run downloads Maven's plugins and JUnit (a minute or two); later runs take seconds.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>dev.algorung</groupId>
<artifactId>shoprung-tests</artifactId>
<version>0.1.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.11.4</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
</plugin>
</plugins>
</build>
</project> - **groupId, artifactId, version** name your project. groupId is usually your company's domain backwards.line 6
- Compile for Java 21.
releasealso stops you from using anything newer than Java 21 by accident.line 11 - Read the source files as UTF-8 on every machine, so a test with "café" works on Windows too.line 12
- JUnit 5.11, pinned. A pinned version gives the same build today and in a year. (JUnit 6 came out in 2025; everything in this lab works the same there.)line 13
junit-jupiterbrings the JUnit 5 API, the parameterized tests module and the engine that runs them.line 19testscope: JUnit is only on the classpath while compiling and running tests, never in the shipped code.line 21- The compiler plugin, pinned too. Maven picks a default version when you do not, and that default changes between Maven versions.line 30
- **Surefire** is the plugin that runs tests during
mvn test. It finds every class whose name ends inTestundersrc/test/java.line 34
pytest==9.1.1 - One package, pinned with
==, so everyone gets the same pytest. pytest needs no other setup: it finds files namedtest_*.pyand functions namedtest_*.line 1
Python version of this step:
mvn test [INFO] Scanning for projects... [INFO] [INFO] -------------------< dev.algorung:shoprung-tests >-------------------- [INFO] Building shoprung-tests 0.1.0 ... [INFO] No sources to compile ... [INFO] No tests to run. [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------
mkdir shoprung-tests-py && cd shoprung-tests-py
# save requirements.txt here, then:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pytestmkdir shoprung-tests-py && cd shoprung-tests-py
# save requirements.txt here, then:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pytestmkdir shoprung-tests-py; cd shoprung-tests-py
# save requirements.txt here, then:
py -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
pytest Successfully installed iniconfig-2.x packaging-2x.x pluggy-1.6.0 pygments-2.x.x pytest-9.1.1 ============================= test session starts ============================== collected 0 items ============================ no tests ran in 0.01s =============================
.venv) keeps this project's packages apart from every other project on your machine.Stuck on this step?
mvn: command not found(or "not recognized" on Windows)- Maven is not on your PATH in this terminal. Open a new terminal. On Windows check the PATH line in setup ran, then run
mvn -vagain. Non-parseable POMorUnrecognised tag- A tag is not closed or is misspelled. Copy the whole file again with the Copy button; the line number in the message points at the problem.
- Windows:
Activate.ps1 cannot be loaded because running scripts is disabled - Run
Set-ExecutionPolicy -Scope CurrentUser RemoteSignedonce, answer Y, then activate again.
Your first class and your first tests
Money formatting and the shipping rule in code, with six passing tests.
You will put ShopRung's money rules (requirements PRICE-1 to PRICE-10) into a small class and test it. Testing the rules directly, with no browser and no server, is a unit test: it runs in milliseconds and points straight at the broken rule.
One decision first: money is whole cents in a long, so $50.00 is 5000. Never use double for money: 0.1 + 0.2 is 0.30000000000000004 in Java. ShopRung itself stores cents for the same reason.
Create the two files below: the class in src/main/java/..., the test in src/test/java/.... A test is a method with @Test. assertEquals(expected, actual) fails the test when the two differ; the expected value always comes first, so the failure message reads the right way round.
The shipping rule (PRICE-9) is a boundary: $4.99 below $75.00, free from $75.00. Instead of five copies of the same test, @ParameterizedTest runs one method once per row of @CsvSource. Each row is one test case: the boundary, one cent below it, one above it, and the edge cases.
package dev.algorung.shop;
/**
* ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Java.
* Every amount is whole cents in a long: $50.00 is 5000. No double, so no rounding surprises.
*/
public final class Pricing {
public static final long FREE_SHIPPING_FROM = 7_500; // $75.00, after the discount
public static final long SHIPPING = 499; // $4.99
private Pricing() {}
/** 1250 becomes "$12.50" (PRICE-1). */
public static String money(long cents) {
if (cents < 0) throw new IllegalArgumentException("cents must not be negative: " + cents);
return String.format("$%d.%02d", cents / 100, cents % 100);
}
/** $4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing. */
public static long shipping(long afterDiscount) {
if (afterDiscount == 0) return 0;
return afterDiscount >= FREE_SHIPPING_FROM ? 0 : SHIPPING;
}
} - Named constants instead of magic numbers.
7_500: Java lets you write underscores in numbers to make them readable.line 8 - A class of static helpers: a private constructor stops anyone creating an instance.line 11
%02dpads the cents to two digits, so 5 cents prints as$0.05, not$0.5.line 16- ShopRung shows $0.00 shipping for an empty cart. Your code matches the real shop, not your guess.line 21
- The whole boundary is in this one character.
>instead of>=is exactly ShopRung'sfree-shipping-boundarybug.line 22
package dev.algorung.shop;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class PricingTest {
@Test
void moneyHasADollarSignAndTwoDecimals() {
assertEquals("$12.50", Pricing.money(1250));
assertEquals("$0.05", Pricing.money(5));
}
@ParameterizedTest(name = "{0} cents after the discount -> shipping {1}")
@CsvSource({
"7499, 499", // one cent below the edge
"7500, 0", // exactly on the edge: free
"7501, 0",
"1, 499",
"0, 0", // an empty cart ships nothing
})
void shippingIsFreeFrom75Dollars(long afterDiscount, long expected) {
assertEquals(expected, Pricing.shipping(afterDiscount));
}
} - A static import lets you write
assertEquals(...)instead ofAssertions.assertEquals(...).line 3 - Test classes do not need to be
publicin JUnit 5. The name ends inTest, which is how Surefire finds it.line 9 - Expected first, actual second.line 12
namesets how each row shows in the report:7499 cents after the discount -> shipping 499.line 16- One row per case. JUnit converts each value to the parameter type (
longhere) for you.line 18 - The parameters match the columns, in order.line 24
"""ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Python.
Every amount is whole cents in an int: $50.00 is 5000. No float, so no rounding surprises.
"""
FREE_SHIPPING_FROM = 7_500 # $75.00, after the discount
SHIPPING = 499 # $4.99
def money(cents: int) -> str:
"""1250 becomes "$12.50" (PRICE-1)."""
if cents < 0:
raise ValueError(f"cents must not be negative: {cents}")
return f"${cents // 100}.{cents % 100:02d}"
def shipping(after_discount: int) -> int:
"""$4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing."""
if after_discount == 0:
return 0
return 0 if after_discount >= FREE_SHIPPING_FROM else SHIPPING - Named constants. Python ints never overflow, and like Java you can write
7_500.line 5 //divides whole numbers,%is the remainder, and:02dpads the cents to two digits.line 13- ShopRung shows $0.00 shipping for an empty cart.line 18
- The whole boundary is in this one character:
>here is ShopRung'sfree-shipping-boundarybug.line 20
import pytest
from pricing import money, shipping
def test_money_has_a_dollar_sign_and_two_decimals():
assert money(1250) == "$12.50"
assert money(5) == "$0.05"
@pytest.mark.parametrize("after_discount, expected", [
(7499, 499), # one cent below the edge
(7500, 0), # exactly on the edge: free
(7501, 0),
(1, 499),
(0, 0), # an empty cart ships nothing
])
def test_shipping_is_free_from_75_dollars(after_discount, expected):
assert shipping(after_discount) == expected - A test is a function whose name starts with
test_. A plainassertis all you need: pytest shows both sides when it fails.line 6 - The pytest version of
@ParameterizedTest: the names of the arguments, then one tuple per case.line 11
Python version of this step:
mvn test [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running dev.algorung.shop.PricingTest [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PricingTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
pytest -v collected 6 items test_pricing.py::test_money_has_a_dollar_sign_and_two_decimals PASSED [ 16%] test_pricing.py::test_shipping_is_free_from_75_dollars[7499-499] PASSED [ 33%] test_pricing.py::test_shipping_is_free_from_75_dollars[7500-0] PASSED [ 50%] test_pricing.py::test_shipping_is_free_from_75_dollars[7501-0] PASSED [ 66%] test_pricing.py::test_shipping_is_free_from_75_dollars[1-499] PASSED [ 83%] test_pricing.py::test_shipping_is_free_from_75_dollars[0-0] PASSED [100%] ============================== 6 passed in 0.02s ===============================
Stuck on this step?
No tests to runalthough the test file exists- The test is in the wrong folder or the class name does not end in
Test. It must besrc/test/java/dev/algorung/shop/PricingTest.java, and the first line must bepackage dev.algorung.shop;. package org.junit.jupiter.api does not exist- The test file is under
src/main/java. JUnit hastestscope, so it only exists for files undersrc/test/java. Move the file. - Python:
ModuleNotFoundError: No module named 'pricing' - Run
pytestfrom the project folder, the one withpricing.pyin it, and keep the test file in that same folder.
Coupons, and every boundary in one table
The three coupons and the cart totals, with nine boundary rows from lab 1 as tests.
Now the coupon rules: SAVE10 takes 10% off from $50.00 (PRICE-3), FLAT5 takes $5.00 off from $20.00 (PRICE-4), WELCOME15 expired on 31 December 2025 (PRICE-5), codes are not case-sensitive (PRICE-2), and an unknown code gets "No coupon called ..." (PRICE-7). A Java enum fits: a fixed list of named values, each with its own data. The messages are copied from ShopRung, word for word.
Then totals() adds them up: total = subtotal - discount + shipping (PRICE-10), with shipping worked out after the discount (PRICE-9). A record holds the four numbers. Records get equals for free, so one assertEquals compares all four.
The table in the test is the boundary analysis from lab 1, now as code. Every row is a real ShopRung cart: 4 notebooks are $50.00, the hoodie is $49.99, the keyboard is $75.00. An empty cell (the coupon column in two rows) arrives as null, which means "no coupon".
package dev.algorung.shop;
import java.time.LocalDate;
import java.util.Locale;
/** ShopRung's three coupons (PRICE-2 to PRICE-7), with the same rules and messages as the shop. */
public enum Coupon {
SAVE10(true, 10, 5_000, null), // 10% off from $50.00
FLAT5(false, 500, 2_000, null), // $5.00 off from $20.00
WELCOME15(true, 15, 0, LocalDate.of(2025, 12, 31)); // expired
private final boolean percent;
private final long amount; // a percent, or cents
private final long minSubtotal; // cents
private final LocalDate expiresOn;
Coupon(boolean percent, long amount, long minSubtotal, LocalDate expiresOn) {
this.percent = percent;
this.amount = amount;
this.minSubtotal = minSubtotal;
this.expiresOn = expiresOn;
}
/** Finds a coupon by code. Codes are not case-sensitive (PRICE-2); an unknown code is refused (PRICE-7). */
public static Coupon of(String code) {
String c = code == null ? "" : code.trim().toUpperCase(Locale.ROOT);
for (Coupon coupon : values()) {
if (coupon.name().equals(c)) return coupon;
}
throw new IllegalArgumentException("No coupon called " + (c.isEmpty() ? "(empty)" : c));
}
/** Why this coupon cannot be used, or null when it can. */
public String problem(long subtotal, LocalDate today) {
if (expiresOn != null && today.isAfter(expiresOn)) return "This coupon has expired";
if (subtotal < minSubtotal) return "This coupon needs a subtotal of at least " + Pricing.money(minSubtotal);
return null;
}
/** The discount in cents. A percentage rounds to the nearest cent, half a cent up (PRICE-6). */
public long discount(long subtotal) {
if (percent) return (subtotal * amount + 50) / 100;
return Math.min(amount, subtotal); // a fixed amount never makes the total negative
}
} - Each constant passes its data to the constructor: percent or not, the amount, the minimum subtotal and the expiry date.line 8
Locale.ROOTmakes upper-casing the same on every computer. With a Turkish locale,"i".toUpperCase()is not"I".line 26- The same message ShopRung shows, including
(empty)for an empty code.line 30 - The date is passed in, not read from the clock inside. That is what makes the rule testable on any day.line 35
- Below the minimum is refused, so exactly the minimum is accepted: "$50.00 or more".line 36
- Rounding half a cent up in whole numbers (PRICE-6): 10% of 5045 cents is 504.5, and (50450 + 50) / 100 = 505. No floating point anywhere.line 42
package dev.algorung.shop;
import java.time.LocalDate;
/**
* ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Java.
* Every amount is whole cents in a long: $50.00 is 5000. No double, so no rounding surprises.
*/
public final class Pricing {
public static final long FREE_SHIPPING_FROM = 7_500; // $75.00, after the discount
public static final long SHIPPING = 499; // $4.99
/** The four numbers a cart shows. */
public record Totals(long subtotal, long discount, long shipping, long total) {}
private Pricing() {}
/** 1250 becomes "$12.50" (PRICE-1). */
public static String money(long cents) {
if (cents < 0) throw new IllegalArgumentException("cents must not be negative: " + cents);
return String.format("$%d.%02d", cents / 100, cents % 100);
}
/** $4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing. */
public static long shipping(long afterDiscount) {
if (afterDiscount == 0) return 0;
return afterDiscount >= FREE_SHIPPING_FROM ? 0 : SHIPPING;
}
/** Subtotal, discount, shipping and total (PRICE-10). A coupon that does not apply gives no discount (PRICE-8). */
public static Totals totals(long subtotal, Coupon coupon, LocalDate today) {
if (subtotal < 0) throw new IllegalArgumentException("subtotal must not be negative: " + subtotal);
long discount = 0;
if (coupon != null && coupon.problem(subtotal, today) == null) discount = coupon.discount(subtotal);
long shipping = shipping(subtotal - discount);
return new Totals(subtotal, discount, shipping, subtotal - discount + shipping);
}
} - A record: an immutable holder with a constructor, getters (
t.total()),equalsand a readabletoString, all generated.line 14 - A coupon that does not apply simply gives no discount (PRICE-8), like ShopRung's cart.line 34
- Shipping is decided on the amount **after** the discount.line 35
package dev.algorung.shop;
import static org.junit.jupiter.api.Assertions.assertEquals;
import dev.algorung.shop.Pricing.Totals;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class PricingTest {
// A fixed "today", so the expired-coupon rule gives the same answer on every day the tests run.
static final LocalDate TODAY = LocalDate.of(2026, 11, 30);
@Test
void moneyHasADollarSignAndTwoDecimals() {
assertEquals("$12.50", Pricing.money(1250));
assertEquals("$0.05", Pricing.money(5));
}
@ParameterizedTest(name = "{0} cents after the discount -> shipping {1}")
@CsvSource({
"7499, 499", // one cent below the edge
"7500, 0", // exactly on the edge: free
"7501, 0",
"1, 499",
"0, 0", // an empty cart ships nothing
})
void shippingIsFreeFrom75Dollars(long afterDiscount, long expected) {
assertEquals(expected, Pricing.shipping(afterDiscount));
}
@ParameterizedTest(name = "{0} cents with {1} -> -{2} +{3} = {4}")
@CsvSource({
// subtotal, coupon, discount, shipping, total
"5000, SAVE10, 500, 499, 4999", // 4 x Clean Code Notebook: SAVE10 on the edge
"4999, SAVE10, 0, 499, 5498", // the Hoodie: one cent short
"5045, save10, 505, 499, 5039", // 10% of $50.45 is $5.045: half a cent rounds up
"2000, FLAT5, 500, 499, 1999", // the T-Shirt: FLAT5 on the edge
"1999, FLAT5, 0, 499, 2498",
"7500, , 0, 0, 7500", // the Keyboard, no coupon: free shipping on the edge
"7499, , 0, 499, 7998",
"8000, FLAT5, 500, 0, 7500", // shipping is counted AFTER the discount
"7500, FLAT5, 500, 499, 7499", // ... so a coupon can lose free shipping
})
void cartTotals(long subtotal, String code, long discount, long shipping, long total) {
Coupon coupon = code == null ? null : Coupon.of(code);
Totals t = Pricing.totals(subtotal, coupon, TODAY);
assertEquals(new Totals(subtotal, discount, shipping, total), t);
}
} - A fixed date. A test that reads today's date can pass today and fail next year.line 13
- TC-06 from lab 1: SAVE10 exactly on its edge. In ShopRung this cart shows a total of $49.99.line 36
- Lower-case code (PRICE-2) and the rounding rule in one row: 5 sticker packs and the mouse.line 38
- An empty cell becomes
null. To pass an empty string instead, write''.line 41 - 4 T-shirts minus FLAT5 is exactly $75.00, so shipping is free. The next row shows the opposite.line 43
- One assertion compares all four numbers, because records compare field by field.line 49
"""ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Python.
Every amount is whole cents in an int: $50.00 is 5000. No float, so no rounding surprises.
"""
from dataclasses import dataclass
from datetime import date
FREE_SHIPPING_FROM = 7_500 # $75.00, after the discount
SHIPPING = 499 # $4.99
@dataclass(frozen=True)
class Coupon:
code: str
percent: bool
amount: int # a percent, or cents
min_subtotal: int # cents
expires_on: date | None = None
COUPONS = {
"SAVE10": Coupon("SAVE10", True, 10, 5_000), # 10% off from $50.00
"FLAT5": Coupon("FLAT5", False, 500, 2_000), # $5.00 off from $20.00
"WELCOME15": Coupon("WELCOME15", True, 15, 0, date(2025, 12, 31)), # expired
}
@dataclass(frozen=True)
class Totals:
subtotal: int
discount: int
shipping: int
total: int
def money(cents: int) -> str:
"""1250 becomes "$12.50" (PRICE-1)."""
if cents < 0:
raise ValueError(f"cents must not be negative: {cents}")
return f"${cents // 100}.{cents % 100:02d}"
def shipping(after_discount: int) -> int:
"""$4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing."""
if after_discount == 0:
return 0
return 0 if after_discount >= FREE_SHIPPING_FROM else SHIPPING
def coupon(code: str | None) -> Coupon:
"""Finds a coupon. Codes are not case-sensitive (PRICE-2); an unknown code is refused (PRICE-7)."""
c = (code or "").strip().upper()
if c not in COUPONS:
raise ValueError(f"No coupon called {c or '(empty)'}")
return COUPONS[c]
def problem(c: Coupon, subtotal: int, today: date) -> str | None:
"""Why the coupon cannot be used, or None when it can."""
if c.expires_on and today > c.expires_on:
return "This coupon has expired"
if subtotal < c.min_subtotal:
return f"This coupon needs a subtotal of at least {money(c.min_subtotal)}"
return None
def discount(c: Coupon, subtotal: int) -> int:
"""The discount in cents. A percentage rounds to the nearest cent, half a cent up (PRICE-6)."""
if c.percent:
return (subtotal * c.amount + 50) // 100
return min(c.amount, subtotal) # a fixed amount never makes the total negative
def totals(subtotal: int, c: Coupon | None, today: date) -> Totals:
"""Subtotal, discount, shipping and total (PRICE-10). A coupon that does not apply gives no discount (PRICE-8)."""
if subtotal < 0:
raise ValueError(f"subtotal must not be negative: {subtotal}")
off = discount(c, subtotal) if c and problem(c, subtotal, today) is None else 0
ship = shipping(subtotal - off)
return Totals(subtotal, off, ship, subtotal - off + ship) - A frozen dataclass is Python's record: generated
__init__,==and a readable repr, and it cannot be changed.line 12 - A dict from code to coupon, the Python version of the enum.line 21
- Not case-sensitive (PRICE-2), and spaces around the code are ignored, like the shop.line 52
- Half a cent rounds up, in whole numbers.
//is whole-number division.line 70 - Shipping is decided after the discount.line 79
from datetime import date
import pytest
from pricing import Totals, coupon, money, shipping, totals
# A fixed "today", so the expired-coupon rule gives the same answer on every day the tests run.
TODAY = date(2026, 11, 30)
def test_money_has_a_dollar_sign_and_two_decimals():
assert money(1250) == "$12.50"
assert money(5) == "$0.05"
@pytest.mark.parametrize("after_discount, expected", [
(7499, 499), # one cent below the edge
(7500, 0), # exactly on the edge: free
(7501, 0),
(1, 499),
(0, 0), # an empty cart ships nothing
])
def test_shipping_is_free_from_75_dollars(after_discount, expected):
assert shipping(after_discount) == expected
@pytest.mark.parametrize("subtotal, code, off, ship, total", [
(5000, "SAVE10", 500, 499, 4999), # 4 x Clean Code Notebook: SAVE10 on the edge
(4999, "SAVE10", 0, 499, 5498), # the Hoodie: one cent short
(5045, "save10", 505, 499, 5039), # 10% of $50.45 is $5.045: half a cent rounds up
(2000, "FLAT5", 500, 499, 1999), # the T-Shirt: FLAT5 on the edge
(1999, "FLAT5", 0, 499, 2498),
(7500, None, 0, 0, 7500), # the Keyboard, no coupon: free shipping on the edge
(7499, None, 0, 499, 7998),
(8000, "FLAT5", 500, 0, 7500), # shipping is counted AFTER the discount
(7500, "FLAT5", 500, 499, 7499), # ... so a coupon can lose free shipping
])
def test_cart_totals(subtotal, code, off, ship, total):
c = coupon(code) if code else None
assert totals(subtotal, c, TODAY) == Totals(subtotal, off, ship, total) - A fixed date, so the expired-coupon rule never depends on the day you run the tests.line 8
Nonemeans no coupon.line 33- Dataclasses compare field by field, so one assert checks all four numbers.line 40
Python version of this step:
mvn test [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running dev.algorung.shop.PricingTest [INFO] Tests run: 15, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PricingTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 15, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
pytest -q ............... [100%] 15 passed in 0.02s
Stuck on this step?
ParameterResolutionExceptionorArgumentConversionException- A row has a different number of values than the method has parameters, or a value that is not a number in a
longcolumn. Count the commas in the row the message names. cannot find symbol: class Totals- Check the import
import dev.algorung.shop.Pricing.Totals;at the top of the test.Totalslives insidePricing.
assertAll and assertThrows
See every wrong number at once, and test that bad input is refused.
Two more tools you will use in every test project:
assertAllruns every check inside it and reports all the failures together. A plain list ofassertEqualsstops at the first one, so you fix one number, run again, and find the next.assertThrowspasses only when the code throws the exception you name. It returns the exception, so you can also check its message.
The new tests check what a customer sees ($49.99, not 4999), that each coupon message matches ShopRung exactly, and that an impossible input, a negative subtotal, is refused instead of giving a strange total.
package dev.algorung.shop;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import dev.algorung.shop.Pricing.Totals;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class PricingTest {
// A fixed "today", so the expired-coupon rule gives the same answer on every day the tests run.
static final LocalDate TODAY = LocalDate.of(2026, 11, 30);
@Test
void moneyHasADollarSignAndTwoDecimals() {
assertEquals("$12.50", Pricing.money(1250));
assertEquals("$0.05", Pricing.money(5));
}
@ParameterizedTest(name = "{0} cents after the discount -> shipping {1}")
@CsvSource({
"7499, 499", // one cent below the edge
"7500, 0", // exactly on the edge: free
"7501, 0",
"1, 499",
"0, 0", // an empty cart ships nothing
})
void shippingIsFreeFrom75Dollars(long afterDiscount, long expected) {
assertEquals(expected, Pricing.shipping(afterDiscount));
}
@ParameterizedTest(name = "{0} cents with {1} -> -{2} +{3} = {4}")
@CsvSource({
// subtotal, coupon, discount, shipping, total
"5000, SAVE10, 500, 499, 4999", // 4 x Clean Code Notebook: SAVE10 on the edge
"4999, SAVE10, 0, 499, 5498", // the Hoodie: one cent short
"5045, save10, 505, 499, 5039", // 10% of $50.45 is $5.045: half a cent rounds up
"2000, FLAT5, 500, 499, 1999", // the T-Shirt: FLAT5 on the edge
"1999, FLAT5, 0, 499, 2498",
"7500, , 0, 0, 7500", // the Keyboard, no coupon: free shipping on the edge
"7499, , 0, 499, 7998",
"8000, FLAT5, 500, 0, 7500", // shipping is counted AFTER the discount
"7500, FLAT5, 500, 499, 7499", // ... so a coupon can lose free shipping
})
void cartTotals(long subtotal, String code, long discount, long shipping, long total) {
Coupon coupon = code == null ? null : Coupon.of(code);
Totals t = Pricing.totals(subtotal, coupon, TODAY);
assertEquals(new Totals(subtotal, discount, shipping, total), t);
}
@Test
void save10OnFourNotebooks() {
Totals t = Pricing.totals(4 * 1250, Coupon.SAVE10, TODAY);
assertAll("4 x Clean Code Notebook with SAVE10",
() -> assertEquals("$50.00", Pricing.money(t.subtotal())),
() -> assertEquals("$5.00", Pricing.money(t.discount())),
() -> assertEquals("$4.99", Pricing.money(t.shipping())),
() -> assertEquals("$49.99", Pricing.money(t.total())));
}
@Test
void anUnknownCouponIsRefusedByName() {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Coupon.of("SAVE20"));
assertEquals("No coupon called SAVE20", e.getMessage());
}
@Test
void couponMessagesMatchTheShop() {
assertAll(
() -> assertEquals("This coupon has expired", Coupon.WELCOME15.problem(10_000, TODAY)),
() -> assertEquals("This coupon needs a subtotal of at least $50.00", Coupon.SAVE10.problem(4_999, TODAY)),
() -> assertNull(Coupon.SAVE10.problem(5_000, TODAY)));
}
@Test
void aNegativeSubtotalIsRefused() {
assertThrows(IllegalArgumentException.class, () -> Pricing.totals(-1, null, TODAY));
}
} - The first argument is a heading for the failure report. Each lambda (
() -> ...) is one check.line 58 - The code under test goes in a lambda, so JUnit can run it and catch what it throws.line 67
- Check the message too: "it threw something" is a weak test.line 68
nullmeans "no problem": exactly $50.00 is accepted.line 76
from datetime import date
import pytest
from pricing import Totals, coupon, money, problem, shipping, totals
# A fixed "today", so the expired-coupon rule gives the same answer on every day the tests run.
TODAY = date(2026, 11, 30)
def test_money_has_a_dollar_sign_and_two_decimals():
assert money(1250) == "$12.50"
assert money(5) == "$0.05"
@pytest.mark.parametrize("after_discount, expected", [
(7499, 499), # one cent below the edge
(7500, 0), # exactly on the edge: free
(7501, 0),
(1, 499),
(0, 0), # an empty cart ships nothing
])
def test_shipping_is_free_from_75_dollars(after_discount, expected):
assert shipping(after_discount) == expected
@pytest.mark.parametrize("subtotal, code, off, ship, total", [
(5000, "SAVE10", 500, 499, 4999), # 4 x Clean Code Notebook: SAVE10 on the edge
(4999, "SAVE10", 0, 499, 5498), # the Hoodie: one cent short
(5045, "save10", 505, 499, 5039), # 10% of $50.45 is $5.045: half a cent rounds up
(2000, "FLAT5", 500, 499, 1999), # the T-Shirt: FLAT5 on the edge
(1999, "FLAT5", 0, 499, 2498),
(7500, None, 0, 0, 7500), # the Keyboard, no coupon: free shipping on the edge
(7499, None, 0, 499, 7998),
(8000, "FLAT5", 500, 0, 7500), # shipping is counted AFTER the discount
(7500, "FLAT5", 500, 499, 7499), # ... so a coupon can lose free shipping
])
def test_cart_totals(subtotal, code, off, ship, total):
c = coupon(code) if code else None
assert totals(subtotal, c, TODAY) == Totals(subtotal, off, ship, total)
def test_save10_on_four_notebooks():
t = totals(4 * 1250, coupon("SAVE10"), TODAY)
shown = {"subtotal": money(t.subtotal), "discount": money(t.discount), "shipping": money(t.shipping), "total": money(t.total)}
assert shown == {"subtotal": "$50.00", "discount": "$5.00", "shipping": "$4.99", "total": "$49.99"}
def test_an_unknown_coupon_is_refused_by_name():
with pytest.raises(ValueError) as e:
coupon("SAVE20")
assert str(e.value) == "No coupon called SAVE20"
def test_coupon_messages_match_the_shop():
assert problem(coupon("WELCOME15"), 10_000, TODAY) == "This coupon has expired"
assert problem(coupon("SAVE10"), 4_999, TODAY) == "This coupon needs a subtotal of at least $50.00"
assert problem(coupon("SAVE10"), 5_000, TODAY) is None
def test_a_negative_subtotal_is_refused():
with pytest.raises(ValueError):
totals(-1, None, TODAY) - pytest has no
assertAll. Compare one dict instead: when it fails, pytest lists every key that differs.line 45 - The pytest version of
assertThrows. The test fails if the block does not raiseValueError.line 50 e.valueis the exception; check its message.line 52
Python version of this step:
mvn test [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running dev.algorung.shop.PricingTest [INFO] Tests run: 19, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PricingTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 19, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
pytest -q ................... [100%] 19 passed in 0.03s
Watch your tests catch a bug
Break the code on purpose, see exactly which tests fail, then put it back.
A test you have never seen fail might not be able to fail. So break the code: in Coupon.java, change subtotal < minSubtotal to subtotal <= minSubtotal. One character. Now a coupon needs more than its minimum, which is ShopRung's coupon-boundary bug.
Run the tests. Four fail, and each failure says what was expected and what came back. Look at which ones: the $50.00 and $20.00 rows, the four-notebook cart and the message check. The $49.99 and $19.99 rows still pass. Only the tests sitting exactly on the boundary catch this bug.
Change <= back to < and run mvn test again: 19 tests pass.
/** Why this coupon cannot be used, or null when it can. */
public String problem(long subtotal, LocalDate today) {
if (expiresOn != null && today.isAfter(expiresOn)) return "This coupon has expired";
if (subtotal <= minSubtotal) return "This coupon needs a subtotal of at least " + Pricing.money(minSubtotal);
return null;
} - The bug:
<=instead of<. Put it in, run the tests, then take it out again.line 4
def problem(c: Coupon, subtotal: int, today: date) -> str | None:
"""Why the coupon cannot be used, or None when it can."""
if c.expires_on and today > c.expires_on:
return "This coupon has expired"
if subtotal <= c.min_subtotal:
return f"This coupon needs a subtotal of at least {money(c.min_subtotal)}"
return None - The bug:
<=instead of<. Put it in, run pytest, then take it out again.line 5
Python version of this step:
mvn test [ERROR] Tests run: 19, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 0.07 s <<< FAILURE! -- in dev.algorung.shop.PricingTest ... [ERROR] Failures: [ERROR] PricingTest.cartTotals:52 expected: <Totals[subtotal=5000, discount=500, shipping=499, total=4999]> but was: <Totals[subtotal=5000, discount=0, shipping=499, total=5499]> [ERROR] PricingTest.cartTotals:52 expected: <Totals[subtotal=2000, discount=500, shipping=499, total=1999]> but was: <Totals[subtotal=2000, discount=0, shipping=499, total=2499]> [ERROR] PricingTest.couponMessagesMatchTheShop:73 Multiple Failures (1 failure) org.opentest4j.AssertionFailedError: expected: <null> but was: <This coupon needs a subtotal of at least $50.00> [ERROR] PricingTest.save10OnFourNotebooks:58 4 x Clean Code Notebook with SAVE10 (2 failures) org.opentest4j.AssertionFailedError: expected: <$5.00> but was: <$0.00> org.opentest4j.AssertionFailedError: expected: <$49.99> but was: <$54.99> [INFO] [ERROR] Tests run: 19, Failures: 4, Errors: 0, Skipped: 0 [INFO] BUILD FAILURE
pytest -q FAILED test_pricing.py::test_cart_totals[5000-SAVE10-500-499-4999] - Assertio... FAILED test_pricing.py::test_cart_totals[2000-FLAT5-500-499-1999] - Assertion... FAILED test_pricing.py::test_save10_on_four_notebooks - AssertionError: asser... FAILED test_pricing.py::test_coupon_messages_match_the_shop - AssertionError:... 4 failed, 15 passed in 0.04s
Stuck on this step?
- All 19 tests still pass with the bug in
- You edited a copy, or the file is not saved. Save
Coupon.javaand runmvn testagain; Maven recompiles changed files by itself.
The SDET interview programs, with tests
Reverse the words, find duplicates with a Map, check a palindrome and count characters, each with edge-case tests.
SDET interviews almost always include a short coding round, and these four programs come up again and again. What lifts an answer is the same thing that lifts a test suite: the edge cases. Empty text, one word, extra spaces, upper and lower case, punctuation.
- Reverse the words: split on any run of spaces, then walk the array backwards.
- Duplicates: count with a
Map, one pass, O(n). ALinkedHashMapkeeps the order items first appeared. The test data is ShopRung SKUs, like a duplicate check on an order export. - Palindrome: two pointers walking in from both ends, skipping anything that is not a letter or digit. No new string needed.
- Count characters:
Map.mergeadds 1 to the count, or puts 1 if the character is new.
Write the tests first if you like: they are the interviewer's follow-up questions written down. @ValueSource is the simple sibling of @CsvSource: one value per test.
package dev.algorung.shop;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** The four programs SDET interviews ask for most, written the way you would on a whiteboard. */
public final class Puzzles {
private Puzzles() {}
/** " hello big world " becomes "world big hello". Extra spaces are dropped. */
public static String reverseWords(String text) {
String[] words = text.trim().split("\\s+");
StringBuilder out = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
out.append(words[i]);
if (i > 0) out.append(' ');
}
return out.toString();
}
/** The items that appear more than once, in the order they first appeared. */
public static List<String> duplicates(List<String> items) {
Map<String, Integer> counts = new LinkedHashMap<>();
for (String item : items) {
counts.merge(item, 1, Integer::sum);
}
List<String> result = new ArrayList<>();
for (Map.Entry<String, Integer> e : counts.entrySet()) {
if (e.getValue() > 1) result.add(e.getKey());
}
return result;
}
/** True when the letters and digits read the same both ways, ignoring case: "Never odd or even". */
public static boolean isPalindrome(String text) {
int left = 0, right = text.length() - 1;
while (left < right) {
char a = text.charAt(left), b = text.charAt(right);
if (!Character.isLetterOrDigit(a)) { left++; continue; }
if (!Character.isLetterOrDigit(b)) { right--; continue; }
if (Character.toLowerCase(a) != Character.toLowerCase(b)) return false;
left++;
right--;
}
return true;
}
/** How many times each character appears, spaces left out: "hello" gives {h=1, e=1, l=2, o=1}. */
public static Map<Character, Integer> countCharacters(String text) {
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : text.toCharArray()) {
if (c != ' ') counts.merge(c, 1, Integer::sum);
}
return counts;
}
} "\\s+"is the regular expression\s+: one or more whitespace characters (spaces, tabs, new lines).trim()first, or leading spaces give an empty first word.line 14- If the key is new, store 1; otherwise add 1 to what is there. One line instead of an
if.line 27 - Two pointers: O(n) time and no extra memory. Interviewers often ask for this after a first "reverse the string and compare" answer.line 38
- Compare ignoring case, so "Never odd or even" counts.line 43
package dev.algorung.shop;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
class PuzzlesTest {
@ParameterizedTest(name = "[{0}] -> [{1}]")
@CsvSource({
"'hello big world', 'world big hello'",
"' hello big world ', 'world big hello'", // extra spaces
"one, one", // a single word
"'', ''", // empty text
})
void reverseWords(String text, String expected) {
assertEquals(expected, Puzzles.reverseWords(text));
}
@Test
void reverseWordsRefusesNull() {
assertThrows(NullPointerException.class, () -> Puzzles.reverseWords(null));
}
@Test
void duplicateSkusInFirstSeenOrder() {
List<String> skus = List.of("BK-101", "MG-201", "BK-101", "ST-501", "MG-201", "BK-101");
assertEquals(List.of("BK-101", "MG-201"), Puzzles.duplicates(skus));
}
@Test
void noDuplicates() {
assertEquals(List.of(), Puzzles.duplicates(List.of("BK-101", "MG-201")));
assertEquals(List.of(), Puzzles.duplicates(List.of()));
}
@ParameterizedTest
@ValueSource(strings = {"racecar", "Never odd or even", "A man, a plan, a canal: Panama", "a", ""})
void palindromes(String text) {
assertTrue(Puzzles.isPalindrome(text));
}
@ParameterizedTest
@ValueSource(strings = {"ShopRung", "ab", "abca"})
void notPalindromes(String text) {
assertFalse(Puzzles.isPalindrome(text));
}
@Test
void countCharacters() {
assertEquals(Map.of('h', 1, 'e', 1, 'l', 2, 'o', 1), Puzzles.countCharacters("hello"));
assertEquals(Map.of('a', 2, 'b', 1), Puzzles.countCharacters("a b a"));
assertEquals(Map.of(), Puzzles.countCharacters(""));
}
} - Single quotes keep the spaces inside a CSV value. Without them JUnit trims each value.line 20
''is an empty string. An empty cell without quotes would benull.line 22- Decide what
nullshould do and pin it down with a test, so nobody changes it by accident.line 30 - One test per value.
"a"and""are the edge cases: both read the same backwards.line 46 - Two maps are equal when they hold the same pairs, in any order.line 59
"""The four programs SDET interviews ask for most, written the way you would on a whiteboard."""
def reverse_words(text: str) -> str:
""" " hello big world " becomes "world big hello". Extra spaces are dropped."""
words = text.split()
out = []
for i in range(len(words) - 1, -1, -1):
out.append(words[i])
return " ".join(out)
def duplicates(items: list[str]) -> list[str]:
"""The items that appear more than once, in the order they first appeared."""
counts: dict[str, int] = {} # a dict keeps insertion order
for item in items:
counts[item] = counts.get(item, 0) + 1
return [item for item, n in counts.items() if n > 1]
def is_palindrome(text: str) -> bool:
"""True when the letters and digits read the same both ways, ignoring case: "Never odd or even"."""
left, right = 0, len(text) - 1
while left < right:
a, b = text[left], text[right]
if not a.isalnum():
left += 1
elif not b.isalnum():
right -= 1
elif a.lower() != b.lower():
return False
else:
left += 1
right -= 1
return True
def count_characters(text: str) -> dict[str, int]:
"""How many times each character appears, spaces left out: "hello" gives {h: 1, e: 1, l: 2, o: 1}."""
counts: dict[str, int] = {}
for c in text:
if c != " ":
counts[c] = counts.get(c, 0) + 1
return counts split()with no argument splits on any run of whitespace and drops empty pieces, so extra spaces need no special care.line 6- The count so far (0 if new) plus one.
collections.Counterdoes this in one call; interviewers usually want to see the loop first.line 17 - Two pointers from both ends: O(n) time, no new string.line 23
import pytest
from puzzles import count_characters, duplicates, is_palindrome, reverse_words
@pytest.mark.parametrize("text, expected", [
("hello big world", "world big hello"),
(" hello big world ", "world big hello"), # extra spaces
("one", "one"), # a single word
("", ""), # empty text
])
def test_reverse_words(text, expected):
assert reverse_words(text) == expected
def test_reverse_words_treats_tabs_and_new_lines_as_spaces():
assert reverse_words("a\tb\nc") == "c b a"
def test_duplicate_skus_in_first_seen_order():
skus = ["BK-101", "MG-201", "BK-101", "ST-501", "MG-201", "BK-101"]
assert duplicates(skus) == ["BK-101", "MG-201"]
def test_no_duplicates():
assert duplicates(["BK-101", "MG-201"]) == []
assert duplicates([]) == []
@pytest.mark.parametrize("text", ["racecar", "Never odd or even", "A man, a plan, a canal: Panama", "a", ""])
def test_palindromes(text):
assert is_palindrome(text)
@pytest.mark.parametrize("text", ["ShopRung", "ab", "abca"])
def test_not_palindromes(text):
assert not is_palindrome(text)
def test_count_characters():
assert count_characters("hello") == {"h": 1, "e": 1, "l": 2, "o": 1}
assert count_characters("a b a") == {"a": 2, "b": 1}
assert count_characters("") == {} - Extra spaces at the start, middle and end.line 8
- Tabs and new lines count as spaces too.line 17
- With one argument, the cases are a plain list.line 30
Python version of this step:
mvn test [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running dev.algorung.shop.PricingTest [INFO] Tests run: 19, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PricingTest [INFO] Running dev.algorung.shop.PuzzlesTest [INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PuzzlesTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 35, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
pytest -q ................................... [100%] 35 passed in 0.04s
Stuck on this step?
reverseWordsreturns the words with a space at the start- You split before trimming.
" hello".split("\\s+")gives["", "hello"]. Calltrim()first.
A first API check of the running ShopRung
Call the real shop over HTTP from a JUnit test, and skip cleanly when it is not running.
Unit tests check your copy of the rules. This test checks the real shop, from the outside, the way a customer's browser talks to it: send an HTTP request, check the status code and the body. That is a black-box test: it knows nothing about ShopRung's code.
Java has had an HTTP client built in since Java 11, java.net.http.HttpClient, so you need no new library. Later labs use REST Assured, which reads more nicely; this one shows what any HTTP test does underneath.
An API test needs the server running. If it is not, the tests should be skipped, not failed: a failure means "the shop is broken", and that would be a lie. JUnit's Assumptions.assumeTrue does this: when the assumption is false, the test is reported as skipped with your message.
First run the tests with ShopRung stopped and see five skipped tests. Then start ShopRung as in lab 1 and run them again. ShopRung on another port? Set SHOPRUNG_URL, for example SHOPRUNG_URL=http://localhost:8081 mvn test (PowerShell: $env:SHOPRUNG_URL="http://localhost:8081"; mvn test).
package dev.algorung.shop;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Black-box checks against the running ShopRung. Every test is skipped when ShopRung is not running. */
class ShopRungApiTest {
static final String BASE = System.getenv().getOrDefault("SHOPRUNG_URL", "http://localhost:8080");
static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
static HttpResponse<String> get(String path) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create(BASE + path))
.timeout(Duration.ofSeconds(5))
.GET()
.build();
return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
}
static HttpResponse<String> post(String path, String json) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create(BASE + path))
.timeout(Duration.ofSeconds(5))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
}
static boolean running;
@BeforeAll
static void checkShopRungOnce() {
try {
running = get("/api/health").statusCode() == 200;
} catch (Exception e) {
running = false; // connection refused: nothing is listening on that port
}
}
@BeforeEach
void needsShopRung() {
assumeTrue(running, "ShopRung is not running at " + BASE + ". Start it with npm start.");
}
@Test
void healthSaysUp() throws Exception {
HttpResponse<String> r = get("/api/health");
assertEquals(200, r.statusCode());
assertTrue(r.body().contains("\"status\":\"UP\""), r.body());
}
@Test
void searchIsNotCaseSensitive() throws Exception { // SRCH-2
String lower = get("/api/products?q=mug").body();
String upper = get("/api/products?q=MUG").body();
assertTrue(lower.contains("\"count\":2"), lower);
assertEquals(lower, upper);
}
@Test
void aOneLetterSearchIsRefused() throws Exception { // SRCH-3, NF-4
HttpResponse<String> r = get("/api/products?q=m");
assertEquals(400, r.statusCode());
assertTrue(r.body().contains("\"error\":\"query_too_short\""), r.body());
}
@Test
void theRedMugIsOutOfStock() throws Exception { // CART-4: product 5 has stock 0
String body = get("/api/products/5").body();
assertTrue(body.contains("\"stock\":0") && body.contains("\"inStock\":false"), body);
}
@Test
void aWrongPasswordGetsTheSameMessage() throws Exception { // ACC-6
HttpResponse<String> r = post("/api/auth/login", "{\"email\":\"alice@shoprung.test\",\"password\":\"wrong-1\"}");
assertEquals(401, r.statusCode());
assertTrue(r.body().contains("Email or password is wrong"), r.body());
}
} - The address comes from an environment variable, with ShopRung's default as the fallback. The same tests then run against any copy of the shop.line 18
- Always set timeouts. Without them a test against a hung server waits forever and blocks the whole run.line 19
- Read the response body as text.line 26
- The request body, here a small JSON object written by hand.line 33
- Runs once, before any test in the class: one health check instead of five.line 40
- Runs before each test. When ShopRung is down, each test is reported as skipped with this message.line 51
- Two products have "mug" in their name: Green Build Mug and Red Build Mug.
containson raw JSON is fine for a first check; the REST Assured lab reads JSON properly.line 65 - SRCH-2: "mug" and "MUG" must give the same answer.line 66
- A one-letter search is refused with 400 and
query_too_short(SRCH-3), as JSON (NF-4).line 72 - ACC-6: a wrong password gets 401 and the same message as an unknown email.line 85
"""Black-box checks against the running ShopRung. Every test is skipped when ShopRung is not running."""
import json
import os
import urllib.error
import urllib.request
import pytest
BASE = os.environ.get("SHOPRUNG_URL", "http://localhost:8080")
def call(method, path, body=None):
"""Sends one request and returns (status code, JSON body). Python's standard library only."""
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(BASE + path, data=data, method=method, headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(request, timeout=5) as response:
return response.status, json.loads(response.read())
except urllib.error.HTTPError as e: # 4xx and 5xx arrive as an exception: read the body anyway
return e.code, json.loads(e.read())
@pytest.fixture(scope="module", autouse=True)
def shoprung_is_running():
try:
call("GET", "/api/health")
except OSError: # connection refused: nothing is listening on that port
pytest.skip(f"ShopRung is not running at {BASE}. Start it with npm start.")
def test_health_says_up():
status, body = call("GET", "/api/health")
assert status == 200
assert body["status"] == "UP"
def test_search_is_not_case_sensitive(): # SRCH-2
_, lower = call("GET", "/api/products?q=mug")
_, upper = call("GET", "/api/products?q=MUG")
assert lower["count"] == 2
assert lower == upper
def test_a_one_letter_search_is_refused(): # SRCH-3, NF-4
status, body = call("GET", "/api/products?q=m")
assert status == 400
assert body["error"] == "query_too_short"
def test_the_red_mug_is_out_of_stock(): # CART-4: product 5 has stock 0
_, body = call("GET", "/api/products/5")
assert body["stock"] == 0
assert body["inStock"] is False
def test_a_wrong_password_gets_the_same_message(): # ACC-6
status, body = call("POST", "/api/auth/login", {"email": "alice@shoprung.test", "password": "wrong-1"})
assert status == 401
assert body["message"] == "Email or password is wrong" - The address from an environment variable, with ShopRung's default as the fallback.line 9
urllibcomes with Python, so nothing to install. Always pass a timeout.line 17urllibraises an exception for 4xx and 5xx. The error still carries the status and the JSON body, so read them and return them like a normal answer.line 19- A fixture that runs once for this file (
scope="module") before its tests, without being asked for (autouse).line 23 - Connection refused is an
OSError. pytest then skips every test in the file with the message.line 27 - Python reads the JSON into dicts, so you can check fields directly.line 40
Python version of this step:
# ShopRung stopped:
mvn test
# then start ShopRung in another terminal and run again:
mvn test [INFO] Running dev.algorung.shop.ShopRungApiTest [WARNING] Tests run: 5, Failures: 0, Errors: 0, Skipped: 5, Time elapsed: 0.04 s -- in dev.algorung.shop.ShopRungApiTest ... [WARNING] Tests run: 40, Failures: 0, Errors: 0, Skipped: 5 [INFO] BUILD SUCCESS (second run, ShopRung running) [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.3 s -- in dev.algorung.shop.ShopRungApiTest ... [INFO] Tests run: 40, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
# ShopRung stopped:
pytest -rs
# then start ShopRung in another terminal and run again:
pytest test_pricing.py ................... [ 47%] test_puzzles.py ................ [ 87%] test_shoprung_api.py sssss [100%] SKIPPED [1] test_shoprung_api.py:31: ShopRung is not running at http://localhost:8080. Start it with npm start. ... ======================== 35 passed, 5 skipped in 0.08s ========================= (second run, ShopRung running) 40 passed in 0.12s
Stuck on this step?
- The API tests are skipped although ShopRung is running
- Check the port. Open http://localhost:8080/api/health in a browser: it must show
"status":"UP". If ShopRung runs on another port, setSHOPRUNG_URLas in the text above. searchIsNotCaseSensitivefails with"count":0- The
search-casebug is switched on. Check the yellow bar in the shop, or run the bug switch command with"enabled":[]to turn every bug off.
Run part of the suite, and read the report
Run one class or one test, and find the report files that CI reads.
When one test fails you do not want to run everything. Maven's -Dtest picks a class, or one method after #. Keep the quotes: they make the command work the same in zsh, bash and PowerShell.
Every run also writes a report to target/surefire-reports/: a .txt summary per class, and a TEST-<class>.xml file in the JUnit XML format. Every CI system (GitHub Actions, Jenkins, GitLab) reads that XML to show which tests failed. pytest writes the same format with --junitxml.
mvn test "-Dtest=PuzzlesTest"
mvn test "-Dtest=PricingTest#cartTotals"
ls target/surefire-reports [INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0 ... [INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0 ... TEST-dev.algorung.shop.PricingTest.xml dev.algorung.shop.PricingTest.txt
pytest -k palindrome -v
pytest --junitxml=report.xml collected 40 items / 32 deselected / 8 selected test_puzzles.py::test_palindromes[racecar] PASSED [ 12%] ... test_puzzles.py::test_not_palindromes[abca] PASSED [100%] ======================= 8 passed, 32 deselected in 0.04s ======================= ... - generated xml file: .../report.xml - 40 passed in 0.09s
Stuck on this step?
No tests matching pattern "PricingTest#cartTotals" were executed!- Check the spelling: class and method names are case-sensitive. Use the method name, not the display name of a row.
Check it works
Two checks. First, with ShopRung running and no bugs on, the whole suite passes: 40 tests, no failures, none skipped.
Second, prove the API test can fail. Switch on ShopRung's search-case bug (search becomes case-sensitive), run the suite, and exactly one test fails: searchIsNotCaseSensitive (Python: test_search_is_not_case_sensitive), because "mug" now finds nothing. Then switch the bugs off and run again: all green.
# bug on (macOS and Linux; PowerShell commands are in the Windows tab below)
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["search-case"]}'
mvn test # or: pytest
# bugs off
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["search-case"]}'curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["search-case"]}'Invoke-RestMethod -Method Post http://localhost:8080/api/test/bugs -ContentType "application/json" -Body '{"enabled":["search-case"]}' {"mystery":false,"active":["search-case"],"known":{...}}
mvn test:
[ERROR] Failures:
[ERROR] ShopRungApiTest.searchIsNotCaseSensitive:65 {"count":0,"items":[]} ==> expected: <true> but was: <false>
[ERROR] Tests run: 40, Failures: 1, Errors: 0, Skipped: 0
pytest:
FAILED test_shoprung_api.py::test_search_is_not_case_sensitive - assert 0 == 2
1 failed, 39 passed in 0.08s Troubleshooting
error: release version 21 not supported
Maven is running with an older Java. Run mvn -v and look at Java version. Set JAVA_HOME to your Java 21 (macOS: export JAVA_HOME=$(/usr/libexec/java_home -v 21)), open a new terminal and try again.
Could not resolve dependencies or Could not transfer artifact on the first run
Maven could not download from Maven Central. Check your internet connection. At work, a company proxy or an internal repository (Nexus, Artifactory) may be required: ask for the settings.xml your team uses and put it in ~/.m2/.
Tests pass in the IDE but mvn test finds none (or the other way round)
Check the class name ends in Test and the file is under src/test/java. Surefire only runs classes that match *Test, Test*, *Tests or *TestCase. Your IDE may run anything you click on.
The IDE shows JUnit imports in red
The IDE has not loaded the pom.xml yet. IntelliJ: right-click pom.xml, then Maven > Sync Project (older versions: Reload project). VS Code: open the folder that contains pom.xml, not a parent folder.
Python: pytest: command not found
The virtual environment is not active in this terminal. Run source .venv/bin/activate (Windows: .venv\Scripts\Activate.ps1); your prompt then starts with (.venv).
What changes in production
- Pin every version in the pom.xml (or requirements file), plugins included. Many teams also commit the Maven Wrapper (
mvn wrapper:wrappercreatesmvnw), so everyone and CI build with the exact same Maven. - Unit tests and API tests run at different times. Unit tests run on every build and need nothing. API tests need a running app, so CI starts it first, or they move to a separate stage (with Maven, often the Failsafe plugin and classes named
*IT). - Money is never a
double. Real shops use whole cents in alongorBigDecimalwith an explicit rounding mode. A test suite that pins the rounding rule, like yours, is how teams catch a rounding change before customers do. - The JUnit XML report is the contract with CI. GitHub Actions, Jenkins and GitLab all read
target/surefire-reports, show failed tests by name and keep their history.
Interview angle
“How would you test a function that applies a discount coupon, and how do you set up the project?”
I start from the rules: the minimum subtotal, the amount or percentage, the rounding, the expiry date and the messages. Each rule has a boundary, so my cases sit on it and one cent either side: $49.99, $50.00 and $50.45 to check rounding, plus an expired code, a lower-case code and an unknown code. I keep money in whole cents so there are no floating-point surprises, and I pass today's date in so the expiry test never depends on the clock. In JUnit 5 that is a @ParameterizedTest with a @CsvSource table, assertThrows for invalid input and assertAll when one case checks several values. The project is plain Maven with pinned JUnit and Surefire versions, and API tests against the running service are skipped with an assumption when it is down, so a red build always means a real failure.
Clean up
Keep the project: the next lab puts it in Git and opens a pull request. Stop ShopRung with Ctrl+C when you are done, and make sure every bug is off.
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'Invoke-RestMethod -Method Post http://localhost:8080/api/test/bugs -ContentType "application/json" -Body '{"enabled":[]}' Practice
These run in your browser and check your answer.
First character that does not repeat
Another favourite interview question. Write first_unique(text) that returns the first character that appears exactly once in text, or None if there is none. Case matters: "A" and "a" are different. Count first, then walk the text again.
def first_unique(text):
counts = {}
for c in text:
counts[c] = counts.get(c, 0) + 1
# your code here: walk the text again
return text[0]
print(first_unique("swiss"))
Hint
Loop over `text` a second time and return the first `c` whose count is 1. After the loop, return `None`.
How much more for free shipping?
ShopRung could tell customers how far they are from free shipping. Write cents_to_free_shipping(after_discount): how many more cents the cart needs (after the discount) to reach free shipping at 7500 cents. Return 0 when it is already free. Mind the boundary: at exactly 7500 the answer is 0.
FREE_SHIPPING_FROM = 7500
def cents_to_free_shipping(after_discount):
return FREE_SHIPPING_FROM - after_discount
print(cents_to_free_shipping(7499))
Hint
The difference can go below zero. `max(0, ...)` keeps it at zero.
The full project
Every file from this lab, as it is after the last step.