func ShouldCASError(t testing.TB, s store.Store, key string, from, to store.CASV, wantErr error) { err := s.CAS(key, from, to, nil) if err != wantErr { t.Errorf("CAS(%#v, %v, %v) returned error %v, but wanted %v", key, from, to, err, wantErr) } }
func ShouldGetError(t testing.TB, s store.Store, key string, wantErr error) { got, _, err := s.Get(key, store.GetOptions{}) if err != wantErr { t.Errorf("Get(%#v) = (%#v, %v), but wanted err = %v", key, got, err, wantErr) } }
func ShouldStatMiss(t testing.TB, s store.Store, key string) { st, err := s.Stat(key, nil) if err != store.ErrNotFound { t.Errorf("Stat(%#v) returned (%v, %v), but wanted %v", key, st, err, store.ErrNotFound) } }
func ShouldGetPartialMiss(t testing.TB, s store.RangeReadStore, key string, start, length int64) { _, _, err := s.GetPartial(key, start, length, store.GetOptions{}) if err != store.ErrNotFound { t.Errorf("GetPartial(%#v, %v, %v) returned err %v, but wanted %v", key, start, length, err, store.ErrNotFound) } }
func validateIndex(t testing.TB, repo restic.Repository, idx *Index) { for id := range repo.List(restic.DataFile, nil) { if _, ok := idx.Packs[id]; !ok { t.Errorf("pack %v missing from index", id.Str()) } } }
func testMetric(t testing.TB) { var scenarios = []struct { input Metric fingerprint Fingerprint }{ { input: Metric{}, fingerprint: 2676020557754725067, }, { input: Metric{ "first_name": "electro", "occupation": "robot", "manufacturer": "westinghouse", }, fingerprint: 13260944541294022935, }, { input: Metric{ "x": "y", }, fingerprint: 1470933794305433534, }, } for i, scenario := range scenarios { if scenario.fingerprint != scenario.input.Fingerprint() { t.Errorf("%d. expected %d, got %d", i, scenario.fingerprint, scenario.input.Fingerprint()) } } }
func loadTestPointers(tb testing.TB) []geo.Pointer { f, err := os.Open("../testdata/points.csv.gz") if err != nil { tb.Fatalf("unable to open test file %v", err) } defer f.Close() gzReader, err := gzip.NewReader(f) if err != nil { tb.Fatalf("unable to create gz reader: %v", err) } defer gzReader.Close() // read in events var pointers []geo.Pointer scanner := bufio.NewScanner(gzReader) for scanner.Scan() { parts := strings.Split(scanner.Text(), ",") lat, _ := strconv.ParseFloat(parts[0], 64) lng, _ := strconv.ParseFloat(parts[1], 64) if lat == 0 || lng == 0 { tb.Errorf("latlng not parsed correctly, %s %s", parts[0], parts[1]) } pointers = append(pointers, &event{ Location: geo.NewPoint(lng, lat), }) } return pointers }
func testIPv6(t testing.TB, g *GeoIP, name string) { addrs := []string{ "::1:ffff:ffff", "::2:0:0", "::2:0:40", "::2:0:50", "::2:0:58", } for _, v := range addrs { ip := net.ParseIP(v) res, err := g.LookupIPValue(ip) expected := expectedValue(ip, name) if expected == nil { if err == nil { t.Errorf("expecting an error for IP %s in DB %s", ip, name) } } else { if err != nil { t.Error(err) } else { if !deepEqual(t, res, expected) { t.Errorf("expecting %v for IP %s in DB %s, got %v instead", expected, ip, name, res) } } } } }
// AfterTest snapshots the currently-running goroutines and returns a // function to be run at the end of tests to see whether any // goroutines leaked. func AfterTest(t testing.TB) func() { orig := map[string]bool{} for _, g := range interestingGoroutines() { orig[g] = true } return func() { // Loop, waiting for goroutines to shut down. // Wait up to 5 seconds, but finish as quickly as possible. deadline := timeutil.Now().Add(5 * time.Second) for { var leaked []string for _, g := range interestingGoroutines() { if !orig[g] { leaked = append(leaked, g) } } if len(leaked) == 0 { return } if timeutil.Now().Before(deadline) { time.Sleep(50 * time.Millisecond) continue } for _, g := range leaked { t.Errorf("Leaked goroutine: %v", g) } return } } }
func closeDB(t testing.TB, db *DB) { if e := recover(); e != nil { fmt.Printf("Panic: %v\n", e) panic(e) } defer setHookpostCloseConn(nil) setHookpostCloseConn(func(_ *fakeConn, err error) { if err != nil { t.Errorf("Error closing fakeConn: %v", err) } }) for node, i := db.freeConn.Front(), 0; node != nil; node, i = node.Next(), i+1 { dc := node.Value.(*driverConn) if n := len(dc.openStmt); n > 0 { // Just a sanity check. This is legal in // general, but if we make the tests clean up // their statements first, then we can safely // verify this is always zero here, and any // other value is a leak. t.Errorf("while closing db, freeConn %d/%d had %d open stmts; want 0", i, db.freeConn.Len(), n) } } err := db.Close() if err != nil { t.Fatalf("error closing DB: %v", err) } db.mu.Lock() count := db.numOpen db.mu.Unlock() if count != 0 { t.Fatalf("%d connections still open after closing DB", db.numOpen) } }
func verifyStorage(t testing.TB, s Storage, samples clientmodel.Samples, maxAge time.Duration) bool { result := true for _, i := range rand.Perm(len(samples)) { sample := samples[i] if sample.Timestamp.Before(clientmodel.TimestampFromTime(time.Now().Add(-maxAge))) { continue // TODO: Once we have a guaranteed cutoff at the // retention period, we can verify here that no results // are returned. } fp := sample.Metric.Fingerprint() p := s.NewPreloader() p.PreloadRange(fp, sample.Timestamp, sample.Timestamp, time.Hour) found := s.NewIterator(fp).GetValueAtTime(sample.Timestamp) if len(found) != 1 { t.Errorf("Sample %#v: Expected exactly one value, found %d.", sample, len(found)) result = false p.Close() continue } want := float64(sample.Value) got := float64(found[0].Value) if want != got || sample.Timestamp != found[0].Timestamp { t.Errorf( "Value (or timestamp) mismatch, want %f (at time %v), got %f (at time %v).", want, sample.Timestamp, got, found[0].Timestamp, ) result = false } p.Close() } return result }
func loadIDSet(t testing.TB, filename string) restic.BlobSet { f, err := os.Open(filename) if err != nil { t.Logf("unable to open golden file %v: %v", filename, err) return restic.NewBlobSet() } sc := bufio.NewScanner(f) blobs := restic.NewBlobSet() for sc.Scan() { var h restic.BlobHandle err := json.Unmarshal([]byte(sc.Text()), &h) if err != nil { t.Errorf("file %v contained invalid blob: %#v", filename, err) continue } blobs.Insert(h) } if err = f.Close(); err != nil { t.Errorf("closing file %v failed with error %v", filename, err) } return blobs }
func NoError(t testing.TB, err error) bool { if err != nil { t.Errorf("%s%v", assertPos(0), err) return false } return true }
func NotEqual(t testing.TB, name string, act, exp interface{}) bool { if act == exp { t.Errorf("%s%s is not expected to be %q", assertPos(0), name, fmt.Sprint(exp)) return false } return true }
// AfterTest snapshots the currently-running goroutines and returns a // function to be run at the end of tests to see whether any // goroutines leaked. func AfterTest(t testing.TB) func() { orig := interestingGoroutines() return func() { if t.Failed() { return } if r := recover(); r != nil { panic(r) } // Loop, waiting for goroutines to shut down. // Wait up to 5 seconds, but finish as quickly as possible. deadline := timeutil.Now().Add(5 * time.Second) for { var leaked []string for id, stack := range interestingGoroutines() { if _, ok := orig[id]; !ok { leaked = append(leaked, stack) } } if len(leaked) == 0 { return } if timeutil.Now().Before(deadline) { time.Sleep(50 * time.Millisecond) continue } sort.Strings(leaked) for _, g := range leaked { t.Errorf("Leaked goroutine: %v", g) } return } } }
func testDistribution(t testing.TB, counts map[string]int, min, max float64) { for k, v := range counts { if float64(v) < min || float64(v) > max { t.Errorf("Key %v has value %v which is out of range %v-%v", k, v, min, max) } } }
func Equal(tb testing.TB, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !reflect.DeepEqual(expected, actual) { logMessage(tb, msgAndArgs...) tb.Errorf("Not equal: %#v (expected)\n"+ " != %#v (actual)", expected, actual) } }
func (s *testProcessor001ProcessScenario) test(t testing.TB, set int) { reader, err := os.Open(path.Join("fixtures", s.in)) if err != nil { t.Fatalf("%d. couldn't open scenario input file %s: %s", set, s.in, err) } options := &ProcessOptions{ Timestamp: test001Time, } err = Processor001.ProcessSingle(reader, s, options) if s.err != err && (s.err == nil || err == nil || err.Error() != s.err.Error()) { t.Fatalf("%d. expected err of %s, got %s", set, s.err, err) } if len(s.actual) != len(s.expected) { t.Fatalf("%d. expected output length of %d, got %d", set, len(s.expected), len(s.actual)) } for i, expected := range s.expected { sort.Sort(s.actual[i]) sort.Sort(expected) if !expected.Equal(s.actual[i]) { t.Errorf("%d.%d. expected %s, got %s", set, i, expected, s.actual[i]) } } }
// AfterTest should be called (generally with "defer leaktest.AfterTest(t)") // from each test which uses goroutines. This waits for all goroutines // on a blacklist to terminate and provides more precise error reporting // than TestMainWithLeakCheck alone. func AfterTest(t testing.TB) { http.DefaultTransport.(*http.Transport).CloseIdleConnections() if testing.Short() { return } var bad string badSubstring := map[string]string{ ").readLoop(": "a Transport", ").writeLoop(": "a Transport", "created by net/http/httptest.(*Server).Start": "an httptest.Server", "timeoutHandler": "a TimeoutHandler", "net.(*netFD).connect(": "a timing out dial", ").noteClientGone(": "a closenotifier sender", "created by net/rpc.NewClientWithCodec": "an rpc client", } var stacks string for i := 0; i < 4; i++ { bad = "" stacks = strings.Join(interestingGoroutines(), "\n\n") for substr, what := range badSubstring { if strings.Contains(stacks, substr) { bad = what } } if bad == "" { return } // Bad stuff found, but goroutines might just still be // shutting down, so give it some time. time.Sleep(10 * time.Millisecond) } t.Errorf("Test appears to have leaked %s:\n%s", bad, stacks) }
func NewSSLTestServer(t testing.TB, protocol uint8) *TestServer { pem, err := ioutil.ReadFile("testdata/pki/ca.crt") certPool := x509.NewCertPool() if !certPool.AppendCertsFromPEM(pem) { t.Errorf("Failed parsing or appending certs") } mycert, err := tls.LoadX509KeyPair("testdata/pki/cassandra.crt", "testdata/pki/cassandra.key") if err != nil { t.Errorf("could not load cert") } config := &tls.Config{ Certificates: []tls.Certificate{mycert}, RootCAs: certPool, } listen, err := tls.Listen("tcp", "127.0.0.1:0", config) if err != nil { t.Fatal(err) } headerSize := 8 if protocol > protoVersion2 { headerSize = 9 } srv := &TestServer{ Address: listen.Addr().String(), listen: listen, t: t, protocol: protocol, headerSize: headerSize, quit: make(chan struct{}), } go srv.serve() return srv }
func testLabelValues(t testing.TB) { var scenarios = []struct { in LabelValues out LabelValues }{ { in: LabelValues{"ZZZ", "zzz"}, out: LabelValues{"ZZZ", "zzz"}, }, { in: LabelValues{"aaa", "AAA"}, out: LabelValues{"AAA", "aaa"}, }, } for i, scenario := range scenarios { sort.Sort(scenario.in) for j, expected := range scenario.out { if expected != scenario.in[j] { t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) } } } }
// @param expToFunc could be a func with a single input value and a bool return, or a bool value directly. func ValueShould(t testing.TB, name string, act interface{}, expToFunc interface{}, descIfFailed string) bool { expFunc := reflect.ValueOf(expToFunc) actValue := reflect.ValueOf(act) var succ bool if expFunc.Kind() == reflect.Bool { succ = expFunc.Bool() } else if expFunc.Kind() == reflect.Func { if expFunc.Type().NumIn() != 1 { t.Errorf("%sassert: expToFunc must have one parameter", assertPos(0)) return false } if expFunc.Type().NumOut() != 1 { t.Errorf("%sassert: expToFunc must have one return value", assertPos(0)) return false } if expFunc.Type().Out(0).Kind() != reflect.Bool { t.Errorf("%sassert: expToFunc must return a bool", assertPos(0)) return false } succ = expFunc.Call([]reflect.Value{actValue})[0].Bool() } else { t.Errorf("%sassert: expToFunc must be a func or a bool", assertPos(0)) return false } if !succ { t.Errorf("%s%s %s: %q(type %v)", assertPos(0), name, descIfFailed, fmt.Sprint(act), actValue.Type()) } return succ }
func nle(t testing.TB, a, b vector) { if compareLE(a, b) { _, file, line, _ := runtime.Caller(1) file = filepath.Base(file) t.Errorf("%s:%d: expected a<=b: %s </= %s", file, line, a, b) } }
// VerifyNoImports verifies that a package doesn't depend (directly or // indirectly) on forbidden packages. The forbidden packages are specified as // either exact matches or prefix matches. // If GOPATH isn't set, it is an indication that the source is not available and // the test is skipped. func VerifyNoImports( t testing.TB, pkgPath string, cgo bool, forbiddenPkgs, forbiddenPrefixes []string, ) { // Skip test if source is not available. if build.Default.GOPATH == "" { t.Skip("GOPATH isn't set") } imports, err := TransitiveImports(pkgPath, true) if err != nil { t.Fatal(err) } for _, forbidden := range forbiddenPkgs { if _, ok := imports[forbidden]; ok { t.Errorf("Package %s includes %s, which is forbidden", pkgPath, forbidden) } } for _, forbiddenPrefix := range forbiddenPrefixes { for k := range imports { if strings.HasPrefix(k, forbiddenPrefix) { t.Errorf("Package %s includes %s, which is forbidden", pkgPath, k) } } } }
func Equal(t testing.TB, name string, act, exp interface{}) bool { m, eq := deepValueDiff(name, reflect.ValueOf(act), reflect.ValueOf(exp)) if eq { return true } t.Errorf("%s%s", assertPos(0), m) return false }
func (c *concurrentTxStmtExecTest) test(t testing.TB) error { _, err := c.stmt.Exec(3, chrisBirthday) if err != nil { t.Errorf("error on exec: %v", err) return err } return nil }
func newPqUpdateTest(t testing.TB) *Update { tbl, err := NewTable("emp", pqEmp{}) if err != nil { t.Errorf("create table err: %v", err) } emp := NewPQUpdate(tbl) return emp }
func newPQSelectTest(t testing.TB) *Select { tbl, err := NewTable("emp", pqEmp{}) if err != nil { t.Errorf("create table err: %v", err) } emp := NewPQSelect(tbl, true) return emp }
// Assert that the given Endpoint matches the IP and port in the given // IpPortTuple. func assertAddress(t testing.TB, expected common.IpPortTuple, endpoint interface{}) { e, ok := endpoint.(*common.Endpoint) if !ok { t.Errorf("Expected a common.Endpoint but got %v", endpoint) } assert.Equal(t, expected.Src_ip.String(), e.Ip) assert.Equal(t, expected.Src_port, e.Port) }
func testFile(tb testing.TB, path string, expected string) { mimetype, err := m.TypeByFile(path) if err != nil { panic(err) } if mimetype != expected { tb.Errorf("expected %s; got %s.", expected, mimetype) } }