How to use Errorf method of main Package

Best Syzkaller code snippet using main.Errorf

peek_test.go

Source:peek_test.go Github

copy

Full Screen

...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

...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

...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 }...

Full Screen

Full Screen

tokenize_test.go

Source:tokenize_test.go Github

copy

Full Screen

...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

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

Full Screen

Full Screen

Errorf

Using AI Code Generation

copy

Full Screen

1import (2func main() {3file, err := os.Create("test.log")4if err != nil {5log.Fatalf("failed to create file: %s", err)6}7log.SetOutput(file)8log.SetPrefix("LOG: ")9log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile)10log.Println("This is a test log entry")11log.Fatalln("This is a fatal log entry")12log.Panicln("This is a panic log entry")13}14log.Panicln(0xc00004df60, 0x2, 0x2)15main.main()16os/signal.signal_recv(0x0)17os/signal.loop()18database/sql.(*DB).connectionOpener(0xc0000c0000, 0x5f5d40, 0xc0000a4000)

Full Screen

Full Screen

Errorf

Using AI Code Generation

copy

Full Screen

1func main() {2 fmt.Printf("Errorf: %v3", fmt.Errorf("Errorf: %v", 1))4}5func main() {6 fmt.Printf("Errorf: %v7", fmt.Errorf("Errorf: %v", 1))8}9func main() {10 fmt.Printf("Errorf: %v11", fmt.Errorf("Errorf: %v", 1))12}13func main() {14 fmt.Printf("Errorf: %v15", fmt.Errorf("Errorf: %v", 1))16}17func main() {18 fmt.Printf("Errorf: %v19", fmt.Errorf("Errorf: %v", 1))20}21func main() {22 fmt.Printf("Errorf: %v23", fmt.Errorf("Errorf: %v", 1))24}25func main() {26 fmt.Printf("Errorf: %v27", fmt.Errorf("Errorf: %v", 1))28}29func main() {30 fmt.Printf("Errorf: %v31", fmt.Errorf("Errorf: %v", 1))32}33func main() {34 fmt.Printf("Errorf: %v35", fmt.Errorf("Errorf: %v", 1))36}

Full Screen

Full Screen

Errorf

Using AI Code Generation

copy

Full Screen

1func main() {2 fmt.Errorf("Errorf")3}4func main() {5 fmt.Errorf("Errorf %d", 1)6}7func main() {8 fmt.Errorf("%s %d", "Errorf", 1)9}10Recommended Posts: Go | Errorf() Method

Full Screen

Full Screen

Errorf

Using AI Code Generation

copy

Full Screen

1import (2func main(){3 fmt.Errorf("Errorf method")4}5import (6func main(){7 fmt.Errorln("Errorln method")8}9import (10func main(){11 fmt.Fatal("Fatal method")12}13import (14func main(){15 fmt.Fatalf("Fatalf method")16}17import (18func main(){19 fmt.Fatalln("Fatalln method")20}21import (22func main(){23 fmt.Panic("Panic method")24}25main.main()

Full Screen

Full Screen

Errorf

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Errorf("Errorf method")4}5import "fmt"6func main() {7 fmt.Errorf("Errorf method")8}9import (10func main() {11 fmt.Errorf("Errorf method")12 errors.Errorf("Errorf method")13}14import "log"15func main() {16 log.Errorf("Errorf method")17}18import "github.com/sirupsen/logrus"19func main() {20 logrus.Errorf("Errorf method")21}22import "go.uber.org/zap"23func main() {24 zap.Errorf("Errorf method")25}

Full Screen

Full Screen

Errorf

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 log.Fatalf("This is a %s", "fatal error")4}5import (6func main() {7 log.Panicf("This is a %s", "panic error")8}9log.Panicf(0x52d1f1, 0x14, 0x0, 0x0, 0x0)10main.main()11import (12func main() {13 log.SetFlags(0)14 log.Panicf("This is a %s", "panic error")15}16log.Panicf(0x52d1f1, 0x14, 0x0, 0x0, 0x0)17main.main()18import (19func main() {

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.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful