How to use errorf method of main Package

Best Mock code snippet using main.errorf

peek_test.go

Source:peek_test.go Github

copy

Full Screen

1// Copyright 2018 Google Inc. All Rights Reserved.2//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.14// +build linux15package peek_test16import (17 "flag"18 "fmt"19 "log"20 "os"21 "os/exec"22 "reflect"23 "regexp"24 "sync"25 "testing"26 "cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug"27 "cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug/local"28 "cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug/remote"29)30var expectedVarValues = map[string]interface{}{31 `main.Z_bool_false`: false,32 `main.Z_bool_true`: true,33 `main.Z_complex128`: complex128(1.987654321 - 2.987654321i),34 `main.Z_complex64`: complex64(1.54321 + 2.54321i),35 `main.Z_float32`: float32(1.54321),36 `main.Z_float64`: float64(1.987654321),37 `main.Z_int16`: int16(-32321),38 `main.Z_int32`: int32(-1987654321),39 `main.Z_int64`: int64(-9012345678987654321),40 `main.Z_int8`: int8(-121),41 `main.Z_uint16`: uint16(54321),42 `main.Z_uint32`: uint32(3217654321),43 `main.Z_uint64`: uint64(12345678900987654321),44 `main.Z_uint8`: uint8(231),45}46// TODO: the string forms of some types we're testing aren't stable47var expectedVars = map[string]string{48 `main.Z_array`: `[5]int8{-121, 121, 3, 2, 1}`,49 `main.Z_array_empty`: `[0]int8{}`,50 `main.Z_bool_false`: `false`,51 `main.Z_bool_true`: `true`,52 `main.Z_channel`: `(chan int16 0xX)`,53 `main.Z_channel_2`: `(chan int16 0xX)`,54 `main.Z_channel_buffered`: `(chan int16 0xX [6/10])`,55 `main.Z_channel_nil`: `(chan int16 <nil>)`,56 `main.Z_array_of_empties`: `[2]{}{{} {}, ({} 0xX)}`,57 `main.Z_complex128`: `(1.987654321-2.987654321i)`,58 `main.Z_complex64`: `(1.54321+2.54321i)`,59 `main.Z_float32`: `1.54321`,60 `main.Z_float64`: `1.987654321`,61 `main.Z_func_int8_r_int8`: `func(int8, *int8) void @0xX `,62 `main.Z_func_int8_r_pint8`: `func(int8, **int8) void @0xX `,63 `main.Z_func_bar`: `func(*main.FooStruct) void @0xX `,64 `main.Z_func_nil`: `func(int8, *int8) void @0xX `,65 `main.Z_int`: `-21`,66 `main.Z_int16`: `-32321`,67 `main.Z_int32`: `-1987654321`,68 `main.Z_int64`: `-9012345678987654321`,69 `main.Z_int8`: `-121`,70 `main.Z_int_typedef`: `88`,71 `main.Z_interface`: `("*main.FooStruct", 0xX)`,72 `main.Z_interface_nil`: `(<nil>, <nil>)`,73 `main.Z_interface_typed_nil`: `("*main.FooStruct", <nil>)`,74 `main.Z_map`: `map[-21:3.54321]`,75 `main.Z_map_2`: `map[1024:1]`,76 `main.Z_map_3`: `map[1024:1 512:-1]`,77 `main.Z_map_empty`: `map[]`,78 `main.Z_map_nil`: `map[]`,79 `main.Z_pointer`: `0xX`,80 `main.Z_pointer_nil`: `0x0`,81 `main.Z_slice`: `[]uint8{115, 108, 105, 99, 101}`,82 `main.Z_slice_2`: `[]int8{-121, 121}`,83 `main.Z_slice_nil`: `[]uint8{}`,84 `main.Z_string`: `"I'm a string"`,85 `main.Z_struct`: `main.FooStruct {21, "hi"}`,86 `main.Z_uint`: `21`,87 `main.Z_uint16`: `54321`,88 `main.Z_uint32`: `3217654321`,89 `main.Z_uint64`: `12345678900987654321`,90 `main.Z_uint8`: `231`,91 `main.Z_uintptr`: `21`,92 `main.Z_unsafe_pointer`: `0xX`,93 `main.Z_unsafe_pointer_nil`: `0x0`,94}95// expectedEvaluate contains expected results of the debug.Evaluate function.96// A nil value indicates that an error is expected.97var expectedEvaluate = map[string]debug.Value{98 `x`: int16(42),99 `local_array`: debug.Array{42, 42, 5, 8},100 `local_channel`: debug.Channel{42, 42, 42, 0, 0, 2, 0},101 `local_channel_buffered`: debug.Channel{42, 42, 42, 6, 10, 2, 8},102 `local_map`: debug.Map{42, 42, 1},103 `local_map_2`: debug.Map{42, 42, 1},104 `local_map_3`: debug.Map{42, 42, 2},105 `local_map_empty`: debug.Map{42, 42, 0},106 `x + 5`: int16(47),107 `x - 5`: int16(37),108 `x / 5`: int16(8),109 `x % 5`: int16(2),110 `x & 2`: int16(2),111 `x | 1`: int16(43),112 `x ^ 3`: int16(41),113 `5 + x`: int16(47),114 `5 - x`: int16(-37),115 `100 / x`: int16(2),116 `100 % x`: int16(16),117 `2 & x`: int16(2),118 `1 | x`: int16(43),119 `3 ^ x`: int16(41),120 `12`: 12,121 `+42`: 42,122 `23i`: 23i,123 `34.0`: 34.0,124 `34.5`: 34.5,125 `1e5`: 100000.0,126 `0x42`: 66,127 `'c'`: 'c',128 `"de"`: debug.String{2, `de`},129 "`ef`": debug.String{2, `ef`},130 `"de" + "fg"`: debug.String{4, `defg`},131 `/* comment */ -5`: -5,132 `false`: false,133 `true`: true,134 `!false`: true,135 `!true`: false,136 `5 + 5`: 10,137 `true || false`: true,138 `false || false`: false,139 `true && false`: false,140 `true && true`: true,141 `!(5 > 8)`: true,142 `10 + 'a'`: 'k',143 `10 + 10.5`: 20.5,144 `10 + 10.5i`: 10 + 10.5i,145 `'a' + 10.5`: 107.5,146 `'a' + 10.5i`: 97 + 10.5i,147 `10.5 + 20.5i`: 10.5 + 20.5i,148 `10 * 20`: 200,149 `10.0 - 20.5`: -10.5,150 `(6 + 8i) * 4`: 24 + 32i,151 `(6 + 8i) * (1 + 1i)`: -2 + 14i,152 `(6 + 8i) * (6 - 8i)`: complex128(100),153 `(6 + 8i) / (3 + 4i)`: complex128(2),154 `local_array[2]`: int8(3),155 `&local_array[1]`: debug.Pointer{42, 42},156 `local_map[-21]`: float32(3.54321),157 `local_map[+21]`: float32(0),158 `local_map_3[1024]`: int8(1),159 `local_map_3[512]`: int8(-1),160 `local_map_empty[21]`: float32(0),161 `"hello"[2]`: uint8('l'),162 `local_array[1:3][1]`: int8(3),163 `local_array[0:4][2:3][0]`: int8(3),164 `local_array[:]`: debug.Slice{debug.Array{42, 42, 5, 8}, 5},165 `local_array[:2]`: debug.Slice{debug.Array{42, 42, 2, 8}, 5},166 `local_array[2:]`: debug.Slice{debug.Array{42, 42, 3, 8}, 3},167 `local_array[1:3]`: debug.Slice{debug.Array{42, 42, 2, 8}, 4},168 `local_array[:3:4]`: debug.Slice{debug.Array{42, 42, 3, 8}, 4},169 `local_array[1:3:4]`: debug.Slice{debug.Array{42, 42, 2, 8}, 3},170 `local_array[1:][1:][1:]`: debug.Slice{debug.Array{42, 42, 2, 8}, 2},171 `(&local_array)[:]`: debug.Slice{debug.Array{42, 42, 5, 8}, 5},172 `(&local_array)[:2]`: debug.Slice{debug.Array{42, 42, 2, 8}, 5},173 `(&local_array)[2:]`: debug.Slice{debug.Array{42, 42, 3, 8}, 3},174 `(&local_array)[1:3]`: debug.Slice{debug.Array{42, 42, 2, 8}, 4},175 `(&local_array)[:3:4]`: debug.Slice{debug.Array{42, 42, 3, 8}, 4},176 `(&local_array)[1:3:4]`: debug.Slice{debug.Array{42, 42, 2, 8}, 3},177 `lookup("main.Z_array")`: debug.Array{42, 42, 5, 8},178 `lookup("main.Z_array_empty")`: debug.Array{42, 42, 0, 8},179 `lookup("main.Z_bool_false")`: false,180 `lookup("main.Z_bool_true")`: true,181 `lookup("main.Z_channel")`: debug.Channel{42, 42, 42, 0, 0, 2, 0},182 `lookup("main.Z_channel_buffered")`: debug.Channel{42, 42, 42, 6, 10, 2, 8},183 `lookup("main.Z_channel_nil")`: debug.Channel{42, 0, 0, 0, 0, 2, 0},184 `lookup("main.Z_array_of_empties")`: debug.Array{42, 42, 2, 0},185 `lookup("main.Z_complex128")`: complex128(1.987654321 - 2.987654321i),186 `lookup("main.Z_complex64")`: complex64(1.54321 + 2.54321i),187 `lookup("main.Z_float32")`: float32(1.54321),188 `lookup("main.Z_float64")`: float64(1.987654321),189 `lookup("main.Z_func_int8_r_int8")`: debug.Func{42},190 `lookup("main.Z_func_int8_r_pint8")`: debug.Func{42},191 `lookup("main.Z_func_bar")`: debug.Func{42},192 `lookup("main.Z_func_nil")`: debug.Func{0},193 `lookup("main.Z_int")`: -21,194 `lookup("main.Z_int16")`: int16(-32321),195 `lookup("main.Z_int32")`: int32(-1987654321),196 `lookup("main.Z_int64")`: int64(-9012345678987654321),197 `lookup("main.Z_int8")`: int8(-121),198 `lookup("main.Z_int_typedef")`: int16(88),199 `lookup("main.Z_interface")`: debug.Interface{},200 `lookup("main.Z_interface_nil")`: debug.Interface{},201 `lookup("main.Z_interface_typed_nil")`: debug.Interface{},202 `lookup("main.Z_map")`: debug.Map{42, 42, 1},203 `lookup("main.Z_map_2")`: debug.Map{42, 42, 1},204 `lookup("main.Z_map_3")`: debug.Map{42, 42, 2},205 `lookup("main.Z_map_empty")`: debug.Map{42, 42, 0},206 `lookup("main.Z_map_nil")`: debug.Map{42, 42, 0},207 `lookup("main.Z_pointer")`: debug.Pointer{42, 42},208 `lookup("main.Z_pointer_nil")`: debug.Pointer{42, 0},209 `lookup("main.Z_slice")`: debug.Slice{debug.Array{42, 42, 5, 8}, 5},210 `lookup("main.Z_slice_2")`: debug.Slice{debug.Array{42, 42, 2, 8}, 5},211 `lookup("main.Z_slice_nil")`: debug.Slice{debug.Array{42, 0, 0, 8}, 0},212 `lookup("main.Z_string")`: debug.String{12, `I'm a string`},213 `lookup("main.Z_struct")`: debug.Struct{[]debug.StructField{{"a", debug.Var{}}, {"b", debug.Var{}}}},214 `lookup("main.Z_uint")`: uint(21),215 `lookup("main.Z_uint16")`: uint16(54321),216 `lookup("main.Z_uint32")`: uint32(3217654321),217 `lookup("main.Z_uint64")`: uint64(12345678900987654321),218 `lookup("main.Z_uint8")`: uint8(231),219 `lookup("main.Z_uintptr")`: uint(21),220 `lookup("main.Z_unsafe_pointer")`: debug.Pointer{0, 42},221 `lookup("main.Z_unsafe_pointer_nil")`: debug.Pointer{0, 0},222 `lookup("main.Z_int") + lookup("main.Z_int")`: -42,223 `lookup("main.Z_int16") < 0`: true,224 `lookup("main.Z_uint32") + lookup("main.Z_uint32")`: uint32(2140341346),225 `lookup("main.Z_bool_true") || lookup("main.Z_bool_false")`: true,226 `lookup("main.Z_bool_true") && lookup("main.Z_bool_false")`: false,227 `lookup("main.Z_bool_false") || lookup("main.Z_bool_false")`: false,228 `!lookup("main.Z_bool_true")`: false,229 `!lookup("main.Z_bool_false")`: true,230 `lookup("main.Z_array")[2]`: int8(3),231 `lookup("main.Z_array")[1:3][1]`: int8(3),232 `lookup("main.Z_array")[0:4][2:3][0]`: int8(3),233 `lookup("main.Z_array_of_empties")[0]`: debug.Struct{},234 `lookup("main.Z_complex128") * 10.0`: complex128(19.87654321 - 29.87654321i),235 `lookup("main.Z_complex64") * 0.1`: complex64(0.154321 + 0.254321i),236 `lookup("main.Z_float32") * 10.0`: float32(15.4321),237 `lookup("main.Z_float64") * 0.1`: float64(0.1987654321),238 `lookup("main.Z_int") + 1`: int(-20),239 `lookup("main.Z_int16") - 10`: int16(-32331),240 `lookup("main.Z_int32") / 10`: int32(-198765432),241 `lookup("main.Z_int64") / 10`: int64(-901234567898765432),242 `lookup("main.Z_int8") + 10`: int8(-111),243 `lookup("main.Z_map")[-21]`: float32(3.54321),244 `lookup("main.Z_map")[+21]`: float32(0),245 `lookup("main.Z_map_empty")[21]`: float32(0),246 `lookup("main.Z_slice")[1]`: uint8(108),247 `lookup("main.Z_slice_2")[1]`: int8(121),248 `lookup("main.Z_slice")[1:5][0:3][1]`: uint8('i'),249 `lookup("main.Z_array")[1:3:4]`: debug.Slice{debug.Array{42, 42, 2, 8}, 3},250 `(&lookup("main.Z_array"))[1:3:4]`: debug.Slice{debug.Array{42, 42, 2, 8}, 3},251 `lookup("main.Z_string") + "!"`: debug.String{13, `I'm a string!`},252 `lookup("main.Z_struct").a`: 21,253 `(&lookup("main.Z_struct")).a`: 21,254 `lookup("main.Z_uint")/10`: uint(2),255 `lookup("main.Z_uint16")/10`: uint16(5432),256 `lookup("main.Z_uint32")/10`: uint32(321765432),257 `lookup("main.Z_uint64")/10`: uint64(1234567890098765432),258 `lookup("main.Z_uint8")/10`: uint8(23),259 `lookup("main.Z_pointer").a`: 21,260 `(*lookup("main.Z_pointer")).a`: 21,261 `(&*lookup("main.Z_pointer")).a`: 21,262 `lookup("main.Z_pointer").b`: debug.String{2, `hi`},263 `(*lookup("main.Z_pointer")).b`: debug.String{2, `hi`},264 `(&*lookup("main.Z_pointer")).b`: debug.String{2, `hi`},265 `lookup("main.Z_map_nil")[32]`: float32(0),266 `&lookup("main.Z_int16")`: debug.Pointer{42, 42},267 `&lookup("main.Z_array")[1]`: debug.Pointer{42, 42},268 `&lookup("main.Z_slice")[1]`: debug.Pointer{42, 42},269 `*&lookup("main.Z_int16")`: int16(-32321),270 `*&*&*&*&lookup("main.Z_int16")`: int16(-32321),271 `lookup("time.Local")`: debug.Pointer{42, 42},272 `5 + false`: nil,273 ``: nil,274 `x + ""`: nil,275 `x / 0`: nil,276 `0 / 0`: nil,277 `'a' / ('a'-'a')`: nil,278 `0.0 / 0.0`: nil,279 `3i / 0.0`: nil,280 `x % 0`: nil,281 `0 % 0`: nil,282 `'a' % ('a'-'a')`: nil,283 `local_array[-2] + 1`: nil,284 `local_array[22] + 1`: nil,285 `local_slice[-2] + 1`: nil,286 `local_slice[22] + 1`: nil,287 `local_string[-2]`: nil,288 `local_string[22]`: nil,289 `"hello"[-2]`: nil,290 `"hello"[22]`: nil,291 `local_pointer_nil.a`: nil,292 `(local_struct).c`: nil,293 `(&local_struct).c`: nil,294 `(*local_pointer).c`: nil,295 `lookup("not a real symbol")`: nil,296 `lookup("x")`: nil,297 `lookup(x)`: nil,298 `lookup(42)`: nil,299}300func isHex(r uint8) bool {301 switch {302 case '0' <= r && r <= '9':303 return true304 case 'a' <= r && r <= 'f':305 return true306 case 'A' <= r && r <= 'F':307 return true308 default:309 return false310 }311}312// structRE is used by matches to remove 'struct ' from type names, which is not313// output by every version of the compiler.314var structRE = regexp.MustCompile("struct *")315// Check s matches the pattern in p.316// An 'X' in p greedily matches one or more hex characters in s.317func matches(p, s string) bool {318 // Remove 'struct' and following spaces from s.319 s = structRE.ReplaceAllString(s, "")320 j := 0321 for i := 0; i < len(p); i++ {322 if j == len(s) {323 return false324 }325 c := p[i]326 if c == 'X' {327 if !isHex(s[j]) {328 return false329 }330 for j < len(s) && isHex(s[j]) {331 j++332 }333 continue334 }335 if c != s[j] {336 return false337 }338 j++339 }340 return j == len(s)341}342const (343 proxySrc = "cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug/cmd/debugproxy"344 traceeSrc = "cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug/tests/peek/testdata"345)346var (347 // Locations of the proxy and tracee executables.348 proxyBinary = "./debugproxy.out"349 traceeBinary = "./tracee.out"350 // Onces that ensure initProxy and initTracee are called at most once.351 proxyOnce sync.Once352 traceeOnce sync.Once353 // Flags for setting the location of the proxy and tracee, so they don't need to be built.354 proxyFlag = flag.String("proxy", "", "Location of debugproxy. If empty, proxy will be built.")355 traceeFlag = flag.String("target", "", "Location of target. If empty, target will be built.")356 // Executables this test has built, which will be removed on completion of the tests.357 filesToRemove []string358)359func TestMain(m *testing.M) {360 flag.Parse()361 x := m.Run()362 for _, f := range filesToRemove {363 os.Remove(f)364 }365 os.Exit(x)366}367func run(name string, args ...string) error {368 cmd := exec.Command(name, args...)369 cmd.Stdout = os.Stdout370 cmd.Stderr = os.Stderr371 return cmd.Run()372}373func initProxy() {374 if *proxyFlag != "" {375 proxyBinary = *proxyFlag376 remote.DebugproxyCmd = proxyBinary377 return378 }379 if err := run("go", "build", "-o", proxyBinary, proxySrc); err != nil {380 log.Fatalf("couldn't build proxy: %v", err)381 }382 filesToRemove = append(filesToRemove, proxyBinary)383 remote.DebugproxyCmd = proxyBinary384}385func initTracee() {386 if *traceeFlag != "" {387 traceeBinary = *traceeFlag388 return389 }390 if err := run("go", "build", "-o", traceeBinary, traceeSrc); err != nil {391 log.Fatalf("couldn't build target: %v", err)392 }393 filesToRemove = append(filesToRemove, traceeBinary)394}395func TestLocalProgram(t *testing.T) {396 t.Skip("Fails looking for runtime.lessstack for some reason")397 traceeOnce.Do(initTracee)398 prog, err := local.New(traceeBinary)399 if err != nil {400 t.Fatal("local.New:", err)401 }402 testProgram(t, prog)403}404func TestRemoteProgram(t *testing.T) {405 t.Skip("Fails looking for runtime.lessstack for some reason")406 traceeOnce.Do(initTracee)407 proxyOnce.Do(initProxy)408 prog, err := remote.New("localhost", traceeBinary)409 if err != nil {410 t.Fatal("remote.New:", err)411 }412 testProgram(t, prog)413}414func testProgram(t *testing.T, prog debug.Program) {415 _, err := prog.Run("some", "arguments")416 if err != nil {417 log.Fatalf("Run: %v", err)418 }419 pcs, err := prog.BreakpointAtFunction("main.foo")420 if err != nil {421 log.Fatalf("BreakpointAtFunction: %v", err)422 }423 fmt.Printf("breakpoints set at %x\n", pcs)424 _, err = prog.Resume()425 if err != nil {426 log.Fatalf("Resume: %v", err)427 }428 gs, err := prog.Goroutines()429 if err != nil {430 t.Fatalf("Goroutines(): got error %s", err)431 }432 for _, g := range gs {433 fmt.Println(g)434 for _, f := range g.StackFrames {435 fmt.Println(f)436 }437 }438 frames, err := prog.Frames(100)439 if err != nil {440 log.Fatalf("prog.Frames error: %v", err)441 }442 fmt.Printf("%#v\n", frames)443 if len(frames) == 0 {444 t.Fatalf("no stack frames returned")445 }446 if frames[0].Function != "main.foo" {447 t.Errorf("function name: got %s expected main.foo", frames[0].Function)448 }449 if len(frames[0].Params) != 2 {450 t.Errorf("got %d parameters, expected 2", len(frames[0].Params))451 } else {452 x := frames[0].Params[0]453 y := frames[0].Params[1]454 if x.Name != "x" {455 x, y = y, x456 }457 if x.Name != "x" {458 t.Errorf("parameter name: got %s expected x", x.Name)459 }460 if y.Name != "y" {461 t.Errorf("parameter name: got %s expected y", y.Name)462 }463 if val, err := prog.Value(x.Var); err != nil {464 t.Errorf("value of x: %s", err)465 } else if val != int16(42) {466 t.Errorf("value of x: got %T(%v) expected int16(42)", val, val)467 }468 if val, err := prog.Value(y.Var); err != nil {469 t.Errorf("value of y: %s", err)470 } else if val != float32(1.5) {471 t.Errorf("value of y: got %T(%v) expected float32(1.5)", val, val)472 }473 }474 varnames, err := prog.Eval(`re:main\.Z_.*`)475 if err != nil {476 log.Fatalf("prog.Eval error: %v", err)477 }478 // Evaluate each of the variables found above, and check they match479 // expectedVars.480 seen := make(map[string]bool)481 for _, v := range varnames {482 val, err := prog.Eval("val:" + v)483 if err != nil {484 log.Fatalf("prog.Eval error for %s: %v", v, err)485 } else {486 fmt.Printf("%s = %v\n", v, val)487 if seen[v] {488 log.Fatalf("repeated variable %s\n", v)489 }490 seen[v] = true491 if len(val) != 1 {492 log.Fatalf("should be one value for %s\n", v)493 }494 expected, ok := expectedVars[v]495 if !ok {496 log.Fatalf("unexpected variable %s\n", v)497 } else {498 if !matches(expected, val[0]) {499 log.Fatalf("expected %s = %s\n", v, expected)500 }501 }502 }503 }504 for v, e := range expectedVars {505 if !seen[v] {506 log.Fatalf("didn't get %s = %s\n", v, e)507 }508 }509 // Remove the breakpoint at main.foo.510 err = prog.DeleteBreakpoints(pcs)511 if err != nil {512 log.Fatalf("DeleteBreakpoints: %v", err)513 }514 // Set a breakpoint at line 125, resume, and check we stopped there.515 pcsLine125, err := prog.BreakpointAtLine("testdata/main.go", 125)516 if err != nil {517 t.Fatal("BreakpointAtLine:", err)518 }519 status, err := prog.Resume()520 if err != nil {521 log.Fatalf("Resume: %v", err)522 }523 stoppedAt := func(pcs []uint64) bool {524 for _, pc := range pcs {525 if status.PC == pc {526 return true527 }528 }529 return false530 }531 if !stoppedAt(pcsLine125) {532 t.Errorf("stopped at %X; expected one of %X.", status.PC, pcsLine125)533 }534 for k, v := range expectedEvaluate {535 val, err := prog.Evaluate(k)536 if v == nil {537 if err == nil {538 t.Errorf("got Evaluate(%s) = %v, expected error", k, val)539 }540 continue541 }542 if err != nil {543 t.Errorf("Evaluate(%s): got error %s, expected %v", k, err, v)544 continue545 }546 typ := reflect.TypeOf(v)547 if typ != reflect.TypeOf(val) && typ != reflect.TypeOf(int(0)) && typ != reflect.TypeOf(uint(0)) {548 t.Errorf("got Evaluate(%s) = %T(%v), expected %T(%v)", k, val, val, v, v)549 continue550 }551 // For types with fields like Address, TypeID, etc., we can't know the exact552 // value, so we only test whether those fields are zero or not.553 switch v := v.(type) {554 default:555 if v != val {556 t.Errorf("got Evaluate(%s) = %T(%v), expected %T(%v)", k, val, val, v, v)557 }558 case debug.Array:559 val := val.(debug.Array)560 if v.ElementTypeID == 0 && val.ElementTypeID != 0 {561 t.Errorf("got Evaluate(%s) = %+v, expected zero ElementTypeID", k, val)562 }563 if v.ElementTypeID != 0 && val.ElementTypeID == 0 {564 t.Errorf("got Evaluate(%s) = %+v, expected non-zero ElementTypeID", k, val)565 }566 if v.Address == 0 && val.Address != 0 {567 t.Errorf("got Evaluate(%s) = %+v, expected zero Address", k, val)568 }569 if v.Address != 0 && val.Address == 0 {570 t.Errorf("got Evaluate(%s) = %+v, expected non-zero Address", k, val)571 }572 case debug.Slice:573 val := val.(debug.Slice)574 if v.ElementTypeID == 0 && val.ElementTypeID != 0 {575 t.Errorf("got Evaluate(%s) = %+v, expected zero ElementTypeID", k, val)576 }577 if v.ElementTypeID != 0 && val.ElementTypeID == 0 {578 t.Errorf("got Evaluate(%s) = %+v, expected non-zero ElementTypeID", k, val)579 }580 if v.Address == 0 && val.Address != 0 {581 t.Errorf("got Evaluate(%s) = %+v, expected zero Address", k, val)582 }583 if v.Address != 0 && val.Address == 0 {584 t.Errorf("got Evaluate(%s) = %+v, expected non-zero Address", k, val)585 }586 case debug.Map:587 val := val.(debug.Map)588 if v.TypeID == 0 && val.TypeID != 0 {589 t.Errorf("got Evaluate(%s) = %+v, expected zero TypeID", k, val)590 }591 if v.TypeID != 0 && val.TypeID == 0 {592 t.Errorf("got Evaluate(%s) = %+v, expected non-zero TypeID", k, val)593 }594 if v.Address == 0 && val.Address != 0 {595 t.Errorf("got Evaluate(%s) = %+v, expected zero Address", k, val)596 }597 if v.Address != 0 && val.Address == 0 {598 t.Errorf("got Evaluate(%s) = %+v, expected non-zero Address", k, val)599 }600 case debug.Pointer:601 val := val.(debug.Pointer)602 if v.TypeID == 0 && val.TypeID != 0 {603 t.Errorf("got Evaluate(%s) = %+v, expected zero TypeID", k, val)604 }605 if v.TypeID != 0 && val.TypeID == 0 {606 t.Errorf("got Evaluate(%s) = %+v, expected non-zero TypeID", k, val)607 }608 if v.Address == 0 && val.Address != 0 {609 t.Errorf("got Evaluate(%s) = %+v, expected zero Address", k, val)610 }611 if v.Address != 0 && val.Address == 0 {612 t.Errorf("got Evaluate(%s) = %+v, expected non-zero Address", k, val)613 }614 case debug.Channel:615 val := val.(debug.Channel)616 if v.ElementTypeID == 0 && val.ElementTypeID != 0 {617 t.Errorf("got Evaluate(%s) = %+v, expected zero ElementTypeID", k, val)618 }619 if v.ElementTypeID != 0 && val.ElementTypeID == 0 {620 t.Errorf("got Evaluate(%s) = %+v, expected non-zero ElementTypeID", k, val)621 }622 if v.Address == 0 && val.Address != 0 {623 t.Errorf("got Evaluate(%s) = %+v, expected zero Address", k, val)624 }625 if v.Address != 0 && val.Address == 0 {626 t.Errorf("got Evaluate(%s) = %+v, expected non-zero Address", k, val)627 }628 if v.Buffer == 0 && val.Buffer != 0 {629 t.Errorf("got Evaluate(%s) = %+v, expected zero Buffer", k, val)630 }631 if v.Buffer != 0 && val.Buffer == 0 {632 t.Errorf("got Evaluate(%s) = %+v, expected non-zero Buffer", k, val)633 }634 case debug.Struct:635 val := val.(debug.Struct)636 if len(v.Fields) != len(val.Fields) {637 t.Errorf("got Evaluate(%s) = %T(%v), expected %T(%v)", k, val, val, v, v)638 break639 }640 for i := range v.Fields {641 a := v.Fields[i].Name642 b := val.Fields[i].Name643 if a != b {644 t.Errorf("Evaluate(%s): field name mismatch: %s vs %s", k, a, b)645 break646 }647 }648 case debug.Func:649 val := val.(debug.Func)650 if v.Address == 0 && val.Address != 0 {651 t.Errorf("got Evaluate(%s) = %+v, expected zero Address", k, val)652 }653 if v.Address != 0 && val.Address == 0 {654 t.Errorf("got Evaluate(%s) = %+v, expected non-zero Address", k, val)655 }656 case int:657 // ints in a remote program can be returned as int32 or int64658 switch val := val.(type) {659 case int32:660 if val != int32(v) {661 t.Errorf("got Evaluate(%s) = %T(%v), expected %v", k, val, val, v)662 }663 case int64:664 if val != int64(v) {665 t.Errorf("got Evaluate(%s) = %T(%v), expected %v", k, val, val, v)666 }667 default:668 t.Errorf("got Evaluate(%s) = %T(%v), expected %T(%v)", k, val, val, v, v)669 }670 case uint:671 // uints in a remote program can be returned as uint32 or uint64672 switch val := val.(type) {673 case uint32:674 if val != uint32(v) {675 t.Errorf("got Evaluate(%s) = %T(%v), expected %v", k, val, val, v)676 }677 case uint64:678 if val != uint64(v) {679 t.Errorf("got Evaluate(%s) = %T(%v), expected %v", k, val, val, v)680 }681 default:682 t.Errorf("got Evaluate(%s) = %T(%v), expected %T(%v)", k, val, val, v, v)683 }684 }685 }686 // Evaluate a struct.687 v := `lookup("main.Z_struct")`688 val, err := prog.Evaluate(v)689 if err != nil {690 t.Fatalf("Evaluate: %s", err)691 }692 s, ok := val.(debug.Struct)693 if !ok {694 t.Fatalf("got Evaluate(%q) = %T(%v), expected debug.Struct", v, val, val)695 }696 // Check the values of its fields.697 if len(s.Fields) != 2 {698 t.Fatalf("got Evaluate(%q) = %+v, expected 2 fields", v, s)699 }700 if v0, err := prog.Value(s.Fields[0].Var); err != nil {701 t.Errorf("Value: %s", err)702 } else if v0 != int32(21) && v0 != int64(21) {703 t.Errorf("Value: got %T(%v), expected 21", v0, v0)704 }705 if v1, err := prog.Value(s.Fields[1].Var); err != nil {706 t.Errorf("Value: %s", err)707 } else if v1 != (debug.String{2, "hi"}) {708 t.Errorf("Value: got %T(%v), expected `hi`", v1, v1)709 }710 // Remove the breakpoint at line 125, set a breakpoint at main.f1 and main.f2,711 // then delete the breakpoint at main.f1. Resume, then check we stopped at712 // main.f2.713 err = prog.DeleteBreakpoints(pcsLine125)714 if err != nil {715 log.Fatalf("DeleteBreakpoints: %v", err)716 }717 pcs1, err := prog.BreakpointAtFunction("main.f1")718 if err != nil {719 log.Fatalf("BreakpointAtFunction: %v", err)720 }721 pcs2, err := prog.BreakpointAtFunction("main.f2")722 if err != nil {723 log.Fatalf("BreakpointAtFunction: %v", err)724 }725 err = prog.DeleteBreakpoints(pcs1)726 if err != nil {727 log.Fatalf("DeleteBreakpoints: %v", err)728 }729 status, err = prog.Resume()730 if err != nil {731 log.Fatalf("Resume: %v", err)732 }733 if !stoppedAt(pcs2) {734 t.Errorf("stopped at %X; expected one of %X.", status.PC, pcs2)735 }736 // Check we get the expected results calling VarByName then Value737 // for the variables in expectedVarValues.738 for name, exp := range expectedVarValues {739 if v, err := prog.VarByName(name); err != nil {740 t.Errorf("VarByName(%s): %s", name, err)741 } else if val, err := prog.Value(v); err != nil {742 t.Errorf("value of %s: %s", name, err)743 } else if val != exp {744 t.Errorf("value of %s: got %T(%v) want %T(%v)", name, val, val, exp, exp)745 }746 }747 // Check some error cases for VarByName and Value.748 if _, err = prog.VarByName("not a real name"); err == nil {749 t.Error("VarByName for invalid name: expected error")750 }751 if _, err = prog.Value(debug.Var{}); err == nil {752 t.Error("value of invalid var: expected error")753 }754 if v, err := prog.VarByName("main.Z_int16"); err != nil {755 t.Error("VarByName(main.Z_int16) error:", err)756 } else {757 v.Address = 0758 // v now has a valid type but a bad address.759 _, err = prog.Value(v)760 if err == nil {761 t.Error("value of invalid location: expected error")762 }763 }764 // checkValue tests that we can get a Var for a variable with the given name,765 // that we can then get the value of that Var, and that calling fn for that766 // value succeeds.767 checkValue := func(name string, fn func(val debug.Value) error) {768 if v, err := prog.VarByName(name); err != nil {769 t.Errorf("VarByName(%s): %s", name, err)770 } else if val, err := prog.Value(v); err != nil {771 t.Errorf("value of %s: %s", name, err)772 } else if err := fn(val); err != nil {773 t.Errorf("value of %s: %s", name, err)774 }775 }776 checkValue("main.Z_uintptr", func(val debug.Value) error {777 if val != uint32(21) && val != uint64(21) {778 // Z_uintptr should be an unsigned integer with size equal to the debugged779 // program's address size.780 return fmt.Errorf("got %T(%v) want 21", val, val)781 }782 return nil783 })784 checkValue("main.Z_int", func(val debug.Value) error {785 if val != int32(-21) && val != int64(-21) {786 return fmt.Errorf("got %T(%v) want -21", val, val)787 }788 return nil789 })790 checkValue("main.Z_uint", func(val debug.Value) error {791 if val != uint32(21) && val != uint64(21) {792 return fmt.Errorf("got %T(%v) want 21", val, val)793 }794 return nil795 })796 checkValue("main.Z_pointer", func(val debug.Value) error {797 if _, ok := val.(debug.Pointer); !ok {798 return fmt.Errorf("got %T(%v) expected Pointer", val, val)799 }800 return nil801 })802 checkValue("main.Z_pointer_nil", func(val debug.Value) error {803 if p, ok := val.(debug.Pointer); !ok {804 return fmt.Errorf("got %T(%v) expected Pointer", val, val)805 } else if p.Address != 0 {806 return fmt.Errorf("got %T(%v) expected nil pointer", val, val)807 }808 return nil809 })810 checkValue("main.Z_array", func(val debug.Value) error {811 a, ok := val.(debug.Array)812 if !ok {813 return fmt.Errorf("got %T(%v) expected Array", val, val)814 }815 if a.Len() != 5 {816 return fmt.Errorf("got array length %d expected 5", a.Len())817 }818 expected := [5]int8{-121, 121, 3, 2, 1}819 for i := uint64(0); i < 5; i++ {820 if v, err := prog.Value(a.Element(i)); err != nil {821 return fmt.Errorf("reading element %d: %s", i, err)822 } else if v != expected[i] {823 return fmt.Errorf("element %d: got %T(%v) want %T(%d)", i, v, v, expected[i], expected[i])824 }825 }826 return nil827 })828 checkValue("main.Z_slice", func(val debug.Value) error {829 s, ok := val.(debug.Slice)830 if !ok {831 return fmt.Errorf("got %T(%v) expected Slice", val, val)832 }833 if s.Len() != 5 {834 return fmt.Errorf("got slice length %d expected 5", s.Len())835 }836 expected := []uint8{115, 108, 105, 99, 101}837 for i := uint64(0); i < 5; i++ {838 if v, err := prog.Value(s.Element(i)); err != nil {839 return fmt.Errorf("reading element %d: %s", i, err)840 } else if v != expected[i] {841 return fmt.Errorf("element %d: got %T(%v) want %T(%d)", i, v, v, expected[i], expected[i])842 }843 }844 return nil845 })846 checkValue("main.Z_map_empty", func(val debug.Value) error {847 m, ok := val.(debug.Map)848 if !ok {849 return fmt.Errorf("got %T(%v) expected Map", val, val)850 }851 if m.Length != 0 {852 return fmt.Errorf("got map length %d expected 0", m.Length)853 }854 return nil855 })856 checkValue("main.Z_map_nil", func(val debug.Value) error {857 m, ok := val.(debug.Map)858 if !ok {859 return fmt.Errorf("got %T(%v) expected Map", val, val)860 }861 if m.Length != 0 {862 return fmt.Errorf("got map length %d expected 0", m.Length)863 }864 return nil865 })866 checkValue("main.Z_map_3", func(val debug.Value) error {867 m, ok := val.(debug.Map)868 if !ok {869 return fmt.Errorf("got %T(%v) expected Map", val, val)870 }871 if m.Length != 2 {872 return fmt.Errorf("got map length %d expected 2", m.Length)873 }874 keyVar0, valVar0, err := prog.MapElement(m, 0)875 if err != nil {876 return err877 }878 keyVar1, valVar1, err := prog.MapElement(m, 1)879 if err != nil {880 return err881 }882 key0, err := prog.Value(keyVar0)883 if err != nil {884 return err885 }886 key1, err := prog.Value(keyVar1)887 if err != nil {888 return err889 }890 val0, err := prog.Value(valVar0)891 if err != nil {892 return err893 }894 val1, err := prog.Value(valVar1)895 if err != nil {896 return err897 }898 // The map should contain 1024,1 and 512,-1 in some order.899 ok1 := key0 == int16(1024) && val0 == int8(1) && key1 == int16(512) && val1 == int8(-1)900 ok2 := key1 == int16(1024) && val1 == int8(1) && key0 == int16(512) && val0 == int8(-1)901 if !ok1 && !ok2 {902 return fmt.Errorf("got values (%d,%d) and (%d,%d), expected (1024,1) and (512,-1) in some order", key0, val0, key1, val1)903 }904 _, _, err = prog.MapElement(m, 2)905 if err == nil {906 return fmt.Errorf("MapElement: reading at a bad index succeeded, expected error")907 }908 return nil909 })910 checkValue("main.Z_string", func(val debug.Value) error {911 s, ok := val.(debug.String)912 if !ok {913 return fmt.Errorf("got %T(%v) expected String", val, val)914 }915 if s.Length != 12 {916 return fmt.Errorf("got string length %d expected 12", s.Length)917 }918 expected := "I'm a string"919 if s.String != expected {920 return fmt.Errorf("got %s expected %s", s.String, expected)921 }922 return nil923 })924 checkValue("main.Z_channel", func(val debug.Value) error {925 c, ok := val.(debug.Channel)926 if !ok {927 return fmt.Errorf("got %T(%v) expected Channel", val, val)928 }929 if c.Buffer == 0 {930 return fmt.Errorf("got buffer address %d expected nonzero", c.Buffer)931 }932 if c.Length != 0 {933 return fmt.Errorf("got length %d expected 0", c.Length)934 }935 if c.Capacity != 0 {936 return fmt.Errorf("got capacity %d expected 0", c.Capacity)937 }938 return nil939 })940 checkValue("main.Z_channel_2", func(val debug.Value) error {941 c, ok := val.(debug.Channel)942 if !ok {943 return fmt.Errorf("got %T(%v) expected Channel", val, val)944 }945 if c.Buffer == 0 {946 return fmt.Errorf("got buffer address %d expected nonzero", c.Buffer)947 }948 if c.Length != 0 {949 return fmt.Errorf("got length %d expected 0", c.Length)950 }951 if c.Capacity != 0 {952 return fmt.Errorf("got capacity %d expected 0", c.Capacity)953 }954 return nil955 })956 checkValue("main.Z_channel_nil", func(val debug.Value) error {957 c, ok := val.(debug.Channel)958 if !ok {959 return fmt.Errorf("got %T(%v) expected Channel", val, val)960 }961 if c.Buffer != 0 {962 return fmt.Errorf("got buffer address %d expected 0", c.Buffer)963 }964 if c.Length != 0 {965 return fmt.Errorf("got length %d expected 0", c.Length)966 }967 if c.Capacity != 0 {968 return fmt.Errorf("got capacity %d expected 0", c.Capacity)969 }970 return nil971 })972 checkValue("main.Z_channel_buffered", func(val debug.Value) error {973 c, ok := val.(debug.Channel)974 if !ok {975 return fmt.Errorf("got %T(%v) expected Channel", val, val)976 }977 if c.Buffer == 0 {978 return fmt.Errorf("got buffer address %d expected nonzero", c.Buffer)979 }980 if c.Length != 6 {981 return fmt.Errorf("got length %d expected 6", c.Length)982 }983 if c.Capacity != 10 {984 return fmt.Errorf("got capacity %d expected 10", c.Capacity)985 }986 if c.Stride != 2 {987 return fmt.Errorf("got stride %d expected 2", c.Stride)988 }989 expected := []int16{8, 9, 10, 11, 12, 13}990 for i := uint64(0); i < 6; i++ {991 if v, err := prog.Value(c.Element(i)); err != nil {992 return fmt.Errorf("reading element %d: %s", i, err)993 } else if v != expected[i] {994 return fmt.Errorf("element %d: got %T(%v) want %T(%d)", i, v, v, expected[i], expected[i])995 }996 }997 v := c.Element(6)998 if v.Address != 0 {999 return fmt.Errorf("invalid element returned Var with address %d, expected 0", v.Address)1000 }1001 return nil1002 })1003 checkValue("main.Z_func_bar", func(val debug.Value) error {1004 f, ok := val.(debug.Func)1005 if !ok {1006 return fmt.Errorf("got %T(%v) expected Func", val, val)1007 }1008 if f.Address == 0 {1009 return fmt.Errorf("got func address %d expected nonzero", f.Address)1010 }1011 return nil1012 })1013 checkValue("main.Z_func_nil", func(val debug.Value) error {1014 f, ok := val.(debug.Func)1015 if !ok {1016 return fmt.Errorf("got %T(%v) expected Func", val, val)1017 }1018 if f.Address != 0 {1019 return fmt.Errorf("got func address %d expected zero", f.Address)1020 }1021 return nil1022 })1023}...

