QA and Test Automation · Lab 22 of 35
Build Test Framework Layers With Allure Reports: Java and Python
Turn loose tests into a small framework for ShopRung's API: a config layer, a client where every call is an Allure step with the request and response attached, named test data, a base test, and labelled tests. 6 tests and an Allure report that explains its own failures.
⏱ 75 minIntermediate💸 Free8 stepsJava + Python
Java 21 + MavenJUnit 5.11Allure 2.29 (allure-junit5)Python 3.12 + pytest + allure-pytest 2.13 (second path)Allure CLI 2.32ShopRung
Overview video
What you will build
A small, layered test framework for ShopRung's API, the shape most SDET teams use, and a report anyone can read:
- Config: the base URL, timeouts and passwords from environment variables, with safe defaults.
- Client: every ShopRung call in one class. Each call is an Allure step with the request and response attached.
- Test data: named carts (
CART_AT_50,CART_AT_74_99,CART_AT_75) so the numbers live in one place. - Base test / fixtures: seed data before every test, and logged-in clients by name.
- 6 tests with Allure features, stories and severity: SAVE10 at $50.00, expired WELCOME15, both sides of free shipping, stock after an order, and Bob opening Alice's order.
Five ShopRung bugs each fail exactly one test, and the Allure report shows which step failed and the server's own answer.
Before you start
- The episodes behind it: Framework architecture, Design patterns for testers and Reporting and logging.
- Java 21 and Maven from your first Java test project, or Python 3.12 from the pytest API lab.
- ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start, and leave it running.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Install the Allure command line
The Allure CLI turns raw results into the HTML report. It needs Java 8 or newer (the Python path needs it too). On a Mac, Homebrew is easiest; anywhere with Node.js, the npm package works.
brew install allure
allure --versionnpm install -g allure-commandline
allure --versionnpm install -g allure-commandline
allure --version 2.32.0
S3Make the project folders
Java: a framework package for the layers and a tests package for the tests. Python: the same two folders and a virtual environment.
# Java
mkdir -p shoprung-framework/src/test/java/dev/algorung/framework shoprung-framework/src/test/java/dev/algorung/tests shoprung-framework/src/test/resources
# Python
mkdir -p shoprung-framework-py/framework shoprung-framework-py/tests && cd shoprung-framework-py && python3 -m venv .venv && source .venv/bin/activate# Java
mkdir -p shoprung-framework/src/test/java/dev/algorung/framework shoprung-framework/src/test/java/dev/algorung/tests shoprung-framework/src/test/resources
# Python
mkdir -p shoprung-framework-py/framework shoprung-framework-py/tests && cd shoprung-framework-py && python3 -m venv .venv && source .venv/bin/activate# Java
mkdir shoprung-framework\src\test\java\dev\algorung\framework, shoprung-framework\src\test\java\dev\algorung\tests, shoprung-framework\src\test\resources
# Python
mkdir shoprung-framework-py\framework, shoprung-framework-py\tests; cd shoprung-framework-py; py -m venv .venv; .venv\Scripts\Activate.ps1 The build file and where results go
JUnit 5, the Allure adapter and a JSON library; raw results in one folder.
Create pom.xml. The Allure BOM keeps Allure modules on one version, and allure-junit5 is the adapter: while JUnit runs, it writes one JSON file per test (plus attachments) into a results folder. allure.properties names that folder: target/allure-results.
Python: allure-pytest is the adapter for pytest. In pytest.ini, --alluredir=allure-results turns it on and --clean-alluredir empties the folder first, so old runs never mix into a new report. The smoke marker is declared so pytest accepts it.
<?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-framework</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-bom</artifactId>
<version>2.29.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
</plugin>
</plugins>
</build>
</project> - Allure 2.29 for every Allure module below.line 26
- The adapter: JUnit 5 events become Allure result files.line 42
allure.results.directory=target/allure-results pytest==8.3.4
httpx==0.28.1
allure-pytest==2.13.5 [pytest]
pythonpath = .
addopts = -q --alluredir=allure-results --clean-alluredir
markers =
smoke: the fastest, most important checks - Write raw Allure results on every run.line 3
- Registered markers avoid pytest's "unknown mark" warning.line 5
Python version of this step:
mvn -q test-compile (no output: the project compiles)
pip install -r requirements.txt Successfully installed allure-pytest-2.13.5 allure-python-commons-2.13.5 ... httpx-0.28.1 ... pytest-8.3.4
Layer 1: configuration
One place that says where the shop is and how to log in.
Create Config.java (Python: framework/config.py, plus an empty framework/__init__.py). Everything that changes between a laptop, CI and staging comes from environment variables: BASE_URL, TIMEOUT_SECONDS, and the passwords. The defaults match a local ShopRung, so the suite runs with no setup.
Tests never read environment variables themselves. If you later add a config file or a secrets manager, only this layer changes.
package dev.algorung.framework;
import java.util.Map;
/** Layer 1, configuration: where the shop is and who logs in. Values come from the environment, with safe defaults. */
public record Config(String baseUrl, int timeoutSeconds) {
public static final Map<String, String[]> USERS = Map.of(
"alice", new String[] {"alice@shoprung.test", env("ALICE_PASSWORD", "Alice123!")},
"bob", new String[] {"bob@shoprung.test", env("BOB_PASSWORD", "Bob12345!")});
public static Config load() {
return new Config(env("BASE_URL", "http://localhost:8080"), Integer.parseInt(env("TIMEOUT_SECONDS", "10")));
}
private static String env(String name, String fallback) {
return System.getenv().getOrDefault(name, fallback);
}
} - In CI, the real value comes from a secret; the default is ShopRung's public practice password.line 9
- Read once, passed to the layers that need it.line 12
"""The ShopRung test framework: config, client and data layers.""" """Layer 1, configuration: where the shop is and who logs in. Values come from the environment, with safe defaults."""
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
base_url: str
timeout: float
def load() -> Config:
return Config(
base_url=os.getenv("BASE_URL", "http://localhost:8080"),
timeout=float(os.getenv("TIMEOUT_SECONDS", "10")),
)
USERS = {
"alice": ("alice@shoprung.test", os.getenv("ALICE_PASSWORD", "Alice123!")),
"bob": ("bob@shoprung.test", os.getenv("BOB_PASSWORD", "Bob12345!")),
} - Point the suite elsewhere with
BASE_URL=... pytest.line 14
Python version of this step:
Layer 2: a client that reports itself
Every API call wrapped in an Allure step, with the request and response attached.
Create ShopRungClient.java (Python: framework/client.py). All HTTP details live here, and its private call method does one extra job: it wraps each request in Allure.step with a readable title ("Apply coupon save10") and attaches what was sent and what came back.
This is the trick that makes reports useful. Tests will not mention Allure for each call, yet every failed test will show the exact sequence of calls and ShopRung's answers, with no extra logging code.
package dev.algorung.framework;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.qameta.allure.Allure;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
/**
* Layer 2, the API client: every ShopRung call in one place. Each call is an Allure step with the request and
* response attached, so a failed test's report shows exactly what was sent and what came back.
*/
public class ShopRungClient {
private static final ObjectMapper JSON = new ObjectMapper();
private final Config config;
private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
private final Map<String, Integer> products = new HashMap<>();
private String token;
/** A status code and a parsed JSON body. */
public record Response(int status, JsonNode body) {
}
public ShopRungClient(Config config) {
this.config = config;
for (JsonNode p : call("Load the product list", "GET", "/api/products", null).body().get("items")) {
products.put(p.get("name").asText(), p.get("id").asInt());
}
}
public void reset() {
call("Reset ShopRung to its seed data", "POST", "/api/test/reset", null);
}
public ShopRungClient logIn(String who) {
String[] user = Config.USERS.get(who);
Response r = call("Log in as " + who, "POST", "/api/auth/login", Map.of("email", user[0], "password", user[1]));
if (r.status() != 200) {
throw new IllegalStateException("Login failed for " + who + ": " + r.body());
}
token = r.body().get("token").asText();
return this;
}
public Response add(String name, int quantity) {
return call("Add " + quantity + " x " + name, "POST", "/api/cart/items",
Map.of("productId", products.get(name), "quantity", quantity));
}
public Response applyCoupon(String code) {
return call("Apply coupon " + code, "POST", "/api/cart/coupon", Map.of("code", code));
}
public JsonNode cart() {
return call("Read the cart", "GET", "/api/cart", null).body();
}
public Response placeOrder() {
return call("Place the order", "POST", "/api/orders", null);
}
public Response order(long id) {
return call("Open order " + id, "GET", "/api/orders/" + id, null);
}
public int stockOf(String name) {
for (JsonNode p : call("Read stock of " + name, "GET", "/api/products", null).body().get("items")) {
if (p.get("name").asText().equals(name)) {
return p.get("stock").asInt();
}
}
throw new IllegalArgumentException("No product called " + name);
}
private Response call(String title, String method, String path, Object body) {
return Allure.step(title, () -> {
String json = body == null ? null : JSON.writeValueAsString(body);
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(config.baseUrl() + path))
.timeout(Duration.ofSeconds(config.timeoutSeconds()))
.header("Content-Type", "application/json")
.method(method, json == null
? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(json));
if (token != null) {
request.header("Authorization", "Bearer " + token);
}
HttpResponse<String> response = http.send(request.build(), HttpResponse.BodyHandlers.ofString());
Allure.addAttachment("request", "text/plain", method + " " + path + "\n" + (json == null ? "" : json));
Allure.addAttachment("response " + response.statusCode(), "application/json", response.body());
return new Response(response.statusCode(), JSON.readTree(response.body()));
});
}
} - Runs the lambda as a named step; its result is returned, and a failure marks the step failed.line 82
- The request, visible inside the step in the report.line 94
- The response body, named with its status code.line 95
- Small helpers keep tests free of JSON digging.line 72
"""Layer 2, the API client: every ShopRung call in one place. Each call is an Allure step with the request and
response attached, so a failed test's report shows exactly what was sent and what came back."""
import json
import allure
import httpx
from framework.config import USERS, Config
class ShopRungClient:
def __init__(self, config: Config):
self.http = httpx.Client(base_url=config.base_url, timeout=config.timeout)
self.products = {p["name"]: p["id"] for p in self.http.get("/api/products").json()["items"]}
def _call(self, title, method, path, body=None):
with allure.step(title):
r = self.http.request(method, path, json=body)
sent = f"{method} {path}\n{json.dumps(body, indent=2) if body is not None else ''}"
allure.attach(sent, "request", allure.attachment_type.TEXT)
allure.attach(r.text, f"response {r.status_code}", allure.attachment_type.JSON)
return r
def reset(self):
return self._call("Reset ShopRung to its seed data", "POST", "/api/test/reset")
def log_in(self, who):
email, password = USERS[who]
r = self._call(f"Log in as {who}", "POST", "/api/auth/login", {"email": email, "password": password})
r.raise_for_status()
self.http.headers["Authorization"] = f"Bearer {r.json()['token']}"
return r
def add(self, name, quantity):
return self._call(f"Add {quantity} x {name}", "POST", "/api/cart/items",
{"productId": self.products[name], "quantity": quantity})
def apply_coupon(self, code):
return self._call(f"Apply coupon {code}", "POST", "/api/cart/coupon", {"code": code})
def cart(self):
return self._call("Read the cart", "GET", "/api/cart").json()
def place_order(self):
return self._call("Place the order", "POST", "/api/orders")
def order(self, order_id):
return self._call(f"Open order {order_id}", "GET", f"/api/orders/{order_id}")
def close(self):
self.http.close() - Everything inside becomes one step in the report.line 17
- The response body as JSON, named with its status.line 21
Python version of this step:
Layer 3: named test data
Carts with names that say why the numbers matter.
Create TestData.java (Python: framework/data.py). CART_AT_50 is exactly the SAVE10 threshold, CART_AT_74_99 is one cent below free shipping, CART_AT_75 is exactly free shipping. The comments show the arithmetic once, and fill adds a whole cart.
When the shop's prices change, you fix one file, and a test that says fill(alice, CART_AT_75) explains itself.
package dev.algorung.framework;
import java.util.List;
/** Layer 3, test data: named carts the tests build, so the numbers live in one place. */
public final class TestData {
private TestData() {
}
public record Line(String name, int quantity) {
}
/** 4 x $12.50 = $50.00, exactly the SAVE10 threshold. */
public static final List<Line> CART_AT_50 = List.of(new Line("Clean Code Notebook", 4));
/** $50.00 + $20.00 + $4.99 = $74.99, one cent below free shipping. */
public static final List<Line> CART_AT_74_99 = List.of(
new Line("Clean Code Notebook", 4), new Line("Ship It T-Shirt", 1), new Line("Sticker Pack: Edge Cases", 1));
/** 6 x $12.50 = $75.00, exactly free shipping. */
public static final List<Line> CART_AT_75 = List.of(new Line("Clean Code Notebook", 6));
public static void fill(ShopRungClient client, List<Line> lines) {
for (Line line : lines) {
ShopRungClient.Response r = client.add(line.name(), line.quantity());
if (r.status() != 200) {
throw new IllegalStateException("Could not add " + line + ": " + r.body());
}
}
}
} - $50.00 + $20.00 + $4.99 = $74.99.line 16
"""Layer 3, test data: named carts the tests build, so the numbers live in one place."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Line:
name: str
quantity: int
# 4 x $12.50 = $50.00, exactly the SAVE10 threshold
CART_AT_50 = [Line("Clean Code Notebook", 4)]
# $50.00 + $20.00 + $4.99 = $74.99, one cent below free shipping
CART_AT_74_99 = [Line("Clean Code Notebook", 4), Line("Ship It T-Shirt", 1), Line("Sticker Pack: Edge Cases", 1)]
# 6 x $12.50 = $75.00, exactly free shipping
CART_AT_75 = [Line("Clean Code Notebook", 6)]
def fill(client, lines):
for line in lines:
r = client.add(line.name, line.quantity)
assert r.status_code == 200, r.text Python version of this step:
Layer 4: the base test
Seed data before every test, and logged-in clients by name.
Create BaseTest.java. Every test class extends it: @BeforeEach resets ShopRung, and as("alice") returns a client already logged in as Alice. Python: tests/conftest.py does the same with fixtures: an autouse reset, a client_for factory that closes its clients afterwards, and an alice shortcut.
package dev.algorung.framework;
import org.junit.jupiter.api.BeforeEach;
/** Layer 4, test setup: every test starts from ShopRung's seed data and asks for logged-in clients by name. */
public abstract class BaseTest {
protected final Config config = Config.load();
@BeforeEach
void seedData() {
new ShopRungClient(config).reset();
}
protected ShopRungClient as(String who) {
return new ShopRungClient(config).logIn(who);
}
} - Each test starts from the same seed data, so tests never depend on each other.line 9
- Reads like the test:
as("bob").order(id).line 14
"""Fixtures wire the layers together: config, a reset, and a logged-in client per user."""
import pytest
from framework import config
from framework.client import ShopRungClient
@pytest.fixture(scope="session")
def settings():
return config.load()
@pytest.fixture
def client_for(settings):
opened = []
def _client(who):
client = ShopRungClient(settings)
client.log_in(who)
opened.append(client)
return client
yield _client
for client in opened:
client.close()
@pytest.fixture(autouse=True)
def seed_data(settings):
client = ShopRungClient(settings)
client.reset()
client.close()
@pytest.fixture
def alice(client_for):
return client_for("alice") - Runs before every test without being asked for.line 28
- A factory: as many logged-in users as a test needs.line 14
Python version of this step:
Labelled tests: coupons
Short tests with features, stories and severity for the report.
Create CouponTest.java (Python: tests/test_coupons.py). @Feature, @Story and @Severity group results in the report's Behaviors view and let readers sort by importance. @Tag("smoke") (Python: @pytest.mark.smoke) marks the fastest, most important checks.
Each test is three lines of intent: build the cart, act, then one named step that checks the result. Run them.
package dev.algorung.tests;
import static dev.algorung.framework.TestData.CART_AT_50;
import static dev.algorung.framework.TestData.fill;
import static org.junit.jupiter.api.Assertions.assertEquals;
import dev.algorung.framework.BaseTest;
import dev.algorung.framework.ShopRungClient;
import io.qameta.allure.Allure;
import io.qameta.allure.Feature;
import io.qameta.allure.Severity;
import io.qameta.allure.SeverityLevel;
import io.qameta.allure.Story;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Feature("Coupons")
class CouponTest extends BaseTest {
@Test
@Tag("smoke")
@Story("SAVE10")
@Severity(SeverityLevel.CRITICAL)
void save10AtExactly50Dollars() {
ShopRungClient alice = as("alice");
fill(alice, CART_AT_50);
ShopRungClient.Response r = alice.applyCoupon("save10");
Allure.step("Check SAVE10 is applied and the total is $49.99", () -> {
assertEquals(200, r.status(), r.body().toString());
assertEquals("$5.00", r.body().get("discount").asText());
assertEquals("$49.99", r.body().get("total").asText());
});
}
@Test
@Story("WELCOME15")
@Severity(SeverityLevel.NORMAL)
void expiredWelcome15IsRefused() {
ShopRungClient alice = as("alice");
fill(alice, CART_AT_50);
ShopRungClient.Response r = alice.applyCoupon("WELCOME15");
Allure.step("Check the coupon is refused as expired", () -> {
assertEquals(400, r.status());
assertEquals("This coupon has expired", r.body().get("message").asText());
});
}
} - On the class: every test here is under Coupons.line 17
- A wrong discount is money: critical.line 23
- The checks get their own step, so the report shows "the check failed", not "a call failed".line 28
import allure
import pytest
from framework.data import CART_AT_50, fill
@allure.feature("Coupons")
@allure.story("SAVE10")
@allure.severity(allure.severity_level.CRITICAL)
@pytest.mark.smoke
def test_save10_at_exactly_50_dollars(alice):
fill(alice, CART_AT_50)
r = alice.apply_coupon("save10")
with allure.step("Check SAVE10 is applied and the total is $49.99"):
assert r.status_code == 200, r.text
assert r.json()["discount"] == "$5.00"
assert r.json()["total"] == "$49.99"
@allure.feature("Coupons")
@allure.story("WELCOME15")
@allure.severity(allure.severity_level.NORMAL)
def test_expired_welcome15_is_refused(alice):
fill(alice, CART_AT_50)
r = alice.apply_coupon("WELCOME15")
with allure.step("Check the coupon is refused as expired"):
assert r.status_code == 400
assert r.json()["message"] == "This coupon has expired" - Shown in the report and usable as a filter.line 9
Python version of this step:
mvn test -Dtest=CouponTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
pytest tests/test_coupons.py .. [100%] 2 passed in 0.21s
Shipping and orders, then smoke
A parameterized boundary test, two order tests, and a smoke run.
Create ShippingTest.java and OrderTest.java (Python: test_shipping.py and test_orders.py). The shipping test runs twice, once per named cart, so both sides of $75.00 are covered with one method. The order tests check a side effect, stock drops by 4 after an order, and privacy: Bob gets 404 for Alice's order.
Run all 6, then only the smoke tests: the SAVE10 check and the placed order.
package dev.algorung.tests;
import static dev.algorung.framework.TestData.CART_AT_74_99;
import static dev.algorung.framework.TestData.CART_AT_75;
import static dev.algorung.framework.TestData.fill;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.fasterxml.jackson.databind.JsonNode;
import dev.algorung.framework.BaseTest;
import dev.algorung.framework.ShopRungClient;
import dev.algorung.framework.TestData.Line;
import io.qameta.allure.Allure;
import io.qameta.allure.Feature;
import io.qameta.allure.Severity;
import io.qameta.allure.SeverityLevel;
import io.qameta.allure.Story;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@Feature("Shipping")
class ShippingTest extends BaseTest {
static Stream<Arguments> carts() {
return Stream.of(
Arguments.of("74.99 pays shipping", CART_AT_74_99, "$4.99", "$79.98"),
Arguments.of("75.00 ships free", CART_AT_75, "$0.00", "$75.00"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("carts")
@Story("Free shipping from $75.00")
@Severity(SeverityLevel.CRITICAL)
void shippingBoundary(String label, List<Line> cart, String shipping, String total) {
ShopRungClient alice = as("alice");
fill(alice, cart);
JsonNode view = alice.cart();
Allure.step("Check shipping is " + shipping + " and the total is " + total, () -> {
assertEquals(shipping, view.get("shipping").asText());
assertEquals(total, view.get("total").asText());
});
}
} - The first argument names each run in the report: "74.99 pays shipping".line 32
package dev.algorung.tests;
import static dev.algorung.framework.TestData.CART_AT_50;
import static dev.algorung.framework.TestData.fill;
import static org.junit.jupiter.api.Assertions.assertEquals;
import dev.algorung.framework.BaseTest;
import dev.algorung.framework.ShopRungClient;
import io.qameta.allure.Allure;
import io.qameta.allure.Feature;
import io.qameta.allure.Severity;
import io.qameta.allure.SeverityLevel;
import io.qameta.allure.Story;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Feature("Orders")
class OrderTest extends BaseTest {
@Test
@Tag("smoke")
@Story("Place an order")
@Severity(SeverityLevel.BLOCKER)
void placedOrderReducesStock() {
ShopRungClient alice = as("alice");
int before = alice.stockOf("Clean Code Notebook");
fill(alice, CART_AT_50);
ShopRungClient.Response r = alice.placeOrder();
int after = alice.stockOf("Clean Code Notebook");
Allure.step("Check the order is PLACED and 4 notebooks left stock", () -> {
assertEquals(201, r.status(), r.body().toString());
assertEquals("PLACED", r.body().get("status").asText());
assertEquals(before - 4, after);
});
}
@Test
@Story("Privacy")
@Severity(SeverityLevel.CRITICAL)
void aCustomerCannotOpenAnotherCustomersOrder() {
ShopRungClient alice = as("alice");
fill(alice, CART_AT_50);
long orderId = alice.placeOrder().body().get("id").asLong();
ShopRungClient.Response r = as("bob").order(orderId);
Allure.step("Check Bob gets 404 for Alice's order", () -> assertEquals(404, r.status(), r.body().toString()));
}
} - Checks the stock rule (ORD) that the API response alone would never show.line 33
- A second user: the only way to test access control.line 44
import allure
import pytest
from framework.data import CART_AT_74_99, CART_AT_75, fill
@allure.feature("Shipping")
@allure.story("Free shipping from $75.00")
@allure.severity(allure.severity_level.CRITICAL)
@pytest.mark.parametrize("cart, shipping, total", [
pytest.param(CART_AT_74_99, "$4.99", "$79.98", id="74.99 pays shipping"),
pytest.param(CART_AT_75, "$0.00", "$75.00", id="75.00 ships free"),
])
def test_shipping_boundary(alice, cart, shipping, total):
fill(alice, cart)
view = alice.cart()
with allure.step(f"Check shipping is {shipping} and the total is {total}"):
assert view["shipping"] == shipping
assert view["total"] == total - Readable ids for each run, in the console and the report.line 11
import allure
import pytest
from framework.data import CART_AT_50, fill
@allure.feature("Orders")
@allure.story("Place an order")
@allure.severity(allure.severity_level.BLOCKER)
@pytest.mark.smoke
def test_placed_order_reduces_stock(alice):
before = {p["name"]: p["stock"] for p in alice.http.get("/api/products").json()["items"]}
fill(alice, CART_AT_50)
r = alice.place_order()
with allure.step("Check the order is PLACED and 4 notebooks left stock"):
assert r.status_code == 201, r.text
assert r.json()["status"] == "PLACED"
after = {p["name"]: p["stock"] for p in alice.http.get("/api/products").json()["items"]}
assert after["Clean Code Notebook"] == before["Clean Code Notebook"] - 4
@allure.feature("Orders")
@allure.story("Privacy")
@allure.severity(allure.severity_level.CRITICAL)
def test_a_customer_cannot_open_another_customers_order(alice, client_for):
fill(alice, CART_AT_50)
order_id = alice.place_order().json()["id"]
bob = client_for("bob")
r = bob.order(order_id)
with allure.step("Check Bob gets 404 for Alice's order"):
assert r.status_code == 404, r.text - A second, independent client logged in as Bob.line 28
Python version of this step:
mvn test
mvn test -Dgroups=smoke [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 ... [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
pytest
pytest -m smoke ...... [100%] 6 passed in 0.75s .. [100%] 2 passed, 4 deselected in 0.24s
Generate and read the report
Turn raw results into the Allure report and find your way around it.
Every run wrote JSON files into the results folder. allure serve builds the report and opens it in your browser; allure generate writes a static site you can keep as a CI artifact.
Look at Overview (totals and severity), Behaviors (Coupons, Shipping, Orders, then the stories), and open a test: each client call is a step, and each step holds its request and response. The parameterized test shows two entries with their names.
allure serve target/allure-results
# or keep a static report:
allure generate target/allure-results -o target/allure-report --clean Generating report to temp directory... Report successfully generated to ... Starting web server... Server started at <http://...>. Press <Ctrl+C> to exit
allure serve allure-results
# or keep a static report:
allure generate allure-results -o allure-report --clean Report successfully generated to allure-report
Stuck on this step?
- The report says "0 test cases" or shows old results.
- Point Allure at the right folder:
target/allure-resultsfor Java,allure-resultsfor Python. In Java,mvn clean testempties old results first. - Opening
index.htmldirectly shows a blank page. - The report loads its data with JavaScript, which browsers block from files. Use
allure serveorallure open allure-report.
Check it works
Switch on ShopRung's stock-not-reduced bug and run the suite: only the placed-order test fails, with assert 40 == (40 - 4) in Python (Java: expected: <36> but was: <40>). Generate the report and open the failed test: Add 4 x Clean Code Notebook and Place the order passed with their responses attached (201, status PLACED), and Check the order is PLACED and 4 notebooks left stock failed. The API said yes; the stock said no.
Then try coupon-boundary, expired-coupon, free-shipping-boundary and order-leak: each fails exactly one test, with ShopRung's answer in the attached response. slow-search fails nothing: no test searches. Turn the bugs off at the end.
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["stock-not-reduced"]}'
pytest # or: mvn test
allure serve allure-results E assert 40 == (40 - 4) FAILED tests/test_orders.py::test_placed_order_reduces_stock - assert 40 == (40 - 4) 1 failed, 5 passed in 0.73s In the report (Orders › Place an order, severity blocker): ✔ Add 4 x Clean Code Notebook 📎 request 📎 response 200 ✔ Place the order 📎 request 📎 response 201 ✘ Check the order is PLACED and 4 notebooks left stock
Troubleshooting
Java: no target/allure-results folder after mvn test.
allure-junit5 is missing from the pom, or allure.properties is not in src/test/resources.
Steps do not appear inside tests, only the test name.
Calls must go through the client's call method, which wraps them in Allure.step (Python: with allure.step).
allure: command not found
Install the CLI (setup step 2). It needs Java on the PATH even for the Python path.
Java: -Dgroups=smoke runs all tests.
Surefire 3 reads JUnit 5 tags through groups. Check the tag is @Tag("smoke") on the method and the Surefire version in the pom.
Python: PytestUnknownMarkWarning: Unknown pytest.mark.smoke.
Declare the marker under markers in pytest.ini, as in step 1.
What changes in production
- Real frameworks have exactly these layers, plus page objects for UI: config, clients, data builders, base tests or fixtures, and thin tests.
- The client or page object layer adds Allure steps and attachments once, so every test gets readable reports for free.
- CI uploads
allure-results, keeps the previous report'shistoryfolder for trends, and publishes the report per branch so bug tickets can link to it. - Secrets come from the CI secret store through environment variables; the framework's defaults are only for local practice systems.
Interview angle
“How do you design a test automation framework?”
In layers. Configuration reads environments and secrets from environment variables. A client or page object layer holds every API call or locator, and also adds reporting: each call is an Allure step with request and response attached. Test data builders give named, meaningful data. A base test or fixtures handle setup like resetting data and logging in users. Tests stay short, labelled with feature, story and severity, tagged for smoke runs, and parameterized for boundaries. Reports come from the Allure adapter, generated in CI with history.
Clean up
Practice
These run in your browser and check your answer.
Read Allure results
Allure writes one result per test with a status and a list of steps. Write first_failed_step(result) that returns the name of the first step whose status is not "passed", or None if every step passed.
def first_failed_step(result):
for step in result["steps"]:
if step["status"] == "failed":
return step["name"]
Hint
Allure also has "broken" and "skipped". Compare with != "passed" and return None at the end.
The full project
Every file from this lab, as it is after the last step.