Skip to content

Add compilation validation to e2e tests#86

Open
adnaan wants to merge 5 commits intomainfrom
claude/issue-52-rJSwW
Open

Add compilation validation to e2e tests#86
adnaan wants to merge 5 commits intomainfrom
claude/issue-52-rJSwW

Conversation

@adnaan
Copy link
Contributor

@adnaan adnaan commented Feb 8, 2026

Summary

This PR adds comprehensive compilation validation to all end-to-end tests to catch syntax errors, type mismatches, and missing dependencies in generated code before they reach production.

Key Changes

  • New helper module (e2e/helpers/validation.go): Introduces ValidateCompilation() function that:

    • Runs sqlc generate if applicable (for database-dependent code)
    • Executes go mod tidy to catch dependency issues
    • Runs go build ./... to validate all generated code compiles
    • Sets GOWORK=off to isolate test environments from workspace configuration
  • Updated test files: Added compilation validation calls to all e2e tests:

    • app_creation_test.go: 4 tests
    • migration_test.go: 2 tests
    • resource_generation_test.go: 11 tests
    • seeding_test.go: 3 tests
  • Updated .gitignore: Added !e2e/helpers/ to ensure the new helpers directory is tracked in version control

Implementation Details

  • Validation is performed at the end of each test to ensure all resources are generated before compilation checks
  • The helper function uses t.Helper() to maintain clean test output and error reporting
  • Environment isolation via GOWORK=off prevents interference from workspace configurations
  • Comprehensive error messages include command output for debugging failed validations

https://claude.ai/code/session_017p67y5KMaW2a5HvF3wSAML

E2E tests previously verified file generation but never checked if the
generated code actually compiles. This adds a ValidateCompilation helper
that runs sqlc generate, go mod tidy, and go build ./... after code
generation to catch syntax errors, type mismatches, and missing
dependencies.

- Create e2e/helpers/validation.go with ValidateCompilation helper
- Add compilation checks to all resource generation tests (11 tests)
- Add compilation checks to all app creation tests (4 tests)
- Add compilation checks to migration workflow tests (2 tests)
- Add compilation checks to seeding tests (3 tests)
- Update .gitignore to track e2e/helpers/ directory

Closes #52

https://claude.ai/code/session_017p67y5KMaW2a5HvF3wSAML
Copilot AI review requested due to automatic review settings February 8, 2026 09:32
@claude
Copy link

claude bot commented Feb 8, 2026

PR Review: Add compilation validation to e2e tests

Summary

This PR adds comprehensive compilation validation to all end-to-end tests, ensuring generated code compiles before reaching production. The implementation is solid and follows good testing practices.

Strengths

1. Excellent Design

  • The ValidateCompilation helper is well-structured and reusable
  • Proper use of t.Helper() for clean error reporting
  • Good separation of concerns with a dedicated helpers package
  • Consistent integration across all 20 test cases

2. Comprehensive Coverage

  • All e2e test files updated systematically
  • Strategic placement at end of tests ensures all resources are generated before validation

3. Environment Isolation

  • GOWORK=off prevents workspace interference
  • Aligns with CONTRIBUTING.md guidance about workspace vs isolated testing

4. Smart Dependencies

  • Only runs sqlc generate when sqlc.yaml exists
  • Proper ordering: sqlc to go mod tidy to go build

Code Quality Observations

Error Handling - Comprehensive error messages with command output for debugging

Logging - Clear progress messages and success confirmation

Consistency - Same validation call pattern across all tests

Suggestions for Consideration

1. Performance Optimization (Minor)
The validation runs three potentially slow commands sequentially. Consider caching Go build artifacts or adding a flag to skip validation in rapid iteration mode.

2. Code Reusability (Minor)
Some duplication with existing runSqlc function, but current approach keeps helper self-contained which is fine.

3. Documentation (Nice to have)
Consider adding package-level doc comment explaining the purpose of the helpers package.

Security

No security concerns identified - commands use proper argument passing, no credential handling, isolated test environments.

Test Coverage

