cobra_test.go
This file
Path
cobra_test.go
301 lines · 6.9 KiB · Go
Last changed by
Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
History of this fileTake it
1// Copyright 2013-2023 The Cobra Authors2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415package cobra1617import (18 "os"19 "os/exec"20 "path/filepath"21 "runtime"22 "strings"23 "testing"24 "text/template"25)2627func assertNoErr(t *testing.T, e error) {28 if e != nil {29 t.Error(e)30 }31}3233func TestAddTemplateFunctions(t *testing.T) {34 AddTemplateFunc("t", func() bool { return true })35 AddTemplateFuncs(template.FuncMap{36 "f": func() bool { return false },37 "h": func() string { return "Hello," },38 "w": func() string { return "world." }})3940 c := &Command{}41 c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)4243 const expected = "Hello, world."44 if got := c.UsageString(); got != expected {45 t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)46 }47}4849func TestLevenshteinDistance(t *testing.T) {50 tests := []struct {51 name string52 s string53 t string54 ignoreCase bool55 expected int56 }{57 {58 name: "Equal strings (case-sensitive)",59 s: "hello",60 t: "hello",61 ignoreCase: false,62 expected: 0,63 },64 {65 name: "Equal strings (case-insensitive)",66 s: "Hello",67 t: "hello",68 ignoreCase: true,69 expected: 0,70 },71 {72 name: "Different strings (case-sensitive)",73 s: "kitten",74 t: "sitting",75 ignoreCase: false,76 expected: 3,77 },78 {79 name: "Different strings (case-insensitive)",80 s: "Kitten",81 t: "Sitting",82 ignoreCase: true,83 expected: 3,84 },85 {86 name: "Empty strings",87 s: "",88 t: "",89 ignoreCase: false,90 expected: 0,91 },92 {93 name: "One empty string",94 s: "abc",95 t: "",96 ignoreCase: false,97 expected: 3,98 },99 {100 name: "Both empty strings",101 s: "",102 t: "",103 ignoreCase: true,104 expected: 0,105 },106 }107108 for _, tt := range tests {109 t.Run(tt.name, func(t *testing.T) {110 // Act111 got := ld(tt.s, tt.t, tt.ignoreCase)112113 // Assert114 if got != tt.expected {115 t.Errorf("Expected ld: %v\nGot: %v", tt.expected, got)116 }117 })118 }119}120121func TestStringInSlice(t *testing.T) {122 tests := []struct {123 name string124 a string125 list []string126 expected bool127 }{128 {129 name: "String in slice (case-sensitive)",130 a: "apple",131 list: []string{"orange", "banana", "apple", "grape"},132 expected: true,133 },134 {135 name: "String not in slice (case-sensitive)",136 a: "pear",137 list: []string{"orange", "banana", "apple", "grape"},138 expected: false,139 },140 {141 name: "String in slice (case-insensitive)",142 a: "APPLE",143 list: []string{"orange", "banana", "apple", "grape"},144 expected: false,145 },146 {147 name: "Empty slice",148 a: "apple",149 list: []string{},150 expected: false,151 },152 {153 name: "Empty string",154 a: "",155 list: []string{"orange", "banana", "apple", "grape"},156 expected: false,157 },158 {159 name: "Empty strings match",160 a: "",161 list: []string{"orange", ""},162 expected: true,163 },164 {165 name: "Empty string in empty slice",166 a: "",167 list: []string{},168 expected: false,169 },170 }171172 for _, tt := range tests {173 t.Run(tt.name, func(t *testing.T) {174 // Act175 got := stringInSlice(tt.a, tt.list)176177 // Assert178 if got != tt.expected {179 t.Errorf("Expected stringInSlice: %v\nGot: %v", tt.expected, got)180 }181 })182 }183}184185func TestRpad(t *testing.T) {186 tests := []struct {187 name string188 inputString string189 padding int190 expected string191 }{192 {193 name: "Padding required",194 inputString: "Hello",195 padding: 10,196 expected: "Hello ",197 },198 {199 name: "No padding required",200 inputString: "World",201 padding: 5,202 expected: "World",203 },204 {205 name: "Empty string",206 inputString: "",207 padding: 8,208 expected: " ",209 },210 {211 name: "Zero padding",212 inputString: "cobra",213 padding: 0,214 expected: "cobra",215 },216 }217218 for _, tt := range tests {219 t.Run(tt.name, func(t *testing.T) {220 // Act221 got := rpad(tt.inputString, tt.padding)222223 // Assert224 if got != tt.expected {225 t.Errorf("Expected rpad: %v\nGot: %v", tt.expected, got)226 }227 })228 }229}230231// TestDeadcodeElimination checks that a simple program using cobra in its232// default configuration is linked taking full advantage of the linker's233// deadcode elimination step.234//235// If reflect.Value.MethodByName/reflect.Value.Method are reachable the236// linker will not always be able to prove that exported methods are237// unreachable, making deadcode elimination less effective. Using238// text/template and html/template makes reflect.Value.MethodByName239// reachable.240// Since cobra can use text/template templates this test checks that in its241// default configuration that code path can be proven to be unreachable by242// the linker.243//244// See also: https://github.com/spf13/cobra/pull/1956245func TestDeadcodeElimination(t *testing.T) {246 if runtime.GOOS == "windows" {247 t.Skip("go tool nm fails on windows")248 }249250 // check that a simple program using cobra in its default configuration is251 // linked with deadcode elimination enabled.252 const (253 dirname = "test_deadcode"254 progname = "test_deadcode_elimination"255 )256 _ = os.Mkdir(dirname, 0770)257 defer os.RemoveAll(dirname)258 filename := filepath.Join(dirname, progname+".go")259 err := os.WriteFile(filename, []byte(`package main260261import (262 "fmt"263 "os"264265 "github.com/spf13/cobra"266)267268var rootCmd = &cobra.Command{269 Version: "1.0",270 Use: "example_program",271 Short: "example_program - test fixture to check that deadcode elimination is allowed",272 Run: func(cmd *cobra.Command, args []string) {273 fmt.Println("hello world")274 },275 Aliases: []string{"alias1", "alias2"},276 Example: "stringer --help",277}278279func main() {280 if err := rootCmd.Execute(); err != nil {281 fmt.Fprintf(os.Stderr, "Whoops. There was an error while executing your CLI '%s'", err)282 os.Exit(1)283 }284}285`), 0600)286 if err != nil {287 t.Fatalf("could not write test program: %v", err)288 }289 buf, err := exec.Command("go", "build", filename).CombinedOutput()290 if err != nil {291 t.Fatalf("could not compile test program: %s", string(buf))292 }293 defer os.Remove(progname)294 buf, err = exec.Command("go", "tool", "nm", progname).CombinedOutput()295 if err != nil {296 t.Fatalf("could not run go tool nm: %v", err)297 }298 if strings.Contains(string(buf), "MethodByName") {299 t.Error("compiled programs contains MethodByName symbol")300 }301}