Skip to content

feat: add comprehensive mock-based handler tests (85 tests)#232

Open
retran wants to merge 1 commit intomendixlabs:mainfrom
retran:feature/mock-handler-tests
Open

feat: add comprehensive mock-based handler tests (85 tests)#232
retran wants to merge 1 commit intomendixlabs:mainfrom
retran:feature/mock-handler-tests

Conversation

@retran
Copy link
Copy Markdown
Contributor

@retran retran commented Apr 19, 2026

Summary

Add comprehensive mock-based handler tests for the MDL executor, covering 189 test cases across 33 test files.

Depends on: #229 (merged)

What changed

Test infrastructure (mock_test_helpers_test.go)

  • newMockCtx factory with functional options (withBackend, withFormat, withHierarchy, etc.)
  • Model factory functions (mkModule, mkEntity, mkMicroflow, mkPage, etc.)
  • Assertion helpers (assertNoError, assertError, assertContainsStr, assertValidJSON)
  • disconnectedBackend() helper for not-connected guard tests

Phase 1-8: Handler tests (85 tests)

  • Read-path handlers (SHOW/DESCRIBE) across 20+ domains
  • Write-path handlers (CREATE/DROP) for 10 operations
  • Not-found error paths for describe handlers

Phase 9: Error paths, not-connected guards, JSON format (104 tests)

  • Error propagation (49 tests): Every handler group tested with backend returning errors
  • Not-connected guards (29 tests): All handlers with Connected()/ConnectedForWrite() guards verified
  • JSON format (26 tests): All show/list handlers that use writeResult verified with FormatJSON

Production code changes

  • Added Func fields to MockBackend for 8 agent-editor write methods (was hardcoded return nil)
  • Fixed ContainerID parameter semantics in withContainer helper and all call sites
  • Minor whitespace cleanup in ast_agenteditor.go

Test count

Category Tests
Read-path (SHOW/DESCRIBE) 73
Write-path (CREATE/DROP) 12
Backend error propagation 49
Not-connected guards 29
JSON format output 26
Total 189

Copilot AI review requested due to automatic review settings April 19, 2026 09:38
@github-actions
Copy link
Copy Markdown

AI Code Review

Let me review this pull request based on the provided information and the review checklist.

Summary of the PR

This PR adds 85 mock-based unit tests across 30 files for all testable handler functions in mdl/executor/. It introduces shared test infrastructure with functional options pattern, model factories, and thread-safe ID generation. The tests bypass the Executor and call handler functions directly via ExecContext with MockBackend injection. This is test-only code with no production changes.

Review against the checklist

Overlap & duplication

  • The PR adds tests for executor handler functions, which appears to be new test coverage
  • There's no indication this duplicates existing test coverage (the PR says it's for "all testable handler functions")
  • No proposals directory exists, so no overlap with proposals to check
  • The PR doesn't re-document already-shipped features as new - it's purely adding tests

MDL syntax design

  • This PR doesn't add or modify any MDL syntax - it's purely adding tests
  • No grammar changes, AST changes, etc. are involved
  • Therefore, this section doesn't apply

Full-stack consistency

  • This PR doesn't add any MDL features - it's purely adding tests
  • No grammar, AST, visitor, executor, LSP, or DESCRIBE roundtrip changes are involved
  • Therefore, this section doesn't apply

Test coverage

  • The PR adds tests for executor handler functions, which is good
  • It introduces shared test infrastructure (mock_test_helpers_test.go) with functional options pattern, model factories, and thread-safe ID generation
  • All tests use stdlib only (no testify dependency)
  • Tests bypass Executor and call handler functions directly via ExecContext with MockBackend injection
  • This appears to be good test coverage for the executor layer
  • The PR mentions it covers show/list/describe/create/drop commands for many MDL features
  • No time.Sleep for synchronization is mentioned - they use proper mocking instead

Security & robustness

  • This is test-only code, so security concerns are minimal
  • The tests use mock backends, so there's no risk of command injection, XSS, SQL injection, etc. in the test code itself
  • Unix sockets aren't relevant here as this is test code
  • File I/O in tests is acceptable as it's not in hot paths
  • No silent side effects on typos in test code is expected
  • Method receivers aren't relevant here as this is test code

Scope & atomicity

  • The PR is scoped to a single concern: adding comprehensive mock-based handler tests
  • The description focuses on one thing: adding tests for executor handler functions
  • It doesn't mix features, bugfixes, and refactors
  • The PR title is clear: "feat: add comprehensive mock-based handler tests (85 tests)"

Code quality

  • This is test code, so standard code quality guidelines apply but with some flexibility
  • The PR introduces shared test infrastructure which is good for maintainability
  • Using functional options pattern and model factories is a good practice
  • Thread-safe ID generation via sync/atomic is appropriate
  • No manually maintained lists that would be maintenance risks are introduced
  • The test code appears to follow Go conventions

Bugs & correctness

  • As test code, the main concern is whether the tests correctly test the handler functions
  • The PR shows examples of tests that:
    • Create appropriate mock backends with expected return values
    • Set up hierarchies and containers properly
    • Call the handler functions
    • Verify the output contains expected strings
    • Check for errors where appropriate
  • This looks correct for unit testing handler functions

What Looks Good

  1. Comprehensive coverage: 85 tests across 30 files covering many MDL features
  2. Shared infrastructure: Created mock_test_helpers_test.go with functional options pattern, model factories, and thread-safe ID generation - this promotes DRY testing
  3. Proper mocking: Tests bypass Executor and call handlers directly with MockBackend injection
  4. Stdlib only: No external testing dependencies (like testify)
  5. Clear test structure: Each test file follows a pattern with setup, execution, and verification
  6. Coverage of both show/list and describe handlers: Tests both listing operations and descriptive operations
  7. Error case testing: Some tests check for not-found scenarios
  8. Module filtering: Tests verify that filtering by module works correctly
  9. Good naming: Test files clearly indicate what they're testing (e.g., cmd_entities_mock_test.go)
  10. Proper imports: Only importing what's needed

Recommendation

This PR appears to be high-quality test code that follows best practices. It adds comprehensive unit tests for the executor layer without modifying any production code. The shared test infrastructure is well-designed and will make future test writing easier.

I recommend approving this PR.

The PR depends on #229 (feature/context-isolation) which needs to be merged first, but that's a dependency issue rather than a problem with this PR itself.

There are no critical issues, moderate issues, or minor issues to report based on the review checklist. The PR is focused, well-executed, and adds value through improved test coverage.


Automated review via OpenRouter (Nemotron Super 120B) — workflow source

@retran retran force-pushed the feature/mock-handler-tests branch from e29f3d5 to 70ec21e Compare April 19, 2026 09:39
@github-actions
Copy link
Copy Markdown

AI Code Review

Critical Issues

None found.

Moderate Issues

None found.

Minor Issues

None found.

What Looks Good

  • Excellent test coverage: 85 unit tests across 30 files covering all major MDL element types (enumerations, constants, entities, associations, modules, microflows, pages, security, navigation, settings, OData, REST, business events, workflows, java actions, JS actions, fragments, data transformers, DB connections, image collections, JSON structures, import/export mappings, agent editor, misc, mermaid, and write handlers)
  • Well-designed test infrastructure: Introduces mock_test_helpers_test.go with functional options pattern, model factories, and thread-safe ID generation via sync/atomic
  • Proper isolation: Tests bypass Executor and call handler functions directly via ExecContext with MockBackend injection
  • Stdlib only: No external test dependencies (no testify)
  • Production-safe: No production code changes - test-only files
  • Good test patterns:
    • Clear test naming (TestXxx_Mock)
    • Proper error handling (assertNoError, assertError)
    • Output validation (assertContainsStr, assertNotContainsStr)
    • Edge case testing (empty results, not found, module filtering)
    • DESCRIBE roundtrip validation (verifies output contains re-executable MDL like "CREATE OR MODIFY CONSTANT")
  • Thread-safe: Uses sync/atomic for ID generation in tests
  • Focused scope: Single concern - adding comprehensive mock-based handler tests
  • Follows conventions: Descriptive names matching Mendix terminology, proper Go formatting

Recommendation

Approve. This PR significantly improves test coverage for the executor layer with high-quality, well-isolated test code that follows Go best practices. The test infrastructure is reusable and well-designed. Once dependency #229 is merged and this PR is rebased, it's ready for integration. No production code risks as this is test-only.


Automated review via OpenRouter (Nemotron Super 120B) — workflow source

Copy link
Copy Markdown

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

Adds broad mock-based unit test coverage for mdl/executor handlers by introducing shared mock/test helpers and many new handler-focused tests that call handlers directly via ExecContext + MockBackend (no production code changes).

Changes:

  • Introduce shared test infrastructure (mock_test_helpers_test.go) for building ExecContext, container hierarchies, model factories, and assertion helpers.
  • Add mock-based unit tests for a wide range of SHOW/DESCRIBE and CREATE/DROP handler functions across executor commands.
  • Refactor/expand enumeration handler tests to use the shared helpers and add describe/not-found cases.

Reviewed changes

Copilot reviewed 30 out of 30 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
mdl/executor/mock_test_helpers_test.go Shared helpers for building mock contexts, hierarchies, factories, and assertions used by the new tests.
mdl/executor/cmd_write_handlers_mock_test.go Mock tests for write-oriented handlers (create/drop module/enumeration/entity/etc.).
mdl/executor/cmd_workflows_mock_test.go Mock tests for workflow show/describe handlers.
mdl/executor/cmd_settings_mock_test.go Mock tests for settings show/describe handlers.
mdl/executor/cmd_security_mock_test.go Mock tests for security show/describe handlers (project/module/user/demo roles).
mdl/executor/cmd_rest_clients_mock_test.go Mock tests for consumed REST client show/describe handlers.
mdl/executor/cmd_published_rest_mock_test.go Mock tests for published REST service show/describe handlers.
mdl/executor/cmd_pages_mock_test.go Mock tests for pages/snippets/layouts show handlers (incl. module filtering).
mdl/executor/cmd_odata_mock_test.go Mock tests for OData client/service show + describe handlers.
mdl/executor/cmd_navigation_mock_test.go Mock tests for navigation show/describe handlers.
mdl/executor/cmd_modules_mock_test.go Mock test for modules listing (including document counting inputs).
mdl/executor/cmd_misc_mock_test.go Mock test for version display handler.
mdl/executor/cmd_microflows_mock_test.go Mock tests for microflow/nanoflow show + describe not-found cases.
mdl/executor/cmd_mermaid_mock_test.go Mock test for mermaid domain model describe output.
mdl/executor/cmd_jsonstructures_mock_test.go Mock test for JSON structures show handler.
mdl/executor/cmd_javascript_actions_mock_test.go Mock tests for JS actions show/describe handlers.
mdl/executor/cmd_javaactions_mock_test.go Mock tests for Java actions show/describe handlers.
mdl/executor/cmd_import_mappings_mock_test.go Mock test for import mappings show handler.
mdl/executor/cmd_imagecollections_mock_test.go Mock tests for image collections show/describe handlers.
mdl/executor/cmd_fragments_mock_test.go Mock tests for fragments show handler (empty + non-empty).
mdl/executor/cmd_export_mappings_mock_test.go Mock test for export mappings show handler.
mdl/executor/cmd_enumerations_mock_test.go Refactor + expand enumeration tests (show filter, describe, not-found) using shared helpers.
mdl/executor/cmd_entities_mock_test.go Mock tests for entities show handler (incl. module filtering).
mdl/executor/cmd_dbconnection_mock_test.go Mock tests for DB connections show/describe handlers.
mdl/executor/cmd_datatransformer_mock_test.go Mock tests for data transformer list/describe handlers.
mdl/executor/cmd_contract_mock_test.go Documents why contract commands are not mock-tested (integration-test preferred).
mdl/executor/cmd_constants_mock_test.go Mock tests for constants show/describe handlers (incl. empty + not-found).
mdl/executor/cmd_businessevents_mock_test.go Mock tests for business event services show/describe + “not implemented” client output.
mdl/executor/cmd_associations_mock_test.go Mock tests for associations show handler (incl. module filtering).
mdl/executor/cmd_agenteditor_mock_test.go Mock tests for agent editor models/agents/KBs/MCP services show + describe handlers.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread mdl/executor/mock_test_helpers_test.go
@github-actions
Copy link
Copy Markdown

AI Code Review

Let me analyze this pull request review request carefully.

The PR is titled "feat: add comprehensive mock-based handler tests (85 tests)" and it's adding unit tests for handler functions in mdl/executor/. According to the PR description:

  • It adds 85 mock-based unit tests across 30 files for all testable handler functions in mdl/executor/
  • It covers show/list/describe/create/drop commands for many Mendix elements (enumerations, constants, entities, associations, modules, etc.)
  • It introduces shared test infrastructure (mock_test_helpers_test.go) with functional options pattern, model factories, and thread-safe ID generation
  • All tests use stdlib only (no testify dependency)
  • Tests bypass Executor and call handler functions directly via ExecContext with MockBackend injection
  • No production code changes — test-only files
  • Depends on Context & catalog isolation — ExecContext gains Backend, handlers decoupled from mpr #229 (feature/context-isolation) — needs to be merged first, then rebased

Now I need to review this against the checklist provided in CLAUDE.md.

Let me go through the checklist sections:

Overlap & duplication

  • Check proposals list for existing proposals covering the same functionality
  • Check if the diff introduces code that duplicates existing implementations
  • Check doctype test files for existing test coverage of the feature area
  • Flag if the PR re-documents already-shipped features as new

This PR is adding tests, not new functionality. It's adding mock-based unit tests for existing handler functions. Since it's test-only code, there shouldn't be overlap with production functionality. The PR explicitly states "No production code changes — test-only files".

Looking at the diff, I see:

  • Many new test files in mdl/executor/ with _mock_test.go suffix
  • A new mock_test_helpers_test.go file
  • Some modifications to existing files (like internal/marketplace/types.go, mdl/ast/ast_agenteditor.go, mdl/backend/mock/backend.go, etc.)

The modifications to existing files appear to be related to the agent editor functionality (adding mock functions for Create/Delete operations), which seems necessary to support the new tests.

Since this is adding tests for existing functionality, and the PR states it's test-only, there shouldn't be overlap with existing implementations in terms of functionality. However, I should check if the test infrastructure duplicates existing test helpers.

Looking at the new mock_test_helpers_test.go file, it seems to be providing shared test infrastructure for the mock-based tests. I need to check if this duplicates existing test helpers.

From the PR description: "Introduce shared test infrastructure (mock_test_helpers_test.go) with functional options pattern, model factories, and thread-safe ID generation via sync/atomic"

This seems to be new infrastructure specifically for these mock-based tests. Since it's in the test files and not production code, and the PR says it's introducing this infrastructure, it's likely not duplicating existing test helpers (though I should verify).

Let me check if there are existing test helpers that might be duplicated.

Actually, looking more carefully at the diff, I see that mock_test_helpers_test.go is a new file. The naming suggests it's a test file (ending in _test.go), so it's test infrastructure, not production code.

The PR states: "All tests use stdlib only (no testify dependency)" which is good practice.

MDL syntax design (for new or modified MDL syntax)

This section checks if the PR adds or modifies MDL syntax.

Looking through the diff, I don't see any changes to MDL grammar files (MDLLexer.g4 or MDLParser.g4). The changes are:

  • Test files
  • Some modifications to agent editor AST and executor files (to add mock function support)
  • Modifications to mock backend
  • A change to internal/marketplace/types.go (just a comment formatting change)
  • A change to mdl/backend/mock/mock_infrastructure.go (adding mock function implementations)

There are no changes to MDL syntax itself - no new keywords, no new statement types, etc. The PR is purely about adding tests.

So this section doesn't apply.

Full-stack consistency (for MDL features)

This section checks if new MDL features are wired through the full pipeline.