Excellent - all 20 e2e tests now validate compilation. Catches syntax errors, type mismatches, missing dependencies, and template rendering issues.

Best Practices Alignment

Follows Go and repository conventions, consistent with existing test patterns, proper use of t.Helper(), gitignore updated correctly.

Performance Impact

Expected to add approximately 10-30 seconds per test. This is an acceptable tradeoff for catching compilation issues early.

Final Recommendation

APPROVE - This is a high-quality PR that adds significant value.

Key benefits:

  1. Prevents broken code from reaching production
  2. Faster feedback loop for developers
  3. Comprehensive coverage across all e2e tests
  4. Clean, maintainable implementation

Minor suggestions above are optional enhancements - the PR is ready to merge as-is.

Great work on this defensive testing improvement!

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a reusable compilation-validation step to the HTTP-tagged end-to-end tests to ensure generated apps build successfully (and to surface dependency/tooling issues earlier in CI).

Changes:

  • Added e2e/helpers/validation.go with ValidateCompilation() to run sqlc generate (when configured), go mod tidy, and go build ./... under GOWORK=off.
  • Updated multiple HTTP e2e tests to invoke helpers.ValidateCompilation(t, appDir) after generation/migration/seed workflows.
  • Updated .gitignore to ensure the new e2e/helpers/ directory is tracked.

Reviewed changes

Copilot reviewed 5 out of 6 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
e2e/helpers/validation.go New helper that performs sqlc/tidy/build validation in generated app dirs.
e2e/app_creation_test.go Runs compilation validation after app creation scenarios.
e2e/migration_test.go Runs compilation validation after migration workflows.
e2e/resource_generation_test.go Runs compilation validation after resource generation scenarios.
e2e/seeding_test.go Runs compilation validation after seed/cleanup workflows.
.gitignore Un-ignores e2e/helpers/ so the helper package is committed.

