package com.ankurm.prreviewer; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.chat.model.ChatModel; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.context.ApplicationContextInitializer; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import org.slf4j.LoggerFactory; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executors; import static com.ankurm.prreviewer.GiteaAdmin.*; import static org.assertj.core.api.Assertions.assertThat; /** Runs against a real, local, throwaway Gitea started by {@code scripts/gitea-up.sh}. */ @EnabledIfEnvironmentVariable(named = "GITEA_URL", matches = "http://(localhost|127\\.0\\.0\\.1).*") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class GiteaLiveTest { private final GiteaAdmin gitea = new GiteaAdmin(); /** Cart.java with two added lines, at 7 and 26, on branch "feature". */ private String cartPull(String repo) { gitea.create(repo, "src/Cart.java", cart(List.of()), "main", null); gitea.update(repo, "src/Cart.java", cart(List.of("7: String password = \"hunter2\";", "26: void pay() { System.out.println(\"pay\"); }")), "main", "feature"); gitea.openPull(repo, "feature"); return repo; } private GiteaAdmin.Answer review(String repo, String sha, Object... lineAndBody) { List> comments = new ArrayList<>(); for (int i = 0; i < lineAndBody.length; i += 3) { comments.add(Map.of("path", lineAndBody[i], "new_position", lineAndBody[i + 1], "body", lineAndBody[i + 2])); } return gitea.call(BOT, "POST", "/repos/" + repo + "/pulls/1/reviews", Map.of("commit_id", sha, "event", "COMMENT", "body", "probe", "comments", comments)); } @Test @Order(1) void whatGiteaAcceptsAsACommentPosition() { String repo = cartPull(gitea.repo("accept")); String sha = gitea.headSha(repo, 1); var t = new Transcript("11-gitea-accepts.txt"); t.line("the diff:"); t.block(gitea.diff(repo, 1)); t.line(""); t.line("one review per row, one inline comment each (Gitea %s)", gitea.call(DEV, "GET", "/version", null).json().path("version").asString()); record Row(String what, String path, int line, String marker) {} var rows = List.of( new Row("an added line", "src/Cart.java", 7, "probe-added"), new Row("a context line", "src/Cart.java", 8, "probe-context"), new Row("a line outside every hunk", "src/Cart.java", 15, "probe-outside"), new Row("a file that does not exist", "src/Nope.java", 3, "probe-nofile"), new Row("line 0", "src/Cart.java", 0, "probe-zero"), new Row("a line past the end of the file", "src/Cart.java", 9999, "probe-past")); List status = new ArrayList<>(); for (Row r : rows) { status.add(review(repo, sha, r.path(), r.line(), r.marker()).status()); } String conversation = gitea.webPage("/" + repo + "/pulls/1"); String files = gitea.webPage("/" + repo + "/pulls/1/files"); t.line("%-33s %5s %4s %-18s %s", "comment on", "line", "HTTP", "shown: conversation", "shown: files changed"); for (int i = 0; i < rows.size(); i++) { String p = "

" + rows.get(i).marker() + "

"; t.line("%-33s %5d %4d %-18s %s", rows.get(i).what(), rows.get(i).line(), status.get(i), count(conversation, p) > 0 ? "yes" : "no", count(files, p) > 0 ? "yes" : "no"); } var pending = gitea.reviews(repo, 1, BOT).stream().filter(r -> r.path("state").asString().equals("PENDING")).count(); t.line("PENDING reviews left behind by those calls: %d", pending); t.write(); assertThat(status).containsExactly(200, 200, 200, 200, 200, 500); } private void dump(Transcript t, String repo) { for (var r : gitea.reviews(repo, 1, BOT)) { t.line(" review %-8s body=%-8s comments: %s", r.path("state").asString(), '"' + r.path("body").asString() + '"', gitea.comments(repo, 1, r.path("id").asLong(), BOT).stream() .map(c -> c.path("body").asString() + "@" + c.path("position").asInt()).toList()); } } @Test @Order(2) void oneBadLineLeavesAPendingReviewBehind() { String repo = cartPull(gitea.repo("pending")); String sha = gitea.headSha(repo, 1); var t = new Transcript("12-gitea-pending-review.txt"); Object[] batch = {"src/Cart.java", 7, "good-A", "src/Cart.java", 9999, "ghost", "src/Cart.java", 26, "good-B"}; for (int i = 1; i <= 3; i++) { t.line("POST review [good-A@7, ghost@9999, good-B@26], attempt %d -> HTTP %d", i, review(repo, sha, batch).status()); } t.line("reviews as the bot sees them now:"); dump(t, repo); var next = review(repo, sha, "src/Cart.java", 26, "unrelated"); t.line(""); t.line("POST review [unrelated@26] -> HTTP %d", next.status()); t.line("reviews now:"); dump(t, repo); var published = gitea.comments(repo, 1, next.json().path("id").asLong(), BOT); assertThat(published).extracting(c -> c.path("body").asString()) .containsExactlyInAnyOrder("good-A", "good-A", "good-A", "unrelated"); // The same leftover, but the next writer is our service: it clears pending reviews first. String repo2 = cartPull(gitea.repo("cleanup")); review(repo2, gitea.headSha(repo2, 1), batch); t.line(""); t.line("second repository, same failed batch once, then ReviewService.review():"); var service = new ReviewService(new ModelReviewer(org.springframework.ai.chat.client.ChatClient.create(ScriptedChatModel.ruleBased())), new GiteaClient(URL, BOT), ReviewServiceTest.SETTINGS); service.review(repo2, 1, gitea.headSha(repo2, 1)); for (var r : gitea.reviews(repo2, 1, BOT)) { var bodies = gitea.comments(repo2, 1, r.path("id").asLong(), BOT).stream() .map(c -> c.path("body").asString().lines().findFirst().orElse("") + " @" + c.path("position").asInt()).toList(); t.line(" review %s", r.path("state").asString()); bodies.forEach(b -> t.line(" %s", b)); assertThat(bodies).noneMatch(b -> b.startsWith("good-A")); } t.write(); } @Test @Order(3) void anOldCommitIdDoesNotPinTheLine() { String repo = cartPull(gitea.repo("stale")); String old = gitea.headSha(repo, 1); gitea.update(repo, "src/Cart.java", cart(List.of("4: // one", "5: // two", "6: // three", "7: // four", "11: String password = \"hunter2\";", "30: void pay() { System.out.println(\"pay\"); }")), "feature", null); var t = new Transcript("13-gitea-stale-commit.txt"); t.line("commit A adds the password on line 7. commit B then inserts four comment lines above it."); var answer = review(repo, old, "src/Cart.java", 7, "about the password"); t.line("POST review with commit_id=A, new_position=7 -> HTTP %d, review stale=%s", answer.status(), answer.json().path("stale").asBoolean()); var c = gitea.comments(repo, 1, answer.json().path("id").asLong(), BOT).getFirst(); t.line("diff_hunk Gitea attached to the comment:"); t.block(c.path("diff_hunk").asString()); t.write(); assertThat(c.path("diff_hunk").asString()).contains("// four").doesNotContain("password"); } @Test @Order(4) void endToEndThroughARealWebhook() throws Exception { var model = ScriptedChatModel.ruleBased(); ApplicationContextInitializer scripted = ctx -> ctx.registerBean(ChatModel.class, () -> model); var logs = new ListAppender(); try (ConfigurableApplicationContext app = new SpringApplicationBuilder(ReviewerApplication.class) .initializers(scripted) .run("--server.port=0", "--spring.ai.model.chat=none", "--reviewer.gitea-url=" + URL, "--reviewer.gitea-token=" + BOT, "--reviewer.webhook-secret=s3cret")) { logs.start(); ((Logger) LoggerFactory.getLogger(WebhookController.class)).addAppender(logs); int port = app.getEnvironment().getProperty("local.server.port", Integer.class); String repo = gitea.repo("e2e"); gitea.create(repo, "src/UserDao.java", Samples.BASE, "main", null); gitea.hook(repo, "http://" + System.getenv("WEBHOOK_HOST") + ":" + port + "/webhook/gitea", "s3cret"); var t = new Transcript("14-end-to-end.txt"); gitea.update(repo, "src/UserDao.java", Samples.FEATURE, "main", "feature"); gitea.openPull(repo, "feature"); t.line("1. pull request opened -> %s", outcome(logs, 1)); String shifted = "// Copyright\n// All rights reserved\n" + Samples.FEATURE; gitea.update(repo, "src/UserDao.java", shifted, "feature", null); t.line("2. push: two lines on top -> %s", outcome(logs, 2)); gitea.update(repo, "src/UserDao.java", shifted.replace(" return role == \"admin\";", " System.out.println(role);\n return role == \"admin\";"), "feature", null); t.line("3. push: one new problem -> %s", outcome(logs, 3)); t.line(""); t.line("inline comments on the pull request, read back from Gitea:"); List bodies = new ArrayList<>(); for (var r : gitea.reviews(repo, 1, DEV)) { t.line(" review by %s, state %s, stale=%s", r.path("user").path("login").asString(), r.path("state").asString(), r.path("stale").asBoolean()); for (var c : gitea.comments(repo, 1, r.path("id").asLong(), DEV)) { bodies.add(c.path("body").asString()); t.line(" %s:%d %s", c.path("path").asString(), c.path("position").asInt(), c.path("body").asString().lines().findFirst().orElse("")); } } t.line(""); t.line("first comment body as stored:"); t.block(bodies.getFirst()); String page = gitea.webPage("/" + repo + "/pulls/1"); t.line(""); // Gitea keeps the raw markdown of every comment in a hidden div for its edit box. String visible = page.replaceAll("(?s)
.*?
", ""); t.line("conversation page: marker in the hidden raw-markdown blocks %d time(s), in the rendered comments %d time(s)", count(page, "<!-- pr-reviewer:") - count(visible, "<!-- pr-reviewer:"), count(visible, "pr-reviewer:")); t.write(); assertThat(bodies).hasSize(3); } finally { ((Logger) LoggerFactory.getLogger(WebhookController.class)).detachAppender(logs); } } /** Waits for the n-th "reviewed ..." log line and summarises its report. */ private static String outcome(ListAppender logs, int n) throws InterruptedException { for (int i = 0; i < 300; i++) { var done = new ArrayList<>(logs.list).stream().filter(e -> e.getMessage().startsWith("reviewed")).toList(); if (done.size() >= n) { ReviewReport r = (ReviewReport) done.get(n - 1).getArgumentArray()[3]; return "%-11s posted %d, already there %d".formatted(r.status(), r.posted().size(), r.dropped().stream().filter(d -> d.reason().equals("ALREADY_POSTED")).count()); } Thread.sleep(100); } throw new AssertionError("no review " + n); } @Test @Order(5) void failedAndSlowDeliveriesAreNotRetried() throws IOException, InterruptedException { List seen = new CopyOnWriteArrayList<>(); HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", 0), 0); long start = System.nanoTime(); server.createContext("/", exchange -> { exchange.getRequestBody().readAllBytes(); String path = exchange.getRequestURI().getPath(); seen.add(path); if (path.equals("/slow")) { try { Thread.sleep(8_000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } try { exchange.sendResponseHeaders(path.equals("/fail") ? 500 : 202, -1); } catch (IOException ignored) { // Gitea has hung up by now } exchange.close(); }); server.setExecutor(Executors.newVirtualThreadPerTaskExecutor()); server.start(); try { String repo = gitea.repo("delivery"); String base = "http://" + System.getenv("WEBHOOK_HOST") + ":" + server.getAddress().getPort(); gitea.hook(repo, base + "/fail", "s"); gitea.hook(repo, base + "/slow", "s"); cartPull(repo); Thread.sleep(60_000); var t = new Transcript("15-delivery-not-retried.txt"); t.line("one pull request opened, two webhooks, 60 seconds of waiting"); t.line("receiver that answers 500 : %d request(s) received", seen.stream().filter("/fail"::equals).count()); t.line("receiver that answers after 8 seconds: %d request(s) received", seen.stream().filter("/slow"::equals).count()); t.write(); assertThat(seen).containsExactlyInAnyOrder("/fail", "/slow"); } finally { server.stop(0); } } @Test @Order(6) void whereTheTimeGoes() { String repo = gitea.repo("latency"); StringBuilder file = new StringBuilder("class C%d {\n"); for (int i = 0; i < 100; i++) { file.append(i % 25 == 0 ? " void f" + i + "() { System.out.println(" + i + "); }\n" : " int field" + i + " = " + i + ";\n"); } file.append("}\n"); gitea.create(repo, "README2.md", "x\n", "main", "feature"); for (int i = 0; i < 8; i++) { gitea.create(repo, "src/C" + i + ".java", file.toString().formatted(i), "feature", null); } gitea.openPull(repo, "feature"); var settings = new ReviewSettings("reviewbot", 6000, 20, 100, Severity.MINOR); var model = ScriptedChatModel.ruleBased(); var t = new Transcript("16-pipeline-latency.txt"); t.line("8 new files, 102 lines each; local Gitea; the model is scripted and answers instantly"); t.line("%-34s %6s %6s %6s %6s %6s %6s", "run", "chunks", "posted", "fetch", "model", "dedup", "post"); String sha = gitea.headSha(repo, 1); for (int run = 1; run <= 5; run++) { var r = new ReviewService(new ModelReviewer(org.springframework.ai.chat.client.ChatClient.create(model)), new GiteaClient(URL, BOT), settings).review(repo, 1, sha); t.line("%-34s %6d %6d %4dms %4dms %4dms %4dms", "run " + run + (run == 1 ? " (cold JVM paths)" : ""), r.chunks(), r.posted().size(), r.timings().fetch(), r.timings().model(), r.timings().dedup(), r.timings().post()); } // De-duplication reads every earlier review with one request each. for (int i = 0; i < 60; i++) { review(repo, sha, "src/C0.java", 2, "older review " + i); } var client = new GiteaClient(URL, BOT); var service = new ReviewService(new ModelReviewer(org.springframework.ai.chat.client.ChatClient.create(model)), client, settings); long reviews = client.reviews(repo, 1).size(); service.review(repo, 1, sha); var r = service.review(repo, 1, sha); assertThat(reviews).isGreaterThan(50); // more than one page assertThat(r.posted()).isEmpty(); t.line(""); t.line("after %d reviews on the pull request: dedup phase %d ms (one request per review)", reviews, r.timings().dedup()); t.write(); } }