func TestFalse(t *testing.T) { t.Run("should not end testing if the condition is falsey", func(t *testing.T) { tester := new(mockTester) assert.False(tester, false, "") if tester.errorfCalls != 0 { t.Errorf( "Expected Errorf not to have been called, it had been called %d times.", tester.errorfCalls, ) } }) t.Run("should end testing if the condition is truthy", func(t *testing.T) { tester := new(mockTester) assert.False(tester, true, "") if tester.errorfCalls != 1 { t.Errorf( "Expected Errorf to have been called once, it had been called %d times.", tester.errorfCalls, ) } }) }
func TestExamples(t *testing.T) { flag.Parse() if !*examplesTest && os.Getenv("CI") == "" { t.Skip("skipping examples tests, pass --examples to execute it") return } defer deleteTempFolders() examples, err := filepath.Glob(examplesFolder()) if err != nil { t.Errorf("error finding tests: %s", err) } for _, example := range examples { _, name := filepath.Split(filepath.Dir(example)) if ignored[name] { continue } t.Run(name, func(t *testing.T) { testExample(t, name, example) }) } }
func TestParseHexColor(t *testing.T) { for _, tc := range []struct { hex string expected color.Color }{ { hex: "F84", expected: color.NRGBA{R: 0xff, G: 0x88, B: 0x44, A: 0xff}, }, { hex: "F842", expected: color.NRGBA{R: 0x88, G: 0x44, B: 0x22, A: 0xff}, }, { hex: "FC8642", expected: color.NRGBA{R: 0xfc, G: 0x86, B: 0x42, A: 0xff}, }, { hex: "FC864210", expected: color.NRGBA{R: 0x86, G: 0x42, B: 0x10, A: 0xfc}, }, } { t.Run(tc.hex, func(t *testing.T) { res, err := parseHexColor(tc.hex) if err != nil { t.Fatal(err) } if res != tc.expected { t.Fatalf("unexpected result for \"%s\": got %#v, want %#v", tc.hex, res, tc.expected) } }) } }
func TestHandlerAdd(t *testing.T) { tests := []struct { description string params *articles.HandlerAddParams code int }{ {"No Title", &articles.HandlerAddParams{}, http.StatusBadRequest}, {"Title filled with spaces", &articles.HandlerAddParams{Title: " "}, http.StatusBadRequest}, {"As few params as possible", &articles.HandlerAddParams{Title: "My Super Article"}, http.StatusCreated}, {"Duplicate title", &articles.HandlerAddParams{Title: "My Super Article"}, http.StatusCreated}, } for _, tc := range tests { t.Run(tc.description, func(t *testing.T) { rec := callHandlerAdd(t, tc.params) assert.Equal(t, tc.code, rec.Code) if rec.Code == http.StatusCreated { var a articles.Article if err := json.NewDecoder(rec.Body).Decode(&a); err != nil { t.Fatal(err) } assert.NotEmpty(t, a.ID) assert.NotEmpty(t, a.Slug) assert.Equal(t, tc.params.Title, a.Title) if err := a.FullyDelete(); err != nil { t.Fatal(err) } } }) } }
func TestScanln(t *testing.T) { for _, r := range readers { t.Run(r.name, func(t *testing.T) { testScan(t, r.f, Fscanln) }) } }
func TestRefreshAsync(t *testing.T) { t.Parallel() for _, scenario := range refreshAsyncScenarios { t.Run(scenario.description, func(t *testing.T) { discovery := dnsdisco.NewDiscovery(scenario.service, scenario.proto, scenario.name) discovery.SetRetriever(scenario.retriever) discovery.SetHealthChecker(scenario.healthChecker) finish := discovery.RefreshAsync(scenario.refreshInterval) defer close(finish) time.Sleep(scenario.refreshInterval + (50 * time.Millisecond)) target, port := discovery.Choose() if target != scenario.expectedTarget { t.Errorf("mismatch targets. Expecting: “%s”; found “%s”", scenario.expectedTarget, target) } if port != scenario.expectedPort { t.Errorf("mismatch ports. Expecting: “%d”; found “%d”", scenario.expectedPort, port) } if errs := discovery.Errors(); !reflect.DeepEqual(errs, scenario.expectedErrors) { t.Errorf("mismatch errors. Expecting: “%#v”; found “%#v”", scenario.expectedErrors, errs) } }) } }
func TestReplace(t *testing.T) { tests := []struct { where string start int end int what string result string }{ {"0123456789", 3, 5, "abcdef", "012abcdef56789"}, {"0123456789", 3, 5, "ab", "012ab56789"}, {"0123456789", 3, 3, "abcd", "012abcd3456789"}, {"0123456789", 0, 2, "abcd", "abcd23456789"}, {"0123456789", 0, 0, "ab", "ab0123456789"}, {"0123456789", 10, 10, "ab", "0123456789ab"}, {"0123456789", 8, 10, "ab", "01234567ab"}, {"0123456789", 5, 5, "", "0123456789"}, {"0123456789", 3, 8, "", "01289"}, {"0123456789", 3, 8, "ab", "012ab89"}, {"0123456789", 0, 5, "a", "a56789"}, {"0123456789", 5, 10, "ab", "01234ab"}, } for _, test := range tests { t.Run(fmt.Sprintf("%+v", test), func(t *testing.T) { result := replace([]byte(test.where), test.start, test.end, []byte(test.what)) if test.result != string(result) { t.Errorf("want '%v', got '%v'", test.result, string(result)) } }) } }
// Test if two runs produce identical results // even when writing different sizes to the Writer. func TestDeterministic(t *testing.T) { t.Parallel() for i := 0; i <= 9; i++ { t.Run(fmt.Sprint("L", i), func(t *testing.T) { testDeterministic(i, t) }) } t.Run("LM2", func(t *testing.T) { testDeterministic(-2, t) }) }
func TestDiff_DeepCopy(t *testing.T) { cases := map[string]*Diff{ "empty": &Diff{}, "basic diff": &Diff{ Modules: []*ModuleDiff{ &ModuleDiff{ Path: []string{"root"}, Resources: map[string]*InstanceDiff{ "aws_instance.foo": &InstanceDiff{ Attributes: map[string]*ResourceAttrDiff{ "num": &ResourceAttrDiff{ Old: "0", New: "2", }, }, }, }, }, }, }, } for name, tc := range cases { t.Run(name, func(t *testing.T) { dup := tc.DeepCopy() if !reflect.DeepEqual(dup, tc) { t.Fatalf("\n%#v\n\n%#v", dup, tc) } }) } }
func TestCredentialDescribe(t *testing.T) { cases := map[string]struct { args []string reply stack.Descriptions want []*stack.Description }{ "all credentials": { nil, stack.Descriptions{ "provider 1": {Credential: []stack.Value{{Name: "key", Type: "string"}}}, "provider 2": {Credential: []stack.Value{{Name: "token", Type: "string"}}}, }, []*stack.Description{ {Provider: "provider 1", Credential: []stack.Value{{Name: "key", Type: "string"}}}, {Provider: "provider 2", Credential: []stack.Value{{Name: "token", Type: "string"}}}, }, }, "filtered credential": { []string{"--provider", "foobar"}, stack.Descriptions{ "provider 1": {Credential: []stack.Value{{Name: "key", Type: "string"}}}, "provider 2": {Credential: []stack.Value{{Name: "token", Type: "string"}}}, "foobar": {Credential: []stack.Value{{Name: "foo", Type: "enum"}}}, }, []*stack.Description{ {Provider: "foobar", Credential: []stack.Value{{Name: "foo", Type: "enum"}}}, }, }, } for name, cas := range cases { t.Run(name, func(t *testing.T) { var buf bytes.Buffer cmd := &MainCmd{ Stdout: &buf, Stderr: os.Stderr, } cmd.FT.Add("credential.describe", stack.CredentialDescribeResponse{Description: cas.reply}) args := []string{"credential", "describe", "--json"} err := cmd.Run(append(args, cas.args...)...) if err != nil { t.Fatalf("Run()=%s", err) } var got []*stack.Description if err := json.Unmarshal(buf.Bytes(), &got); err != nil { t.Fatalf("Unmarshal()=%s", err) } if !reflect.DeepEqual(got, cas.want) { t.Fatalf("got %#v, want %#v", got, cas.want) } }) } }
func TestStateDeepCopy(t *testing.T) { cases := []struct { One, Two *State F func(*State) interface{} }{ // Version { &State{Version: 5}, &State{Version: 5}, func(s *State) interface{} { return s.Version }, }, // TFVersion { &State{TFVersion: "5"}, &State{TFVersion: "5"}, func(s *State) interface{} { return s.TFVersion }, }, } for i, tc := range cases { t.Run(fmt.Sprintf("copy-%d", i), func(t *testing.T) { actual := tc.F(tc.One.DeepCopy()) expected := tc.F(tc.Two) if !reflect.DeepEqual(actual, expected) { t.Fatalf("Bad: %d\n\n%s\n\n%s", i, actual, expected) } }) } }
func testOrm(t *testing.T, o *Orm, name string) { tests := []func(*testing.T, *Orm){ testCodecs, testAutoIncrement, testTime, testSaveDelete, testLoadSaveMethods, testLoadSaveMethodsErrors, testData, testInnerPointer, testTransactions, testFuncTransactions, testCompositePrimaryKey, testReferences, testQueryAll, testDefaults, testMigrations, testSaveUnchanged, testQueryTransform, } for _, v := range tests { t.Run(testName(name, v), func(t *testing.T) { clearRegistry(o) v(t, o) }) } }
func TestGenerator(t *testing.T) { for _, s := range []string{"gen_anyof_good_bad"} { t.Run(s, func(t *testing.T) { testHelper(t, "data/"+s) }) } }
func TestEqual(t *testing.T) { t.Run("should not end testing if the expected equals the actual", func(t *testing.T) { tester := new(mockTester) assert.Equal(tester, 42, 42) if tester.errorfCalls != 0 { t.Errorf( "Expected Errorf not to have been called, it had been called %d times.", tester.errorfCalls, ) } }) t.Run("should end testing if the expected does not equal the actual", func(t *testing.T) { tester := new(mockTester) assert.Equal(tester, 24, 42) if tester.errorfCalls != 1 { t.Errorf( "Expected Errorf to have been called once, it had been called %d times.", tester.errorfCalls, ) } }) }
func TestParseSysRCOutput(t *testing.T) { table := []struct { Input string K string V string }{ { Input: "keyrate: fast\n", K: "keyrate", V: "fast", }, { Input: "dumpdev: \n", K: "dumpdev", V: "", }, } for _, item := range table { t.Run(item.Input, func(t *testing.T) { k, v, err := parseSysRCOutput(item.Input) if err != nil { t.Error(err) } if k != item.K || v != item.V { t.Errorf("expected: k=%q, v=%q, got: k=%q, v=%q", item.K, item.V, k, v) } }) } }
func TestMedia(t *testing.T) { cases := []struct { input []int64 expected []int64 }{ { []int64{1, 2, 3, 4, 5, 6}, []int64{1, 1, 2, 2, 3, 3}, }, { []int64{10, 30, 20, 31, 32, 33, 40, 1, 2}, []int64{10, 10, 20, 20, 30, 30, 31, 30, 30}, }, } for i, tc := range cases { t.Run(strconv.Itoa(i), func(t *testing.T) { m := &Median{} for i, n := range tc.input { m.Add(n) t.Logf("Added %d Median: %d Struct: %v", n, m.Value(), m) if m.Value() != tc.expected[i] { t.Errorf("got median %d wanted %d", m.Value(), tc.expected[i]) } } }) } }
// TestContentTypes tests the content-type regexp that is used as // an example in fabio.properties func TestContentTypes(t *testing.T) { tests := []string{ "text/foo", "text/foo; charset=UTF-8", "text/plain", "text/plain; charset=UTF-8", "application/json", "application/json; charset=UTF-8", "application/javascript", "application/javascript; charset=UTF-8", "application/font-woff", "application/font-woff; charset=UTF-8", "application/xml", "application/xml; charset=UTF-8", "vendor/vendor.foo+json", "vendor/vendor.foo+json; charset=UTF-8", "vendor/vendor.foo+xml", "vendor/vendor.foo+xml; charset=UTF-8", } for _, tt := range tests { tt := tt // capture loop var t.Run(tt, func(t *testing.T) { if !contentTypes.MatchString(tt) { t.Fatalf("%q does not match content types regexp", tt) } }) } }
// ListTest tests the List handler func TestHandlerList(t *testing.T) { for i := 0; i < 10; i++ { a := articles.NewTestArticle(t, nil) testhelpers.SaveModel(t, a) } defer testhelpers.PurgeModels(t) tests := []struct { description string countWanted int code int }{ {"No params", 10, http.StatusOK}, } for _, tc := range tests { t.Run(tc.description, func(t *testing.T) { rec := callHandlerList(t) assert.Equal(t, tc.code, rec.Code) if rec.Code == http.StatusOK { var body []*articles.Article if err := json.NewDecoder(rec.Body).Decode(&body); err != nil { t.Fatal(err) } assert.Equal(t, tc.countWanted, len(body)) } }) } }
func TestDiscover(t *testing.T) { t.Parallel() for _, scenario := range discoverScenarios { t.Run(scenario.description, func(t *testing.T) { target, port, err := dnsdisco.Discover(scenario.service, scenario.proto, scenario.name) if target != scenario.expectedTarget { t.Errorf("mismatch targets. Expecting: “%s”; found “%s”", scenario.expectedTarget, target) } if port != scenario.expectedPort { t.Errorf("mismatch ports. Expecting: “%d”; found “%d”", scenario.expectedPort, port) } // As the resolver change between machines, we can't guess the DNSError name's attribute. So we // need to inject the value on the expected error dnsError, ok1 := err.(*net.DNSError) expectedDNSError, ok2 := scenario.expectedError.(*net.DNSError) if ok1 && ok2 { expectedDNSError.Server = dnsError.Server } if !reflect.DeepEqual(err, scenario.expectedError) { t.Errorf("mismatch errors. Expecting: “%v”; found “%v”", scenario.expectedError, err) } }) } }
func TestTableDriven(t *testing.T) { elts := []setElement{ setElement{val: strconv.Itoa(rand.Int())}, setElement{val: strconv.Itoa(rand.Int())}, setElement{val: strconv.Itoa(rand.Int())}, setElement{val: strconv.Itoa(rand.Int())}, setElement{val: strconv.Itoa(rand.Int())}, setElement{val: strconv.Itoa(rand.Int())}, } st := newSet() for i, elt := range elts { t.Run(fmt.Sprintf("element%d", i), func(t *testing.T) { if st.exists(elt) { t.Errorf("element %d reported as existing", i) return } if !st.add(elt) { t.Errorf("element %d reported as existing", i) } if !st.exists(elt) { t.Errorf("element %d reported as missing", i) return } if !st.remove(elt) { t.Errorf("element %d reported as not removed", i) return } }) } }
func TestMetricSetFactory(t *testing.T) { t.Run("without HostParser", func(t *testing.T) { registry := NewRegister() err := registry.AddMetricSet(moduleName, metricSetName, fakeMetricSetFactory) if err != nil { t.Fatal(err) } ms, hp, err := registry.metricSetFactory(moduleName, metricSetName) if err != nil { t.Fatal(err) } assert.NotNil(t, ms) assert.Nil(t, hp) }) t.Run("with HostParser", func(t *testing.T) { registry := NewRegister() hostParser := func(Module, string) (HostData, error) { return HostData{}, nil } err := registry.AddMetricSet(moduleName, metricSetName, fakeMetricSetFactory, hostParser) if err != nil { t.Fatal(err) } ms, hp, err := registry.metricSetFactory(moduleName, metricSetName) if err != nil { t.Fatal(err) } assert.NotNil(t, ms) assert.NotNil(t, hp) // Can't compare functions in Go so just check for non-nil. }) }
// TestTags verifies that the -tags argument controls which files to check. func TestTags(t *testing.T) { t.Parallel() Build(t) for _, tag := range []string{"testtag", "x testtag y", "x,testtag,y"} { tag := tag t.Run(tag, func(t *testing.T) { t.Parallel() t.Logf("-tags=%s", tag) args := []string{ "-tags=" + tag, "-v", // We're going to look at the files it examines. "testdata/tagtest", } cmd := exec.Command("./"+binary, args...) output, err := cmd.CombinedOutput() if err != nil { t.Fatal(err) } // file1 has testtag and file2 has !testtag. if !bytes.Contains(output, []byte(filepath.Join("tagtest", "file1.go"))) { t.Error("file1 was excluded, should be included") } if bytes.Contains(output, []byte(filepath.Join("tagtest", "file2.go"))) { t.Error("file2 was included, should be excluded") } }) } }
func TestScanfMulti(t *testing.T) { for _, r := range readers { t.Run(r.name, func(t *testing.T) { testScanfMulti(t, r.f) }) } }
// TestVet tests self-contained files in testdata/*.go. // // If a file contains assembly or has inter-dependencies, it should be // in its own test, like TestVetAsm, TestDivergentPackagesExamples, // etc below. func TestVet(t *testing.T) { Build(t) t.Parallel() // errchk ./testvet gos, err := filepath.Glob(filepath.Join(dataDir, "*.go")) if err != nil { t.Fatal(err) } wide := runtime.GOMAXPROCS(0) if wide > len(gos) { wide = len(gos) } batch := make([][]string, wide) for i, file := range gos { batch[i%wide] = append(batch[i%wide], file) } for i, files := range batch { files := files t.Run(fmt.Sprint(i), func(t *testing.T) { t.Parallel() t.Logf("files: %q", files) Vet(t, files) }) } }
func TestPosString(t *testing.T) { cases := []struct { Input Pos String string }{ { Pos{Line: 1, Column: 1}, "1:1", }, { Pos{Line: 2, Column: 3}, "2:3", }, { Pos{Line: 3, Column: 2, Filename: "template.hil"}, "template.hil:3:2", }, } for i, tc := range cases { t.Run(strconv.Itoa(i), func(t *testing.T) { got := tc.Input.String() if want, got := tc.String, got; want != got { t.Errorf("%#v produced %q; want %q", tc.Input, got, want) } }) } }
func TestSimplifyAndExpr(t *testing.T) { defer leaktest.AfterTest(t)() testData := []struct { expr string expected string }{ {`a < 1 AND b < 1 AND a < 2 AND b < 2`, `(a < 1) AND (b < 1)`}, {`(a > 1 AND a < 2) AND (a > 0 AND a < 3)`, `(a > 1) AND (a < 2)`}, {`a = 1 AND a = 2`, `false`}, {`a = 1 AND a = NULL`, `false`}, {`a = 1 AND a != NULL`, `false`}, {`a = 1 AND b = 1`, `(a = 1) AND (b = 1)`}, } for _, d := range testData { t.Run(d.expr+"~"+d.expected, func(t *testing.T) { sel := makeSelectNode(t) expr1 := parseAndNormalizeExpr(t, d.expr, sel) expr2, equiv := simplifyExpr(expr1) if s := expr2.String(); d.expected != s { t.Errorf("%s: expected %s, but found %s", d.expr, d.expected, s) } if !equiv { t.Errorf("%s: expected equivalent, but found %v", d.expr, equiv) } }) } }
func TestDockerCLI(t *testing.T) { containerConfig := container.Config{ Image: postgresTestImage, Cmd: []string{"stat", cluster.CockroachBinaryInContainer}, } if err := testDockerOneShot(t, "cli_test", containerConfig); err != nil { t.Skipf(`TODO(dt): No binary in one-shot container, see #6086: %s`, err) } paths, err := filepath.Glob(testGlob) if err != nil { t.Fatal(err) } if len(paths) == 0 { t.Fatalf("no testfiles found (%v)", testGlob) } verbose := testing.Verbose() || log.V(1) for _, p := range paths { testFile := filepath.Base(p) testPath := filepath.Join(containerPath, testFile) t.Run(testFile, func(t *testing.T) { cmd := cmdBase if verbose { cmd = append(cmd, "-d") } cmd = append(cmd, "-f", testPath, cluster.CockroachBinaryInContainer) containerConfig.Cmd = cmd if err := testDockerOneShot(t, "cli_test", containerConfig); err != nil { t.Error(err) } }) } }
func TestBatchPrevNextWithNoop(t *testing.T) { defer leaktest.AfterTest(t)() leftKey := roachpb.Key("a") middleKey := roachpb.RKey("b") rightKey := roachpb.Key("c") var ba roachpb.BatchRequest ba.Add(&roachpb.GetRequest{Span: roachpb.Span{Key: leftKey}}) ba.Add(&roachpb.NoopRequest{}) ba.Add(&roachpb.GetRequest{Span: roachpb.Span{Key: rightKey}}) t.Run("prev", func(t *testing.T) { rk, err := prev(ba, middleKey) if err != nil { t.Fatal(err) } if !rk.Equal(leftKey) { t.Errorf("got %s, expected %s", rk, leftKey) } }) t.Run("next", func(t *testing.T) { rk, err := next(ba, middleKey) if err != nil { t.Fatal(err) } if !rk.Equal(rightKey) { t.Errorf("got %s, expected %s", rk, rightKey) } }) }
func TestHexStringToInts(t *testing.T) { for _, tc := range []struct { hex string expected []uint8 }{ { hex: "", expected: nil, }, { hex: "1", expected: []uint8{0x1}, }, { hex: "0123456789abcdefABCDEF", expected: []uint8{ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, }, }, } { t.Run(tc.hex, func(t *testing.T) { res, err := hexStringToInts(tc.hex) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(res, tc.expected) { t.Fatalf("unexpected result for \"%s\": got %#v, want %#v", tc.hex, res, tc.expected) } }) } }
func TestNotOK(t *testing.T) { t.Run("should not end testing if the given error is not nil", func(t *testing.T) { tester := new(mockTester) assert.NotOK(tester, errors.New("Testing")) if tester.errorfCalls != 0 { t.Errorf( "Expected Errorf not to have been called, it had been called %d times.", tester.errorfCalls, ) } }) t.Run("should end testing if the given error is nil", func(t *testing.T) { tester := new(mockTester) assert.NotOK(tester, nil) if tester.errorfCalls != 1 { t.Errorf( "Expected Errorf to have been called once, it had been called %d times.", tester.errorfCalls, ) } }) }