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

1 / 6

0 of 8 steps done

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

Setup

S1Start ShopRung

Start ShopRung as in lab 1 with npm start, and leave it running.

Run
curl http://localhost:8080/api/health
You should see
{"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.

Run
brew install allure
allure --version
You should seeyour text will differ: the model writes it
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.

Run
# 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
1

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.

pom.xml
<?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>
  1. Allure 2.29 for every Allure module below.line 26
  2. The adapter: JUnit 5 events become Allure result files.line 42
src/test/resources/allure.properties
allure.results.directory=target/allure-results
Run
mvn -q test-compile
You should seeyour text will differ: the model writes it
(no output: the project compiles)
2

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.

src/test/java/dev/algorung/framework/Config.java
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);
    }
}
  1. In CI, the real value comes from a secret; the default is ShopRung's public practice password.line 9
  2. Read once, passed to the layers that need it.line 12
3

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.

src/test/java/dev/algorung/framework/ShopRungClient.java
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()));
        });
    }
}
  1. Runs the lambda as a named step; its result is returned, and a failure marks the step failed.line 82
  2. The request, visible inside the step in the report.line 94
  3. The response body, named with its status code.line 95
  4. Small helpers keep tests free of JSON digging.line 72
4

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.

src/test/java/dev/algorung/framework/TestData.java
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());
            }
        }
    }
}
  1. $50.00 + $20.00 + $4.99 = $74.99.line 16
5

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.

src/test/java/dev/algorung/framework/BaseTest.java
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);
    }
}
  1. Each test starts from the same seed data, so tests never depend on each other.line 9
  2. Reads like the test: as("bob").order(id).line 14
6

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.

src/test/java/dev/algorung/tests/CouponTest.java
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());
        });
    }
}
  1. On the class: every test here is under Coupons.line 17
  2. A wrong discount is money: critical.line 23
  3. The checks get their own step, so the report shows "the check failed", not "a call failed".line 28
Run
mvn test -Dtest=CouponTest
You should seeyour text will differ: the model writes it
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
7

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.

src/test/java/dev/algorung/tests/ShippingTest.java
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());
        });
    }
}
  1. The first argument names each run in the report: "74.99 pays shipping".line 32
src/test/java/dev/algorung/tests/OrderTest.java
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()));
    }
}
  1. Checks the stock rule (ORD) that the API response alone would never show.line 33
  2. A second user: the only way to test access control.line 44
Run
mvn test
mvn test -Dgroups=smoke
You should seeyour text will differ: the model writes it
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
...
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
8

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.

Run
allure serve target/allure-results
# or keep a static report:
allure generate target/allure-results -o target/allure-report --clean
You should seeyour text will differ: the model writes it
Generating report to temp directory...
Report successfully generated to ...
Starting web server...
Server started at <http://...>. Press <Ctrl+C> to exit
Stuck on this step?
The report says "0 test cases" or shows old results.
Point Allure at the right folder: target/allure-results for Java, allure-results for Python. In Java, mvn clean test empties old results first.
Opening index.html directly shows a blank page.
The report loads its data with JavaScript, which browsers block from files. Use allure serve or allure 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.

Test
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
You should see
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's history folder 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.

Exercise
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.

Download Java project (.zip) Download Python project (.zip)