Full Screen

Full Screen

flag_test.go

Source:flag_test.go Github

copy

Full Screen

1package cli2import (3 "fmt"4 "os"5 "reflect"6 "strings"7 "testing"8)9var boolFlagTests = []struct {10 name string11 expected string12}{13 {"help", "--help\t"},14 {"h", "-h\t"},15}16func TestBoolFlagHelpOutput(t *testing.T) {17 for _, test := range boolFlagTests {18 flag := BoolFlag{Name: test.name}19 output := flag.String()20 if output != test.expected {21 t.Errorf("%s does not match %s", output, test.expected)22 }23 }24}25var stringFlagTests = []struct {26 name string27 value string28 expected string29}{30 {"help", "", "--help \t"},31 {"h", "", "-h \t"},32 {"h", "", "-h \t"},33 {"test", "Something", "--test \"Something\"\t"},34}35func TestStringFlagHelpOutput(t *testing.T) {36 for _, test := range stringFlagTests {37 flag := StringFlag{Name: test.name, Value: test.value}38 output := flag.String()39 if output != test.expected {40 t.Errorf("%s does not match %s", output, test.expected)41 }42 }43}44func TestStringFlagWithEnvVarHelpOutput(t *testing.T) {45 os.Clearenv()46 os.Setenv("APP_FOO", "derp")47 for _, test := range stringFlagTests {48 flag := StringFlag{Name: test.name, Value: test.value, EnvVar: "APP_FOO"}49 output := flag.String()50 if !strings.HasSuffix(output, " [$APP_FOO]") {51 t.Errorf("%s does not end with [$APP_FOO]", output)52 }53 }54}55var stringSliceFlagTests = []struct {56 name string57 value *StringSlice58 expected string59}{60 {"help", func() *StringSlice {61 s := &StringSlice{}62 s.Set("")63 return s64 }(), "--help [--help option --help option]\t"},65 {"h", func() *StringSlice {66 s := &StringSlice{}67 s.Set("")68 return s69 }(), "-h [-h option -h option]\t"},70 {"h", func() *StringSlice {71 s := &StringSlice{}72 s.Set("")73 return s74 }(), "-h [-h option -h option]\t"},75 {"test", func() *StringSlice {76 s := &StringSlice{}77 s.Set("Something")78 return s79 }(), "--test [--test option --test option]\t"},80}81func TestStringSliceFlagHelpOutput(t *testing.T) {82 for _, test := range stringSliceFlagTests {83 flag := StringSliceFlag{Name: test.name, Value: test.value}84 output := flag.String()85 if output != test.expected {86 t.Errorf("%q does not match %q", output, test.expected)87 }88 }89}90func TestStringSliceFlagWithEnvVarHelpOutput(t *testing.T) {91 os.Clearenv()92 os.Setenv("APP_QWWX", "11,4")93 for _, test := range stringSliceFlagTests {94 flag := StringSliceFlag{Name: test.name, Value: test.value, EnvVar: "APP_QWWX"}95 output := flag.String()96 if !strings.HasSuffix(output, " [$APP_QWWX]") {97 t.Errorf("%q does not end with [$APP_QWWX]", output)98 }99 }100}101var intFlagTests = []struct {102 name string103 expected string104}{105 {"help", "--help \"0\"\t"},106 {"h", "-h \"0\"\t"},107}108func TestIntFlagHelpOutput(t *testing.T) {109 for _, test := range intFlagTests {110 flag := IntFlag{Name: test.name}111 output := flag.String()112 if output != test.expected {113 t.Errorf("%s does not match %s", output, test.expected)114 }115 }116}117func TestIntFlagWithEnvVarHelpOutput(t *testing.T) {118 os.Clearenv()119 os.Setenv("APP_BAR", "2")120 for _, test := range intFlagTests {121 flag := IntFlag{Name: test.name, EnvVar: "APP_BAR"}122 output := flag.String()123 if !strings.HasSuffix(output, " [$APP_BAR]") {124 t.Errorf("%s does not end with [$APP_BAR]", output)125 }126 }127}128var durationFlagTests = []struct {129 name string130 expected string131}{132 {"help", "--help \"0\"\t"},133 {"h", "-h \"0\"\t"},134}135func TestDurationFlagHelpOutput(t *testing.T) {136 for _, test := range durationFlagTests {137 flag := DurationFlag{Name: test.name}138 output := flag.String()139 if output != test.expected {140 t.Errorf("%s does not match %s", output, test.expected)141 }142 }143}144func TestDurationFlagWithEnvVarHelpOutput(t *testing.T) {145 os.Clearenv()146 os.Setenv("APP_BAR", "2h3m6s")147 for _, test := range durationFlagTests {148 flag := DurationFlag{Name: test.name, EnvVar: "APP_BAR"}149 output := flag.String()150 if !strings.HasSuffix(output, " [$APP_BAR]") {151 t.Errorf("%s does not end with [$APP_BAR]", output)152 }153 }154}155var intSliceFlagTests = []struct {156 name string157 value *IntSlice158 expected string159}{160 {"help", &IntSlice{}, "--help [--help option --help option]\t"},161 {"h", &IntSlice{}, "-h [-h option -h option]\t"},162 {"h", &IntSlice{}, "-h [-h option -h option]\t"},163 {"test", func() *IntSlice {164 i := &IntSlice{}165 i.Set("9")166 return i167 }(), "--test [--test option --test option]\t"},168}169func TestIntSliceFlagHelpOutput(t *testing.T) {170 for _, test := range intSliceFlagTests {171 flag := IntSliceFlag{Name: test.name, Value: test.value}172 output := flag.String()173 if output != test.expected {174 t.Errorf("%q does not match %q", output, test.expected)175 }176 }177}178func TestIntSliceFlagWithEnvVarHelpOutput(t *testing.T) {179 os.Clearenv()180 os.Setenv("APP_SMURF", "42,3")181 for _, test := range intSliceFlagTests {182 flag := IntSliceFlag{Name: test.name, Value: test.value, EnvVar: "APP_SMURF"}183 output := flag.String()184 if !strings.HasSuffix(output, " [$APP_SMURF]") {185 t.Errorf("%q does not end with [$APP_SMURF]", output)186 }187 }188}189var float64FlagTests = []struct {190 name string191 expected string192}{193 {"help", "--help \"0\"\t"},194 {"h", "-h \"0\"\t"},195}196func TestFloat64FlagHelpOutput(t *testing.T) {197 for _, test := range float64FlagTests {198 flag := Float64Flag{Name: test.name}199 output := flag.String()200 if output != test.expected {201 t.Errorf("%s does not match %s", output, test.expected)202 }203 }204}205func TestFloat64FlagWithEnvVarHelpOutput(t *testing.T) {206 os.Clearenv()207 os.Setenv("APP_BAZ", "99.4")208 for _, test := range float64FlagTests {209 flag := Float64Flag{Name: test.name, EnvVar: "APP_BAZ"}210 output := flag.String()211 if !strings.HasSuffix(output, " [$APP_BAZ]") {212 t.Errorf("%s does not end with [$APP_BAZ]", output)213 }214 }215}216var genericFlagTests = []struct {217 name string218 value Generic219 expected string220}{221 {"test", &Parser{"abc", "def"}, "--test \"abc,def\"\ttest flag"},222 {"t", &Parser{"abc", "def"}, "-t \"abc,def\"\ttest flag"},223}224func TestGenericFlagHelpOutput(t *testing.T) {225 for _, test := range genericFlagTests {226 flag := GenericFlag{Name: test.name, Value: test.value, Usage: "test flag"}227 output := flag.String()228 if output != test.expected {229 t.Errorf("%q does not match %q", output, test.expected)230 }231 }232}233func TestGenericFlagWithEnvVarHelpOutput(t *testing.T) {234 os.Clearenv()235 os.Setenv("APP_ZAP", "3")236 for _, test := range genericFlagTests {237 flag := GenericFlag{Name: test.name, EnvVar: "APP_ZAP"}238 output := flag.String()239 if !strings.HasSuffix(output, " [$APP_ZAP]") {240 t.Errorf("%s does not end with [$APP_ZAP]", output)241 }242 }243}244func TestParseMultiString(t *testing.T) {245 (&App{246 Flags: []Flag{247 StringFlag{Name: "serve, s"},248 },249 Action: func(ctx *Context) {250 if ctx.String("serve") != "10" {251 t.Errorf("main name not set")252 }253 if ctx.String("s") != "10" {254 t.Errorf("short name not set")255 }256 },257 }).Run([]string{"run", "-s", "10"})258}259func TestParseDestinationString(t *testing.T) {260 var dest string261 a := App{262 Flags: []Flag{263 StringFlag{264 Name: "dest",265 Destination: &dest,266 },267 },268 Action: func(ctx *Context) {269 if dest != "10" {270 t.Errorf("expected destination String 10")271 }272 },273 }274 a.Run([]string{"run", "--dest", "10"})275}276func TestParseMultiStringFromEnv(t *testing.T) {277 os.Clearenv()278 os.Setenv("APP_COUNT", "20")279 (&App{280 Flags: []Flag{281 StringFlag{Name: "count, c", EnvVar: "APP_COUNT"},282 },283 Action: func(ctx *Context) {284 if ctx.String("count") != "20" {285 t.Errorf("main name not set")286 }287 if ctx.String("c") != "20" {288 t.Errorf("short name not set")289 }290 },291 }).Run([]string{"run"})292}293func TestParseMultiStringFromEnvCascade(t *testing.T) {294 os.Clearenv()295 os.Setenv("APP_COUNT", "20")296 (&App{297 Flags: []Flag{298 StringFlag{Name: "count, c", EnvVar: "COMPAT_COUNT,APP_COUNT"},299 },300 Action: func(ctx *Context) {301 if ctx.String("count") != "20" {302 t.Errorf("main name not set")303 }304 if ctx.String("c") != "20" {305 t.Errorf("short name not set")306 }307 },308 }).Run([]string{"run"})309}310func TestParseMultiStringSlice(t *testing.T) {311 (&App{312 Flags: []Flag{313 StringSliceFlag{Name: "serve, s", Value: &StringSlice{}},314 },315 Action: func(ctx *Context) {316 if !reflect.DeepEqual(ctx.StringSlice("serve"), []string{"10", "20"}) {317 t.Errorf("main name not set")318 }319 if !reflect.DeepEqual(ctx.StringSlice("s"), []string{"10", "20"}) {320 t.Errorf("short name not set")321 }322 },323 }).Run([]string{"run", "-s", "10", "-s", "20"})324}325func TestParseMultiStringSliceFromEnv(t *testing.T) {326 os.Clearenv()327 os.Setenv("APP_INTERVALS", "20,30,40")328 (&App{329 Flags: []Flag{330 StringSliceFlag{Name: "intervals, i", Value: &StringSlice{}, EnvVar: "APP_INTERVALS"},331 },332 Action: func(ctx *Context) {333 if !reflect.DeepEqual(ctx.StringSlice("intervals"), []string{"20", "30", "40"}) {334 t.Errorf("main name not set from env")335 }336 if !reflect.DeepEqual(ctx.StringSlice("i"), []string{"20", "30", "40"}) {337 t.Errorf("short name not set from env")338 }339 },340 }).Run([]string{"run"})341}342func TestParseMultiStringSliceFromEnvCascade(t *testing.T) {343 os.Clearenv()344 os.Setenv("APP_INTERVALS", "20,30,40")345 (&App{346 Flags: []Flag{347 StringSliceFlag{Name: "intervals, i", Value: &StringSlice{}, EnvVar: "COMPAT_INTERVALS,APP_INTERVALS"},348 },349 Action: func(ctx *Context) {350 if !reflect.DeepEqual(ctx.StringSlice("intervals"), []string{"20", "30", "40"}) {351 t.Errorf("main name not set from env")352 }353 if !reflect.DeepEqual(ctx.StringSlice("i"), []string{"20", "30", "40"}) {354 t.Errorf("short name not set from env")355 }356 },357 }).Run([]string{"run"})358}359func TestParseMultiInt(t *testing.T) {360 a := App{361 Flags: []Flag{362 IntFlag{Name: "serve, s"},363 },364 Action: func(ctx *Context) {365 if ctx.Int("serve") != 10 {366 t.Errorf("main name not set")367 }368 if ctx.Int("s") != 10 {369 t.Errorf("short name not set")370 }371 },372 }373 a.Run([]string{"run", "-s", "10"})374}375func TestParseDestinationInt(t *testing.T) {376 var dest int377 a := App{378 Flags: []Flag{379 IntFlag{380 Name: "dest",381 Destination: &dest,382 },383 },384 Action: func(ctx *Context) {385 if dest != 10 {386 t.Errorf("expected destination Int 10")387 }388 },389 }390 a.Run([]string{"run", "--dest", "10"})391}392func TestParseMultiIntFromEnv(t *testing.T) {393 os.Clearenv()394 os.Setenv("APP_TIMEOUT_SECONDS", "10")395 a := App{396 Flags: []Flag{397 IntFlag{Name: "timeout, t", EnvVar: "APP_TIMEOUT_SECONDS"},398 },399 Action: func(ctx *Context) {400 if ctx.Int("timeout") != 10 {401 t.Errorf("main name not set")402 }403 if ctx.Int("t") != 10 {404 t.Errorf("short name not set")405 }406 },407 }408 a.Run([]string{"run"})409}410func TestParseMultiIntFromEnvCascade(t *testing.T) {411 os.Clearenv()412 os.Setenv("APP_TIMEOUT_SECONDS", "10")413 a := App{414 Flags: []Flag{415 IntFlag{Name: "timeout, t", EnvVar: "COMPAT_TIMEOUT_SECONDS,APP_TIMEOUT_SECONDS"},416 },417 Action: func(ctx *Context) {418 if ctx.Int("timeout") != 10 {419 t.Errorf("main name not set")420 }421 if ctx.Int("t") != 10 {422 t.Errorf("short name not set")423 }424 },425 }426 a.Run([]string{"run"})427}428func TestParseMultiIntSlice(t *testing.T) {429 (&App{430 Flags: []Flag{431 IntSliceFlag{Name: "serve, s", Value: &IntSlice{}},432 },433 Action: func(ctx *Context) {434 if !reflect.DeepEqual(ctx.IntSlice("serve"), []int{10, 20}) {435 t.Errorf("main name not set")436 }437 if !reflect.DeepEqual(ctx.IntSlice("s"), []int{10, 20}) {438 t.Errorf("short name not set")439 }440 },441 }).Run([]string{"run", "-s", "10", "-s", "20"})442}443func TestParseMultiIntSliceFromEnv(t *testing.T) {444 os.Clearenv()445 os.Setenv("APP_INTERVALS", "20,30,40")446 (&App{447 Flags: []Flag{448 IntSliceFlag{Name: "intervals, i", Value: &IntSlice{}, EnvVar: "APP_INTERVALS"},449 },450 Action: func(ctx *Context) {451 if !reflect.DeepEqual(ctx.IntSlice("intervals"), []int{20, 30, 40}) {452 t.Errorf("main name not set from env")453 }454 if !reflect.DeepEqual(ctx.IntSlice("i"), []int{20, 30, 40}) {455 t.Errorf("short name not set from env")456 }457 },458 }).Run([]string{"run"})459}460func TestParseMultiIntSliceFromEnvCascade(t *testing.T) {461 os.Clearenv()462 os.Setenv("APP_INTERVALS", "20,30,40")463 (&App{464 Flags: []Flag{465 IntSliceFlag{Name: "intervals, i", Value: &IntSlice{}, EnvVar: "COMPAT_INTERVALS,APP_INTERVALS"},466 },467 Action: func(ctx *Context) {468 if !reflect.DeepEqual(ctx.IntSlice("intervals"), []int{20, 30, 40}) {469 t.Errorf("main name not set from env")470 }471 if !reflect.DeepEqual(ctx.IntSlice("i"), []int{20, 30, 40}) {472 t.Errorf("short name not set from env")473 }474 },475 }).Run([]string{"run"})476}477func TestParseMultiFloat64(t *testing.T) {478 a := App{479 Flags: []Flag{480 Float64Flag{Name: "serve, s"},481 },482 Action: func(ctx *Context) {483 if ctx.Float64("serve") != 10.2 {484 t.Errorf("main name not set")485 }486 if ctx.Float64("s") != 10.2 {487 t.Errorf("short name not set")488 }489 },490 }491 a.Run([]string{"run", "-s", "10.2"})492}493func TestParseDestinationFloat64(t *testing.T) {494 var dest float64495 a := App{496 Flags: []Flag{497 Float64Flag{498 Name: "dest",499 Destination: &dest,500 },501 },502 Action: func(ctx *Context) {503 if dest != 10.2 {504 t.Errorf("expected destination Float64 10.2")505 }506 },507 }508 a.Run([]string{"run", "--dest", "10.2"})509}510func TestParseMultiFloat64FromEnv(t *testing.T) {511 os.Clearenv()512 os.Setenv("APP_TIMEOUT_SECONDS", "15.5")513 a := App{514 Flags: []Flag{515 Float64Flag{Name: "timeout, t", EnvVar: "APP_TIMEOUT_SECONDS"},516 },517 Action: func(ctx *Context) {518 if ctx.Float64("timeout") != 15.5 {519 t.Errorf("main name not set")520 }521 if ctx.Float64("t") != 15.5 {522 t.Errorf("short name not set")523 }524 },525 }526 a.Run([]string{"run"})527}528func TestParseMultiFloat64FromEnvCascade(t *testing.T) {529 os.Clearenv()530 os.Setenv("APP_TIMEOUT_SECONDS", "15.5")531 a := App{532 Flags: []Flag{533 Float64Flag{Name: "timeout, t", EnvVar: "COMPAT_TIMEOUT_SECONDS,APP_TIMEOUT_SECONDS"},534 },535 Action: func(ctx *Context) {536 if ctx.Float64("timeout") != 15.5 {537 t.Errorf("main name not set")538 }539 if ctx.Float64("t") != 15.5 {540 t.Errorf("short name not set")541 }542 },543 }544 a.Run([]string{"run"})545}546func TestParseMultiBool(t *testing.T) {547 a := App{548 Flags: []Flag{549 BoolFlag{Name: "serve, s"},550 },551 Action: func(ctx *Context) {552 if ctx.Bool("serve") != true {553 t.Errorf("main name not set")554 }555 if ctx.Bool("s") != true {556 t.Errorf("short name not set")557 }558 },559 }560 a.Run([]string{"run", "--serve"})561}562func TestParseDestinationBool(t *testing.T) {563 var dest bool564 a := App{565 Flags: []Flag{566 BoolFlag{567 Name: "dest",568 Destination: &dest,569 },570 },571 Action: func(ctx *Context) {572 if dest != true {573 t.Errorf("expected destination Bool true")574 }575 },576 }577 a.Run([]string{"run", "--dest"})578}579func TestParseMultiBoolFromEnv(t *testing.T) {580 os.Clearenv()581 os.Setenv("APP_DEBUG", "1")582 a := App{583 Flags: []Flag{584 BoolFlag{Name: "debug, d", EnvVar: "APP_DEBUG"},585 },586 Action: func(ctx *Context) {587 if ctx.Bool("debug") != true {588 t.Errorf("main name not set from env")589 }590 if ctx.Bool("d") != true {591 t.Errorf("short name not set from env")592 }593 },594 }595 a.Run([]string{"run"})596}597func TestParseMultiBoolFromEnvCascade(t *testing.T) {598 os.Clearenv()599 os.Setenv("APP_DEBUG", "1")600 a := App{601 Flags: []Flag{602 BoolFlag{Name: "debug, d", EnvVar: "COMPAT_DEBUG,APP_DEBUG"},603 },604 Action: func(ctx *Context) {605 if ctx.Bool("debug") != true {606 t.Errorf("main name not set from env")607 }608 if ctx.Bool("d") != true {609 t.Errorf("short name not set from env")610 }611 },612 }613 a.Run([]string{"run"})614}615func TestParseMultiBoolT(t *testing.T) {616 a := App{617 Flags: []Flag{618 BoolTFlag{Name: "serve, s"},619 },620 Action: func(ctx *Context) {621 if ctx.BoolT("serve") != true {622 t.Errorf("main name not set")623 }624 if ctx.BoolT("s") != true {625 t.Errorf("short name not set")626 }627 },628 }629 a.Run([]string{"run", "--serve"})630}631func TestParseDestinationBoolT(t *testing.T) {632 var dest bool633 a := App{634 Flags: []Flag{635 BoolTFlag{636 Name: "dest",637 Destination: &dest,638 },639 },640 Action: func(ctx *Context) {641 if dest != true {642 t.Errorf("expected destination BoolT true")643 }644 },645 }646 a.Run([]string{"run", "--dest"})647}648func TestParseMultiBoolTFromEnv(t *testing.T) {649 os.Clearenv()650 os.Setenv("APP_DEBUG", "0")651 a := App{652 Flags: []Flag{653 BoolTFlag{Name: "debug, d", EnvVar: "APP_DEBUG"},654 },655 Action: func(ctx *Context) {656 if ctx.BoolT("debug") != false {657 t.Errorf("main name not set from env")658 }659 if ctx.BoolT("d") != false {660 t.Errorf("short name not set from env")661 }662 },663 }664 a.Run([]string{"run"})665}666func TestParseMultiBoolTFromEnvCascade(t *testing.T) {667 os.Clearenv()668 os.Setenv("APP_DEBUG", "0")669 a := App{670 Flags: []Flag{671 BoolTFlag{Name: "debug, d", EnvVar: "COMPAT_DEBUG,APP_DEBUG"},672 },673 Action: func(ctx *Context) {674 if ctx.BoolT("debug") != false {675 t.Errorf("main name not set from env")676 }677 if ctx.BoolT("d") != false {678 t.Errorf("short name not set from env")679 }680 },681 }682 a.Run([]string{"run"})683}684type Parser [2]string685func (p *Parser) Set(value string) error {686 parts := strings.Split(value, ",")687 if len(parts) != 2 {688 return fmt.Errorf("invalid format")689 }690 (*p)[0] = parts[0]691 (*p)[1] = parts[1]692 return nil693}694func (p *Parser) String() string {695 return fmt.Sprintf("%s,%s", p[0], p[1])696}697func TestParseGeneric(t *testing.T) {698 a := App{699 Flags: []Flag{700 GenericFlag{Name: "serve, s", Value: &Parser{}},701 },702 Action: func(ctx *Context) {703 if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"10", "20"}) {704 t.Errorf("main name not set")705 }706 if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"10", "20"}) {707 t.Errorf("short name not set")708 }709 },710 }711 a.Run([]string{"run", "-s", "10,20"})712}713func TestParseGenericFromEnv(t *testing.T) {714 os.Clearenv()715 os.Setenv("APP_SERVE", "20,30")716 a := App{717 Flags: []Flag{718 GenericFlag{Name: "serve, s", Value: &Parser{}, EnvVar: "APP_SERVE"},719 },720 Action: func(ctx *Context) {721 if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"20", "30"}) {722 t.Errorf("main name not set from env")723 }724 if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"20", "30"}) {725 t.Errorf("short name not set from env")726 }727 },728 }729 a.Run([]string{"run"})730}731func TestParseGenericFromEnvCascade(t *testing.T) {732 os.Clearenv()733 os.Setenv("APP_FOO", "99,2000")734 a := App{735 Flags: []Flag{736 GenericFlag{Name: "foos", Value: &Parser{}, EnvVar: "COMPAT_FOO,APP_FOO"},737 },738 Action: func(ctx *Context) {739 if !reflect.DeepEqual(ctx.Generic("foos"), &Parser{"99", "2000"}) {740 t.Errorf("value not set from env")741 }742 },743 }744 a.Run([]string{"run"})745}...