sqlcPath := filepath.Join(appDir, "database/sqlc.yaml")
if _, err := os.Stat(sqlcPath); err == nil {
t.Log("Running sqlc generate...")
sqlcCmd := exec.Command("go", "run", "github.com/sqlc-dev/sqlc/cmd/sqlc@latest", "generate", "-f", sqlcPath)
Copy link

Copilot AI Feb 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

go run github.com/sqlc-dev/sqlc/cmd/sqlc@latest makes the test non-deterministic and can break/flap when sqlc releases a new version (and also requires network/module proxy access). Prefer pinning a known-good sqlc version (e.g., @vX.Y.Z) or using a repo-pinned tool dependency so CI and local runs are reproducible.

Copilot uses AI. Check for mistakes.
Comment on lines 22 to 25
sqlcCmd := exec.Command("go", "run", "github.com/sqlc-dev/sqlc/cmd/sqlc@latest", "generate", "-f", sqlcPath)
sqlcCmd.Dir = appDir
sqlcCmd.Env = append(os.Environ(), "GOWORK=off")
if output, err := sqlcCmd.CombinedOutput(); err != nil {
Copy link

Copilot AI Feb 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cmd.Env = append(os.Environ(), "GOWORK=off") can leave multiple GOWORK= entries if the parent environment already sets it; duplicate env keys have platform-dependent behavior, so GOWORK=off may not reliably win. Build the env by filtering out any existing GOWORK= value before appending the override (apply to sqlc/tidy/build commands).

Copilot uses AI. Check for mistakes.
Comment on lines 30 to 36
// Run go mod tidy to catch dependency problems introduced by generated code.
t.Log("Running go mod tidy...")
tidyCmd := exec.Command("go", "mod", "tidy")
tidyCmd.Dir = appDir
tidyCmd.Env = append(os.Environ(), "GOWORK=off")
if output, err := tidyCmd.CombinedOutput(); err != nil {
t.Fatalf("go mod tidy failed in %s: %v\nOutput: %s", appDir, err, output)
Copy link

Copilot AI Feb 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This helper always runs go mod tidy, but createTestApp already runs go mod tidy right after lvt new (e2e/test_helpers_test.go). With these new calls, most http e2e tests will tidy twice per test, which is a noticeable runtime hit. Consider either (a) making ValidateCompilation optionally skip go mod tidy, or (b) letting tests pass SkipGoModTidy: true and relying on this helper to do the single tidy at the end.

Suggested change
// Run go mod tidy to catch dependency problems introduced by generated code.
t.Log("Running go mod tidy...")
tidyCmd := exec.Command("go", "mod", "tidy")
tidyCmd.Dir = appDir
tidyCmd.Env = append(os.Environ(), "GOWORK=off")
if output, err := tidyCmd.CombinedOutput(); err != nil {
t.Fatalf("go mod tidy failed in %s: %v\nOutput: %s", appDir, err, output)
// Run go mod tidy to catch dependency problems introduced by generated code,
// unless explicitly skipped via SKIP_GO_MOD_TIDY=1 in the environment.
if os.Getenv("SKIP_GO_MOD_TIDY") == "1" {
t.Log("Skipping go mod tidy due to SKIP_GO_MOD_TIDY=1")
} else {
t.Log("Running go mod tidy...")
tidyCmd := exec.Command("go", "mod", "tidy")
tidyCmd.Dir = appDir
tidyCmd.Env = append(os.Environ(), "GOWORK=off")
if output, err := tidyCmd.CombinedOutput(); err != nil {
t.Fatalf("go mod tidy failed in %s: %v\nOutput: %s", appDir, err, output)
}

Copilot uses AI. Check for mistakes.
- Pin sqlc to v1.27.0 instead of @latest for reproducible builds
- Filter existing GOWORK env entries before appending GOWORK=off to
  avoid platform-dependent duplicate-key behavior
- Pass SkipGoModTidy: true in tests that use ValidateCompilation so
  go mod tidy runs exactly once (in the helper) instead of twice

https://claude.ai/code/session_017p67y5KMaW2a5HvF3wSAML
@claude
Copy link

claude bot commented Feb 8, 2026

Pull Request Review

This PR adds compilation validation to all e2e tests, which is an excellent improvement for catching issues earlier in the development cycle. The implementation is well-structured with a dedicated helper module and consistent application across all test files.

✅ Strengths

  1. Excellent Design Pattern: Creating a dedicated e2e/helpers/validation.go module is a clean architectural choice that promotes reusability and maintainability.

  2. Comprehensive Coverage: The validation has been added to all 20 e2e test cases across 4 test files, ensuring thorough coverage.

  3. Environment Isolation: The envWithGOWORKOff() function properly handles environment isolation by filtering out pre-existing GOWORK entries before setting it to "off", preventing platform-dependent issues.

  4. Version Pinning: Pinning sqlc to v1.27.0 ensures reproducible builds across CI and local environments.

  5. Proper .gitignore Update: Adding !e2e/helpers/ ensures the new helpers directory is tracked.

  6. Good Documentation: Comments explain the purpose and integration points (e.g., "Tests that use this helper should pass SkipGoModTidy: true").

  7. Proper Use of t.Helper(): This maintains clean test output with correct line numbers for failures.

🔍 Observations & Suggestions

1. Potential Duplication with Existing Test Helper

I noticed there's an existing runSqlc() function in e2e/test_helpers_test.go:49-63 that also runs sqlc generate.

Differences:

  • Old: Uses @latest
  • New: Uses @v1.27.0 (pinned version)

Recommendation: Consider consolidating these or deprecating runSqlc() in favor of the new validation helper to avoid confusion and ensure version consistency across all tests.

2. sqlc Version Consistency

The new helper uses v1.27.0, but the existing runSqlc() uses @latest. This could lead to inconsistent behavior if both are used.

Recommendation: Update all sqlc invocations to use the pinned version, or document why different versions are needed in different contexts.

3. Comment About SkipGoModTidy in Test Files

The comments in test files are clear and helpful! The pattern of explaining why SkipGoModTidy is set improves maintainability.

4. Error Message Clarity

The error messages are good and provide sufficient debugging information with command output included.

Optional enhancement: Consider adding hints about common fixes in error messages for faster issue resolution.

5. Performance Consideration

Running full compilation validation (sqlc generate + go mod tidy + go build ./...) on every test will increase test execution time.

Questions to consider:

  • Have you measured the performance impact on total test suite runtime?
  • Is there a faster incremental validation that could catch most issues?
  • Could validation be optional via an environment flag for quick local development?

This isn't necessarily a blocker, but worth discussing trade-offs between comprehensive validation and test speed.

🔒 Security & Best Practices

✅ No security concerns identified.
✅ Proper error handling with CombinedOutput().
✅ No command injection vulnerabilities (using exec.Command properly).
✅ Environment variable handling is safe.

🧪 Test Coverage

The validation itself is a test utility, so it doesn't need its own unit tests. However, consider:

  • Integration verification: Does the CI pipeline successfully catch compilation failures with this new validation? You might want to temporarily introduce a compilation error to verify the validation works as expected in CI.

📝 Minor Code Quality Notes

  1. Line 43 in validation.go: The comment "since generated handlers depend on sqlc-generated query code" is helpful context.

  2. Consistency in test files: The formatting changes (aligning struct fields) improve readability.

🎯 Overall Assessment

This is a high-quality PR that addresses a real need for catching compilation issues earlier. The implementation is clean, well-documented, and consistently applied. The main consideration is understanding the trade-off between comprehensive validation and test execution time.

Recommendation:Approve with minor suggestions

The suggestions above are mostly optional improvements for future consideration. The PR is ready to merge as-is if the performance impact is acceptable.


Great work on improving test reliability! 🚀

The sqlc@v1.27.0 pin caused CreatedAt redeclaration errors in generated
code. Revert to @latest to match the existing codebase pattern (CI also
installs sqlc@latest). Revert SkipGoModTidy changes since skipping tidy
in createTestApp requires tidy to have run before sqlc generate works.

Keep the GOWORK=off env filtering fix which correctly prevents
platform-dependent duplicate-key behavior.

https://claude.ai/code/session_017p67y5KMaW2a5HvF3wSAML
@claude
Copy link

claude bot commented Feb 8, 2026

Pull Request Review: Add compilation validation to e2e tests

Summary

This PR adds comprehensive compilation validation to all E2E tests, introducing a ValidateCompilation helper that runs sqlc generate, go mod tidy, and go build ./... to catch code generation issues before production. This is a valuable addition that closes #52.


✅ Strengths

1. Well-structured helper function (e2e/helpers/validation.go)

  • Clean separation of concerns with a dedicated helper package
  • Proper use of t.Helper() for clean error traces
  • Clear documentation explaining the purpose
  • Good error messages with command output for debugging

2. Comprehensive test coverage

  • Added validation to all 20 E2E tests across 4 test files
  • Consistent placement at the end of tests after all resources are generated
  • No tests were missed

3. Environment isolation

  • Smart handling of GOWORK=off to prevent workspace interference
  • The envWithGOWORKOff() function properly filters existing entries to avoid platform-dependent duplicate-key issues

4. Iterative improvement through commits

  • The commit history shows thoughtful iteration (initial implementation → review feedback → CI fix)
  • Kept the working solution (sqlc@latest) after discovering version pinning issues
  • Good pragmatic decision-making

🔍 Code Quality Observations

Helper Design (e2e/helpers/validation.go:28-65)
The sequential validation steps are well-ordered:

  1. sqlc generate (if needed) - generates query code
  2. go mod tidy - resolves dependencies
  3. go build ./... - validates compilation

This ordering is correct since each step depends on the previous one.

Error Handling
All commands properly capture and display output on failure, making debugging straightforward.

Consistency
The validation is consistently placed at the end of each test, which is the right location to ensure all generated code is present before compilation checks.


💡 Suggestions for Future Improvements

While this PR is solid as-is, here are some optional enhancements for future consideration:

1. Performance optimization (optional)
The validation runs 3 commands sequentially. Consider:

// Option: Add a skipModTidy parameter for tests that already ran it
func ValidateCompilation(t *testing.T, appDir string, opts ...ValidationOption)

However, the current approach prioritizes correctness over speed, which is appropriate for E2E tests.

2. Consider caching build artifacts (if tests become slow)
Go's build cache should help, but if E2E tests slow down significantly, could explore:

  • Running validation only once per test file (in a cleanup function)
  • Parallel test execution with isolated directories

3. Potential for test helper extraction
The envWithGOWORKOff() pattern might be useful in other test contexts. Consider making it public if other tests need similar env manipulation.


🔒 Security & Best Practices

No security concerns - The code doesn't introduce any vulnerabilities
Follows Go testing conventions - Proper use of testing.T methods
Idiomatic Go - Clean, readable code with good naming
No breaking changes - Pure addition of validation without modifying existing behavior


📋 Testing & CI

Test Coverage

  • ✅ 20 tests updated across 4 files
  • ✅ All test types covered (app creation, resources, migrations, seeding)

CI Considerations
The PR description mentions fixing CI issues through iteration. The final solution uses sqlc@latest which matches the existing CI setup.


🎯 Recommendation

✅ APPROVED - This PR is ready to merge.

Rationale:

  • Addresses the stated goal of catching compilation errors in E2E tests
  • Well-implemented with good error messages
  • Comprehensive coverage across all test files
  • Shows good engineering judgment through iterative fixes
  • No breaking changes or security concerns
  • Clean, maintainable code

Impact:
This will catch an important class of bugs (syntax errors, type mismatches, missing dependencies) much earlier in the development cycle, improving code quality and developer experience.


📝 Minor Notes

  1. The .gitignore change correctly ensures the new e2e/helpers/ directory is tracked
  2. The commit messages follow good practices with clear descriptions
  3. The PR description is thorough and explains the implementation details well

Great work on this improvement! 🎉

The schema template auto-generates a created_at column, so passing
"created_at" as a user field creates duplicate columns. sqlc then
generates a struct with two CreatedAt fields, causing a compilation
error - which is exactly what our new validation correctly catches.

Fix by using "published_at" instead of "created_at" in the type
inference and all-field-types tests. This still tests the _at suffix
time inference without conflicting with the auto-generated column.

Also revert SkipGoModTidy and sqlc version pin (keep GOWORK env fix).

https://claude.ai/code/session_017p67y5KMaW2a5HvF3wSAML
@claude
Copy link

claude bot commented Feb 8, 2026

PR Review: Add compilation validation to e2e tests

This PR adds comprehensive compilation validation to all end-to-end tests to catch syntax errors, type mismatches, and missing dependencies in generated code before they reach production. Overall, this is a valuable improvement that will catch bugs earlier in the development cycle.


✅ Strengths

1. Well-architected helper module

The new e2e/helpers/validation.go is clean, focused, and follows Go best practices:

  • Proper use of t.Helper() for clean test output
  • Good separation of concerns with dedicated helper package
  • Comprehensive error messages with command output for debugging

2. Comprehensive test coverage

All 20 e2e tests now validate compilation, which is exactly what's needed to catch issues early.

3. Smart environment isolation

The envWithGOWORKOff() function properly filters duplicate GOWORK entries to avoid platform-dependent issues - this shows attention to detail.

4. Proper .gitignore update

Adding !e2e/helpers/ ensures the new directory is tracked correctly.


🔍 Code Quality Observations

1. Consistent GOWORK handling across codebase

✅ The PR correctly follows existing patterns. The new helper uses a more robust approach that filters duplicates.

Suggestion: Consider refactoring existing code in test_helpers_test.go:57 and docker_helpers_test.go:334 to use envWithGOWORKOff() for consistency. This would centralize the GOWORK handling logic and prevent future bugs.

2. Sequential validation steps

The validation function runs three sequential steps:

  1. sqlc generate (if applicable)
  2. go mod tidy
  3. go build ./...

✅ This is the correct order - each step depends on the previous one.

Suggestion: Consider making validation steps configurable via ValidationOptions struct to allow tests to skip certain steps when they're not needed (e.g., when Docker already ran go mod tidy).

3. Error handling

Current error messages include command output, which is helpful. Consider also logging successful operations for troubleshooting.


🐛 Potential Issues

1. Performance impact (Minor)

Running go build ./... adds ~5-10 seconds per test. For 20 tests, this could add 2-3 minutes to test suite runtime.

Question: Have you measured the performance impact? Consider:

  • Running validation only in CI (via env var)
  • Caching build artifacts between tests
  • Running validation in parallel for independent tests

Suggested approach:

func ValidateCompilation(t *testing.T, appDir string) {
    t.Helper()
    
    // Skip in local development unless explicitly enabled
    if os.Getenv("CI") != "true" && os.Getenv("VALIDATE_COMPILATION") != "true" {
        t.Log("Skipping compilation validation (set VALIDATE_COMPILATION=true to enable)")
        return
    }
    
    // ... rest of implementation
}

2. Type inference test improvement (Minor)

The test TestResourceGen_TypeInference was correctly modified to avoid "created_at" field collision by using "published_at" instead.

✅ Good catch! This change is correct.

Suggestion: Consider adding validation in the generator itself to warn about reserved field names like created_at, updated_at, id, etc.

3. Coverage gaps (Question)

Looking at the e2e directory, many test files don't appear to call ValidateCompilation():

  • complete_workflow_test.go
  • editmode_test.go
  • kit_*.go
  • modal_test.go
  • pagination_modes_test.go
  • rendering_test.go
  • serve_test.go
  • view_generation_test.go
  • And several others...

Question: Should these tests also include compilation validation? If not, why not?


🔒 Security Concerns

✅ No security issues found

The code:

  • Uses safe command execution with exec.Command
  • Properly sets environment variables without injection risks
  • Doesn't expose sensitive information in error messages

📊 Performance Considerations

Build time overhead per test: ~6-10 seconds

  1. sqlc generate: ~1-2 seconds
  2. go mod tidy: ~2-3 seconds
  3. go build ./...: ~3-5 seconds

For 20 tests: ~2-3 minutes added to test suite

Recommendations:

  1. Conditional validation based on env vars (fastest win)
  2. Build caching: Consider using build cache to speed up subsequent builds
  3. Parallel execution: Ensure compilation validation doesn't create race conditions

🎯 Best Practices Alignment

✅ Follows repository conventions:

  1. Code style: Matches existing Go formatting and patterns
  2. Documentation: Good inline comments explaining the why, not just the what
  3. Testing: e2e coverage is appropriate for this helper

📝 Documentation suggestions:

Consider adding:

  1. A note in CONTRIBUTING.md about the compilation validation requirement
  2. A reminder in the PR template for contributors to add validation to new e2e tests

🎁 Additional Improvements to Consider (Follow-up PRs)

  1. Add verbosity control for debugging
  2. Consider race detector: Add -race flag to catch race conditions in generated code
  3. Extend to remaining e2e tests that generate code

📋 Summary & Recommendation

Overall Assessment: ✅ APPROVE with minor suggestions

This PR significantly improves test quality by catching compilation issues early. The implementation is solid, follows best practices, and integrates well with the existing codebase.

Required before merge:

None - the PR is ready to merge as-is.

Recommended improvements (can be follow-up PRs):

  1. Add performance optimizations (conditional validation based on env vars)
  2. Extend validation to remaining e2e tests
  3. Consider refactoring existing GOWORK handling to use the new helper
  4. Add documentation to CONTRIBUTING.md

Blocking issues:

None


Great work on this improvement! The test suite will be much more robust with this change. 🎉

@claude
Copy link

claude bot commented Feb 8, 2026

PR Review: Add compilation validation to e2e tests

Thank you for this excellent improvement to the test suite! This PR adds a critical layer of validation that will catch compilation issues early. Here's my detailed review:


✅ Strengths

  1. Well-structured helper module - The e2e/helpers/validation.go file is clean, focused, and follows Go best practices with proper use of t.Helper() for clear error reporting.

  2. Comprehensive coverage - All 20 e2e tests now include compilation validation, ensuring consistent quality checks across the entire test suite.

  3. Smart sqlc integration - The helper correctly detects and runs sqlc generate only when needed, avoiding unnecessary overhead.

  4. Environment isolation - The GOWORK=off handling is well-designed, with the envWithGOWORKOff() helper properly filtering duplicates to avoid platform-specific issues.

  5. Clear error messages - All validation failures include command output, making debugging straightforward.

  6. Test fixes - The changes to use published_at instead of created_at in resource_generation_test.go:81,397,434 properly avoid conflicts with auto-generated schema columns.


📋 Code Quality & Best Practices

Excellent:

  • Proper use of t.Helper() (validation.go:29)
  • Clear, descriptive comments explaining the "why" not just the "what"
  • Follows Go naming conventions
  • Minimal, focused changes to existing tests
  • Good separation of concerns with the helpers package

Minor suggestions:

  1. Consider caching the GOWORK=off environment (validation.go:14-22):
    Currently, envWithGOWORKOff() is called once per validation, but since the environment is stable during test execution, you could cache it at package level:

    var goWorkOffEnv = sync.OnceValue(func() []string {
        var env []string
        for _, e := range os.Environ() {
            if !strings.HasPrefix(e, "GOWORK=") {
                env = append(env, e)
            }
        }
        return append(env, "GOWORK=off")
    })

    This is a micro-optimization and not critical for e2e tests.

  2. Command output in logs - Consider adding successful command output to logs when -v flag is used, not just on failures:

    if output, err := tidyCmd.CombinedOutput(); err != nil {
        t.Fatalf("go mod tidy failed in %s: %v\nOutput: %s", appDir, err, output)
    } else if testing.Verbose() {
        t.Logf("go mod tidy output: %s", output)
    }

🐛 Potential Issues

None found - The code is solid with no apparent bugs or issues.


⚡ Performance Considerations

  1. Test execution time - This will significantly increase e2e test duration since each test now runs:

    • sqlc generate (if applicable)
    • go mod tidy
    • go build ./...

    This is an acceptable tradeoff for the value provided. However, consider:

    • Running validation in parallel where possible (though current sequential approach is safer)
    • Adding a flag to skip validation for rapid local iteration (-short mode)
  2. Disk I/O - Each test creates temp directories and builds. This is already the case, and the validation doesn't add significant overhead beyond what's necessary.


🔒 Security Concerns

None identified - The code doesn't handle user input or expose vulnerabilities. The use of exec.Command is safe since all parameters are controlled by the test code.


🧪 Test Coverage

Excellent coverage:

  • All 4 app creation tests updated ✅
  • All 2 migration tests updated ✅
  • All 11 resource generation tests updated ✅
  • All 3 seeding tests updated ✅

Suggestion: Consider adding a test for the validation helper itself:

// e2e/helpers/validation_test.go
func TestValidateCompilation_InvalidCode(t *testing.T) {
    // Create temp app with intentionally broken code
    // Verify ValidateCompilation fails appropriately
}

📚 Documentation

The PR description is excellent and comprehensive. The code comments are clear and explain the rationale well.

Minor suggestion: Add a comment in the main e2e test files explaining why validation is called at the end:

// Validate generated code compiles. This catches syntax errors, type mismatches,
// and missing dependencies before they reach production. Must be called after all
// resources are generated.
helpers.ValidateCompilation(t, appDir)

🎯 Recommendations

  1. Merge with confidence - This PR is ready to merge as-is.

  2. Future enhancement - Consider adding a -skip-validation flag for faster local iteration:

    var skipValidation = flag.Bool("skip-validation", false, "skip compilation validation in e2e tests")
    
    func ValidateCompilation(t *testing.T, appDir string) {
        if skipValidation != nil && *skipValidation {
            t.Log("Skipping compilation validation")
            return
        }
        // ... rest of validation
    }
  3. CI/CD consideration - Ensure CI doesn't use -skip-validation to maintain the safety net.


Summary

This is a high-quality PR that adds significant value to the test suite with minimal code changes. The implementation is clean, well-documented, and follows Go best practices. The tradeoff of increased test time for improved safety is worthwhile.

Verdict: ✅ Approved - Ready to merge

Great work on improving the test infrastructure! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants