Skip to content

feat(mock): Add support for repeated message fields in mock generator #28

@SebastienMelki

Description

@SebastienMelki

Feature Description

The mock generator currently generates TODO comments for repeated message fields instead of properly initializing and populating them with mock data. This feature will add full support for generating mock data for repeated/list message fields.

Current State

When encountering a repeated message field, the generator outputs:

// TODO: Handle repeated message field FieldName

Proposed Solution

1. Implement Repeated Message Generation

Replace the TODO comment at internal/httpgen/mock_generator.go:198 with logic to:

  • Generate a slice of message pointers with a configurable default size (e.g., 2 items)
  • Initialize each message instance in the slice
  • Recursively populate fields for each message instance

2. Example Implementation

case protoreflect.MessageKind:
    if field.Desc.IsList() {
        // Generate repeated message field
        gf.P(varName, ".", fieldName, " = []*", field.Message.GoIdent, "{")
        for i := 0; i < defaultListSize; i++ {
            gf.P("&", field.Message.GoIdent, "{},")
        }
        gf.P("}")
        
        // Populate each instance
        for i := 0; i < defaultListSize; i++ {
            instanceVar := fmt.Sprintf("%s.%s[%d]", varName, fieldName, i)
            g.generateMockFieldAssignments(gf, field.Message, instanceVar)
        }
    } else {
        // Existing single message logic
    }

3. Configuration

Add constants for controlling mock generation:

const (
    defaultListSize = 2  // Number of items in mock lists
    maxNestingDepth = 3  // Prevent infinite recursion
)

Testing Requirements

  • Create test proto files with various repeated message field scenarios
  • Verify generated mock code compiles successfully
  • Ensure mock data is properly structured and valid
  • Test nested repeated messages (e.g., repeated User users where User contains repeated Address addresses)

Files Affected

  • internal/httpgen/mock_generator.go - Main implementation
  • internal/httpgen/testdata/proto/*.proto - Test cases
  • internal/httpgen/testdata/golden/*_http_mock.pb.go - Golden files

Success Criteria

  • Repeated message fields generate valid Go slice initialization code
  • Each message in the slice is properly populated with mock data
  • Generated code compiles without errors
  • Recursive field population works for nested messages
  • Depth limiting prevents infinite recursion

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions