Repository navigation
testing: add more unit tests to increase branch coverage - #7227
mohammed90 wants to merge 58 commits into
Conversation
|
AI disclosure: copilot + claude opus Bugs FoundBug 1:
|
|
Total change in coverage: === BEFORE (master) === Per file delta:
|
|
|
Thanks for working on this Mohammed! Can't wait to review this when it's ready. Random side note: I wonder if we should turn off verbose output for our tests, and only show failures, it's a LOT to scroll through otherwise. |
I think that's probably a good idea. We rarely need to analyze the specific details of the output, it ends up just being a lot of noise. We can run it locally with more verbosity, or just commit a flag while dev-ing on a PR to make it louder when debugging. It makes me sad that Go's module system causes the top-level dir of the project to get so polluted with files, especially test files which aren't particularly meaningful to be located there. Is there really nothing we can do about this? 😭 It's a lot of new files. I'm not sure I'll ever really have time to dive deep on these tests, but since it's almost entirely just tests that are passing, I see no harm in merging this if you're happy with it @mohammed90 |
For testing of exported funcs and methods, we can have a testing package with only |
There was a problem hiding this comment.
Pull request overview
Review by GitHub Copilot (agent). This PR primarily adds a broad set of new unit tests across multiple Caddy modules to improve branch coverage, plus a couple of small correctness fixes in core networking/admin logic.
Changes:
- Add many new unit tests covering Caddyfile unmarshaling, small helpers, crypto-related utilities, and handler behaviors across multiple modules.
- Fix an off-by-one in port-range span validation (
listeners.go). - Make admin origin host matching case-insensitive per RFC 3986 (
admin.go), and clarifyrandStringexclusion behavior in comments.
Reviewed changes
Copilot reviewed 50 out of 50 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| modules/filestorage/filestorage_test.go | Adds FileStorage module and Caddyfile parsing tests. |
| modules/caddytls/values_test.go | Adds tests for TLS cipher/protocol helper functions and maps. |
| modules/caddytls/certselection_test.go | Adds tests for custom certificate selection policy + bigInt JSON. |
| modules/caddypki/certificates_test.go | Adds tests for root/intermediate cert generation helpers. |
| modules/caddyhttp/vars_test.go | Adds tests for vars helpers and matcher behavior (includes a problematic “BUG” assertion). |
| modules/caddyhttp/templates/frontmatter_test.go | Adds tests for front matter extraction/parsing. |
| modules/caddyhttp/staticerror_test.go | Adds tests for StaticError handler and Caddyfile parsing. |
| modules/caddyhttp/rewrite/rewrite_utils_test.go | Adds tests/benchmarks for reverse() helper. |
| modules/caddyhttp/reverseproxy/hosts_test.go | Adds tests for Host/Upstream counters/health and concurrency. |
| modules/caddyhttp/requestbody/requestbody_test.go | Adds tests for request body limiting wrapper/handler. |
| modules/caddyhttp/push/handler_test.go | Adds tests for Link header parsing and remote resource detection. |
| modules/caddyhttp/proxyprotocol/policy_test.go | Adds tests for proxy protocol policy parsing/marshal/unmarshal. |
| modules/caddyhttp/marshalers_test.go | Adds tests for log marshalers (HTTP request + TLS state). |
| modules/caddyhttp/logging/logappend_test.go | Adds tests for log_append behavior (uses reflect/unsafe to inspect unexported fields). |
| modules/caddyhttp/ip_range_test.go | Adds tests for CIDR parsing and StaticIPRange (but re-implements Provision logic). |
| modules/caddyhttp/intercept/intercept_test.go | Adds tests for intercept handler Caddyfile parsing. |
| modules/caddyhttp/httpredirectlistener_test.go | Adds tests for first-bytes HTTP detection and module info. |
| modules/caddyhttp/errors.go | Updates randString doc comment. |
| modules/caddyhttp/errors_utils_test.go | Adds tests/benchmarks for randString. |
| modules/caddyhttp/errors_test.go | Adds tests for HandlerError/Error behavior. |
| modules/caddyhttp/encode/zstd/zstd_test.go | Adds tests for zstd encoder module/provision/unmarshal. |
| modules/caddyhttp/encode/gzip/gzip_test.go | Adds tests for gzip encoder module/validate/unmarshal. |
| modules/caddyhttp/caddyauth/bcrypt_test.go | Adds tests for bcrypt hash module behavior. |
| modules/caddyhttp/caddyauth/argon2id_test.go | Adds tests for argon2id hash decode/compare/hash helpers. |
| listeners.go | Fixes port-range span check to be inclusive. |
| internal/sockets_test.go | Adds tests for unix socket permission parsing helper. |
| internal/ranges_test.go | Adds tests for private ranges + MaxSizeSubjectsListForLog (contains contradictory “BUG” narrative). |
| internal/metrics/metrics_test.go | Expands tests/benchmarks for metric sanitizers. |
| internal/logmarshalers_test.go | Adds tests for header redaction and log array marshaling. |
| internal/logbuffer_test.go | Adds tests for buffered logging core behavior and concurrency. |
| internal/filesystems/filesystems_test.go | Adds tests for FileSystemMap behavior and OsFS interface compliance. |
| filesystem_test.go | Adds tests of a test-defined mock filesystem (does not exercise production code; mock Read EOF behavior is incorrect). |
| filepath_test.go | Adds tests/benchmarks for FastAbs (non-windows). |
| cmd/packagesfuncs_test.go | Adds tests/benchmarks for module@version splitting. |
| caddyconfig/httpcaddyfile/shorthands_test.go | Adds tests for shorthand placeholder rewriting. |
| caddyconfig/configadapters_test.go | Adds tests for JSON helpers and adapter lookup behavior. |
| caddyconfig/caddyfile/importgraph_test.go | Adds tests for import graph operations (some “bug documentation” tests don’t assert). |
| caddyconfig/caddyfile/importargs_test.go | Adds tests for variadic args parsing + args replacer (some ineffective assertions). |
| caddyconfig/caddyfile/adapter_test.go | Adds tests for formatting-difference detection. |
| api_error_test.go | Adds tests/benchmarks for APIError behavior and JSON round-trips. |
| admin.go | Makes origin host comparison case-insensitive. |
Suppressed comments (2)
caddyconfig/caddyfile/importgraph_test.go:240
- Like the self-loop test, this “bug documentation” test never fails; it only logs when the buggy behavior is observed. That makes the suite pass even when the behavior is wrong and provides no protection against regressions. Prefer an assertion (with corresponding implementation fix) or an explicit t.Skip with a TODO.
// This test documents a known bug: removeNode doesn't clean up edges.
// Edges FROM the removed node remain in the adjacency list.
g := &importGraph{}
g.addNodes([]string{"a", "b", "c"})
_ = g.addEdge("a", "b")
filesystem_test.go:52
- Read() should return io.EOF when the file is exhausted; returning fs.ErrClosed indicates the file was closed, not that it reached EOF.
func (m *mockFile) Read(b []byte) (int, error) {
if m.pos >= len(m.content) {
return 0, fs.ErrClosed
}
n := copy(b, m.content[m.pos:])
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // BUG: SetVar with nil for non-existent key should be a no-op per its documentation, | ||
| // but it actually inserts a nil value into the map. The nil check only deletes | ||
| // existing keys; if the key doesn't exist, execution falls through to the | ||
| // final `varMap[key] = value` line, storing nil. | ||
| SetVar(ctx, "nonexistent", nil) | ||
| if _, ok := vars["nonexistent"]; !ok { | ||
| t.Error("BUG: SetVar(nil) for non-existent key unexpectedly did NOT set the key. If this passes, the bug described in code comments may have been fixed.") | ||
| } |
| // BUG: When maxToDisplay is 0, code still appends one domain | ||
| // because append happens before the break check in the loop. | ||
| // Expected behavior: 1 item (just suffix). Actual: 2 items | ||
| // (1 leaked domain + suffix). | ||
| wantLen: 2, | ||
| wantSuffix: true, |
| // BUG: Self-loops are not detected by willCycle(). The function checks if | ||
| // adding edge from→to would create a cycle by traversing edges from "to" | ||
| // to see if "from" is reachable. But for a self-loop (from==to), the edge | ||
| // doesn't exist yet, so the DFS finds nothing and returns false. | ||
| // A self-importing file would NOT be caught by this cycle detection. | ||
| err := g.addEdge("a", "a") | ||
| if err != nil { | ||
| t.Log("Self-loop was correctly detected (bug may have been fixed)") | ||
| } else { | ||
| t.Log("BUG CONFIRMED: addEdge('a', 'a') did not detect self-loop cycle") | ||
| } |
| s := &StaticIPRange{Ranges: tt.ranges} | ||
| // We can't easily create a caddy.Context here without full module setup, | ||
| // but Provision only uses the ranges field, so we test the logic directly. | ||
| // The Provision method calls CIDRExpressionToPrefix which we test separately. | ||
| var parsedCount int | ||
| var gotErr bool | ||
| for _, r := range s.Ranges { | ||
| _, err := CIDRExpressionToPrefix(r) | ||
| if err != nil { | ||
| gotErr = true | ||
| break | ||
| } | ||
| parsedCount++ | ||
| } | ||
|
|
||
| if gotErr != tt.wantErr { | ||
| t.Errorf("provision error = %v, wantErr %v", gotErr, tt.wantErr) | ||
| } | ||
| if !tt.wantErr && parsedCount != tt.wantLen { | ||
| t.Errorf("parsed %d ranges, want %d", parsedCount, tt.wantLen) | ||
| } | ||
| }) |
| func TestMakeArgsReplacerEmpty(t *testing.T) { | ||
| repl := makeArgsReplacer([]string{}) | ||
|
|
||
| // With no args, any index should be out of bounds | ||
| got := repl.ReplaceAll("{args[0]}", "") | ||
| if got == "something" { | ||
| t.Errorf("repl.ReplaceAll with empty args should not produce a value, got %q", got) | ||
| } | ||
| } | ||
|
|
||
| func TestMakeArgsReplacerNil(t *testing.T) { | ||
| repl := makeArgsReplacer(nil) | ||
|
|
||
| // Should not panic with nil args | ||
| got := repl.ReplaceAll("{args[0]}", "DEFAULT") | ||
| if got == "" { | ||
| // The replacer returns the default when unmatched | ||
| t.Log("nil args: correctly returned empty/default for {args[0]}") | ||
| } | ||
| _ = got | ||
| } |
| { | ||
| name: "same case excludes l,0", | ||
| sameCase: true, | ||
| excluded: []rune{'l', 'o'}, | ||
| }, |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 51 out of 51 changed files in this pull request and generated no new comments.
Suppressed comments (5)
modules/caddyhttp/vars_test.go:73
- The test currently asserts (and documents) a "BUG" that isn’t supported by SetVar’s doc comment or implementation. SetVar only deletes the key when value==nil and the key already exists; otherwise it behaves like an assignment (storing a nil value). Please update the test to match the documented behavior (or, if the intended behavior is different, adjust SetVar + its docs accordingly rather than codifying a bug in the test).
internal/ranges_test.go:99 - This test case is currently written to expect and describe a known bug (leaking one domain when maxToDisplay==0). Tests should assert intended behavior. Consider changing this case to expect no domain names when maxToDisplay is 0 (suffix-only), and then fix MaxSizeSubjectsListForLog accordingly so the test guards against regressions.
name: "max is zero",
subjects: map[string]struct{}{
"a.com": {},
"b.com": {},
},
maxToDisplay: 0,
// BUG: When maxToDisplay is 0, code still appends one domain
// because append happens before the break check in the loop.
// Expected behavior: 1 item (just suffix). Actual: 2 items
// (1 leaked domain + suffix).
wantLen: 2,
wantSuffix: true,
},
caddyconfig/caddyfile/importgraph_test.go:190
- This test logs when a self-loop cycle isn’t detected, so it will pass even when the cycle detection is broken. If self-imports should be rejected, assert that addEdge("a", "a") returns an error (and update willCycle/addEdge accordingly). If self-imports are allowed by design, the test should be removed instead of logging "BUG CONFIRMED".
err := g.addEdge("a", "a")
if err != nil {
t.Log("Self-loop was correctly detected (bug may have been fixed)")
} else {
t.Log("BUG CONFIRMED: addEdge('a', 'a') did not detect self-loop cycle")
}
caddyconfig/caddyfile/importgraph_test.go:259
- Similarly, this test only logs when removeNode leaves behind edges from the removed node, so it doesn’t actually guard behavior. Either remove the test or make it assert graph consistency (e.g. removing a node should also remove its outgoing adjacency list).
// ...but edges from "b" may still be present in the edges map (this is a bug).
// We test this to document the behavior.
if g.edges != nil {
if targets, ok := g.edges["b"]; ok && len(targets) > 0 {
t.Log("BUG CONFIRMED: removeNode does not clean up outgoing edges. " +
"Edges from removed node 'b' still exist in adjacency list.")
}
}
modules/caddyhttp/caddyauth/argon2id_test.go:291
- TestArgon2idHashVersionInOutput doesn’t actually validate anything meaningful right now:
versionStr := "v=" + strings.Split(...)[2]producesv=v=19, so the conditional is false and the test becomes a no-op. This should directly assert that the hash contains the expected$v=19$marker (or parse and compare against argon2.Version).
// Verify version field matches current argon2 version
versionStr := "v=" + strings.Split(string(hashed), "$")[2]
if versionStr != "v=v=19" {
// argon2.Version is 0x13 = 19
The size of this PR is not, by itself, a reason to reject it. Broad additional test coverage can be worthwhile even when it is large, provided the changes remain tests and each test asserts intended behavior rather than merely reproducing the implementation. I would therefore prefer to keep this open and make it reviewable rather than close it as an AI-generated test dump. There are two concrete cleanup requirements:
The branch is now conflicting, so it will also need a refresh before substantive review and CI. Once the production changes are separated and the known questionable assertions are cleaned up, I am comfortable reviewing/accepting the remaining large test-only change in sections rather than requiring it to be split solely because of line count. |
|
Note for me, once all the other PRs are merged, run: git checkout add-tests
git fetch origin master
git rebase origin/master # should auto-drop the duplicate fix commits
git push --force-with-lease origin add-tests |
The behavior-changing parts are now split into their own commits and PRs. |
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
- reverseproxy: TestHostActiveHealthCounters and TestHostResetHealth tested Host.activeHealth*/countHealth*/resetHealth methods, which master #7916 moved to Upstream. - rewrite: rewrite_utils_test.go tested the reverse() helper, which master #7877 removed as part of a strip_path_suffix bug fix. - root: Config.cancelFunc changed from context.CancelFunc to context.CancelCauseFunc upstream; pass nil cause in the test cleanup.
…is 0 The loop appended before checking the length, so with maxToDisplay=0 one domain leaked into the output before the break check. Reorder so the length check comes first. Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
The doc comment says randString excludes confusing characters like I, l, 1, 0, O. When sameCase is true, uppercase letters are excluded, and l and o should also be excluded. But the dictionary used when sameCase was true still contained '0'. Drop it, and update the test to match the actual documented exclusions. Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Neither test asserted a real outcome (one compared against an unreachable literal, the other logged then discarded the result). Since Replacer.ReplaceAll substitutes the provided default for unknown placeholders, both cases can be checked with deterministic equality. Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
TestStaticIPRangeProvision was re-implementing Provision's loop instead of calling it. The real Provision only touches the Ranges field, so a zero-value caddy.Context is enough to exercise it. Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
The io.Reader contract says a Read at EOF returns io.EOF (0, io.EOF). The mock was returning fs.ErrClosed, which is a distinct sentinel used for reads on already-closed files. Aligning the mock with the stdlib contract keeps tests that iterate over the file happy. Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Self-expalantory. We need to add more tests; and I wondered if LLMs could generate tests covering all the logic branches, so this is the result.
Assistance Disclosure
I used Amp to generate the tests, tweaked few by hand, and fixed the bug by hand. The generated code will not be taken and accepted at face value. Changes to the source code (not tests) by the agent will not be accepted. Only the tests cases with study of coverage.
Prompt: