Chapter 16: Capstone — Ship It End-to-End
16.4 Application minimum bar
Why: the problem
Suppose Swiggy ships a new restaurant API on Friday evening. It starts, but /health was never tested, and the load balancer marks every copy as dead. Orders stop for twenty minutes. The code was fine; the minimum bar was missing. Before any app enters a pipeline, it must pass a few small tests: health answers 200, bad input gets 400, good input gets the right JSON. In this lesson you write those tests in Node, Python and Java Spring Boot, and run them with one command each.
What we will build
Automated tests for the badge API: Jest + Supertest for Node, pytest for Flask, and a Spring Boot app with Actuator health plus a MockMvc test. Each suite runs in seconds and returns exit code 0 when green, ready for CI in lesson 16.5.
What: every term in plain English
- Minimum bar — The smallest set of checks an app must pass before it ships.
- Unit test — A small automatic check of one piece of code.
- Jest / pytest / JUnit — Test runners for Node, Python and Java.
- Supertest / MockMvc — Tools that send fake HTTP requests to your app inside the test, without opening a port.
- Actuator — A Spring Boot add-on that gives /actuator/health for free.
How: step by step
-
Install test tools
cd app && npm install --save-dev jest supertestWhat it does: Adds the test runner and HTTP tester.
Output
added 271 packages in 9s -
Write the test
nano server.test.js # paste Example 1What it does: Creates three tests.
Output
(no output) -
Run the tests
npm testWhat it does: Runs every *.test.js file.
Output
PASS ./server.test.js badge api ✓ GET /health returns ok (31 ms) ✓ GET /badge/ravi_01 returns a badge (6 ms) ✓ GET /badge/ab returns 400 (3 ms) Tests: 3 passed, 3 total -
Check the exit code
npm test >/dev/null 2>&1; echo $?What it does: CI only reads this number.
Output
0 -
Commit
git add . && git commit -m "minimum bar tests"What it does: Saves the tests.
Output
[main 7aa21f0] minimum bar tests
Example 1: Test the Node API with Jest and Supertest
Stack. Node 20, Jest 29
Goal. Test the Node API with Jest and Supertest.
app/server.test.js
// app/server.test.js
const request = require("supertest");
const app = require("./server");
describe("badge api", () => {
test("GET /health returns ok", async () => {
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body.status).toBe("ok");
});
test("GET /badge/ravi_01 returns a badge", async () => {
const res = await request(app).get("/badge/ravi_01");
expect(res.status).toBe(200);
expect(res.body).toEqual({ user: "ravi_01", badge: "verified-learner", issuedBy: "shipit" });
});
test("GET /badge/ab returns 400", async () => {
const res = await request(app).get("/badge/ab");
expect(res.status).toBe(400);
});
});
What each line does
const app = require("./server");— Imports the app without starting a port (thanks to require.main in server.js).describe("badge api", ...)— Groups related tests.await request(app).get("/health")— Sends a fake GET request straight into Express.expect(res.status).toBe(200)— Fails the test if the status is not 200.toEqual({...})— Checks the whole JSON body.
Green output
$ npm test
PASS ./server.test.js
Tests: 3 passed, 3 total
Time: 0.84 s
Expected result. All three checks pass in under a second.
Example 2: Test the Flask API with pytest
Stack. Python 3.11, pytest 8
Goal. Test the Flask API with pytest.
python/test_app.py
# python/test_app.py
import pytest
from app import app
@pytest.fixture
def client():
app.config["TESTING"] = True
with app.test_client() as c:
yield c
def test_health(client):
r = client.get("/health")
assert r.status_code == 200
assert r.get_json()["status"] == "ok"
def test_badge(client):
r = client.get("/badge/insta_user")
assert r.status_code == 200
assert r.get_json()["badge"] == "verified-learner"
@pytest.mark.parametrize("bad", ["ab", "Ravi", "a-b-c", "x" * 31])
def test_bad_usernames(client, bad):
assert client.get(f"/badge/{bad}").status_code == 400
What each line does
@pytest.fixture— Builds a test client once per test.app.test_client()— Flask's fake browser; no port needed.assert ...— Fails the test if the condition is false.@pytest.mark.parametrize(...)— Runs the same test four times with four bad names.
Green output
$ pip install pytest && pytest -q
....... [100%]
7 passed in 0.12s
Expected result. Seven checks (1 + 1 + 4 bad names + 1 counted by pytest) pass.
Example 3: Build the badge API in Spring Boot with Actuator health and a MockMvc test
Stack. Java 21, Spring Boot 3 (create the project at start.spring.io with Web + Actuator)
Goal. Build the badge API in Spring Boot with Actuator health and a MockMvc test.
java/src/main/java/com/shipit/BadgeApplication.java
package com.shipit;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@SpringBootApplication
@RestController
public class BadgeApplication {
public static void main(String[] args) {
SpringApplication.run(BadgeApplication.class, args);
}
@GetMapping("/badge/{user}")
public ResponseEntity<Map<String, String>> badge(@PathVariable String user) {
if (!user.matches("^[a-z0-9_]{3,30}$")) {
return ResponseEntity.badRequest().body(Map.of("error", "invalid username"));
}
return ResponseEntity.ok(Map.of("user", user, "badge", "verified-learner", "issuedBy", "shipit"));
}
}
java/src/main/resources/application.properties
server.port=8080
management.endpoints.web.exposure.include=health,info
management.endpoint.health.probes.enabled=true
java/src/test/java/com/shipit/BadgeApplicationTest.java
package com.shipit;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest
@AutoConfigureMockMvc
class BadgeApplicationTest {
@Autowired MockMvc mvc;
@Test void health() throws Exception {
mvc.perform(get("/actuator/health")).andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("UP"));
}
@Test void badge() throws Exception {
mvc.perform(get("/badge/infosys_dev")).andExpect(status().isOk());
}
@Test void badUser() throws Exception {
mvc.perform(get("/badge/AB")).andExpect(status().isBadRequest());
}
}
What each line does
@SpringBootApplication @RestController— One class is both the app and the web controller.@GetMapping("/badge/{user}")— Maps the URL; {user} becomes the method argument.ResponseEntity.badRequest()— Returns HTTP 400.management.endpoints.web.exposure.include=health,info— Turns on /actuator/health.probes.enabled=true— Adds /actuator/health/liveness and /readiness for Kubernetes.@AutoConfigureMockMvc— Gives a fake HTTP client for tests.jsonPath("$.status").value("UP")— Checks the health JSON says UP.
Green output
$ ./mvnw -q test
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Expected result. Spring Boot gives health for free, and three tests pass.
Verify: did it work?
-
Break a test on purpose
sed -i 's/toBe(400)/toBe(401)/' app/server.test.js && npm test --prefix app | tail -3What it does: Proves the tests really check something.
Output
Tests: 1 failed, 2 passed, 3 total -
Fix it back
git checkout app/server.test.js && npm test --prefix app | tail -1What it does: Restores the file.
Output
Tests: 3 passed, 3 total
When it is red 1
TypeError: app.address is not a function
Cause. server.js does not export the app (module.exports missing), so Supertest gets undefined.
Fix, step by step
- Open server.js.
- Add module.exports = app; at the end.
- Run npm test.
When it is red 2
ModuleNotFoundError: No module named 'app'
Cause. pytest runs from the wrong folder.
Fix, step by step
- cd python
- Run pytest there, or add an empty conftest.py next to app.py.
When it is red 3
Expected status 200 but was 404 for /actuator/health
Cause. Actuator is not in the project.
Fix, step by step
- Add spring-boot-starter-actuator to pom.xml.
- Run ./mvnw test again.
Cleanup
-
Remove test caches
rm -rf app/coverage python/.pytest_cache java/targetWhat it does: Deletes generated files.
Output
(no output)
Ravindra Bagale's Tip
Make the test fail first. If it never fails, that test checks nothing.
Test पहिला fail करून बघा. Fail होत नसेल तर तो test काही check करत नाही.
Test पहले fail करके देखो. Fail न हो तो वो test कुछ check नहीं करता.
Practice tasks
Easy Run Jest
Why: Doing it once with your own hands makes it stick.
What to do: Run the Node tests.
- cd app
- npm test
Check: 3 passed.
Easy Read exit code
Why: Doing it once with your own hands makes it stick.
What to do: Print the npm test exit code.
- npm test; echo $?
Check: 0.
Easy Run pytest
Why: Doing it once with your own hands makes it stick.
What to do: Run the Python tests.
- cd python
- pytest -q
Check: 7 passed.
Easy Break a test
Why: Doing it once with your own hands makes it stick.
What to do: Change 400 to 401 and run.
- Edit the test.
- npm test
Check: 1 failed.
Medium Add a test
Why: Doing it once with your own hands makes it stick.
What to do: Test that /badge/a_b_c returns 200.
- Add a test block.
- npm test
Check: 4 passed.
Medium Coverage
Why: Doing it once with your own hands makes it stick.
What to do: Run jest --coverage.
- npx jest --coverage
Check: A coverage table shows.
Medium Spring project
Why: Doing it once with your own hands makes it stick.
What to do: Create the Spring app with Web + Actuator.
- Use start.spring.io.
- Add the class.
- ./mvnw spring-boot:run
Check: curl :8080/actuator/health shows UP.
Medium Spring tests
Why: Doing it once with your own hands makes it stick.
What to do: Run ./mvnw test.
- ./mvnw test
Check: BUILD SUCCESS.
Hard Version test
Why: Doing it once with your own hands makes it stick.
What to do: Test /health version.
- Set APP_VERSION=9.9.9 in the test.
- Assert it.
Check: Test passes.
Hard Readiness probe
Why: Doing it once with your own hands makes it stick.
What to do: Call /actuator/health/readiness.
- Run the Spring app.
- curl it.
Check: {"status":"UP"}.
Homework: try at home
Try at home
Add a test that /health returns the version from APP_VERSION. In Jest set process.env.APP_VERSION before requiring the app; in pytest use monkeypatch.
Recap
- Minimum bar: health 200, bad input 400, good input correct JSON.
- Tests run without a real port.
- Same tests in Node, Python and Java.
- Exit code 0 means green.
- Break a test once to prove it works.
FAQ
How many tests are enough?
For the capstone, these three ideas. More is good, but finish first.
Do I need a database for tests?
Not for these. Keep unit tests fast.
Why does Spring use /actuator/health?
It is Actuator's standard path. Kubernetes can use it too.
Can tests run in Docker?
Yes, but run them in CI first; simpler.
What is a flaky test?
A test that sometimes passes and sometimes fails. Fix or remove it.
Interview questions
-
What tests do you run before deploying a service?
At least unit tests plus health and input checks; later integration and smoke tests.
-
Difference between liveness and readiness?
Liveness: is it alive (restart if not). Readiness: can it take traffic now.
-
How do you test an HTTP API without a server?
Supertest, Flask test client or MockMvc call the app in memory.
-
Why must tests fail sometimes on purpose?
To prove they detect breakage.
-
How does CI know tests failed?
Non-zero exit code.
Quick quiz
Q1. Why test /health?
Load balancers depend on it; a broken health means no traffic.
Q2. What does Supertest avoid?
Opening a real port.
Q3. What does parametrize do?
Runs one test with many inputs.
Q4. Which Spring add-on gives /actuator/health?
Spring Boot Actuator.
Q5. What does CI look at to decide pass or fail?
The exit code.
Did you understand? Let us try it once more.
Revision card
Interview card