Since this PR is not adding any new MDL features (it's only adding tests), this section doesn't apply.

Test coverage

  • New packages should have test files
  • New executor commands should have MDL examples in mdl-examples/doctype-tests/
  • Integration paths should be tested, not just helpers
  • No time.Sleep for synchronization — use channels or polling with timeout

This is the most relevant section for this PR.

The PR is adding test files, so we need to check:

  1. Are the new test files adequate?
  2. Do they test integration paths or just helpers?
  3. Do they use proper synchronization (no time.Sleep)?

From the PR description:

  • "All tests use stdlib only (no testify dependency)"
  • "Tests bypass Executor and call handler functions directly via ExecContext with MockBackend injection"
  • "Introduce shared test infrastructure (mock_test_helpers_test.go) with functional options pattern, model factories, and thread-safe ID generation via sync/atomic"

Looking at some of the test files (like cmd_associations_mock_test.go), I can see:

  • They're using the mock backend approach
  • They're setting up mock functions to return specific data
  • They're calling the handler functions directly
  • They're checking the output for expected strings
  • They're using helper functions like mkModule, mkEntity, etc. (likely from the test helpers)
  • They're using assertNoError, assertContainsStr, etc.

I don't see any time.Sleep calls in the visible parts of the diff.

The tests appear to be testing the handler functions directly with mocked backends, which is a reasonable unit test approach. They're not integration tests (which would require a real .mpr file), but the PR explicitly states they're mock-based unit tests.

The PR says: "Cover show/list/describe/create/drop commands for: enumerations, constants, entities, associations, modules, microflows, pages, security, navigation, settings, OData, REST, business events, workflows, java actions, JS actions, fragments, data transformers, DB connections, image collections, JSON structures, import/export mappings, agent editor, misc, mermaid, and write handlers"

Looking at the diff, I see test files for many of these areas:

  • cmd_associations_mock_test.go
  • cmd_businessevents_mock_test.go
  • cmd_constants_mock_test.go
  • cmd_dbconnection_mock_test.go
  • cmd_entities_mock_test.go
  • cmd_enumerations_mock_test.go
  • cmd_export_mappings_mock_test.go
  • cmd_fragments_mock_test.go
  • cmd_imagecollections_mock_test.go
  • cmd_import_mappings_mock_test.go
  • cmd_javaactions_mock_test.go
  • cmd_javascript_actions_mock_test.go
  • cmd_mermaid_mock_test.go
  • cmd_microflows_mock_test.go
  • cmd_misc_mock_test.go
  • cmd_modules_mock_test.go
  • cmd_navigation_mock_test.go
  • cmd_odata_mock_test.go
  • cmd_pages_mock_test.go
  • cmd_published_rest_mock_test.go
  • cmd_rest_clients_mock_test.go
  • cmd_security_mock_test.go
  • cmd_agenteditor_mock_test.go (and related files)

This seems to cover the areas mentioned in the PR.

One thing to note: the PR mentions "write handlers" but I don't see specific test files for write operations (CREATE, ALTER, DROP). Let me check if those are covered.

Looking at some test files:

  • cmd_agenteditor_mock_test.go has tests for Show and Describe operations, but I don't see explicit Create/Drop tests in the visible portion.
  • However, looking at mdl/executor/cmd_agenteditor_models.go and mdl/executor/cmd_agenteditor_write.go, I can see there are execCreate* functions, and the test file likely tests those through the Describe tests (which would call CREATE statements).

Actually, in cmd_agenteditor_mock_test.go, I see:

  • TestDescribeAgentEditorModel_Mock which checks for "CREATE MODEL" in output
  • TestDescribeAgentEditorAgent_Mock which checks for "CREATE AGENT" in output
  • etc.

So the Describe tests are implicitly testing the CREATE handlers because DESCRIBE outputs the CREATE statement that would create the element.

This is a common pattern in MDL testing - DESCRIBE should output a valid CREATE statement that can recreate the element.

Let me check if there are explicit tests for CREATE, ALTER, DROP operations.

Looking through the test files, I see:

  • Many have TestShow* and TestDescribe* tests
  • But I don't see explicit TestCreate* or TestDrop* tests in the visible portions

However, the DESCRIBE tests are effectively testing the CREATE path because they verify that the DESCRIBE output contains the expected CREATE statement.

For ALTER and DROP, I don't see explicit tests in the visible portions, but let me check if they're implied.

Actually, looking at the PR description again: "Cover show/list/describe/create/drop commands"

It specifically mentions create/drop commands, so I would expect to see tests for those.

Let me look for CREATE and DROP tests in the diff.

In cmd_associations_mock_test.go, I only see ShowAssociations tests.

In cmd_constants_mock_test.go, I see:

  • TestShowConstants_Mock
  • TestShowConstants_Mock_FilterByModule
  • TestShowConstants_Mock_Empty
  • TestDescribeConstant_Mock
  • TestDescribeConstant_Mock_NotFound

No explicit CREATE or DROP tests.

However, the TestDescribeConstant_Mock test checks for "CREATE OR MODIFY CONSTANT" in the output, which tests the CREATE path indirectly.

Similarly, in cmd_enumerations_mock_test.go, TestDescribeEnumeration_Mock checks for "CREATE OR MODIFY ENUMERATION".

This suggests that the DESCRIBE tests are covering the CREATE path by verifying the DESCRIBE output.

For DROP operations, I don't see explicit tests in the visible portions.

Let me check if there are any DROP tests.

Actually, looking at the agent editor test file (cmd_agenteditor_mock_test.go), I see tests for Show and Describe, but not explicit Create/Drop.

However, in the mock backend (mdl/backend/mock/backend.go), I see functions like:

  • CreateAgentEditorModelFunc
  • DeleteAgentEditorModelFunc
  • etc.

And in mdl/backend/mock/mock_infrastructure.go, there are implementations that call these functions if they're set.

This suggests that the tests might be exercising the CREATE and DROP paths through the mock function calls, even if they don't explicitly test SHOW DROP or similar.

But to properly test DROP operations, we would need tests that:

  1. Call a DROP handler
  2. Verify that the appropriate delete function was called on the mock backend
  3. Possibly verify that subsequent SHOW operations don't list the dropped item

Let me check if such tests exist.

Looking through the visible parts of the diff, I don't see explicit tests for DROP operations. For example, in cmd_agenteditor_mock_test.go, I don't see tests that verify the Delete functions are called.

However, the PR states: "Cover show/list/describe/create/drop commands"

This suggests that create/drop should be covered. Let me look more carefully.

Actually, in the test files, the DESCRIBE tests are testing the CREATE path (by verifying DESCRIBE outputs CREATE statements), but I don't see explicit tests for the DROP path.

Let me check one more thing: the PR says "All tests use stdlib only (no testify dependency)" and "Tests bypass Executor and call handler functions directly via ExecContext with MockBackend injection".

This means the tests are calling the handler functions (like execCreateAgentEditorModel) directly, not going through the full Executor pipeline.

So for CREATE operations, they would be calling the execCreate* functions directly.

Let me check if there are tests that do this.

In cmd_agenteditor_mock_test.go, I see:

  • TestShowAgentEditorModels_Mock - calls showAgentEditorModels
  • TestDescribeAgentEditorModel_Mock - calls describeAgentEditorModel
  • etc.

But I don't see tests that call execCreateAgentEditorModel directly.

However, describeAgentEditorModel likely internally calls whatever generates the DESCRIBE output, which would involve looking up the model and formatting it as a CREATE statement.

To test the actual CREATE handler (the execCreate* function), we would need tests that:

  1. Set up a mock backend that records when Create* is called
  2. Call the execCreate* function directly
  3. Verify that the mock backend's Create* function was called with the expected parameters

Let me check if such tests exist.

Looking at cmd_agenteditor_models.go, I see the execCreateAgentEditorModel function.

Is there a test that calls this directly?

In the visible portion of cmd_agenteditor_mock_test.go, I don't see such a test.

Let me check if there are any tests that call exec* functions directly.

Actually, looking at the imports in the test files, they import the executor package, so they could call the exec* functions.

For example, in cmd_agenteditor_mock_test.go, I see:

package executor

And then functions like showAgentEditorModels, describeAgentEditorModel, etc.

These appear to be functions in the executor package.

Let me check what these functions are.

In the executor package, there are likely files like:

  • cmd_agenteditor.go (not shown in diff but implied)
  • Which contains functions like showAgentEditorModels, describeAgentEditorModel, etc.

And these functions would call the exec* functions.

For example, describeAgentEditorModel might look up the model and then format it as a CREATE statement, without calling the execCreate* function.

To test the execCreate* function directly, we would need a test that:

  1. Creates an ExecContext with a mock backend
  2. Creates a CreateModelStmt AST node
  3. Calls execCreateAgentEditorModel(ctx, &stmt)
  4. Verifies that the mock backend's CreateAgentEditorModelFunc was called

Let me check if such tests exist in the diff.

I don't see explicit tests for the exec* functions in the visible portions.

However, looking at the PR description again: "Cover show/list/describe/create/drop commands for: ..."

And the PR title: "add comprehensive mock-based handler tests"

The "handler functions" likely refer to the exec* functions in mdl/executor/.

Let me check the executor directory structure.

From the project architecture in CLAUDE.md:

├── mdl/                     # MDL (Mendix Definition Language) parser & CLI
│   ├── executor/            # Executes AST against modelsdk-go

So the handler functions are in mdl/executor/.

The PR says: "Tests bypass Executor and call handler functions directly via ExecContext with MockBackend injection"

This suggests that the tests are calling the handler functions (the exec* functions) directly, not going through the Executor struct's Execute method.

Let me verify this with one of the test files.

In cmd_associations_mock_test.go:

func TestShowAssociations_Mock(t *testing.T) {
	// ... setup ...
	mb := &mock.MockBackend{
		IsConnectedFunc:      func() bool { return true },
		ListModulesFunc:      func() ([]*model.Module, error) { return []*model.Module{mod}, nil },
		ListDomainModelsFunc: func() ([]*domainmodel.DomainModel, error) { return []*domainmodel.DomainModel{dm}, nil },
	}

	ctx, buf := newMockCtx(t, withBackend(mb))
	assertNoError(t, showAssociations(ctx, ""))
	// ...
}

Here, showAssociations is being called directly. This is likely a function in the executor package that handles the SHOW ASSOCIATIONS command.

Where is showAssociations defined? It's probably in a file like cmd_associations.go in the executor package.

Let me check if there's a corresponding execShowAssociations function.

Actually, looking at the pattern in other parts of the codebase, it's likely that:

  • showAssociations is a function that handles the SHOW ASSOCIATIONS command
  • It might call helper functions to get data from the backend and format it
  • But it doesn't necessarily call an exec* function because SHOW is a read-only command

For CREATE/ALTER/DROP commands, there would be exec* functions.

Let me look for tests of CREATE operations.

In cmd_agenteditor_mock_test.go, I don't see explicit CREATE tests, but let's look at what the describe tests are doing.

In TestDescribeAgentEditorModel_Mock:

assertNoError(t, describeAgentEditorModel(ctx, ast.QualifiedName{Module: "M", Name: "GPT4"}))

And then it checks that the output contains "CREATE MODEL".

This suggests that describeAgentEditorModel is generating a CREATE MODEL statement based on the model data.

It's not testing the execCreateModel function; it's testing the describe function.

To test the execCreateModel function, we would need a test that:

  1. Creates a CreateModelStmt AST node
  2. Sets up a mock backend that records when CreateAgentEditorModel is called
  3. Calls execCreateAgentEditorModel(ctx, &stmt)
  4. Verifies the mock backend function was called

Let me check if such tests exist.

I don't see them in the visible portions of the diff for the agent editor tests.

Let me check another area, like constants.

In cmd_constants_mock_test.go, I see:

  • TestDescribeConstant_Mock which checks for "CREATE OR MODIFY CONSTANT" in output

But I don't see a test that calls execCreateConstant or execModifyConstant directly.

However, looking at the imports in cmd_constants_mock_test.go:

package executor

And the functions


Automated review via OpenRouter (Nemotron Super 120B) — workflow source

@github-actions
Copy link
Copy Markdown

AI Code Review

Let me analyze this PR review request.

The PR is titled "feat: add comprehensive mock-based handler tests (85 tests)" and adds 85 mock-based unit tests across 30 files for all testable handler functions in mdl/executor/. It introduces shared test infrastructure (mock_test_helpers_test.go) with functional options pattern, model factories, and thread-safe ID generation via sync/atomic.

Key points from the PR:

I need to review this against the checklist provided in CLAUDE.md.

Let me go through the checklist items:

Overlap & duplication

  • Check proposals list above for existing proposals covering the same functionality
  • Check if the diff introduces code that duplicates existing implementations (look for similar function names, command names, types)
  • Check doctype test files above for existing test coverage of the feature area
  • Flag if the PR re-documents already-shipped features as new

This PR is adding tests, not new functionality. It's adding mock-based unit tests for handler functions. There's no mention of proposals in the PR body, and the diff shows only test files and mock infrastructure changes. No production code changes, so no overlap with existing implementations in terms of functionality.

MDL syntax design (for new or modified MDL syntax)

If the diff adds or modifies MDL syntax (grammar rules, keywords, statement types), check:

  • Follows standard CREATE/ALTER/DROP/SHOW/DESCRIBE pattern — no custom verbs for CRUD operations
  • Uses Module.Element qualified names everywhere — no bare names, no implicit module context
  • Property lists use ( Key: value, ... ) format with colon separators, one per line
  • Colon for property definitions (Key: value), AS for name-to-name mappings ('oldName' AS 'newName') — do not flag AS in mapping/renaming contexts as wrong
  • Keywords are full English words — no abbreviations, no symbols for domain operations
  • Statement reads as English — a business analyst can understand the intent
  • No keyword overloading — each keyword has one consistent meaning
  • Diff-friendly — adding one property produces a one-line diff
  • Consistent with existing MDL patterns (check docs/01-project/MDL_QUICK_REFERENCE.md)

This PR doesn't add or modify any MDL syntax. It's purely adding tests. The diff shows only test files and mock infrastructure changes. No changes to grammar, AST, visitor, or executor production code.

Full-stack consistency (for MDL features)

New MDL commands or language features must be wired through the full pipeline. If the diff adds any MDL feature, check:

  • Grammar rule added to MDLParser.g4 (and MDLLexer.g4 if new tokens)
  • AST node type added in mdl/ast/
  • Visitor handler in mdl/visitor/
  • Executor handler in mdl/executor/
  • LSP wiring (cmd/mxcli/lsp.go) if the feature adds formatting, diagnostics, or navigation
  • DESCRIBE roundtrip — if the feature creates artifacts, DESCRIBE should output re-executable MDL
  • VS Code extension (vscode-mdl/package.json) updated if new LSP capabilities added

Again, this PR doesn't add any MDL features. It's adding tests for existing executor handler functions. No changes to the full pipeline.

Test coverage

  • New packages should have test files
  • New executor commands should have MDL examples in mdl-examples/doctype-tests/
  • Integration paths should be tested, not just helpers
  • No time.Sleep for synchronization — use channels or polling with timeout

This PR is specifically about improving test coverage. It adds 85 mock-based unit tests across 30 files for handler functions in mdl/executor/. It introduces shared test infrastructure. The tests bypass the Executor and call handler functions directly via ExecContext with MockBackend injection. This seems to be testing integration paths (the handler functions themselves), not just helpers.

Looking at the diff, I see test files like:

  • cmd_agenteditor_mock_test.go
  • cmd_associations_mock_test.go
  • cmd_businessevents_mock_test.go
  • cmd_constants_mock_test.go
  • etc.

These appear to be testing the handler functions directly. The PR says "Tests bypass Executor and call handler functions directly via ExecContext with MockBackend injection", which suggests they're testing the handler functions in isolation but with proper context.

The PR also mentions "Introduce shared test infrastructure (mock_test_helpers_test.go) with functional options pattern, model factories, and thread-safe ID generation via sync/atomic".

I don't see any obvious use of time.Sleep for synchronization in the visible diff.

Security & robustness

  • Command injection, XSS, SQL injection, temp file issues
  • Unix sockets should use restrictive permissions (0600)
  • File I/O should not be in hot paths (event loops, per-keystroke handlers)
  • No silent side effects on typos (e.g., auto-creating resources on misspelled names)
  • Correct method receivers (pointer vs value) for mutations

This is test code, so security concerns are less relevant. The test code appears to be using mock backends and not dealing with real files, sockets, etc. in a way that would introduce security vulnerabilities.

Scope & atomicity

  • Each commit should do one thing — a feature, a bugfix, or a refactor, not a mix
  • PR should be scoped to a single feature or concern — flag if description needs "and" between unrelated items
  • Independent features should be in separate PRs
  • Refactors touching many files should be their own commit

The PR is scoped to adding comprehensive mock-based handler tests. The description focuses on this single concern: adding tests for handler functions in mdl/executor/. It mentions introducing shared test infrastructure as part of this effort, which is related.

Code quality

  • Refactors should be applied consistently (look for old patterns still present)
  • Manually maintained lists (keyword lists, type mappings) should be flagged as maintenance risks
  • Design docs should match the actual implementation

This is test code, so code quality standards still apply but may be slightly different. Looking at the diff, the test code appears to be well-structured with the shared infrastructure. I don't see obvious code quality issues in the visible portions.

Bugs & correctness

  • Logic errors, race conditions
  • Error handling gaps

Again, this is test code, but we want the tests to be correct. The tests appear to be setting up mock backends and verifying expected behavior. They use helper functions like assertNoError, assertContainsStr, etc.

Now, let me look for any specific issues in the visible parts of the diff:

  1. In internal/marketplace/types.go:

    • There's a change to a comment: // "Module", "Widget", "Theme", "Starter App", ... changed to // "Module", "Widget", "Theme", "Starter App", ... (just removed extra spaces)
    • This seems harmless and is likely just a formatting change.
  2. In mdl/ast/ast_agenteditor.go:

    • There are changes to spacing around field declarations (adding/removing spaces)
    • Example: Name QualifiedName -> Name QualifiedName
    • These appear to be formatting changes that don't affect functionality
  3. In mdl/backend/mock/backend.go:

    • Added new function signatures to MockBackend for AgentEditorBackend:
      • CreateAgentEditorModelFunc
      • DeleteAgentEditorModelFunc
      • CreateAgentEditorKnowledgeBaseFunc
      • DeleteAgentEditorKnowledgeBaseFunc
      • CreateAgentEditorConsumedMCPServiceFunc
      • DeleteAgentEditorConsumedMCPServiceFunc
      • CreateAgentEditorAgentFunc
      • DeleteAgentEditorAgentFunc
    • This is necessary to support the new tests for agent editor functionality
  4. In mdl/backend/mock/mock_infrastructure.go:

    • Implemented the new MockBackend functions with proper delegation to the function fields
    • This looks correct
  5. The test files themselves:

    • They appear to be setting up mock backends with specific behaviors
    • They're calling handler functions directly
    • They're verifying output contains expected strings
    • They're using helper functions like mkModule, mkEntity, etc. which are likely defined in the shared test infrastructure

One thing I notice is that the PR mentions it depends on #229 (feature/context-isolation) and needs to be merged first, then rebased. Since this is a review request, I should note this dependency.

Let me check if there are any obvious issues:

In the test files, I see patterns like:

mb := &mock.MockBackend{
    IsConnectedFunc:           func() bool { return true },
    ListAgentEditorModelsFunc: func() ([]*agenteditor.Model, error) { return []*agenteditor.Model{m1}, nil },
}

This looks correct - they're setting up the mock backend to return specific test data.

The helper functions like mkModule, mkEntity, mkHierarchy, withContainer, nextID are used but not defined in the visible diff. These are likely in the shared test infrastructure mentioned (mock_test_helpers_test.go).

The PR says: "Introduce shared test infrastructure (mock_test_helpers_test.go) with functional options pattern, model factories, and thread-safe ID generation via sync/atomic"

I don't see mock_test_helpers_test.go in the visible diff, but it's mentioned as being introduced.

Let me check if there are any potential issues:

  1. The change in internal/marketplace/types.go seems unrelated to the test additions. It's just a comment formatting change. This might be noise or might be part of a separate change that got included. Since the PR is about adding tests, this change seems out of place.

  2. The changes in mdl/ast/ast_agenteditor.go are just spacing changes in field declarations. These don't affect functionality but might be unnecessary if they're not related to the test additions.

However, looking more closely, the PR body says: "All tests use stdlib only (no testify dependency)" and "Tests bypass Executor and call handler functions directly via ExecContext with MockBackend injection" and "No production code changes — test-only files".

But the diff shows changes to:

  • internal/marketplace/types.go (not test file)
  • mdl/ast/ast_agenteditor.go (not test file)
  • mdl/backend/mock/backend.go (this is mock backend, so arguably test-related)
  • mdl/backend/mock/mock_infrastructure.go (this is mock backend infrastructure)
  • and then many test files

The changes to non-test files are:

  • internal/marketplace/types.go: just a comment change
  • mdl/ast/ast_agenteditor.go: just spacing changes in field declarations
  • mdl/backend/mock/backend.go: adding function signatures to MockBackend (needed for tests)
  • mdl/backend/mock/mock_infrastructure.go: implementing those functions

The changes to mdl/ast/ast_agenteditor.go and internal/marketplace/types.go seem questionable as part of a "test-only files" PR. They might be accidental inclusions or might be necessary for some reason.

Let me think: why would ast_agenteditor.go need to change for test purposes? The AST definitions shouldn't need to change just to add tests for the executor, unless the tests are exposing a need for refactoring the AST.

Actually, looking at the changes in ast_agenteditor.go, they're just changing the spacing of field declarations:

  • Name QualifiedName -> Name QualifiedName
  • etc.

This is purely a formatting change with no functional impact. It's possible this was done by an auto-formatter or as part of cleaning up the file, but it's not related to adding tests.

Similarly, the change in internal/marketplace/types.go is just adjusting comment spacing.

These changes are harmless but might be considered noise in a PR that's supposed to be about adding tests.

However, the changes to the mock backend are necessary to support the new tests for agent editor functionality.

Now, let me check if there are any issues with the test approach:

The PR says tests "bypass Executor and call handler functions directly via ExecContext with MockBackend injection". This is a reasonable unit testing approach - testing the handler functions in isolation with mocked dependencies.

Looking at one of the test files, e.g., cmd_agenteditor_mock_test.go:

func TestShowAgentEditorModels_Mock(t *testing.T) {
	mod := mkModule("M")
	m1 := &agenteditor.Model{
		BaseElement: model.BaseElement{ID: nextID("aem")},
		ContainerID: mod.ID,
		Name:        "GPT4",
		Provider:    "MxCloudGenAI",
		DisplayName: "GPT-4 Turbo",
		Key:         &agenteditor.ConstantRef{QualifiedName: "M.APIKey"},
	}

	h := mkHierarchy(mod)
	withContainer(h, m1.ID, mod.ID)

	mb := &mock.MockBackend{
		IsConnectedFunc:           func() bool { return true },
		ListAgentEditorModelsFunc: func() ([]*agenteditor.Model, error) { return []*agenteditor.Model{m1}, nil },
	}

	ctx, buf := newMockCtx(t, withBackend(mb), withHierarchy(h))
	assertNoError(t, showAgentEditorModels(ctx, ""))

	out := buf.String()
	assertContainsStr(t, out, "Qualified Name")
	assertContainsStr(t, out, "Module")
	assertContainsStr(t, out, "Provider")
	assertContainsStr(t, out, "Key Constant")
	assertContainsStr(t, out, "Display Name")
	assertContainsStr(t, out, "M.GPT4")
	assertContainsStr(t, out, "MxCloudGenAI")
	assertContainsStr(t, out, "M.APIKey")
	assertContainsStr(t, out, "GPT-4 Turbo")
}

This looks like a good unit test:

  • Sets up test data (a module and a model)
  • Sets up a mock backend that returns the test data when ListAgentEditorModels is called
  • Creates an ExecContext with the mock backend
  • Calls the handler function directly (showAgentEditorModels)
  • Verifies the output contains expected strings

The use of helper functions like mkModule, nextID, mkHierarchy, withContainer, newMockCtx, withBackend, withHierarchy, assertNoError, assertContainsStr suggests a well-designed test infrastructure.

One potential concern: the PR mentions "thread-safe ID generation via sync/atomic". I should check if the ID generation in the tests is actually thread-safe.

In the test files, I see nextID("aem") being used. If this uses sync/atomic under the hood (as mentioned in the PR), then it should be thread-safe.

Let me see if I can spot the ID generation in the visible diff... I don't see the implementation of nextID in the visible portions, but the PR says it's in the shared test infrastructure.

Overall, this PR appears to be adding valuable test coverage for the executor handler functions. The approach of testing the handlers directly with mocked dependencies is sound.

The minor issues I noticed:

  1. Changes to internal/marketplace/types.go (just comment formatting) - seems unrelated to the test additions
  2. Changes to mdl/ast/ast_agenteditor.go (just field spacing) - seems unrelated to the test additions

These are harmless but might be considered noise in a PR that's supposed to be about adding tests-only files.

However, it's possible these changes were made as part of preparing the codebase for better testability (e.g., if the AST changes were needed to make the agent editor structures more testable, though I don't see how spacing changes would help with that).

Given that the PR says "No production code changes — test-only files", but we see changes to non-test files, this is a bit inconsistent. However, the changes to non-test files are:

  • internal/marketplace/types.go: trivial comment change
  • mdl/ast/ast_agenteditor.go: trivial spacing changes
  • mdl/backend/mock/backend.go: necessary for tests (adding mock function signatures)
  • mdl/backend/mock/mock_infrastructure.go: necessary for tests (implementing those functions)

So the only non-trivial production code changes are to the mock backend, which is test-related infrastructure.

The changes to the AST file and marketplace types file are truly trivial and likely accidental or done by an auto-formatter.

Let me check if there are any other issues:

In the test files, I notice some tests have descriptions like "not yet implemented":

func TestShowBusinessEventClients_Mock(t *testing.T) {
	ctx, buf := newMockCtx(t)
	assertNoError(t, showBusinessEventClients(ctx, ""))
	assertContainsStr(t, buf.String(), "not yet implemented")
}

This is testing that a not-yet-implemented feature returns an appropriate message, which is reasonable.

Also, I see tests for error cases:

func TestDescribeConstant_Mock_NotFound(t *testing.T) {
	// ... setup ...
	err := describeConstant(ctx, ast.QualifiedName{Module: "MyModule", Name: "Missing"})
	assertError(t, err)
}