Full Screen

Full Screen

loader_test.go

Source:loader_test.go Github

copy

Full Screen

1// Copyright 2013 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4package loader_test5import (6 "fmt"7 "go/build"8 "reflect"9 "sort"10 "strings"11 "sync"12 "testing"13 "llvm.org/llgo/third_party/gotools/go/buildutil"14 "llvm.org/llgo/third_party/gotools/go/loader"15)16// TestFromArgs checks that conf.FromArgs populates conf correctly.17// It does no I/O.18func TestFromArgs(t *testing.T) {19 type result struct {20 Err string21 Rest []string22 ImportPkgs map[string]bool23 CreatePkgs []loader.PkgSpec24 }25 for _, test := range []struct {26 args []string27 tests bool28 want result29 }{30 // Mix of existing and non-existent packages.31 {32 args: []string{"nosuchpkg", "errors"},33 want: result{34 ImportPkgs: map[string]bool{"errors": false, "nosuchpkg": false},35 },36 },37 // Same, with -test flag.38 {39 args: []string{"nosuchpkg", "errors"},40 tests: true,41 want: result{42 ImportPkgs: map[string]bool{"errors": true, "nosuchpkg": true},43 },44 },45 // Surplus arguments.46 {47 args: []string{"fmt", "errors", "--", "surplus"},48 want: result{49 Rest: []string{"surplus"},50 ImportPkgs: map[string]bool{"errors": false, "fmt": false},51 },52 },53 // Ad hoc package specified as *.go files.54 {55 args: []string{"foo.go", "bar.go"},56 want: result{CreatePkgs: []loader.PkgSpec{{57 Filenames: []string{"foo.go", "bar.go"},58 }}},59 },60 // Mixture of *.go and import paths.61 {62 args: []string{"foo.go", "fmt"},63 want: result{64 Err: "named files must be .go files: fmt",65 },66 },67 } {68 var conf loader.Config69 rest, err := conf.FromArgs(test.args, test.tests)70 got := result{71 Rest: rest,72 ImportPkgs: conf.ImportPkgs,73 CreatePkgs: conf.CreatePkgs,74 }75 if err != nil {76 got.Err = err.Error()77 }78 if !reflect.DeepEqual(got, test.want) {79 t.Errorf("FromArgs(%q) = %+v, want %+v", test.args, got, test.want)80 }81 }82}83func TestLoad_NoInitialPackages(t *testing.T) {84 var conf loader.Config85 const wantErr = "no initial packages were loaded"86 prog, err := conf.Load()87 if err == nil {88 t.Errorf("Load succeeded unexpectedly, want %q", wantErr)89 } else if err.Error() != wantErr {90 t.Errorf("Load failed with wrong error %q, want %q", err, wantErr)91 }92 if prog != nil {93 t.Errorf("Load unexpectedly returned a Program")94 }95}96func TestLoad_MissingInitialPackage(t *testing.T) {97 var conf loader.Config98 conf.Import("nosuchpkg")99 conf.Import("errors")100 const wantErr = "couldn't load packages due to errors: nosuchpkg"101 prog, err := conf.Load()102 if err == nil {103 t.Errorf("Load succeeded unexpectedly, want %q", wantErr)104 } else if err.Error() != wantErr {105 t.Errorf("Load failed with wrong error %q, want %q", err, wantErr)106 }107 if prog != nil {108 t.Errorf("Load unexpectedly returned a Program")109 }110}111func TestLoad_MissingInitialPackage_AllowErrors(t *testing.T) {112 var conf loader.Config113 conf.AllowErrors = true114 conf.Import("nosuchpkg")115 conf.ImportWithTests("errors")116 prog, err := conf.Load()117 if err != nil {118 t.Errorf("Load failed unexpectedly: %v", err)119 }120 if prog == nil {121 t.Fatalf("Load returned a nil Program")122 }123 if got, want := created(prog), "errors_test"; got != want {124 t.Errorf("Created = %s, want %s", got, want)125 }126 if got, want := imported(prog), "errors"; got != want {127 t.Errorf("Imported = %s, want %s", got, want)128 }129}130func TestCreateUnnamedPackage(t *testing.T) {131 var conf loader.Config132 conf.CreateFromFilenames("")133 prog, err := conf.Load()134 if err != nil {135 t.Fatalf("Load failed: %v", err)136 }137 if got, want := fmt.Sprint(prog.InitialPackages()), "[(unnamed)]"; got != want {138 t.Errorf("InitialPackages = %s, want %s", got, want)139 }140}141func TestLoad_MissingFileInCreatedPackage(t *testing.T) {142 var conf loader.Config143 conf.CreateFromFilenames("", "missing.go")144 const wantErr = "couldn't load packages due to errors: (unnamed)"145 prog, err := conf.Load()146 if prog != nil {147 t.Errorf("Load unexpectedly returned a Program")148 }149 if err == nil {150 t.Fatalf("Load succeeded unexpectedly, want %q", wantErr)151 }152 if err.Error() != wantErr {153 t.Fatalf("Load failed with wrong error %q, want %q", err, wantErr)154 }155}156func TestLoad_MissingFileInCreatedPackage_AllowErrors(t *testing.T) {157 conf := loader.Config{AllowErrors: true}158 conf.CreateFromFilenames("", "missing.go")159 prog, err := conf.Load()160 if err != nil {161 t.Errorf("Load failed: %v", err)162 }163 if got, want := fmt.Sprint(prog.InitialPackages()), "[(unnamed)]"; got != want {164 t.Fatalf("InitialPackages = %s, want %s", got, want)165 }166}167func TestLoad_ParseError(t *testing.T) {168 var conf loader.Config169 conf.CreateFromFilenames("badpkg", "testdata/badpkgdecl.go")170 const wantErr = "couldn't load packages due to errors: badpkg"171 prog, err := conf.Load()172 if prog != nil {173 t.Errorf("Load unexpectedly returned a Program")174 }175 if err == nil {176 t.Fatalf("Load succeeded unexpectedly, want %q", wantErr)177 }178 if err.Error() != wantErr {179 t.Fatalf("Load failed with wrong error %q, want %q", err, wantErr)180 }181}182func TestLoad_ParseError_AllowErrors(t *testing.T) {183 var conf loader.Config184 conf.AllowErrors = true185 conf.CreateFromFilenames("badpkg", "testdata/badpkgdecl.go")186 prog, err := conf.Load()187 if err != nil {188 t.Errorf("Load failed unexpectedly: %v", err)189 }190 if prog == nil {191 t.Fatalf("Load returned a nil Program")192 }193 if got, want := created(prog), "badpkg"; got != want {194 t.Errorf("Created = %s, want %s", got, want)195 }196 badpkg := prog.Created[0]197 if len(badpkg.Files) != 1 {198 t.Errorf("badpkg has %d files, want 1", len(badpkg.Files))199 }200 wantErr := "testdata/badpkgdecl.go:1:34: expected 'package', found 'EOF'"201 if !hasError(badpkg.Errors, wantErr) {202 t.Errorf("badpkg.Errors = %v, want %s", badpkg.Errors, wantErr)203 }204}205func TestLoad_FromSource_Success(t *testing.T) {206 var conf loader.Config207 conf.CreateFromFilenames("P", "testdata/a.go", "testdata/b.go")208 prog, err := conf.Load()209 if err != nil {210 t.Errorf("Load failed unexpectedly: %v", err)211 }212 if prog == nil {213 t.Fatalf("Load returned a nil Program")214 }215 if got, want := created(prog), "P"; got != want {216 t.Errorf("Created = %s, want %s", got, want)217 }218}219func TestLoad_FromImports_Success(t *testing.T) {220 var conf loader.Config221 conf.ImportWithTests("fmt")222 conf.ImportWithTests("errors")223 prog, err := conf.Load()224 if err != nil {225 t.Errorf("Load failed unexpectedly: %v", err)226 }227 if prog == nil {228 t.Fatalf("Load returned a nil Program")229 }230 if got, want := created(prog), "errors_test fmt_test"; got != want {231 t.Errorf("Created = %q, want %s", got, want)232 }233 if got, want := imported(prog), "errors fmt"; got != want {234 t.Errorf("Imported = %s, want %s", got, want)235 }236 // Check set of transitive packages.237 // There are >30 and the set may grow over time, so only check a few.238 want := map[string]bool{239 "strings": true,240 "time": true,241 "runtime": true,242 "testing": true,243 "unicode": true,244 }245 for _, path := range all(prog) {246 delete(want, path)247 }248 if len(want) > 0 {249 t.Errorf("AllPackages is missing these keys: %q", keys(want))250 }251}252func TestLoad_MissingIndirectImport(t *testing.T) {253 pkgs := map[string]string{254 "a": `package a; import _ "b"`,255 "b": `package b; import _ "c"`,256 }257 conf := loader.Config{Build: fakeContext(pkgs)}258 conf.Import("a")259 const wantErr = "couldn't load packages due to errors: b"260 prog, err := conf.Load()261 if err == nil {262 t.Errorf("Load succeeded unexpectedly, want %q", wantErr)263 } else if err.Error() != wantErr {264 t.Errorf("Load failed with wrong error %q, want %q", err, wantErr)265 }266 if prog != nil {267 t.Errorf("Load unexpectedly returned a Program")268 }269}270func TestLoad_BadDependency_AllowErrors(t *testing.T) {271 for _, test := range []struct {272 descr string273 pkgs map[string]string274 wantPkgs string275 }{276 {277 descr: "missing dependency",278 pkgs: map[string]string{279 "a": `package a; import _ "b"`,280 "b": `package b; import _ "c"`,281 },282 wantPkgs: "a b",283 },284 {285 descr: "bad package decl in dependency",286 pkgs: map[string]string{287 "a": `package a; import _ "b"`,288 "b": `package b; import _ "c"`,289 "c": `package`,290 },291 wantPkgs: "a b",292 },293 {294 descr: "parse error in dependency",295 pkgs: map[string]string{296 "a": `package a; import _ "b"`,297 "b": `package b; import _ "c"`,298 "c": `package c; var x = `,299 },300 wantPkgs: "a b c",301 },302 } {303 conf := loader.Config{304 AllowErrors: true,305 Build: fakeContext(test.pkgs),306 }307 conf.Import("a")308 prog, err := conf.Load()309 if err != nil {310 t.Errorf("%s: Load failed unexpectedly: %v", test.descr, err)311 }312 if prog == nil {313 t.Fatalf("%s: Load returned a nil Program", test.descr)314 }315 if got, want := imported(prog), "a"; got != want {316 t.Errorf("%s: Imported = %s, want %s", test.descr, got, want)317 }318 if got := all(prog); strings.Join(got, " ") != test.wantPkgs {319 t.Errorf("%s: AllPackages = %s, want %s", test.descr, got, test.wantPkgs)320 }321 }322}323func TestCwd(t *testing.T) {324 ctxt := fakeContext(map[string]string{"one/two/three": `package three`})325 for _, test := range []struct {326 cwd, arg, want string327 }{328 {cwd: "/go/src/one", arg: "./two/three", want: "one/two/three"},329 {cwd: "/go/src/one", arg: "../one/two/three", want: "one/two/three"},330 {cwd: "/go/src/one", arg: "one/two/three", want: "one/two/three"},331 {cwd: "/go/src/one/two/three", arg: ".", want: "one/two/three"},332 {cwd: "/go/src/one", arg: "two/three", want: ""},333 } {334 conf := loader.Config{335 Cwd: test.cwd,336 Build: ctxt,337 }338 conf.Import(test.arg)339 var got string340 prog, err := conf.Load()341 if prog != nil {342 got = imported(prog)343 }344 if got != test.want {345 t.Errorf("Load(%s) from %s: Imported = %s, want %s",346 test.arg, test.cwd, got, test.want)347 if err != nil {348 t.Errorf("Load failed: %v", err)349 }350 }351 }352}353// TODO(adonovan): more Load tests:354//355// failures:356// - to parse package decl of *_test.go files357// - to parse package decl of external *_test.go files358// - to parse whole of *_test.go files359// - to parse whole of external *_test.go files360// - to open a *.go file during import scanning361// - to import from binary362// features:363// - InitialPackages364// - PackageCreated hook365// - TypeCheckFuncBodies hook366func TestTransitivelyErrorFreeFlag(t *testing.T) {367 // Create an minimal custom build.Context368 // that fakes the following packages:369 //370 // a --> b --> c! c has an error371 // \ d and e are transitively error-free.372 // e --> d373 //374 // Each package [a-e] consists of one file, x.go.375 pkgs := map[string]string{376 "a": `package a; import (_ "b"; _ "e")`,377 "b": `package b; import _ "c"`,378 "c": `package c; func f() { _ = int(false) }`, // type error within function body379 "d": `package d;`,380 "e": `package e; import _ "d"`,381 }382 conf := loader.Config{383 AllowErrors: true,384 Build: fakeContext(pkgs),385 }386 conf.Import("a")387 prog, err := conf.Load()388 if err != nil {389 t.Errorf("Load failed: %s", err)390 }391 if prog == nil {392 t.Fatalf("Load returned nil *Program")393 }394 for pkg, info := range prog.AllPackages {395 var wantErr, wantTEF bool396 switch pkg.Path() {397 case "a", "b":398 case "c":399 wantErr = true400 case "d", "e":401 wantTEF = true402 default:403 t.Errorf("unexpected package: %q", pkg.Path())404 continue405 }406 if (info.Errors != nil) != wantErr {407 if wantErr {408 t.Errorf("Package %q.Error = nil, want error", pkg.Path())409 } else {410 t.Errorf("Package %q has unexpected Errors: %v",411 pkg.Path(), info.Errors)412 }413 }414 if info.TransitivelyErrorFree != wantTEF {415 t.Errorf("Package %q.TransitivelyErrorFree=%t, want %t",416 pkg.Path(), info.TransitivelyErrorFree, wantTEF)417 }418 }419}420// Test that syntax (scan/parse), type, and loader errors are recorded421// (in PackageInfo.Errors) and reported (via Config.TypeChecker.Error).422func TestErrorReporting(t *testing.T) {423 pkgs := map[string]string{424 "a": `package a; import (_ "b"; _ "c"); var x int = false`,425 "b": `package b; 'syntax error!`,426 }427 conf := loader.Config{428 AllowErrors: true,429 Build: fakeContext(pkgs),430 }431 var mu sync.Mutex432 var allErrors []error433 conf.TypeChecker.Error = func(err error) {434 mu.Lock()435 allErrors = append(allErrors, err)436 mu.Unlock()437 }438 conf.Import("a")439 prog, err := conf.Load()440 if err != nil {441 t.Errorf("Load failed: %s", err)442 }443 if prog == nil {444 t.Fatalf("Load returned nil *Program")445 }446 // TODO(adonovan): test keys of ImportMap.447 // Check errors recorded in each PackageInfo.448 for pkg, info := range prog.AllPackages {449 switch pkg.Path() {450 case "a":451 if !hasError(info.Errors, "cannot convert false") {452 t.Errorf("a.Errors = %v, want bool conversion (type) error", info.Errors)453 }454 if !hasError(info.Errors, "could not import c") {455 t.Errorf("a.Errors = %v, want import (loader) error", info.Errors)456 }457 case "b":458 if !hasError(info.Errors, "rune literal not terminated") {459 t.Errorf("b.Errors = %v, want unterminated literal (syntax) error", info.Errors)460 }461 }462 }463 // Check errors reported via error handler.464 if !hasError(allErrors, "cannot convert false") ||465 !hasError(allErrors, "rune literal not terminated") ||466 !hasError(allErrors, "could not import c") {467 t.Errorf("allErrors = %v, want syntax, type and loader errors", allErrors)468 }469}470func TestCycles(t *testing.T) {471 for _, test := range []struct {472 descr string473 ctxt *build.Context474 wantErr string475 }{476 {477 "self-cycle",478 fakeContext(map[string]string{479 "main": `package main; import _ "selfcycle"`,480 "selfcycle": `package selfcycle; import _ "selfcycle"`,481 }),482 `import cycle: selfcycle -> selfcycle`,483 },484 {485 "three-package cycle",486 fakeContext(map[string]string{487 "main": `package main; import _ "a"`,488 "a": `package a; import _ "b"`,489 "b": `package b; import _ "c"`,490 "c": `package c; import _ "a"`,491 }),492 `import cycle: c -> a -> b -> c`,493 },494 {495 "self-cycle in dependency of test file",496 buildutil.FakeContext(map[string]map[string]string{497 "main": {498 "main.go": `package main`,499 "main_test.go": `package main; import _ "a"`,500 },501 "a": {502 "a.go": `package a; import _ "a"`,503 },504 }),505 `import cycle: a -> a`,506 },507 // TODO(adonovan): fix: these fail508 // {509 // "two-package cycle in dependency of test file",510 // buildutil.FakeContext(map[string]map[string]string{511 // "main": {512 // "main.go": `package main`,513 // "main_test.go": `package main; import _ "a"`,514 // },515 // "a": {516 // "a.go": `package a; import _ "main"`,517 // },518 // }),519 // `import cycle: main -> a -> main`,520 // },521 // {522 // "self-cycle in augmented package",523 // buildutil.FakeContext(map[string]map[string]string{524 // "main": {525 // "main.go": `package main`,526 // "main_test.go": `package main; import _ "main"`,527 // },528 // }),529 // `import cycle: main -> main`,530 // },531 } {532 conf := loader.Config{533 AllowErrors: true,534 Build: test.ctxt,535 }536 var mu sync.Mutex537 var allErrors []error538 conf.TypeChecker.Error = func(err error) {539 mu.Lock()540 allErrors = append(allErrors, err)541 mu.Unlock()542 }543 conf.ImportWithTests("main")544 prog, err := conf.Load()545 if err != nil {546 t.Errorf("%s: Load failed: %s", test.descr, err)547 }548 if prog == nil {549 t.Fatalf("%s: Load returned nil *Program", test.descr)550 }551 if !hasError(allErrors, test.wantErr) {552 t.Errorf("%s: Load() errors = %q, want %q",553 test.descr, allErrors, test.wantErr)554 }555 }556 // TODO(adonovan):557 // - Test that in a legal test cycle, none of the symbols558 // defined by augmentation are visible via import.559}560// ---- utilities ----561// Simplifying wrapper around buildutil.FakeContext for single-file packages.562func fakeContext(pkgs map[string]string) *build.Context {563 pkgs2 := make(map[string]map[string]string)564 for path, content := range pkgs {565 pkgs2[path] = map[string]string{"x.go": content}566 }567 return buildutil.FakeContext(pkgs2)568}569func hasError(errors []error, substr string) bool {570 for _, err := range errors {571 if strings.Contains(err.Error(), substr) {572 return true573 }574 }575 return false576}577func keys(m map[string]bool) (keys []string) {578 for key := range m {579 keys = append(keys, key)580 }581 sort.Strings(keys)582 return583}584// Returns all loaded packages.585func all(prog *loader.Program) []string {586 var pkgs []string587 for _, info := range prog.AllPackages {588 pkgs = append(pkgs, info.Pkg.Path())589 }590 sort.Strings(pkgs)591 return pkgs592}593// Returns initially imported packages, as a string.594func imported(prog *loader.Program) string {595 var pkgs []string596 for _, info := range prog.Imported {597 pkgs = append(pkgs, info.Pkg.Path())598 }599 sort.Strings(pkgs)600 return strings.Join(pkgs, " ")601}602// Returns initially created packages, as a string.603func created(prog *loader.Program) string {604 var pkgs []string605 for _, info := range prog.Created {606 pkgs = append(pkgs, info.Pkg.Path())607 }608 return strings.Join(pkgs, " ")609}...

