diff --git a/chromium/browser_type.go b/chromium/browser_type.go index ed3c2f4b4..4f3dc65c0 100644 --- a/chromium/browser_type.go +++ b/chromium/browser_type.go @@ -304,7 +304,7 @@ func parseArgs(flags map[string]any) ([]string, error) { for name, value := range flags { switch value := value.(type) { case string: - args = append(args, fmt.Sprintf("--%s=%s", name, value)) + args = append(args, parseStringArg(name, value)) case bool: if value { args = append(args, fmt.Sprintf("--%s", name)) @@ -324,6 +324,15 @@ func parseArgs(flags map[string]any) ([]string, error) { return args, nil } +func parseStringArg(flag string, value string) string { + if strings.TrimSpace(value) == "" { + // If the value is empty, we don't include it in the args list. + // Otherwise, it will produce "--name=" which is invalid. + return fmt.Sprintf("--%s", flag) + } + return fmt.Sprintf("--%s=%s", flag, value) +} + func prepareFlags(lopts *common.BrowserOptions, k6opts *k6lib.Options) (map[string]any, error) { // After Puppeteer's and Playwright's default behavior. f := map[string]any{ diff --git a/chromium/browser_type_test.go b/chromium/browser_type_test.go index 9ad6fcb76..9fd9f53b4 100644 --- a/chromium/browser_type_test.go +++ b/chromium/browser_type_test.go @@ -4,6 +4,7 @@ import ( "io/fs" "net" "path/filepath" + "sort" "testing" "github.com/grafana/xk6-browser/common" @@ -251,3 +252,86 @@ func TestExecutablePath(t *testing.T) { }) } } + +func TestParseArgs(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + flags map[string]any + want []string + }{ + { + name: "string_flag_with_value", + flags: map[string]any{ + "flag1": "value1", + "flag2": "value2", + }, + want: []string{ + "--flag1=value1", + "--flag2=value2", + "--remote-debugging-port=0", + }, + }, + { + name: "string_flag_with_empty_value", + flags: map[string]any{ + "flag1": "", + "flag2": "value2", + }, + want: []string{ + "--flag1", + "--flag2=value2", + "--remote-debugging-port=0", + }, + }, + { + name: "bool_flag_true", + flags: map[string]any{ + "flag1": true, + "flag2": true, + }, + want: []string{ + "--flag1", + "--flag2", + "--remote-debugging-port=0", + }, + }, + { + name: "bool_flag_false", + flags: map[string]any{ + "flag1": false, + "flag2": true, + }, + want: []string{ + "--flag2", + "--remote-debugging-port=0", + }, + }, + { + name: "invalid_flag_type", + flags: map[string]any{ + "flag1": 123, + }, + want: nil, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got, err := parseArgs(tt.flags) + + if tt.want == nil { + assert.Error(t, err) + return + } + require.NoError(t, err) + sort.StringSlice(tt.want).Sort() + sort.StringSlice(got).Sort() + assert.Equal(t, tt.want, got) + }) + } +}