This is good - testing error paths.

Now, let me think about the checklist items again:

Overlap & duplication

  • This is adding new test files, so no overlap with existing functionality
  • The shared test infrastructure is new, so no duplication there
  • I don't see evidence that this re-documents already-shipped features as new

MDL syntax design

  • Not applicable (no MDL syntax changes)

Full-stack consistency

  • Not applicable (no new MDL features)

Test coverage

  • This is specifically improving test coverage for executor handlers
  • The PR says it adds 85 tests across 30 files
  • It introduces shared test infrastructure
  • Tests integration paths (the handler functions themselves) not just helpers
  • No obvious time.Sleep usage in the visible diff

Security & robustness

  • Test code, so less critical
  • No obvious security issues in the visible diff
  • Using mocks, so no real file/socket issues

Scope & atomicity

  • Focus

Automated review via OpenRouter (Nemotron Super 120B) — workflow source

Copy link
Copy Markdown

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

Copilot reviewed 32 out of 36 changed files in this pull request and generated 2 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread mdl/backend/mock/backend.go
Comment thread mdl/executor/mock_test_helpers_test.go Outdated
@retran retran force-pushed the feature/mock-handler-tests branch from 16956b5 to 3866c81 Compare April 19, 2026 09:59
@github-actions
Copy link
Copy Markdown

AI Code Review

Critical Issues

  • None found

Moderate Issues

  • None found

Minor Issues

  • None found

What Looks Good

  • Test coverage: Adds 85 mock-based unit tests across 30 files for all testable handler functions in mdl/executor/, achieving excellent coverage for show/list/describe/create/drop commands across numerous MDL feature areas.
  • Test infrastructure: Introduces well-designed shared test infrastructure (mock_test_helpers_test.go) using functional options pattern, model factories, and thread-safe ID generation via sync/atomic.
  • Test approach: Tests bypass Executor and call handler functions directly via ExecContext with MockBackend injection, using stdlib only (no testify dependency). This is an appropriate unit testing strategy.
  • Production changes: Minimal and safe production changes solely to support testability:
    • Added Func fields and delegation for agent-editor write methods in MockBackend
    • Minor AST/handler formatting adjustments (alignment changes only) in agent-editor files
    • All changes are test-focused and don't alter core logic
  • Exclusions justified: Contract commands (EDMX-dependent) are appropriately excluded with clear rationale (complex/fragile fixtures better suited for integration tests).
  • Scope: PR is tightly scoped to adding comprehensive mock-based handler tests without mixing in unrelated feature work or refactors.

Recommendation

Approve - The PR significantly improves test coverage for the executor layer with well-designed tests and minimal, safe production changes solely to enable testability. All checklist items are satisfied for this type of change (test addition). No syntax changes were introduced, so MDL syntax and full-stack consistency checks are not applicable. The test infrastructure is robust and follows best practices.


Automated review via OpenRouter (Nemotron Super 120B) — workflow source

Copy link
Copy Markdown

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

Copilot reviewed 32 out of 36 changed files in this pull request and generated no new comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Phase 1-8: 85 read/write handler tests with mock backend infrastructure
Phase 9: 104 additional tests covering error paths, not-connected guards, and JSON format output

Test categories:
- Read-path handlers (SHOW/DESCRIBE) across 20+ domains
- Write-path handlers (CREATE/DROP) for 10 operations
- Backend error propagation for all handler groups
- Not-connected guard verification for 29 guarded handlers
- JSON format output validation for 26 show/list handlers
@retran retran force-pushed the feature/mock-handler-tests branch from 3866c81 to fc7adcd Compare April 19, 2026 10:53
@github-actions
Copy link
Copy Markdown

AI Code Review

What Looks Good

  • Comprehensive test coverage: 85 unit tests across 30 files for executor handler functions
  • Well-designed test infrastructure: mock_test_helpers_test.go introduces functional options pattern, model factories, and thread-safe ID generation
  • Tests follow project conventions: use stdlib only (no testify), bypass Executor to call handlers directly with MockBackend injection
  • Necessary production changes made for testability: added Func fields and delegation for agent-editor write methods in MockBackend
  • Proper exclusion justification: contract commands (EDMX-dependent) excluded as noted, with rationale about fixture complexity
  • Test infrastructure includes helpful utilities: model factories (mkModule, mkEntity, etc.), hierarchy helpers, assertion functions
  • Consistent patterns observed across test files showing good adherence to established testing approaches

Minor Issues

  • Unnecessary whitespace changes in mdl/executor/cmd_agenteditor_models.go and cmd_agenteditor_write.go (extra spaces around colons in struct literals)
  • These are trivial formatting changes that don't affect functionality but could be cleaned up

Recommendation

Approve. The PR adds valuable test coverage for executor handlers with well-designed test infrastructure. The minor whitespace issues are negligible and don't warrant blocking the merge. The changes to make MockBackend more testable are justified and follow standard patterns.


Automated review via OpenRouter (Nemotron Super 120B) — workflow source

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