Full Screen

Full Screen

tokenize_test.go

Source:tokenize_test.go Github

copy

Full Screen

1package texttokenize2import (3 "testing"4)5func TestParseTokenize(t *testing.T) {6 fields := NewTokenize()7 fields.LoadFile("./testdata/valuefields.html")8 fields.SetIgnoreEmptyLine(false)9 fields.Parse("#main_test1 .descriptionText p")10 val := fields.Get("oписание")11 if val != "" {12 t.Errorf("Error get field, %q", val)13 }14 val = fields.Get("цвет")15 if val != "Зелёный, белый" {16 t.Errorf("Error get field, %q", val)17 }18 val = fields.Get("большой текст")19 if val != "line 1\r\n\r\nline 2\r\n\r\nline 3"{20 t.Errorf("Error get field, %q", val)21 }22}23func TestParseTokenizeMultiline(t *testing.T) {24 fields := NewTokenize()25 fields.LoadFile("./testdata/valuefields.html")26// fields.SetIgnoreEmptyLine(true) // default value "true"27 fields.Parse("#main_test2 .descriptionText p")28 val := fields.Get("описание")29 if val != "Декоративная шкатулка" {30 t.Errorf("Error get field multi-line, %q", val)31 }32 val = fields.Get("цвет")33 if val != "Зелёный, белый" {34 t.Errorf("Error get field, %q", val)35 }36 val = fields.Get("большой текст")37 if val != "line 1\r\nline 2\r\nline 3"{38 t.Errorf("Error get field, %q", val)39 }40}41func TestParseTokenize_MultiParse(t *testing.T) {42 fields := NewTokenize()43 fields.LoadFile("./testdata/valuefields.html")44 fields.Parse("#main_test3 .shortText p")45 fields.Parse("#main_test3 .shortText2")46 val := fields.Get("main material")47 if val != "100% polyester" {48 t.Errorf("Error get field, %q", val)49 }50 val = fields.Get("material 2")51 if val != "110% cotton" {52 t.Errorf("Error get field, %q", val)53 }54}55func TestParseBR(t *testing.T) {56 fields := NewTokenize()57 fields.LoadFile("./testdata/valuefields.html")58 fields.Parse("#main_test4 p")59 val := fields.Get("описание")60 if val != "" {61 t.Errorf("Error get field, %q", val)62 }63 val = fields.Get("цвет")64 if val != "Синий" {65 t.Errorf("Error get field, %q", val)66 }67 val = fields.Get("производитель")68 if val != "Вьетнам" {69 t.Errorf("Error get field, %q", val)70 }71 val = fields.Get("релиз! условия заказа товара")72 if val != "- не доступен для заказа по Москве\r\n- только по полной предоплате\r\n- по 1 паре в руки\r\n- акции на данный товар не распространяются" {73 t.Errorf("Error get field, %q", val)74 }75}...

Full Screen

Full Screen

errorf

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := errors.New("Error")4 fmt.Println(err)5 err = fmt.Errorf("Error %s", err)6 fmt.Println(err)7}8import (9func main() {10 err := log.Errorf("Error")11 fmt.Println(err)12}13import (14func main() {15 err := log.Printf("Error")16 fmt.Println(err)17}18import (19func main() {20 err := log.Fatalf("Error")21 fmt.Println(err)22}23import (24func main() {25 err := log.Panicf("Error")26 fmt.Println(err)27}28import (29func main() {30 err := log.Panicln("Error")31 fmt.Println(err)32}

Full Screen

Full Screen

errorf

Using AI Code Generation

copy

Full Screen

1import (2type Error struct {3}4func (e *Error) Error() string {5}6func main() {7 err := &Error{msg: "error msg"}8 fmt.Errorf("error: %v", err)9}10import (11func main() {12 _, err := net.Dial("tcp", "

Full Screen

Full Screen

errorf

Using AI Code Generation

copy

Full Screen

1import (2func main() {3fmt.Errorf("error message")4}5import (6func main() {7fmt.Errorf("error message")8}9import (10func main() {11fmt.Errorf("error message")12}13import (14func main() {15fmt.Errorf("error message")16}17import (18func main() {19fmt.Errorf("error message")20}21import (22func main() {23fmt.Errorf("error message")24}25import (26func main() {27fmt.Errorf("error message")28}29import (30func main() {31fmt.Errorf("error message")32}33import (34func main() {35fmt.Errorf("error message")36}37import (38func main() {39fmt.Errorf("error message")40}41import (42func main() {43fmt.Errorf("error message")44}45import (46func main() {47fmt.Errorf("error message")48}

Full Screen

Full Screen

errorf

Using AI Code Generation

copy

Full Screen

1func main() {2 fmt.Errorf("Error: %s", "Some error")3}4import "fmt"5func main() {6 fmt.Errorf("Error: %s", "Some error")7}8import "fmt"9func main() {10 fmt.Errorf("Error: %s", "Some error")11}12import "fmt"13func main() {14 fmt.Errorf("Error: %s", "Some error")15}16import "fmt"17func main() {18 fmt.Errorf("Error: %s", "Some error")19}20import "fmt"21func main() {22 fmt.Errorf("Error: %s", "Some error")23}24import "fmt"25func main() {26 fmt.Errorf("Error: %s", "Some error")27}28import "fmt"29func main() {30 fmt.Errorf("Error: %s", "Some error")31}32import "fmt"33func main() {34 fmt.Errorf("Error: %s", "Some error")35}36import "fmt"37func main() {38 fmt.Errorf("Error: %s", "Some error")39}40import "fmt"41func main() {42 fmt.Errorf("Error: %s", "Some error")43}44import "fmt"45func main() {46 fmt.Errorf("Error: %s", "Some error")47}

Full Screen

Full Screen

errorf

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3fmt.Errorf("This is an error")4}5./1.go:6: cannot use "This is an error" (type untyped string) as type error in argument to fmt.Errorf6import "fmt"7func main() {8fmt.Errorf("This is an error")9}10./2.go:6: cannot use "This is an error" (type untyped string) as type error in argument to fmt.Errorf11import "fmt"12func main() {13fmt.Errorf("This is an error")14}15./3.go:6: cannot use "This is an error" (type untyped string) as type error in argument to fmt.Errorf

Full Screen

Full Screen

errorf

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if _, err := os.Stat("test.txt"); err == nil {4 fmt.Println("File Exists")5 } else {6 fmt.Println("File Does Not Exist")7 }8 _, err := os.Create("test.txt")9 if err != nil {10 fmt.Printf("Error Creating File: %v11 } else {12 fmt.Println("File Created")13 }14 _, err = ioutil.ReadFile("test.txt")15 if err != nil {16 fmt.Printf("Error Reading File: %v17 } else {18 fmt.Println("File Read")19 }20 err = ioutil.WriteFile("test.txt", []byte("Hello World"), 0644)21 if err != nil {22 fmt.Printf("Error Writing File: %v23 } else {24 fmt.Println("File Written")25 }26 err = os.Remove("test.txt")27 if err != nil {28 fmt.Printf("Error Deleting File: %v29 } else {30 fmt.Println("File Deleted")31 }32}

Full Screen

Full Screen

errorf

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 log.Printf("This is a log message")5 log.Printf("This is a log message")6 log.Printf("This is a log message")7 log.Fatalf("This is a fatal message")8 log.Printf("This is a log message")9}10import (11func main() {12 fmt.Println("Hello, playground")13 err := fmt.Errorf("This is an error message")14 log.Printf("This is a log message")15 log.Printf("This is a log message")16 log.Printf("This is a log message")17 log.Fatalf("This is a fatal message")18 log.Printf("This is a log message")19 log.Println(err)20}21import (22func main() {23 fmt.Println("Hello, playground")24 err := fmt.Errorf("This is an error message")25 log.Printf("This is a log message")26 log.Printf("This is a log message")27 log.Printf("This is a log message")28 log.Fatalln("This is a fatal message")29 log.Printf("This is a log message")30 log.Println(err)31}32import (33func main() {34 fmt.Println("Hello, playground")35 err := fmt.Errorf("This is an error message")36 log.Printf("This is a log message")37 log.Printf("This is a log message")38 log.Printf("This is a log message")39 log.Fatalln("This is a fatal message")40 log.Printf("This is a log message")41 log.Println(err)42 log.Println("This is a log message")43}44import (45func main() {46 fmt.Println("Hello, playground")47 err := fmt.Errorf("This is an error message")48 log.Printf("This is a log message")49 log.Printf("This is a log message")50 log.Printf("This is a log message")51 log.Fatalln("This is a fatal message")52 log.Printf("This is a log message")53 log.Println(err)54 log.Println("This is a log

Full Screen

Full Screen

errorf

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Errorf("This is an error")4}5Errorf() method of main class6func errorf(format string, a ...interface{}) error7The errorf() method accepts the following parameters:8import (9func main() {10 fmt.Errorf("This is an error")11}12Errorf() method of fmt package13func errorf(format string, a ...interface{}) error14The errorf() method accepts the following parameters:15import (16func main() {17 fmt.Errorf("This is an error")18}19Errorf() method of errors package20func errorf(format string, a ...interface{}) error21The errorf() method accepts the following parameters:22import (23func main() {24 fmt.Errorf("This is an error")25}26Errorf() method

Full Screen

Full Screen

errorf

Using AI Code Generation

copy

Full Screen

1import (2func main() {3}4import (5func main() {6}7import (8func main() {9}10import (11func main() {12}13import (14func main() {15}16import (17func main() {18}19import (20func main() {21 log.Fatalf("this is an

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful