My chess game has three layers. There's a browser page, a small Flask server, and a chess engine written in C. The server runs the engine as a separate program. You can follow the whole build in How to Make AI Projects in C. My build notes say a layer can look fine in the code and still give you a 404 or a 500. It happened to me twice. Below you'll see what each bug looked like, why it happened, and the tests that now catch it. I ran every test on Python 3.14 with GCC 16.1 on Windows.
How the Layers Talk
Browser (HTML/CSS/JS) --JSON--> Flask (server.py) --command line--> C engine (engine.exe) The browser never talks to the engine. It sends the board and a move to Flask. Flask runs the engine as a subprocess and reads one line of output. Then it answers the browser with JSON. So a mistake in one layer pops up in another layer as a vague error. A missing file in the engine layer becomes a 500 in the server layer. A misnamed folder becomes a 404 and leaves the page dead. Each bug below needed a test that looks at the layer where it really breaks.
Bug 1: The Engine Path Gives a 500
The server finds the engine through one path:
BASE = os.path.dirname(os.path.abspath(__file__)) # The compiled binary lives in the engine/ folder next to server.py. Use engine.exe on Windows. ENGINE = os.path.join(BASE, "engine", "engine.exe" if os.name == "nt" else "engine") DEPTH = "4" # how many moves ahead the AI thinks (1-6) My notes list this line as a path that gave a 404 or a 500 when it pointed at the project root instead of the engine folder. If the file isn't where the path says, subprocess.run raises FileNotFoundError inside the route. Flask turns any uncaught exception into a bare 500 Internal Server Error. The real message shows up only in the server's console. I reproduced it by pointing ENGINE at the root:
def test_a_wrong_engine_path_is_a_500(server, project): server.ENGINE = str(project / ("engine.exe" if os.name == "nt" else "engine")) # the root, not engine/ server.app.config["PROPAGATE_EXCEPTIONS"] = False assert post_move(server).status_code == 500 You've already seen the fix in the code above. Build the path from __file__. It becomes absolute, so the folder you start the server in no longer matters. The same 500 can come from somewhere else too, and it's easy to miss. A relative engine path works only when the server starts in the project folder. The next test starts it in the right folder (works) and then in a different one (fails):
def test_a_relative_engine_path_breaks_when_the_server_starts_elsewhere(server, project, monkeypatch, tmp_path): exe = os.path.join("engine", "engine.exe" if os.name == "nt" else "engine") monkeypatch.chdir(project) server.ENGINE = exe # relative: only correct from the project folder assert post_move(server).status_code == 200 monkeypatch.chdir(tmp_path) # same server, started from another folder server.app.config["PROPAGATE_EXCEPTIONS"] = False assert post_move(server).status_code == 500 Windows throws in one more surprise. On my PC, a relative path with a forward slash, engine/engine.exe, raised FileNotFoundError: [WinError 2] The system cannot find the file specified. That happened even when I started the server from the correct folder. The same path built with os.path.join worked, because it writes a backslash on Windows. A test records this, so nobody has to find it out again:
@pytest.mark.skipif(os.name != "nt", reason="Windows only") def test_on_windows_a_relative_path_with_a_forward_slash_is_not_found_even_from_the_right_folder(server, project, monkeypatch): monkeypatch.chdir(project) server.ENGINE = "engine/engine.exe" # the same file, written with a forward slash server.app.config["PROPAGATE_EXCEPTIONS"] = False assert post_move(server).status_code == 500 Bug 2: The Folder Is Called statics and the Page Is Dead
The page pulls in its stylesheet and script like this: <link rel="stylesheet" href="static/style.css"> and <script src="static/script.js">. Flask serves them from the folder named in static_folder. So three things must match: the folder name on disk, the static_folder setting, and the links in the HTML. According to my notes, the link broke when the folder was named statics.
This bug is confusing because the page still loads. You just get an unstyled page. The JavaScript returns a 404, so the buttons and squares do nothing. Nothing points you at the cause. The test renames the folder and checks each piece:
def test_a_static_folder_called_statics_makes_the_page_unstyled_and_dead(project, tmp_path): broken = tmp_path / "Chess-Game" shutil.copytree(project, broken) (broken / "static").rename(broken / "statics") client = load_server(broken, "chess_server_statics").app.test_client() assert client.get("/").status_code == 200 # the page itself still loads... assert client.get("/static/style.css").status_code == 404 # ...but the CSS assert client.get("/static/script.js").status_code == 404 # ...and the JavaScript are gone One more test guards against this whole class of mistake. It reads each static/... link from the HTML and requests it. A renamed or missing file now fails the test, not your user:
def test_every_asset_the_page_links_to_is_served(server): import re html = (Path(server.BASE) / "templates" / "index.html").read_text(encoding="utf-8") links = re.findall(r'(?:href|src)="(static/[^"]+)"', html) assert links, "the page should link to its CSS and JavaScript" client = server.app.test_client() for link in links: assert client.get("/" + link).status_code == 200, link A Test That Passed for the Wrong Reason
My first statics test failed in a strange way. It got a 200 when it expected a 404. The server was handing out a stylesheet from a folder that didn't exist in that copy. Here's why. Flask(__name__) looks the module up in sys.modules. My test helper loaded server.py from a path but never registered it there. So Flask quietly fell back to the current folder, which was the original project with a proper static folder. The helper needed one extra line:
spec = importlib.util.spec_from_file_location(name, folder / "server.py") module = importlib.util.module_from_spec(spec) sys.modules[name] = module # Flask finds the static folder through sys.modules spec.loader.exec_module(module) Here's the takeaway. If a test has never failed, you don't know it works. Break the code on purpose and see whether the test complains.
Bug 3: Clicks on the Board and Captures
The last item in my notes is about the board. It says that attaching click handlers to each square while drawing the board broke captures twice. I didn't keep the failing version, so I can't show you the exact bug. I can show you that captures work now, in the real page, and that the test fails when they stop working. In the real script.js, render() redraws all 64 squares every time. Each square gets a click handler that depends on the current state:
if (p !== '.') { ... if (!locked) { if (p === p.toUpperCase()) sq.onclick = () => selectPiece(idx); else if (selected >= 0) sq.onclick = () => tryMove(selected, idx); // capture } } else if (selected >= 0 && !locked) { sq.onclick = () => tryMove(selected, idx); } The capture is the line ending in // capture. An enemy piece only gets a handler when one of your pieces is selected. The squares are rebuilt each time, so a handler is only as correct as the state when it was drawn. That calls for a browser test, so it drives the real page with Playwright. The AI's reply is scripted, which means the test knows where Black's pawn is. Everything else is real: the Flask server, the C engine and the page. White plays e4, Black answers d5, and then White clicks the e4 pawn and the d5 square:
def test_a_capture_works_in_the_browser(server): """White plays e4, a scripted Black answers d5, and then White captures exd5 by clicking two squares.""" pytest.importorskip("playwright") from playwright.sync_api import sync_playwright from werkzeug.serving import make_server after_e4 = server.apply_move(server.START, "e2e4") after_d5 = server.apply_move(after_e4, "d7d5") srv = make_server("127.0.0.1", 5066, server.app) threading.Thread(target=srv.serve_forever, daemon=True).start() try: with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page() # the AI's reply is scripted so the test knows exactly where Black's pawn is; everything else is real page.route("**/api/ai", lambda r: r.fulfill( status=200, content_type="application/json", body='{"ok": true, "board": "%s", "status": "playing", "move": "d7d5", "message": "AI played d7d5"}' % after_d5)) page.goto("http://127.0.0.1:5066/") square = lambda idx: page.locator(f"#board > div:nth-child({idx + 1})") square(52).click() # e2 square(36).click() # e4 page.wait_for_function("board[27] === 'p' && !locked", timeout=30000) # Black's d5 pawn is on the board square(36).click() # select the e4 pawn square(27).click() # click d5: capture page.wait_for_function("board[27] === 'P'", timeout=30000) assert page.evaluate("board[36]") == "." # the e4 square is empty again browser.close() finally: srv.shutdown() I wanted proof that this test can fail. So I deleted the line ending in // capture from script.js and ran it again. The capture never happened, and the test failed with a timeout. Then I put the line back and the test passed.
Two Comments That Were Lying
Two other bugs weren't about behavior. The top of engine.c claimed there was no castling, yet castling was fully built further down. Also, a comment in server.py put the engine next to server.py, while the code correctly pointed into an engine folder. Nothing crashed. But a reader meets those comments first, and they were wrong. I corrected both in the repository. Tests can't catch a lying comment. A review can.
Running the Tests
pip install -r requirements-dev.txt playwright install chromium pytest Each test compiles the engine in a throwaway copy of the project, so your files are safe. This was my last run:
9 passed in 7.83s Playwright missing on your machine? Then the browser test gets skipped, and the other eight run as usual. If gcc is missing, every test is skipped.
What to Remember
Look for each failure in the layer where it shows up. A bad engine path is a 500 from the server. A wrong folder name is a 404 for the CSS. A broken click is a wrong result on the page.
Build every path the server runs or reads from
__file__, so it's absolute. On Windows, don't handsubprocessa relative path with a forward slash.Keep the static folder name identical in three places: the folder,
static_folder, and the links in the HTML.Check that your test can fail. Break the code once, on purpose, and watch what happens.
The whole project, with the tests, is on GitHub: C-Programing/AI-Projects/Chess-Game. Other posts with tested fixes: FileNotFoundError, A Failed API Call Saved as NULL and Flask Speech to Text With faster-whisper.
