This test tries to register flag completion concurrently to make sure the code handles concurrency properly. This was reported as a problem when tests are run concurrently: https://github.com/spf13/cobra/issues/1320 NOTE: this test can sometimes pass even if the code were to not handle concurrency
(t *testing.T)
| 2119 | // it should never fail. Therefore, if the tests fails sometimes, we will |
| 2120 | // still be able to know there is a problem. |
| 2121 | func TestFlagCompletionConcurrentRegistration(t *testing.T) { |
| 2122 | rootCmd := &Command{Use: "root", Run: emptyRun} |
| 2123 | const maxFlags = 50 |
| 2124 | for i := 1; i < maxFlags; i += 2 { |
| 2125 | flagName := fmt.Sprintf("flag%d", i) |
| 2126 | rootCmd.Flags().String(flagName, "", fmt.Sprintf("test %s flag on root", flagName)) |
| 2127 | } |
| 2128 | |
| 2129 | childCmd := &Command{ |
| 2130 | Use: "child", |
| 2131 | Run: emptyRun, |
| 2132 | } |
| 2133 | for i := 2; i <= maxFlags; i += 2 { |
| 2134 | flagName := fmt.Sprintf("flag%d", i) |
| 2135 | childCmd.Flags().String(flagName, "", fmt.Sprintf("test %s flag on child", flagName)) |
| 2136 | } |
| 2137 | |
| 2138 | rootCmd.AddCommand(childCmd) |
| 2139 | |
| 2140 | // Register completion in different threads to test concurrency. |
| 2141 | var wg sync.WaitGroup |
| 2142 | for i := 1; i <= maxFlags; i++ { |
| 2143 | index := i |
| 2144 | flagName := fmt.Sprintf("flag%d", i) |
| 2145 | wg.Add(1) |
| 2146 | go func() { |
| 2147 | defer wg.Done() |
| 2148 | cmd := rootCmd |
| 2149 | if index%2 == 0 { |
| 2150 | cmd = childCmd |
| 2151 | } |
| 2152 | _ = cmd.RegisterFlagCompletionFunc(flagName, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { |
| 2153 | return []string{fmt.Sprintf("flag%d", index)}, ShellCompDirectiveDefault |
| 2154 | }) |
| 2155 | }() |
| 2156 | } |
| 2157 | |
| 2158 | wg.Wait() |
| 2159 | |
| 2160 | // Test that flag completion works for each flag |
| 2161 | for i := 1; i <= 6; i++ { |
| 2162 | var output string |
| 2163 | var err error |
| 2164 | flagName := fmt.Sprintf("flag%d", i) |
| 2165 | |
| 2166 | if i%2 == 1 { |
| 2167 | output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--"+flagName, "") |
| 2168 | } else { |
| 2169 | output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child", "--"+flagName, "") |
| 2170 | } |
| 2171 | |
| 2172 | if err != nil { |
| 2173 | t.Errorf("Unexpected error: %v", err) |
| 2174 | } |
| 2175 | |
| 2176 | expected := strings.Join([]string{ |
| 2177 | flagName, |
| 2178 | ":0", |
nothing calls this directly
no test coverage detected