QA and Test Automation · Lab 5 of 35
Git for testers: branch, commit, pull request, review and squash
Put your test project under Git, write a .gitignore for Maven and Python, push it to GitHub, add a new ShopRung API test on a branch, open a pull request, answer review comments, then squash it to one clean commit and merge. Every command, with what you should see.
⏱ 50 minBeginner💸 Free8 stepsJava + Python
Git 2.4xGitHub (free account)GitHub CLI (gh)The lab 4 test project (Java or Python)ShopRung
Overview video
What you will build
Your test project from lab 4 in a Git repository on GitHub, with a .gitignore that keeps build output and caches out, and a pull request template that asks every change "how did you test this?".
Then the everyday loop of an SDET, done once from start to finish: a branch for one new test (an unknown ShopRung product must return 404 with a JSON error), commits, a pull request, review comments and a fix, and a squash so main gets one clean commit. At the end, main has two commits and every test passes.
Before you start
- The project from Your first Java test project, in Java or Python. No project? Download it from the end of that lab.
- ShopRung running, as in lab 1 setup, to run the tests before each commit.
- Git for testers explains commits, branches and pull requests with pictures. This lab is the hands-on half.
- A terminal you are comfortable typing in. Every command here works in macOS zsh, Linux bash and Windows PowerShell unless a tab says otherwise.
Setup
S1Install Git
macOS: xcode-select --install installs Apple's command line tools, which include Git; Homebrew's brew install git gives a newer one. Windows: Git for Windows also installs Git Bash and a credential manager; open a new terminal after installing.
xcode-select --install
git --versionsudo apt update
sudo apt install -y git
git --versionwinget install --id Git.Git -e
# open a new terminal, then:
git --version git version 2.4x.x
S2Tell Git who you are
Every commit records a name and an email. Use the email of your GitHub account, so GitHub links the commits to you. To keep your email private, use the noreply address from GitHub Settings > Emails (it looks like 12345678+your-name@users.noreply.github.com).
init.defaultBranch main makes new repositories start on a branch called main, like GitHub does.
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --global --list user.name=Your Name user.email=you@example.com init.defaultbranch=main
S3A GitHub account and the GitHub CLI
Create a free account at github.com if you do not have one. Then install gh, GitHub's command line tool, and log in. Choose GitHub.com, HTTPS, answer Yes to "Authenticate Git with your GitHub credentials", and log in with the browser. After that, git push works without asking for a password.
On Linux, older distributions may not have gh in their package list; the GitHub CLI website lists the official repository to add.
brew install gh
gh auth loginsudo apt install -y gh
gh auth loginwinget install --id GitHub.cli -e
# open a new terminal, then:
gh auth login ? Where do you use GitHub? GitHub.com ? What is your preferred protocol for Git operations on this host? HTTPS ? Authenticate Git with your GitHub credentials? Yes ? How would you like to authenticate GitHub CLI? Login with a web browser ... ✓ Logged in as your-name
S4Open a terminal in your lab 4 project
Java: the shoprung-tests folder (the one with pom.xml). Python: the shoprung-tests-py folder (the one with requirements.txt), with the virtual environment active. Start ShopRung in another terminal. Run the tests once (mvn test or pytest) and check they all pass before Git gets involved.
Make the project a repository
Git starts tracking this folder, and you see what it would pick up.
git init creates a hidden .git folder: that is the repository, the full history of the project. Nothing is tracked yet.
git status is the command you will type most. Run it now and look at what Git offers to track: next to your code there is build output. Java: target/, the compiled classes and reports that every mvn command makes again. Python: __pycache__/, and report.xml if you ran pytest with --junitxml (and .venv/ on Python 3.12; newer Pythons hide it by themselves).
Build output does not belong in Git: it is large, it changes on every run, and it causes conflicts in every pull request. The next step tells Git to ignore it.
git init
git status Initialized empty Git repository in .../shoprung-tests/.git/ On branch main No commits yet Untracked files: (use "git add <file>..." to include in what will be committed) README.md pom.xml src/ target/ nothing added to commit but untracked files present (use "git add" to track)
git init
git status --short Initialized empty Git repository in .../shoprung-tests-py/.git/ ?? README.md ?? __pycache__/ ?? pricing.py ?? puzzles.py ?? report.xml ?? requirements.txt ?? test_pricing.py ?? test_puzzles.py ?? test_shoprung_api.py
Stuck on this step?
- It says
On branch master - Your Git was set up before the
init.defaultBranchsetting. Rungit branch -m mainto rename the branch now, and setgit config --global init.defaultBranch mainfor next time. Reinitialized existing Git repository- The folder was already a repository (for example because you unzipped it inside another one). That is harmless. Run
git logto see whether it already has commits.
Ignore what Git should not track
A .gitignore for Maven or Python, and a pull request template.
A .gitignore file lists patterns Git should ignore. A name ending in / matches a folder anywhere in the project; *.pyc matches every file with that ending. Lines starting with # are comments.
Ignore three kinds of things: build output (made again by the build tool), personal settings (your IDE and operating system), and secrets (.env, where API keys and passwords live). Never commit a password: once it is in the history, removing it from the latest version does not remove it from Git.
Also create .github/pull_request_template.md (note the dot in .github). GitHub pre-fills every new pull request with it, so every change answers the same questions. The second checkbox is the habit from lab 4: a test you never saw fail is not proof of anything.
git check-ignore -v tells you which line of .gitignore ignores a path, which is useful when a file is ignored and you do not know why.
# Maven build output: every mvn command makes it again
target/
# IDE settings: personal, not part of the project
.idea/
*.iml
.vscode/
.classpath
.project
.settings/
# Operating system files
.DS_Store
Thumbs.db
# Local secrets and settings
.env - Maven puts everything it builds in
target/, including the test reports.mvn cleandeletes it, and nothing is lost.line 2 - IntelliJ and VS Code settings are personal. The pom.xml is all another person needs to open the project.line 5
- macOS and Windows create these files in folders by themselves.line 13
- Not used yet, but later labs keep tokens in
.env. Ignore it from day one.line 17
## What this changes
<!-- One or two sentences. Name the requirement ids (PRICE-3, NF-4 ...) or the ticket. -->
## How I tested it
- [ ] The whole suite passes on my machine (`mvn test` or `pytest`)
- [ ] I saw each new test fail once (a wrong expected value, or a ShopRung bug switched on)
- [ ] No sleeps, no hard-coded ports, no passwords or tokens
## Notes for the reviewer - An HTML comment: the author sees it while writing, and it is hidden on the pull request page.line 3
- [ ]is a checkbox. The author ticks each one when it is true.line 7
# Virtual environment: pip install -r requirements.txt makes it again
.venv/
# Python caches
__pycache__/
*.pyc
.pytest_cache/
# Test reports
report.xml
# IDE settings: personal, not part of the project
.idea/
.vscode/
# Operating system files
.DS_Store
Thumbs.db
# Local secrets and settings
.env - The virtual environment holds installed packages for your operating system. Others make their own from
requirements.txt.line 2 - Python writes compiled
.pycfiles here. They are made again on every run.line 5 - The JUnit XML report from
pytest --junitxml. CI makes its own.line 10 - Not used yet, but later labs keep tokens in
.env. Ignore it from day one.line 21
## What this changes
<!-- One or two sentences. Name the requirement ids (PRICE-3, NF-4 ...) or the ticket. -->
## How I tested it
- [ ] The whole suite passes on my machine (`mvn test` or `pytest`)
- [ ] I saw each new test fail once (a wrong expected value, or a ShopRung bug switched on)
- [ ] No sleeps, no hard-coded ports, no passwords or tokens
## Notes for the reviewer - [ ]is a checkbox. The author ticks each one when it is true.line 7
Python version of this step:
git status --short
git check-ignore -v target/classes ?? .github/ ?? .gitignore ?? README.md ?? pom.xml ?? src/ .gitignore:2:target/ target/classes
git status --short
git check-ignore -v .venv __pycache__ report.xml ?? .github/ ?? .gitignore ?? README.md ?? pricing.py ?? puzzles.py ?? requirements.txt ?? test_pricing.py ?? test_puzzles.py ?? test_shoprung_api.py .gitignore:2:.venv/ .venv .gitignore:5:__pycache__/ __pycache__ .gitignore:10:report.xml report.xml
Stuck on this step?
target/still shows ingit status- Check the file is called exactly
.gitignore(Windows Notepad may save it as.gitignore.txt: runls -aordir -Forceto see) and that it is in the project folder, next topom.xml. - I committed
target/before adding the .gitignore - .gitignore only affects files Git does not track yet. Run
git rm -r --cached target, then commit: the folder stays on your disk but leaves the repository.
The first commit
Save the project as the first commit, with a message that says what it is.
A commit is a saved snapshot of the project. It takes two moves: git add puts changes in the staging area (the list of what goes into the next commit), and git commit saves that list with a message. git add . stages everything in this folder that is not ignored.
Check the staged list with git status --short before you commit: A means added. If a file you did not expect is there, this is the moment to fix the .gitignore.
A good commit message starts with a short summary in the imperative, like a command: "Add ...", "Fix ...", "Test that ...". Read it as "this commit will ...". Keep it under about 70 characters so it fits on one line in every tool.
git add .
git status --short
git commit -m "Add ShopRung test project: pricing, puzzles and API checks"
git log --oneline A .github/pull_request_template.md A .gitignore A README.md A pom.xml A src/main/java/dev/algorung/shop/Coupon.java A src/main/java/dev/algorung/shop/Pricing.java A src/main/java/dev/algorung/shop/Puzzles.java A src/test/java/dev/algorung/shop/PricingTest.java A src/test/java/dev/algorung/shop/PuzzlesTest.java A src/test/java/dev/algorung/shop/ShopRungApiTest.java [main (root-commit) 8fd5c45] Add ShopRung test project: pricing, puzzles and API checks 10 files changed, 450 insertions(+) create mode 100644 .github/pull_request_template.md ... 8fd5c45 Add ShopRung test project: pricing, puzzles and API checks
git add .
git status --short
git commit -m "Add ShopRung test project: pricing, puzzles and API checks"
git log --oneline A .github/pull_request_template.md A .gitignore A README.md A pricing.py A puzzles.py A requirements.txt A test_pricing.py A test_puzzles.py A test_shoprung_api.py [main (root-commit) b1c7546] Add ShopRung test project: pricing, puzzles and API checks 9 files changed, 332 insertions(+) ... b1c7546 Add ShopRung test project: pricing, puzzles and API checks
8fd5c45 here) is a fingerprint of the content and its history, so yours is different. Everyone on a team can name an exact version of the tests by that id, which is how a CI run says which code it tested.Stuck on this step?
Author identity unknown/Please tell me who you are- Setup step 2 was skipped. Run the two
git config --global user...commands, then the commit again. - An editor opened and I do not know how to leave it
- You ran
git commitwithout-m. In Vim: press Esc, type:q!and Enter to cancel, then commit with-m "message". In nano: Ctrl+X.
Put it on GitHub
A private GitHub repository called shoprung-tests, with main pushed to it.
Your repository lives on your laptop. GitHub holds a copy, called a remote, that your team and CI can reach. By convention the main remote is called origin.
One gh command creates the repository on GitHub, adds it as origin and pushes main. --private keeps it visible only to you; use --public if you want it on your profile for job applications.
Without gh: on github.com click New repository, name it shoprung-tests, leave every "Initialize" box unticked, then run the two commands GitHub shows under "push an existing repository": git remote add origin https://github.com/your-name/shoprung-tests.git and git push -u origin main.
-u (set upstream) links your local main to origin/main, so later a plain git push and git pull know where to go.
gh repo create shoprung-tests --private --source=. --remote=origin --push
git remote -v ✓ Created repository your-name/shoprung-tests on GitHub https://github.com/your-name/shoprung-tests ✓ Added remote https://github.com/your-name/shoprung-tests.git ... To https://github.com/your-name/shoprung-tests.git * [new branch] HEAD -> main branch 'main' set up to track 'origin/main'. ✓ Pushed commits to https://github.com/your-name/shoprung-tests.git origin https://github.com/your-name/shoprung-tests.git (fetch) origin https://github.com/your-name/shoprung-tests.git (push)
gh repo create shoprung-tests-py --private --source=. --remote=origin --push
git remote -v ✓ Created repository your-name/shoprung-tests-py on GitHub https://github.com/your-name/shoprung-tests-py ✓ Added remote https://github.com/your-name/shoprung-tests-py.git ... * [new branch] HEAD -> main branch 'main' set up to track 'origin/main'. ✓ Pushed commits to https://github.com/your-name/shoprung-tests-py.git origin https://github.com/your-name/shoprung-tests-py.git (fetch) origin https://github.com/your-name/shoprung-tests-py.git (push)
Stuck on this step?
Name already exists on this account- You already have a repository with that name. Pick another name, or delete the old one on github.com (Settings, at the bottom) if you do not need it.
remote origin already exists- The project already has a remote, for example from a clone. Run
git remote -vto see it, andgit remote remove originif it points at the wrong place. Permission deniedorAuthentication failedon push- Run
gh auth status. If you are not logged in, rungh auth loginagain and answer Yes to "Authenticate Git with your GitHub credentials". GitHub does not accept your account password forgit push.
A branch for one change
A new test on its own branch: an unknown product must return 404.
You never change main directly. Each change gets a branch: a movable label on its own line of commits. If the change goes wrong, main is untouched. Name it after what it does; many teams use a prefix like test/, fix/ or feat/.
The change: requirement NF-4 says every API error is JSON. A test for "unknown product" is missing, so add one. GET /api/products/999 on ShopRung answers 404 with {"error":"not_found","message":"No product with id 999"}. The first version below only checks the status code. (That is on purpose: the review in step 7 asks for more.)
Run the tests. Then see the new test fail once: change 999 to 1 (a product that exists), run again, and the test fails because product 1 answers 200. Change it back to 999.
git diff shows exactly what changed, line by line: + lines are new. Read your own diff before every commit. Then commit only that file.
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());
}
@Test
void anUnknownProductIs404() throws Exception { // NF-4
HttpResponse<String> r = get("/api/products/999");
assertEquals(404, r.statusCode());
}
} - A new test at the end of the class. It uses the
gethelper from lab 4.line 90 - ShopRung has 12 products, so id 999 does not exist.line 91
"""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"
def test_an_unknown_product_is_404(): # NF-4
status, _ = call("GET", "/api/products/999")
assert status == 404 - A new test at the end of the file. It uses the
callhelper from lab 4.line 62
Python version of this step:
git switch -c test/unknown-product-404
mvn test
git diff
git add src/test/java/dev/algorung/shop/ShopRungApiTest.java
git commit -m "Test that an unknown product returns 404" Switched to a new branch 'test/unknown-product-404'
...
[INFO] Tests run: 41, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
diff --git a/src/test/java/dev/algorung/shop/ShopRungApiTest.java b/src/test/java/dev/algorung/shop/ShopRungApiTest.java
...
+
+ @Test
+ void anUnknownProductIs404() throws Exception { // NF-4
+ HttpResponse<String> r = get("/api/products/999");
+ assertEquals(404, r.statusCode());
+ }
}
[test/unknown-product-404 a405a0b] Test that an unknown product returns 404
1 file changed, 6 insertions(+) git switch -c test/unknown-product-404
pytest -q
git diff
git add test_shoprung_api.py
git commit -m "Test that an unknown product returns 404" Switched to a new branch 'test/unknown-product-404'
......................................... [100%]
41 passed in 0.10s
diff --git a/test_shoprung_api.py b/test_shoprung_api.py
...
+
+
+def test_an_unknown_product_is_404(): # NF-4
+ status, _ = call("GET", "/api/products/999")
+ assert status == 404
[test/unknown-product-404 e07e80a] Test that an unknown product returns 404
1 file changed, 5 insertions(+)
(with 999 changed to 1, before you changed it back)
FAILED test_shoprung_api.py::test_an_unknown_product_is_404 - assert 200 == 404 Stuck on this step?
git diffshows nothing- The file is not saved, or you already ran
git add(then usegit diff --staged). New files never show ingit diffuntil they are added. git switchis not a git command- Your Git is older than 2.23. Use
git checkout -b test/unknown-product-404instead, and update Git when you can. - The diff is long and fills the screen
- Git shows long output in a pager. Scroll with the arrow keys or Space, and press q to quit.
Push the branch and open a pull request
The branch on GitHub, and a pull request asking to merge it into main.
Push the branch with -u, as you did for main. GitHub answers with a link to open a pull request for it.
A pull request (PR) asks to merge your branch into main, and it is where review happens: the diff, comments on single lines, the CI results, and the approval. Open the link (or run gh pr create --web), and GitHub fills the description with your template. Write what the change does ("Adds a test for NF-4: an unknown product returns 404"), tick the boxes that are true, and click Create pull request.
Look at the Files changed tab: it shows the same diff you read with git diff. That is what your reviewer will read.
git push -u origin test/unknown-product-404
gh pr create --web remote: remote: Create a pull request for 'test/unknown-product-404' on GitHub by visiting: remote: https://github.com/your-name/shoprung-tests/pull/new/test/unknown-product-404 remote: To https://github.com/your-name/shoprung-tests.git * [new branch] test/unknown-product-404 -> test/unknown-product-404 branch 'test/unknown-product-404' set up to track 'origin/test/unknown-product-404'. Opening https://github.com/your-name/shoprung-tests/compare/main...test/unknown-product-404 in your browser.
Stuck on this step?
fatal: The current branch has no upstream branch- You ran
git pushwithout-u origin <branch>on a new branch. Run the command exactly as shown once; after that a plaingit pushworks. - The PR description is empty, no template
- GitHub reads the template from the default branch. Check
.github/pull_request_template.mdwas part of the first commit and is onmainon github.com.
Review comments, and the fix
Answer two review comments with a new commit; the pull request updates by itself.
In a team, a colleague reviews your PR. Here, review it yourself: on the Files changed tab, click the + next to a line to comment on it. (GitHub does not let you approve or request changes on your own pull request, so use plain comments.) A reviewer who knows the requirements would write these two:
On
assertEquals(404, ...): NF-4 is about the JSON error body, but the test only checks the status code. A server that returned 404 with an HTML page would pass. Please check theerrorcode and the message too.On the test name:
Is404names the status code. Say what the user gets, for exampleanUnknownProductIsNotFound, so the report reads as a requirement.
Both are fair, so fix them: rename the test and add the checks below. Run the tests, then commit and push. You do not open a new pull request: every push to the branch updates the same PR, and the reviewer sees the new commit. Reply to each comment ("Done: now checks error and message") and click Resolve conversation.
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());
}
@Test
void anUnknownProductIsNotFound() throws Exception { // NF-4: errors are JSON with a code and a message
HttpResponse<String> r = get("/api/products/999");
assertEquals(404, r.statusCode());
assertTrue(r.body().contains("\"error\":\"not_found\""), r.body());
assertTrue(r.body().contains("No product with id 999"), r.body());
}
} - The name now says what the customer gets, not which number comes back.line 90
- The machine-readable error code from NF-4.line 93
- The human-readable message: it names the id that was not found.line 94
"""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"
def test_an_unknown_product_is_not_found(): # NF-4: errors are JSON with a code and a message
status, body = call("GET", "/api/products/999")
assert status == 404
assert body == {"error": "not_found", "message": "No product with id 999"} - One assert checks the whole error body: the code from NF-4 and the message with the id.line 65
Python version of this step:
mvn test
git commit -am "Check the error code and message, rename the test"
git push
git log --oneline [INFO] Tests run: 41, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS [test/unknown-product-404 e105495] Check the error code and message, rename the test 1 file changed, 3 insertions(+), 1 deletion(-) To https://github.com/your-name/shoprung-tests.git a405a0b..e105495 test/unknown-product-404 -> test/unknown-product-404 e105495 Check the error code and message, rename the test a405a0b Test that an unknown product returns 404 8fd5c45 Add ShopRung test project: pricing, puzzles and API checks
pytest -q
git commit -am "Check the error code and message, rename the test"
git push
git log --oneline 41 passed in 0.09s [test/unknown-product-404 5d0f08b] Check the error code and message, rename the test 1 file changed, 3 insertions(+), 2 deletions(-) ... 5d0f08b Check the error code and message, rename the test e07e80a Test that an unknown product returns 404 b1c7546 Add ShopRung test project: pricing, puzzles and API checks
git commit -am stages every change to files Git already tracks, then commits. It is safe here because you changed one tracked file; it never picks up new files.Stuck on this step?
! [rejected] ... (fetch first)on push- The branch on GitHub has a commit you do not have, for example from a suggestion you accepted in the web page. Run
git pull, thengit pushagain.
Squash to one commit and merge
The PR becomes one clean commit on main, and your laptop catches up.
The branch has two commits: the first try and the review fix. On main, the fix-up history is noise. Squashing turns them into one commit with a message that describes the final change.
Squash on your machine. git reset --soft main moves the branch back to where it started but keeps all your changes staged, so one new commit holds both. Because this rewrites the branch's history, the push needs force. Use --force-with-lease, never plain --force: it refuses if someone else pushed to the branch in the meantime, so you cannot wipe out their work.
Merge on GitHub. On the PR page, open the merge button's menu, choose Squash and merge, check the message, and confirm. (GitHub can also do the squash for you at this point, even without the local squash.) Click Delete branch.
Catch up locally. Switch to main and pull. --prune also forgets remote branches that were deleted on GitHub. GitHub's squash made a new commit, so Git cannot tell your local branch was merged and git branch -d refuses; now that you have seen the PR merged, -D deletes it.
git reset --soft main
git commit -m "Test that an unknown product returns 404 with not_found (NF-4)"
git push --force-with-lease
git log --oneline
# now click "Squash and merge" on the PR page, then:
git switch main
git pull --prune
git branch -D test/unknown-product-404
git log --oneline [test/unknown-product-404 80e845d] Test that an unknown product returns 404 with not_found (NF-4) 1 file changed, 8 insertions(+) To https://github.com/your-name/shoprung-tests.git + e105495...80e845d test/unknown-product-404 -> test/unknown-product-404 (forced update) 80e845d Test that an unknown product returns 404 with not_found (NF-4) 8fd5c45 Add ShopRung test project: pricing, puzzles and API checks Switched to branch 'main' Your branch is up to date with 'origin/main'. From https://github.com/your-name/shoprung-tests - [deleted] (none) -> origin/test/unknown-product-404 8fd5c45..87d820d main -> origin/main Updating 8fd5c45..87d820d Fast-forward src/test/java/dev/algorung/shop/ShopRungApiTest.java | 8 ++++++++ 1 file changed, 8 insertions(+) Deleted branch test/unknown-product-404 (was 80e845d). 87d820d Test that an unknown product returns 404 with not_found (NF-4) (#1) 8fd5c45 Add ShopRung test project: pricing, puzzles and API checks
git reset --soft main
git commit -m "Test that an unknown product returns 404 with not_found (NF-4)"
git push --force-with-lease
# now click "Squash and merge" on the PR page, then:
git switch main
git pull --prune
git branch -D test/unknown-product-404
git log --oneline [test/unknown-product-404 e1c9699] Test that an unknown product returns 404 with not_found (NF-4) 1 file changed, 6 insertions(+) ... + 5d0f08b...e1c9699 test/unknown-product-404 -> test/unknown-product-404 (forced update) Switched to branch 'main' ... Fast-forward test_shoprung_api.py | 6 ++++++ 1 file changed, 6 insertions(+) Deleted branch test/unknown-product-404 (was e1c9699). 3c41a7e Test that an unknown product returns 404 with not_found (NF-4) (#1) b1c7546 Add ShopRung test project: pricing, puzzles and API checks
Stuck on this step?
stale info/rejectedon--force-with-lease- Someone (or the GitHub web page) pushed to the branch after your last pull. Run
git pull, look at what came in, squash again and push. error: the branch ... is not fully merged- Expected after a squash merge: the commits on your branch are not on
main, a new squashed one is. Check the PR shows Merged on GitHub, then usegit branch -D. - I squashed and the commit is missing my changes
- Nothing is lost.
git refloglists every position the branch had;git reset --hard <id>with the id from before the reset puts it back. Ask a teammate before using--hardon anything you are unsure of.
Check it works
Check each of these:
- On github.com, the pull request shows Merged, and the branch is deleted.
git log --onelineonmainshows exactly two commits: the project, and the squashed test with(#1)at the end.git statussays nothing to commit, working tree clean, andgit status --ignoredliststarget/(Python:.venv/and__pycache__/) as ignored, not untracked.- The tests on
mainpass, now 41 of them, with the new not-found test among them.
git log --oneline
git status
mvn test # Python: pytest -qgit log --oneline
git status
mvn test # Python: pytest -qgit log --oneline
git status
mvn test # Python: pytest -q 87d820d Test that an unknown product returns 404 with not_found (NF-4) (#1) 8fd5c45 Add ShopRung test project: pricing, puzzles and API checks On branch main Your branch is up to date with 'origin/main'. nothing to commit, working tree clean [INFO] Tests run: 41, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
Troubleshooting
I committed on main by mistake instead of on a branch
If you have not pushed: git switch -c my-branch (the branch now has the commit), then git switch main and git reset --hard origin/main to put main back. Check git log --oneline on both before and after.
I want to change the message or add a file to the last commit
Stage the file if any, then git commit --amend -m "new message". Only do this before pushing, or push with --force-with-lease on your own branch afterwards.
CONFLICT (content): Merge conflict in ...
Two branches changed the same lines. Open the file, find the <<<<<<<, ======= and >>>>>>> markers, keep the right lines and delete the markers, run the tests, then git add the file and git commit (or git rebase --continue during a rebase).
Windows: every line shows as changed in git diff
Line endings. Run git config --global core.autocrlf true on Windows (Git for Windows usually sets it on install), and add a .gitattributes file with * text=auto so the repository stores one style.
I pushed a password or token
Treat it as leaked: revoke it first (make a new one), because deleting it from the file does not delete it from the history. Then remove it from the code, move it to .env and read it from an environment variable.
What changes in production
mainis protected. Teams turn on branch protection (GitHub rulesets): no direct pushes, at least one approval, and the CI checks must pass before the merge button works.- CI runs the tests on every pull request. The PR page shows a green tick or a red cross next to each check, and reviewers look at that before the code. The lab Suites in GitHub Actions sets this up.
- Test code gets the same review as product code. Reviewers look for missing boundaries, assertions that are too weak (like the status-code-only test here), sleeps, hard-coded data and tests that cannot fail.
- CODEOWNERS (a file in
.github/) can make the QA team a required reviewer for changes to test folders, and developers required reviewers for the code the tests cover.
Interview angle
“Walk me through how a new automated test gets from your laptop into the main branch.”
I pull the latest main and create a branch named after the change, like test/unknown-product-404. I write the test, run the suite, and make sure I have seen the new test fail once, so I know it can catch something. I read my own diff, commit with an imperative message, push with -u and open a small pull request using the team template: what it covers, which requirement, and how I tested it. CI runs the suite on the PR. When a reviewer asks for stronger assertions I push a new commit to the same branch, reply and resolve the comments. Once it is approved and green, we squash and merge so main gets one commit per change, and I delete the branch and pull main. If my branch fell behind, I rebase it on main and push with --force-with-lease, never plain --force.
Clean up
Keep the repository: later labs add to it, and Suites in GitHub Actions runs it in CI. Stop ShopRung with Ctrl+C. If you made a practice repository you no longer want, you can delete it on github.com under the repository's Settings, at the bottom, or with gh (it asks you to confirm, and needs gh auth refresh -s delete_repo once).
gh repo delete your-name/shoprung-tests Practice
These run in your browser and check your answer.
Check a commit subject
Many teams check commit messages in CI. Write subject_problems(message) that looks at the first line of a commit message and returns a list of problems, using these rules: it must not be empty ("empty"), be at most 72 characters ("too long"), start with a capital letter ("lowercase start") and not end with a full stop ("ends with a period"). A good subject returns []. Return the problems in the order of the rules.
def subject_problems(message):
subject = message.split("\n")[0]
problems = []
if len(subject) > 72:
problems.append("too long")
return problems
print(subject_problems("fix the test."))
Hint
Return `["empty"]` straight away when the subject is empty. Then check `subject[0].isupper()` and `subject.endswith(".")`.
The full project
Every file from this lab, as it is after the last step.