func innerTest(client *FlumeClient, t testing.TB) { //header: {businessName=feed, type=list}. //body: 100311 list {"view_self":0,"remoteid":"5445285","timestamp":1403512030,"flume_timestamp":"2014-06-23 16:27:10","business_type":"feed"} body := "{\"view_self\":0,\"remoteid\":\"5445285\",\"timestamp\":1403512030,\"flume_timestamp\":\"2014-06-23 16:27:10\",\"business_type\":\"feed\"}" var demo LogDemo err := json.Unmarshal([]byte(body), &demo) if nil != err { t.Fail() return } data, err := json.Marshal(demo) if nil != err { t.Fail() return } event := NewFlumeEvent("feed", "list", data) events := []*flume.ThriftFlumeEvent{event} for i := 0; i < 1; i++ { err := client.AppendBatch(events) err = client.Append(event) if nil != err { t.Log(err.Error()) t.Fail() } else { t.Logf("%d, send succ ", i) } } }
func innerTest(client *FlumeClient, t testing.TB) { //header: {businessName=feed, type=list}. //body: 100311 list {"view_self":0,"remoteid":"5445285","timestamp":1403512030,"flume_timestamp":"2014-06-23 16:27:10","business_type":"feed"} body := "{\"view_self\":0,\"remoteid\":\"5445285\",\"timestamp\":1403512030,\"flume_timestamp\":\"2014-06-23 16:27:10\",\"business_type\":\"feed\"}" var demo LogDemo err := json.Unmarshal([]byte(body), &demo) if nil != err { t.Fail() return } data, err := json.Marshal(demo) if nil != err { t.Fail() return } header := make(map[string]string, 2) header["businessName"] = "feed" header["type"] = "list" for i := 0; i < 1; i++ { err := client.Append(header, data) if nil != err { t.Log(err.Error()) t.Fail() } else { t.Logf("%d, send succ ", i) } } }
func (c *capture) Equal(t testing.TB, expected string) { // trim the deleteSelf '\b' prefix actual := strings.TrimLeft(c.String(), "\b") ensure.DeepEqual(t, actual, expected) if log && expected != "" { t.Log(equalPrefix, expected) } }
func solveOfficial(tb testing.TB) { test := `1 _ 3 _ _ 6 _ 8 _ _ 5 _ _ 8 _ 1 2 _ 7 _ 9 1 _ 3 _ 5 6 _ 3 _ _ 6 7 _ 9 _ 5 _ 7 8 _ _ _ 3 _ 8 _ 1 _ 3 _ 5 _ 7 _ 4 _ _ 7 8 _ 1 _ 6 _ 8 _ _ 2 _ 4 _ _ 1 2 _ 4 5 _ 7 8 ` expect := `1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 2 3 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9 1 2 3 4 5 6 7 8 ` var puzz puzzle in := bytes.NewBufferString(test) if err := puzz.init(in); err != nil { tb.Error(err) } vout := &bytes.Buffer{} var category string puzz, category = solve(puzz, vout) tb.Log(vout) if err := puzz.solved(); err != nil { tb.Errorf("puzzle not solved [%s]", err) } if !strings.EqualFold("hard", category) { tb.Error("puzzle not hard") } out := &bytes.Buffer{} puzz.printme(out) actual := out.String() if expect != actual { tb.Errorf("Expect [%s] Actual [%s]", expect, actual) } tb.Log(out) }
// cli runs an cli command against a server. func cli(t testing.TB, token, url, command string) string { cmd := NewCmd(url, command) cmd.Authorize(token) b, err := cmd.CombinedOutput() t.Log(fmt.Sprintf("\n$ %s\n%s", command, string(b))) if err != nil { t.Fatal(err) } return string(b) }
// waitForMount blocks (max mountWait * mountSleep) until the subdir // "snapshots" appears in the dir. func waitForMount(t testing.TB, dir string) { for i := 0; i < mountWait; i++ { if snapshotsDirExists(t, dir) { t.Log("mounted directory is ready") return } time.Sleep(mountSleep) } t.Errorf("subdir %q of dir %s never appeared", mountTestSubdir, dir) }
// 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. // If a previous test's check has already failed, this is a noop (to avoid // failing unrelated tests). func AfterTest(t testing.TB) { if atomic.LoadInt32(&hasFailed) > 0 { t.Log("prior leak detected, leaktest disabled") return } if r := recover(); r != nil { // Don't bother with leaktest if we're recovering from a panic. panic(r) } http.DefaultTransport.(*http.Transport).CloseIdleConnections() if testing.Short() || t.Failed() { // If a test has failed, chances are it hasn't shut down cleanly, so // stop checking for leaks in this run altogether. atomic.StoreInt32(&hasFailed, 1) return } if r := recover(); r != nil { panic(r) } 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", "created by net/rpc.(*Server.ServeCodec)": "an rpc server connection", "(*Store).Start": "a store", "(*Range).Send": "a range command", } var stacks string for i := 0; i < 8; 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) } atomic.StoreInt32(&hasFailed, 1) t.Errorf("Test appears to have leaked %s:\n%s", bad, stacks) }
// TestCleanup runs the cleanup function after all tests are run. func TestCleanup(t testing.TB) { if CleanupFn == nil { t.Log("CleanupFn function not set") return } if !test.TestCleanupTempDirs { t.Logf("not cleaning up backend") return } err := CleanupFn() if err != nil { t.Fatalf("Cleanup returned error: %v", err) } }
func performChat(t testing.TB, conn *grpc.ClientConn) error { serverClient := pb.NewPeerClient(conn) stream, err := serverClient.Chat(context.Background()) if err != nil { t.Logf("%v.performChat(_) = _, %v", serverClient, err) return err } defer stream.CloseSend() t.Log("Starting performChat") waitc := make(chan struct{}) go func() { // Be sure to close the channel defer close(waitc) for { in, err := stream.Recv() if err == io.EOF { t.Logf("Received EOR, exiting chat") return } if err != nil { t.Errorf("stream closed with unexpected error: %s", err) return } if in.Type == pb.Message_DISC_HELLO { t.Logf("Received message: %s, sending %s", in.Type, pb.Message_DISC_GET_PEERS) stream.Send(&pb.Message{Type: pb.Message_DISC_GET_PEERS}) } else if in.Type == pb.Message_DISC_PEERS { //stream.Send(&pb.DiscoveryMessage{Type: pb.DiscoveryMessage_PEERS}) t.Logf("Received message: %s", in.Type) t.Logf("Closing stream and channel") return } else { t.Logf("Received message: %s", in.Type) } } }() select { case <-waitc: return nil case <-time.After(1 * time.Second): t.Fail() return fmt.Errorf("Timeout expired while performChat") } }
func createKeyspace(tb testing.TB, cluster *ClusterConfig, keyspace string) { session, err := cluster.CreateSession() if err != nil { tb.Fatal("createSession:", err) } if err = session.Query(`DROP KEYSPACE ` + keyspace).Exec(); err != nil { tb.Log("drop keyspace:", err) } if err := session.Query(fmt.Sprintf(`CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : %d }`, keyspace, *flagRF)).Consistency(All).Exec(); err != nil { tb.Fatalf("error creating keyspace %s: %v", keyspace, err) } tb.Logf("Created keyspace %s", keyspace) session.Close() }
func linesEqual(skip int, t testing.TB, name string, act, exp reflect.Value) bool { actS, expS := sliceToStrings(act), sliceToStrings(exp) if stringSliceEqual(actS, expS) { return true } title := fmt.Sprintf("%sUnexpected %s: ", assertPos(skip), name) if len(expS) == len(actS) { title = fmt.Sprintf("%sboth %d lines", title, len(expS)) } else { title = fmt.Sprintf("%sexp %d, act %d lines", title, len(expS), len(actS)) } t.Error(title) t.Log(" Difference(expected --- actual +++)") _, expMat, actMat := match(len(expS), len(actS), func(expI, actI int) int { if expS[expI] == actS[actI] { return 0 } return 2 }, func(int) int { return 1 }, func(int) int { return 1 }) for i, j := 0, 0; i < len(expS) || j < len(actS); { switch { case j >= len(actS) || i < len(expS) && expMat[i] < 0: t.Logf(" --- %3d: %q", i+1, expS[i]) i++ case i >= len(expS) || j < len(actS) && actMat[j] < 0: t.Logf(" +++ %3d: %q", j+1, actS[j]) j++ default: if expS[i] != actS[j] { t.Logf(" --- %3d: %q", i+1, expS[i]) t.Logf(" +++ %3d: %q", j+1, actS[j]) } // else i++ j++ } } return false }
func run(t testing.TB, commands []Command) { cli := newCLI(t) defer cli.Close() token, err := cli.Empire.AccessTokensCreate(&empire.AccessToken{ User: fakeUser, }) if err != nil { t.Fatal(err) } if err := cli.Authorize(fakeUser.Name, token.Token); err != nil { t.Fatal(err) } for _, cmd := range commands { args := strings.Split(cmd.Command, " ") b, err := cli.Command(args...).CombinedOutput() t.Log(fmt.Sprintf("\n$ %s\n%s", cmd.Command, string(b))) if err != nil { t.Fatal(err) } got := string(b) if want, ok := cmd.Output.(string); ok { if want != "" { want = want + "\n" } if got != want { t.Fatalf("%q != %q", got, want) } } else if regex, ok := cmd.Output.(*regexp.Regexp); ok { if !regex.MatchString(got) { t.Fatalf("%q != %q", got, regex.String()) } } } }
// VerifyModelAgainstFile method verifies the correctness of a particular VAST 3.0 object against // a VAST XML file. A correct VAST document contains all the fields specified in Go struct, and they // are all non-empty fields. // // Thus, the XML file being referenced should contain all the XML elements defined as the validity // of the XML file is irrelevant in this verification. func VerifyModelAgainstFile(t testing.TB, name, file string, modelType reflect.Type) { if modelType.Kind() == reflect.Ptr { t.Fatalf("Mode type %v must not be of pointer kind.\n", modelType) } xmlData, err := ioutil.ReadFile("testdata/" + file) if err != nil { t.Fatalf("Cannot read XML file: %v.\n", err) } model1 := reflect.New(modelType).Interface() model2 := reflect.New(modelType).Interface() if err := xml.Unmarshal(xmlData, model1); err != nil { t.Log(err) t.Fatalf("Cannot unmarshal XML data into %v.\n", modelType) } newXmlData, err := xml.Marshal(model1) if err != nil { t.Fatalf("Cannot marshal model %v into XML data.", modelType) } if err := xml.Unmarshal(newXmlData, model2); err != nil { t.Fatalf("Cannot unmarshal XML data into %v.\n", modelType) } if !reflect.DeepEqual(model1, model2) { t.Error("Unmarshaled model should be the same as re-unmarshaled model.") } verifyElementName(t, name, xmlData) verifyNonEmptyXmlFields(t, model1, modelType) }
func logParticles(s *Space, tb testing.TB) { for _, p := range s.Particles { tb.Log(p.Position) } }
func (c *capture) Contains(t testing.TB, suffix string) { ensure.StringContains(t, c.String(), suffix) if log && suffix != "" { t.Log(equalPrefix, suffix) } }
// debug adapts fuse.Debug to match t.Log calling convention; due to // varargs, we can't just assign tb.Log to fuse.Debug func debug(tb testing.TB) func(msg interface{}) { return func(msg interface{}) { tb.Log(msg) } }