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

1 / 7

0 of 8 steps done

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.

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

Run
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
You should see
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.

Run
brew install gh
gh auth login
You should seeyour text will differ: the model writes it
? 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.

1

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.

Run
git init
git status
You should seeyour text will differ: the model writes it
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)
Stuck on this step?
It says On branch master
Your Git was set up before the init.defaultBranch setting. Run git branch -m main to rename the branch now, and set git config --global init.defaultBranch main for 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 log to see whether it already has commits.
2

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.

.gitignore
# 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
  1. Maven puts everything it builds in target/, including the test reports. mvn clean deletes it, and nothing is lost.line 2
  2. IntelliJ and VS Code settings are personal. The pom.xml is all another person needs to open the project.line 5
  3. macOS and Windows create these files in folders by themselves.line 13
  4. Not used yet, but later labs keep tokens in .env. Ignore it from day one.line 17
.github/pull_request_template.md
## 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
  1. An HTML comment: the author sees it while writing, and it is hidden on the pull request page.line 3
  2. - [ ] is a checkbox. The author ticks each one when it is true.line 7
Run
git status --short
git check-ignore -v target/classes
You should see
?? .github/
?? .gitignore
?? README.md
?? pom.xml
?? src/
.gitignore:2:target/	target/classes
Why this way? A good .gitignore is the first thing a reviewer checks in a new test project. Committed build output makes every pull request noisy and every merge a conflict.
Stuck on this step?
target/ still shows in git status
Check the file is called exactly .gitignore (Windows Notepad may save it as .gitignore.txt: run ls -a or dir -Force to see) and that it is in the project folder, next to pom.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.
3

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.

Run
git add .
git status --short
git commit -m "Add ShopRung test project: pricing, puzzles and API checks"
git log --oneline
You should seeyour text will differ: the model writes it
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
Why this way? The commit id (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 commit without -m. In Vim: press Esc, type :q! and Enter to cancel, then commit with -m "message". In nano: Ctrl+X.
4

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.

Run
gh repo create shoprung-tests --private --source=. --remote=origin --push
git remote -v
You should seeyour text will differ: the model writes it
✓ 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)
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 -v to see it, and git remote remove origin if it points at the wrong place.
Permission denied or Authentication failed on push
Run gh auth status. If you are not logged in, run gh auth login again and answer Yes to "Authenticate Git with your GitHub credentials". GitHub does not accept your account password for git push.
5

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.

src/test/java/dev/algorung/shop/ShopRungApiTest.java 3 new or changed lines
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());
    }
}
  1. A new test at the end of the class. It uses the get helper from lab 4.line 90
  2. ShopRung has 12 products, so id 999 does not exist.line 91
Run
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"
You should seeyour text will differ: the model writes it
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(+)
Stuck on this step?
git diff shows nothing
The file is not saved, or you already ran git add (then use git diff --staged). New files never show in git diff until they are added.
git switch is not a git command
Your Git is older than 2.23. Use git checkout -b test/unknown-product-404 instead, 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.
6

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.

Run
git push -u origin test/unknown-product-404
gh pr create --web
You should seeyour text will differ: the model writes it
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.
Why this way? Small pull requests get better reviews. One new test with a clear description is reviewed in minutes; a PR with forty files changed tends to be skimmed and approved without being read.
Stuck on this step?
fatal: The current branch has no upstream branch
You ran git push without -u origin <branch> on a new branch. Run the command exactly as shown once; after that a plain git push works.
The PR description is empty, no template
GitHub reads the template from the default branch. Check .github/pull_request_template.md was part of the first commit and is on main on github.com.
7

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 the error code and the message too.

On the test name: Is404 names the status code. Say what the user gets, for example anUnknownProductIsNotFound, 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.

src/test/java/dev/algorung/shop/ShopRungApiTest.java 3 new or changed lines
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());
    }
}
  1. The name now says what the customer gets, not which number comes back.line 90
  2. The machine-readable error code from NF-4.line 93
  3. The human-readable message: it names the id that was not found.line 94
Run
mvn test
git commit -am "Check the error code and message, rename the test"
git push
git log --oneline
You should seeyour text will differ: the model writes it
[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
Why this way? 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, then git push again.
8

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.

Run
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
You should seeyour text will differ: the model writes it
[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
Why this way? Teams choose one merge style per repository. Squash and merge gives one commit per PR, easy to read and easy to revert. Rebase and merge keeps each commit. A merge commit keeps the branch shape. Many teams squash, so a test change can be found and undone as one unit.
Stuck on this step?
stale info / rejected on --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 use git branch -D.
I squashed and the commit is missing my changes
Nothing is lost. git reflog lists every position the branch had; git reset --hard <id> with the id from before the reset puts it back. Ask a teammate before using --hard on 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 --oneline on main shows exactly two commits: the project, and the squashed test with (#1) at the end.
  • git status says nothing to commit, working tree clean, and git status --ignored lists target/ (Python: .venv/ and __pycache__/) as ignored, not untracked.
  • The tests on main pass, now 41 of them, with the new not-found test among them.
Test
git log --oneline
git status
mvn test        # Python: pytest -q
You should see
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

  • main is 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).

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

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

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