Skip to content

Bug: microcks test panics with index out of range when global flags are used and <runner> arg is omitted #390

@gyanranjanpanda

Description

@gyanranjanpanda

Bug Report

Summary

The test command guards positional argument count using len(os.Args) < 4 (line 50 of cmd/test.go). When the command is invoked with global persistent flags -- the pattern shown in the project README for CI usage -- os.Args contains enough elements to pass the guard, but Cobra's parsed args slice (which has all flags stripped) may have fewer than 3 elements. Accessing args[2] then causes a runtime panic with a full stack trace instead of a clean error message.

Steps to Reproduce

Build the binary and run with global flags but omit the <runner> argument:

microcks test \
  --microcksURL=http://localhost:8080 \
  --keycloakClientId=foo \
  --keycloakClientSecret=bar \
  'MyAPI:1.0' http://localhost:3000

Actual Behavior

goroutine 1 [running]:
runtime error: index out of range [2] with length 2
...full stack trace...

Expected Behavior

Error: accepts 3 arg(s), received 2
Usage:
  microcks test <apiName:apiVersion> <testEndpoint> <runner> [flags]

Root Cause

The guard was written before global persistent flags (--microcksURL, --keycloakClientId, --keycloakClientSecret, etc.) were added to the root command. At that point os.Args and the positional args slice were in sync. After global flags were introduced, os.Args inflates with each flag, but args (as populated by Cobra after flag parsing) remains positional-only.

// BEFORE (broken): os.Args includes global flags, so the guard is bypassed
if len(os.Args) < 4 {
    ...
}
serviceRef   := args[0]
testEndpoint := args[1]
runnerType   := args[2]  // panics when args has only 2 elements

Fix

Use cobra.ExactArgs(3) on the command definition -- the idiomatic Cobra approach -- which validates argument count before Run is ever called and prints the usage hint automatically.

Additional Notes

  • The three individual strings.HasPrefix(x, "-") guards that follow the count check are also dead code: Cobra strips all flags before handing args to Run, so none of those args can ever start with -.
    • The runner validation error message listed SOAP (not a valid runner) instead of SOAP_HTTP.
      • A regression test is included in the fix PR to assert exit code 1 and no panic stack trace.

Environment

  • microcks-cli version: latest master
    • Go version: 1.22+
      • Reproduced when global flags are passed (typical CI invocation per README)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions