func startSleepCommand(t *testing.T) *exec.Cmd { cmd := exec.Command("sh", "-c", "sleep 100") if err := cmd.Start(); err != nil { t.Error(err) } return cmd }
func TestConnQueryScan(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) var sum, rowCount int32 rows, err := conn.Query("select generate_series(1,$1)", 10) if err != nil { t.Fatalf("conn.Query failed: ", err) } defer rows.Close() for rows.Next() { var n int32 rows.Scan(&n) sum += n rowCount++ } if rows.Err() != nil { t.Fatalf("conn.Query failed: ", err) } if rowCount != 10 { t.Error("Select called onDataRow wrong number of times") } if sum != 55 { t.Error("Wrong values returned") } }
func TestConnQueryEncoder(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) n := pgx.NullInt64{Int64: 1, Valid: true} rows, err := conn.Query("select $1::int8", &n) if err != nil { t.Fatalf("conn.Query failed: ", err) } ok := rows.Next() if !ok { t.Fatal("rows.Next terminated early") } var m pgx.NullInt64 err = rows.Scan(&m) if err != nil { t.Fatalf("rows.Scan failed: ", err) } rows.Close() if !m.Valid { t.Error("m should be valid, but it wasn't") } if m.Int64 != 1 { t.Errorf("m.Int64 should have been 1, but it was %v", m.Int64) } ensureConnValid(t, conn) }
func TestPerimeter(t *testing.T) { //Testing for circle for _, pair := range tests { c := Circle{pair.x, pair.y, pair.r} v := c.perimeter() if v != pair.perimeterC { t.Error( "For", pair.x, pair.y, pair.r, "expected", pair.perimeterC, "got", v, ) } } //Testing for rectangle for _, pair1 := range testsRectanglePerimeter { r := Rectangle{pair1.x1, pair1.y1, pair1.x2, pair1.y2} v := r.perimeter() if v != pair1.perimeterR { t.Error( "For", pair1.x1, pair1.y1, pair1.x2, pair1.y2, "expected", pair1.perimeterR, "got", v, ) } } }
func TestWatchFork(t *testing.T) { if skipTest(t) { return } pid := os.Getpid() tw := newTestWatcher(t) // no watches added yet, so this fork event will no be captured runCommand(t, "date") // watch fork events for this process if err := tw.watcher.Watch(pid, PROC_EVENT_FORK); err != nil { t.Error(err) } // this fork event will be captured, // the exec and exit events will not be captured runCommand(t, "cal") tw.close() if expectEvents(t, 1, "forks", tw.events.forks) { expectEventPid(t, "fork", pid, tw.events.forks[0]) } expectEvents(t, 0, "execs", tw.events.execs) expectEvents(t, 0, "exits", tw.events.exits) }
func TestLinesToIgnore(t *testing.T) { // it 'ignores empty lines' do // expect(env("\n \t \nfoo=bar\n \nfizz=buzz")).to eql('foo' => 'bar', 'fizz' => 'buzz') if !isIgnoredLine("\n") { t.Error("Line with nothing but line break wasn't ignored") } if !isIgnoredLine("\t\t ") { t.Error("Line full of whitespace wasn't ignored") } // it 'ignores comment lines' do // expect(env("\n\n\n # HERE GOES FOO \nfoo=bar")).to eql('foo' => 'bar') if !isIgnoredLine("# comment") { t.Error("Comment wasn't ignored") } if !isIgnoredLine("\t#comment") { t.Error("Indented comment wasn't ignored") } // make sure we're not getting false positives if isIgnoredLine("export OPTION_B='\\n'") { t.Error("ignoring a perfectly valid line to parse") } }
func TestIntegrationLog(t *testing.T) { if testing.Short() { t.Skip("Skipping integration tests in short mode.") } oService := &routing.Service{Client: client} opts, err := oService.GetOptimizations(&routing.RouteQuery{ Limit: 1, }) if err != nil { t.Error("Error occured in external service:", err) return } if len(opts) < 1 { t.Skip("Not enough routes to test activity stream") } opt, err := oService.GetOptimization(&routing.OptimizationParameters{ ProblemID: opts[0].ProblemID, }) if len(opt.Routes) < 1 { t.Skip("Not enough routes to test activity stream") } err = service.Log("TestMessage", opt.Routes[0].ID) if err != nil { t.Error(err) } }
// ensure rate limit is still parsed, even for error responses func TestDo_rateLimit_errorResponse(t *testing.T) { setup() defer teardown() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Add(headerRateLimit, "60") w.Header().Add(headerRateRemaining, "59") w.Header().Add(headerRateReset, "1372700873") http.Error(w, "Bad Request", 400) }) req, _ := client.NewRequest("GET", "/", nil) _, err := client.Do(req, nil) if err == nil { t.Error("Expected error to be returned.") } if _, ok := err.(*RateLimitError); ok { t.Errorf("Did not expect a *RateLimitError error; got %#v.", err) } if got, want := client.Rate().Limit, 60; got != want { t.Errorf("Client rate limit = %v, want %v", got, want) } if got, want := client.Rate().Remaining, 59; got != want { t.Errorf("Client rate remaining = %v, want %v", got, want) } reset := time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC) if client.Rate().Reset.UTC() != reset { t.Errorf("Client rate reset = %v, want %v", client.Rate().Reset, reset) } }
func testRegisterConsumer(t *testing.T) { subscription := make(map[string]int) subscription["topic1"] = 1 consumerInfo := &ConsumerInfo{ Version: int16(1), Subscription: subscription, Pattern: whiteListPattern, Timestamp: time.Now().Unix(), } topicCount := &WildcardTopicsToNumStreams{ Coordinator: coordinator, ConsumerId: fmt.Sprintf(consumerIdPattern, 0), TopicFilter: NewWhiteList("topic1"), NumStreams: 1, ExcludeInternalTopics: true, } err := coordinator.RegisterConsumer(fmt.Sprintf(consumerIdPattern, 0), consumerGroup, topicCount) if err != nil { t.Error(err) } actualConsumerInfo, err := coordinator.GetConsumerInfo(fmt.Sprintf(consumerIdPattern, 0), consumerGroup) assert(t, actualConsumerInfo.Version, consumerInfo.Version) assert(t, actualConsumerInfo.Subscription, consumerInfo.Subscription) assert(t, actualConsumerInfo.Pattern, consumerInfo.Pattern) }
func testGetConsumersInGroup(t *testing.T) { consumers, err := coordinator.GetConsumersInGroup(consumerGroup) if err != nil { t.Error(err) } assert(t, len(consumers), 1) }
func TestMarshalBinary(t *testing.T) { s1 := New(testdata.TwoHoursData[0].T) for _, p := range testdata.TwoHoursData { s1.Push(p.T, p.V) } it1 := s1.Iter() it1.Next() b, err := s1.MarshalBinary() if err != nil { t.Error(err) } s2 := New(s1.T0) err = s2.UnmarshalBinary(b) if err != nil { t.Error(err) } it := s2.Iter() for _, w := range testdata.TwoHoursData { if !it.Next() { t.Fatalf("Next()=false, want true") } tt, vv := it.Values() // t.Logf("it.Values()=(%+v, %+v)\n", time.Unix(int64(tt), 0), vv) if w.T != tt || w.V != vv { t.Errorf("Values()=(%v,%v), want (%v,%v)\n", tt, vv, w.T, w.V) } } }
func TestUnionFsRemoveAll(t *testing.T) { wd, clean := setupUfs(t) defer clean() err := os.MkdirAll(wd+"/ro/dir/subdir", 0755) CheckSuccess(err) contents := "hello" fn := wd + "/ro/dir/subdir/y" err = ioutil.WriteFile(fn, []byte(contents), 0644) CheckSuccess(err) freezeRo(wd + "/ro") err = os.RemoveAll(wd + "/mnt/dir") if err != nil { t.Error("Should delete all") } for _, f := range []string{"dir/subdir/y", "dir/subdir", "dir"} { if fi, _ := os.Lstat(filepath.Join(wd, "mount", f)); fi != nil { t.Errorf("file %s should have disappeared: %v", f, fi) } } names, err := Readdirnames(wd + "/rw/DELETIONS") CheckSuccess(err) if len(names) != 3 { t.Fatal("unexpected names", names) } }
func TestTournamentAndElitism(t *testing.T) { var ( src = rand.NewSource(time.Now().UnixNano()) rng = rand.New(src) nbGenes = 2 size = 3 indis = makeIndividuals(size, nbGenes, rng) ) for i := 0; i < size; i++ { indis[i] = makeIndividual(nbGenes, rng) indis[i].Fitness = float64(i) } var original = make([]Individual, len(indis)) copy(original, indis) // All the individuals participate in the tournament var ( elitism = SelElitism{} tournament = SelTournament{size} elite, _ = elitism.Apply(size, indis, rng) tourney, _ = tournament.Apply(size, indis, rng) ) elite.Sort() tourney.Sort() // Check the individual is from the initial population if elite[0].Fitness != tourney[0].Fitness { t.Error("Elitism and full tournament selection differed") } }
func TestMultiWriter(t *testing.T) { sha1 := sha1.New() sink := new(bytes.Buffer) mw := MultiWriter(sha1, sink) sourceString := "My input text." source := strings.NewReader(sourceString) written, err := Copy(mw, source) if written != int64(len(sourceString)) { t.Errorf("short write of %d, not %d", written, len(sourceString)) } if err != nil { t.Errorf("unexpected error: %v", err) } sha1hex := fmt.Sprintf("%x", sha1.Sum()) if sha1hex != "01cb303fa8c30a64123067c5aa6284ba7ec2d31b" { t.Error("incorrect sha1 value") } if sink.String() != sourceString { t.Errorf("expected %q; got %q", sourceString, sink.String()) } }
func Test_janitar(t *testing.T) { time.Sleep(12 * time.Second) if cache1.Len().Get() == 99999 { t.Error("err") return } }
func TestCacheComplete(t *testing.T) { paths := DefaultPaths() if len(paths) == 0 { t.Skip("No default paths available") } tests := []string{"mscorlib.dll", "System.dll"} t.Log(paths) c := Cache{paths: paths} for _, test := range tests { if asm, err := c.Load(test); err != nil { t.Error(err) } else { t.Logf("Found %s (%s)", test, asm.Name()) } } tests2 := []content.Type{ content.Type{Name: content.FullyQualifiedName{Absolute: "net://type/System.String"}}, } for _, test := range tests2 { if res, err := c.Complete(&test); err != nil { t.Error(err) } else { t.Log(res) } } }
func Test_executing_a_regex_command(t *testing.T) { w := &wsman{} id := w.HandleCommand(MatchPattern(`echo .* >> C:\file.cmd`), func(out, err io.Writer) int { return 0 }) res := httptest.NewRecorder() req, _ := http.NewRequest("POST", "", strings.NewReader(fmt.Sprintf(` <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell"> <env:Header> <a:Action mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/09/shell/Command</a:Action> </env:Header> <env:Body> <rsp:CommandLine><rsp:Command>"echo %d >> C:\file.cmd"</rsp:Command></rsp:CommandLine> </env:Body> </env:Envelope>`, uuid.NewV4().String()))) w.ServeHTTP(res, req) if res.Code != http.StatusOK { t.Errorf("Expected 200 OK but was %d.\n", res.Code) } env, err := xmlpath.Parse(res.Body) if err != nil { t.Error("Couldn't compile the SOAP response.") } xpath, _ := xmlpath.CompileWithNamespace( "//rsp:CommandId", soap.GetAllNamespaces()) result, _ := xpath.String(env) if result != id { t.Errorf("Expected CommandId=%s but was \"%s\"", id, result) } }
func testLineReader(t *testing.T, input []byte) { for stride := 1; stride < len(input); stride++ { done := 0 reader := testReader{input, stride} l := NewReader(&reader, len(input)+1) for { line, isPrefix, err := l.ReadLine() if len(line) > 0 && err != nil { t.Errorf("ReadLine returned both data and error: %s", err) } if isPrefix { t.Errorf("ReadLine returned prefix") } if err != nil { if err != os.EOF { t.Fatalf("Got unknown error: %s", err) } break } if want := testOutput[done : done+len(line)]; !bytes.Equal(want, line) { t.Errorf("Bad line at stride %d: want: %x got: %x", stride, want, line) } done += len(line) } if done != len(testOutput) { t.Error("ReadLine didn't return everything") } } }
func makeIPNet(t *testing.T) *net.IPNet { _, net, err := net.ParseCIDR("1.2.3.0/24") if err != nil { t.Error(err) } return net }
func Test_Remove_Sync(t *testing.T) { FuncName := "GdLists.Remove() AND GdLists.Sync()" ssgl, _ := getGdListIns() Pssgl := &ssgl Pssgl.New() v := Pssgl.Remove(2) l := Pssgl.Len() a := len(Pssgl.Value) b := Pssgl.list.Len() // dd(l) // dd(a) // dd(b) if l != b || a-b != 1 { t.Error(FuncName + " ... failed!") } v.Sync() ls := Pssgl.Len() as := len(Pssgl.Value) // bs := Pssgl.list.Len() // dd(ls) // dd(as) // dd(bs) if as != ls || ls != 4 || Pssgl.Getter(2) != "4" { t.Error(FuncName + " ... failed!") } t.Log(FuncName + " ... ok!") }
func TestNoExistBinary(t *testing.T) { // Can't run a non-existent binary err := exec.Command("/no-exist-binary").Run() if err == nil { t.Error("expected error from /no-exist-binary") } }
func TestInstantiateZero(t *testing.T) { defer func() { recover() }() _ = lfucache.New(0) t.Error("Should not be able to instantiate zero-sized cache") }
func TestBufReader(t *testing.T) { reader, writer := io.Pipe() bufreader := NewBufReader(reader) // Write everything down to a Pipe // Usually, a pipe should block but because of the buffered reader, // the writes will go through done := make(chan bool) go func() { writer.Write([]byte("hello world")) writer.Close() done <- true }() // Drain the reader *after* everything has been written, just to verify // it is indeed buffering <-done output, err := ioutil.ReadAll(bufreader) if err != nil { t.Fatal(err) } if !bytes.Equal(output, []byte("hello world")) { t.Error(string(output)) } }
func TestRegexpTokenizer(t *testing.T) { tokenizer := RegexpTokenizer("[A-Z]+") expected, result := tokenizer("OH hello THERE"), []string{"OH", "THERE"} if !reflect.DeepEqual(expected, result) { t.Error("Expected", expected, "got", result) } }
func TestWatchExit(t *testing.T) { if skipTest(t) { return } tw := newTestWatcher(t) cmd := startSleepCommand(t) childPid := cmd.Process.Pid // watch for exit event of our child process if err := tw.watcher.Watch(childPid, PROC_EVENT_EXIT); err != nil { t.Error(err) } // kill our child process, triggers exit event syscall.Kill(childPid, syscall.SIGTERM) cmd.Wait() tw.close() expectEvents(t, 0, "forks", tw.events.forks) expectEvents(t, 0, "execs", tw.events.execs) if expectEvents(t, 1, "exits", tw.events.exits) { expectEventPid(t, "exit", childPid, tw.events.exits[0]) } }
func TestSuggestedActionAreaUnmarshalData(t *testing.T) { dataMock, err := getDataMock("./testdata/suggested_action_area.json") if err != nil { t.Error(err) } api := SuggestedActionAreaAPI{} api.RawResponse = dataMock result, err := api.unmarshalData() if err != nil { t.Error(err) } if len(result) != 2 { t.Error("Invalid result length: ", len(result)) } fRes := result[0] if fRes.ID != 1 { t.Error("Invalid ID value: ", fRes.ID) } if fRes.Name != "Legal Framework" { t.Error("Invalid Name value: ", fRes.Name) } }
func runCommand(t *testing.T, name string) *exec.Cmd { cmd := exec.Command(name) if err := cmd.Run(); err != nil { t.Error(err) } return cmd }
func Test_Numeric(t *testing.T) { strWant := "0." + strings.Repeat("0123456789", 100)[1:] numWant, _ := big.NewRat(1, 1).SetString(strWant) numParam := param("@num", Numeric, numWant) withStatementResultSet(t, "SELECT @num;", []*Parameter{numParam}, func(rs *ResultSet) { // Use interface{}, so *resultSet.Any will be tested as well. var numHaveInterface interface{} _, err := rs.ScanNext(&numHaveInterface) if err != nil { t.Error("failed to scan next:", err) } numHave, ok := numHaveInterface.(*big.Rat) if !ok { t.Errorf("unexpected type: %T", numHaveInterface) return } strHave := numHave.FloatString(999) if strHave != strWant { t.Errorf("have: %s, but want: %s", strHave, strWant) } }) }
func TestNew(t *testing.T) { config.SetHome(filepath.Join("..", "..", "cmd", "roy", "data")) mi, err := newMIMEInfo() if err != nil { t.Error(err) } tpmap := make(map[string]struct{}) for _, v := range mi { //fmt.Println(v) //if len(v.Magic) > 1 { // fmt.Printf("Multiple magics (%d): %s\n", len(v.Magic), v.MIME) //} for _, c := range v.Magic { for _, d := range c.Matches { tpmap[d.Typ] = struct{}{} if len(d.Mask) > 0 { if d.Typ == "string" { fmt.Println("MAGIC: " + d.Value) } else { fmt.Println("Type: " + d.Typ) } fmt.Println("MASK: " + d.Mask) } } } } /* for k, _ := range tpmap { fmt.Println(k) } */ if len(mi) != 1495 { t.Errorf("expecting %d MIMEInfos, got %d", 1495, len(mi)) } }
func TestSubstitueUser(t *testing.T) { usr, err := user.Current() if err != nil { t.Logf("SKIPPING TEST: unexpected error: %v", err) return } tests := []struct { input string expected string expectErr bool }{ {input: "~/foo", expected: path.Join(os.Getenv("HOME"), "foo")}, {input: "~" + usr.Username + "/bar", expected: usr.HomeDir + "/bar"}, {input: "/foo/bar", expected: "/foo/bar"}, {input: "~doesntexit/bar", expectErr: true}, } for _, test := range tests { output, err := substituteUserHome(test.input) if test.expectErr { if err == nil { t.Error("unexpected non-error") } continue } if err != nil { t.Errorf("unexpected error: %v", err) } if output != test.expected { t.Errorf("expected: %s, saw: %s", test.expected, output) } } }