|
15 | 15 | package cobra
|
16 | 16 |
|
17 | 17 | import (
|
| 18 | + "os" |
| 19 | + "os/exec" |
| 20 | + "path/filepath" |
| 21 | + "strings" |
18 | 22 | "testing"
|
19 | 23 | "text/template"
|
20 | 24 | )
|
@@ -222,3 +226,57 @@ func TestRpad(t *testing.T) {
|
222 | 226 | })
|
223 | 227 | }
|
224 | 228 | }
|
| 229 | + |
| 230 | +func TestDeadcodeElimination(t *testing.T) { |
| 231 | + // check that a simple program using cobra in its default configuration is |
| 232 | + // linked with deadcode elimination enabled. |
| 233 | + const ( |
| 234 | + dirname = "test_deadcode" |
| 235 | + progname = "test_deadcode_elimination" |
| 236 | + ) |
| 237 | + os.Mkdir(dirname, 0770) |
| 238 | + filename := filepath.Join(dirname, progname+".go") |
| 239 | + err := os.WriteFile(filename, []byte(`package main |
| 240 | +
|
| 241 | +import ( |
| 242 | + "fmt" |
| 243 | + "os" |
| 244 | +
|
| 245 | + "github.com/spf13/cobra" |
| 246 | +) |
| 247 | +
|
| 248 | +var rootCmd = &cobra.Command{ |
| 249 | + Version: "1.0", |
| 250 | + Use: "example_program", |
| 251 | + Short: "example_program - test fixture to check that deadcode elimination is allowed", |
| 252 | + Run: func(cmd *cobra.Command, args []string) { |
| 253 | + fmt.Println("hello world") |
| 254 | + }, |
| 255 | + Aliases: []string{"alias1", "alias2"}, |
| 256 | + Example: "stringer --help", |
| 257 | +} |
| 258 | +
|
| 259 | +func main() { |
| 260 | + if err := rootCmd.Execute(); err != nil { |
| 261 | + fmt.Fprintf(os.Stderr, "Whoops. There was an error while executing your CLI '%s'", err) |
| 262 | + os.Exit(1) |
| 263 | + } |
| 264 | +} |
| 265 | +`), 0660) |
| 266 | + if err != nil { |
| 267 | + t.Fatalf("could not write test program: %v", err) |
| 268 | + } |
| 269 | + defer os.RemoveAll(dirname) |
| 270 | + buf, err := exec.Command("go", "build", filename).CombinedOutput() |
| 271 | + if err != nil { |
| 272 | + t.Fatalf("could not compile test program: %s", string(buf)) |
| 273 | + } |
| 274 | + defer os.Remove(progname) |
| 275 | + buf, err = exec.Command("go", "tool", "nm", progname).CombinedOutput() |
| 276 | + if err != nil { |
| 277 | + t.Fatalf("could not run go tool nm: %v", err) |
| 278 | + } |
| 279 | + if strings.Contains(string(buf), "MethodByName") { |
| 280 | + t.Error("compiled programs contains MethodByName symbol") |
| 281 | + } |
| 282 | +} |
0 commit comments