func TestResolveAndReject(t *testing.T) { c.Convey("When Promise is resolved", t, func() { p := NewPromise() go func() { time.Sleep(50 * time.Millisecond) p.Resolve("ok") }() c.Convey("Should return the argument of Resolve", func() { r, err := p.Get() c.So(r, c.ShouldEqual, "ok") c.So(err, c.ShouldBeNil) }) }) c.Convey("When Promise is rejected", t, func() { p := NewPromise() go func() { time.Sleep(50 * time.Millisecond) p.Reject(errors.New("fail")) }() c.Convey("Should return error", func() { r, err := p.Get() c.So(err, c.ShouldNotBeNil) c.So(r, c.ShouldEqual, nil) }) }) }
func TestCertGen(t *testing.T) { origdir, tmpdir := GenTempDir() //fmt.Printf("attempting to generate certs in tempdir: '%s'\n", tmpdir) defer CleanupTempDir(origdir, tmpdir) cv.Convey("Given a built generate_cert/generate_cert utility program", t, func() { cv.Convey("it should generate certs in our temp directory of the expected file length.", func() { c := exec.Command(origdir + "/generate_cert/generate_cert") _, err := c.Output() if err != nil { panic(err) } certExists, certFi := FileExists(tmpdir + "/cert.pem") keyExists, keyFi := FileExists(tmpdir + "/key.pem") //fmt.Printf("certFi = %#v\n", certFi) //fmt.Printf("keyFi = %#v\n", keyFi) cv.So(certExists, cv.ShouldEqual, true) cv.So(keyExists, cv.ShouldEqual, true) cv.So(certFi.Size(), cv.ShouldEqual, 1074) cv.So(keyFi.Size(), cv.ShouldBeGreaterThan, 1600) }) }) }
func TestOrderBy(t *testing.T) { unsorted := []*foo{&foo{"A", 5}, &foo{"B", 1}, &foo{"C", 3}} sorted := []*foo{&foo{"B", 1}, &foo{"C", 3}, &foo{"A", 5}} sortByNum := func(this T, that T) bool { _this := this.(*foo) _that := that.(*foo) return _this.num <= _that.num } c.Convey("Nil comparator passed", t, func() { _, err := From(unsorted).OrderBy(nil).Results() c.So(err, c.ShouldEqual, ErrNilFunc) }) c.Convey("Previous error is reflected in result", t, func() { _, err := From(unsorted).Where(erroneusBinaryFunc).OrderBy(sortByNum).Results() c.So(err, c.ShouldNotEqual, nil) }) c.Convey("Sort empty", t, func() { res, _ := From(empty).OrderBy(sortByNum).Results() c.So(res, shouldSlicesResemble, empty) }) c.Convey("Sort on structs", t, func() { res, _ := From(unsorted).OrderBy(sortByNum).Results() c.So(res, shouldSlicesResemble, sorted) }) }
func TestGroupBy(t *testing.T) { c.Convey("Group empty slice into empty map", t, func() { res, err := From(empty).GroupBy(func(foo T) T { return foo }, func(foo T) T { return foo }) c.So(err, c.ShouldEqual, nil) c.So(res, c.ShouldResemble, make(map[T][]T)) }) type Pet struct { Name string Owner string } barley := Pet{Name: "Barley", Owner: "Damon Zhao"} boots := Pet{Name: "Boots", Owner: "Damon Zhao"} whiskers := Pet{Name: "Whiskers", Owner: "A-limon"} daisy := Pet{Name: "Daisy", Owner: "A-limon"} sasha := Pet{Name: "Sasha", Owner: "Bob"} pets := []Pet{barley, boots, whiskers, daisy, sasha} groupByExpected := map[T][]T{ "Damon Zhao": []T{barley.Name, boots.Name}, "A-limon": []T{whiskers.Name, daisy.Name}, "Bob": []T{sasha.Name}, } c.Convey("Pets group by owner", t, func() { res, err := From(pets).GroupBy(func(pet T) T { return pet.(Pet).Owner }, func(pet T) T { return pet.(Pet).Name }) c.So(err, c.ShouldEqual, nil) c.So(res, c.ShouldResemble, groupByExpected) }) }
func TestCreateQuestion(t *testing.T) { t_conn.Exec("delete from ebs_question") var qId int64 convey.Convey("CreateQuestion", t, func() { parse := CreateQuestionFunc(1) fmt.Println(parse) qId, _ = strconv.ParseInt(fmt.Sprintf("%v", parse["data"]), 10, 64) var v url.Values = make(map[string][]string) v.Add("id", fmt.Sprintf("%v", parse["data"])) hs := hsBuilder("POST", "", v, 5, "liuqg") GetQuestionInfo(hs) json.Unmarshal(*hs.W.(writer).B, &parse) convey.So(parse["data"].(map[string]interface{})["desc"], convey.ShouldEqual, "desc") }) convey.Convey("CreateQuestion 50", t, func() { parse := CreateQuestionFunc2(1) fmt.Println(parse) qId, _ = strconv.ParseInt(fmt.Sprintf("%v", parse["data"]), 10, 64) var v url.Values = make(map[string][]string) v.Add("id", fmt.Sprintf("%v", parse["data"])) hs := hsBuilder("POST", "", v, 5, "liuqg") GetQuestionInfo(hs) json.Unmarshal(*hs.W.(writer).B, &parse) fmt.Println(parse) // convey.So(parse["data"].(map[string]interface {})["desc"],convey.ShouldEqual,"desc") }) }
func TestAnyWithParallel(t *testing.T) { c.Convey("Previous error is reflected on result", t, func() { _, err := From(arr0).Where(erroneusBinaryFunc).AsParallel().AnyWith(alwaysTrueDelayed) c.So(err, c.ShouldNotEqual, nil) }) c.Convey("Given a nil function, ErrNilFunc is returned", t, func() { _, err := From(arr0).Where(alwaysTrueDelayed).AsParallel().AnyWith(nil) c.So(err, c.ShouldNotEqual, nil) }) c.Convey("An error returned from f is reflected on Result", t, func() { _, err := From(arr0).Where(alwaysTrueDelayed).AsParallel().AnyWith(erroneusBinaryFunc) c.So(err, c.ShouldNotEqual, nil) _, err = From(arr0).Where(alwaysFalse).AsParallel().AnyWith(erroneusBinaryFunc) c.So(err, c.ShouldEqual, nil) }) c.Convey("No matches", t, func() { r, _ := From(arr0).AsParallel().AnyWith(alwaysFalseDelayed) c.So(r, c.ShouldEqual, false) r, _ = From(arr0).AsParallel().Where(alwaysFalseDelayed).Any() c.So(r, c.ShouldEqual, false) }) c.Convey("All matches", t, func() { r, _ := From(arr0).AsParallel().AnyWith(alwaysTrueDelayed) c.So(r, c.ShouldEqual, true) r, _ = From(arr0).AsParallel().Where(alwaysTrueDelayed).Any() c.So(r, c.ShouldEqual, true) }) }
func TestFormat(t *testing.T) { c.Convey("Given format funcs", t, func() { funcs := map[string]func(string, ...interface{}){ "Printf": Printf, "Tracef": Tracef, "Debugf": Debugf, "Infof": Infof, "Warningf": Warningf, "Errorf": Errorf, } writer := &MockWriter{} Writer = writer Level = LevelTrace for name, fun := range funcs { c.Convey(name+" format should work", func() { fun("%s answer: %d", name, 42) c.So(writer.GetLastLog(), c.ShouldEqual, name+" answer: 42") }) } c.Convey("Fatalf format should work", func() { c.So(func() { Fatalf("answer: %d", 42) }, c.ShouldPanic) c.So(writer.GetLastLog(), c.ShouldEqual, "answer: 42") }) }) }
func TestNewUUID(t *testing.T) { uuid := NewUUID() convey.Convey("uuid should not be nil", t, func() { convey.So(uuid, convey.ShouldNotEqual, nil) }) uuid2 := NewUUID() convey.Convey("uuid should not be equl to uuid", t, func() { convey.So(uuid, convey.ShouldNotEqual, uuid2) }) for i := 0; i < 100; i++ { u := NewUUID() str := u.String() version := str[14:15] key := str[19:20] // convey.Convey("uuid Version should not be equl to 4", t, func() { // convey.So(version, convey.ShouldEqual, "4") // }) if version != "4" { t.Error("Version must Be == 4 not ", version, " in ", str) } if key != "8" && key != "9" && key != "a" && key != "b" { t.Error("key must be Equal 8, 9, a, b not:", key, " in ", str) } } }
func TestCountParallel(t *testing.T) { c.Convey("Previous error is reflected on result", t, func() { _, err := From(arr0).AsParallel().Where(erroneusBinaryFunc).CountBy(erroneusBinaryFunc) c.So(err, c.ShouldNotEqual, nil) }) c.Convey("Given a nil function, ErrNilFunc is returned", t, func() { _, err := From(arr0).AsParallel().Where(alwaysTrueDelayed).CountBy(nil) c.So(err, c.ShouldNotEqual, nil) }) c.Convey("An error returned from f is reflected on Result", t, func() { _, err := From(arr0).AsParallel().Where(alwaysTrueDelayed).CountBy(erroneusBinaryFunc) c.So(err, c.ShouldNotEqual, nil) _, err = From(arr0).AsParallel().Where(alwaysFalseDelayed).CountBy(erroneusBinaryFunc) c.So(err, c.ShouldEqual, nil) }) c.Convey("No matches", t, func() { cnt, _ := From(arr0).AsParallel().CountBy(alwaysFalseDelayed) c.So(cnt, c.ShouldEqual, 0) cnt, _ = From(arr0).AsParallel().Where(alwaysFalseDelayed).Count() c.So(cnt, c.ShouldEqual, 0) }) c.Convey("All matches", t, func() { cnt, _ := From(arr0).AsParallel().CountBy(alwaysTrueDelayed) c.So(cnt, c.ShouldEqual, len(arr0)) cnt, _ = From(arr0).AsParallel().Count() c.So(cnt, c.ShouldEqual, len(arr0)) }) }
func TestMailBodyExtraction(t *testing.T) { cv.Convey("Given a GoCD success mail message", t, func() { cv.Convey("we should be able to extract the body", func() { cv.So(BodyOfMail(rawPassedEmail), cv.ShouldEqual, expectedPassedBody) }) }) }
func TestInsert(t *testing.T) { h := offheap.NewHashTable(8) cv.Convey("inserting a non-zero key should enable retrieving them with Lookup", t, func() { cv.So(h.Population, cv.ShouldEqual, 0) cv.So(h.Lookup(23), cv.ShouldEqual, nil) c, ok := h.Insert(23) c.SetInt(55) cv.So(c, cv.ShouldNotEqual, nil) cv.So(ok, cv.ShouldEqual, true) cv.So(h.Population, cv.ShouldEqual, 1) cv.So(h.Lookup(23), cv.ShouldNotEqual, nil) cell := h.Lookup(23) cv.So(cell.Value[0], cv.ShouldEqual, 55) }) h.Clear() cv.Convey("inserting a zero key should also be retrievable with Lookup", t, func() { cv.So(h.Population, cv.ShouldEqual, 0) cv.So(h.Lookup(0), cv.ShouldEqual, nil) c, ok := h.Insert(0) c.SetInt(55) cv.So(c, cv.ShouldNotEqual, nil) cv.So(ok, cv.ShouldEqual, true) cv.So(h.Population, cv.ShouldEqual, 1) cv.So(h.Lookup(0), cv.ShouldNotEqual, nil) cell := h.Lookup(0) cv.So(cell.Value[0], cv.ShouldEqual, 55) }) h.Clear() cv.Convey("Insert()-ing the same key twice should return false for the 2nd param on encountering the same key again. For 0 key.", t, func() { cv.So(h.Population, cv.ShouldEqual, 0) c, ok := h.Insert(0) cv.So(c, cv.ShouldNotEqual, nil) cv.So(c.UnHashedKey, cv.ShouldEqual, 0) cv.So(ok, cv.ShouldEqual, true) c, ok = h.Insert(0) cv.So(c, cv.ShouldNotEqual, nil) cv.So(c.UnHashedKey, cv.ShouldEqual, 0) cv.So(ok, cv.ShouldEqual, false) }) h.Clear() cv.Convey("Insert()-ing the same key twice should return false for the 2nd param on encountering the same key again. For not-zero key.", t, func() { cv.So(h.Population, cv.ShouldEqual, 0) c, ok := h.Insert(1) cv.So(c, cv.ShouldNotEqual, nil) cv.So(c.UnHashedKey, cv.ShouldEqual, 1) cv.So(ok, cv.ShouldEqual, true) c, ok = h.Insert(1) cv.So(c, cv.ShouldNotEqual, nil) cv.So(c.UnHashedKey, cv.ShouldEqual, 1) cv.So(ok, cv.ShouldEqual, false) }) }
func TestErrors(t *testing.T) { con.Convey("Verbose printing tests", t, func() { Verbose = true stdout := os.Stdout fname := filepath.Join(tempDir, "stdout1") temp, err := os.Create(fname) con.So(err, con.ShouldBeNil) os.Stdout = temp testString := "This is a test string" Printf(testString) err = temp.Close() con.So(err, con.ShouldBeNil) output, err := ioutil.ReadFile(fname) con.Convey("We can print to stdout when verbose is enabled", func() { con.So(err, con.ShouldBeNil) con.So(string(output), con.ShouldEqual, testString) }) Verbose = false fname = filepath.Join(tempDir, "stdout1") temp, err = os.Create(fname) con.So(err, con.ShouldBeNil) os.Stdout = temp Printf(testString) err = temp.Close() con.So(err, con.ShouldBeNil) output, err = ioutil.ReadFile(fname) con.Convey("We can not print to stdout when verbose is enabled", func() { con.So(err, con.ShouldBeNil) con.So(string(output), con.ShouldEqual, "") }) os.Stdout = stdout }) con.Convey("Mutually exclusive parameters returns an error in the format we expect", t, func() { err := ErrMutuallyExclusiveParameters("1", "2") con.So(err.Error(), con.ShouldEqual, "Mutually exclusive parameters provided: 1 and 2") }) con.Convey("We can test http formatting", t, func() { testErr := errors.New("Test error") errBytes := FormatHTTPError(testErr, 400) type ErrResp struct { Message string `json:"error"` Code int `json:"status_code"` } fmt.Println(string(errBytes)) errResp := &ErrResp{} err := json.Unmarshal(errBytes, &errResp) con.So(err, con.ShouldBeNil) con.So(errResp.Code, con.ShouldEqual, 400) con.So(errResp.Message, con.ShouldEqual, testErr.Error()) }) }
func TestBadWriter(t *testing.T) { c.Convey("Given bad writer", t, func() { Writer = BadWriter{} c.Convey("Log should not fail", func() { c.So(func() { printString("hi, bad writer") }, c.ShouldNotPanic) }) }) }
func TestGitRevisionRetrieval(t *testing.T) { cv.Convey("Given a GoCD passing email message", t, func() { cv.Convey("the git revision: line should be extracted from the body", func() { parsedEmail := ParseEmail(rawPassedEmail) cv.So(parsedEmail.GitRev, cv.ShouldEqual, "0111df6930fa11a28febde2197b591a5a67fb3e4, modified by Jason E. Aten <*****@*****.**> on 2014-07-21 15:36:00.0") }) }) }
func TestLoadConfig(t *testing.T) { LoadConfig("./", "configTest") convey.Convey("v should not be nil", t, func() { convey.So(v, convey.ShouldNotEqual, nil) }) convey.Convey("v should not be nil", t, func() { convey.So(v, convey.ShouldNotEqual, nil) }) }
func TestCheckArrayInterface(t *testing.T) { log.Print("TestCheckArrayInterface") convey.Convey("CheckMapInterfaceInterface(mapInterface) should be true", t, func() { convey.So(CheckArrayInterface(mapInterface), convey.ShouldEqual, false) }) convey.Convey("CheckMapInterfaceInterface(arrayOfInterface) should be false", t, func() { convey.So(CheckArrayInterface(arrayOfInterface), convey.ShouldEqual, true) }) }
func TestAsyncWrite(t *testing.T) { c.Convey("Given AsyncWriter", t, func() { Writer = NewAsyncWriter() c.Convey("Should return 0 bytes and no error", func() { count, err := Writer.Write([]byte("test")) c.So(count, c.ShouldBeZeroValue) c.So(err, c.ShouldBeNil) }) }) }
func TestWrite(t *testing.T) { c.Convey("Given DefaultWriter", t, func() { Writer = DefaultWriter{} c.Convey("Write should go to stdout", func() { count, err := Writer.Write([]byte("test")) c.So(err, c.ShouldBeNil) c.So(count, c.ShouldEqual, 4) }) }) }
func TestConfig(t *testing.T) { test := Config() convey.Convey("test should not be nil", t, func() { convey.So(test, convey.ShouldNotEqual, nil) }) addr := test.GetString("addr") convey.Convey("addr should not be localhost:8081", t, func() { convey.So(addr, convey.ShouldEqual, "localhost:8081") }) }
func TestCheckMapInterfaceInterface(t *testing.T) { log.Print("TesCheckMapInterfaceInterface") mapInterface = make(map[interface{}]interface{}) convey.Convey("CheckMapInterfaceInterface(mapInterface) should be true", t, func() { convey.So(CheckMapInterfaceInterface(mapInterface), convey.ShouldEqual, true) }) arrayOfInterface = make([]interface{}, 0) convey.Convey("CheckMapInterfaceInterface(arrayOfInterface) should be false", t, func() { convey.So(CheckMapInterfaceInterface(arrayOfInterface), convey.ShouldEqual, false) }) }
func TestCritical(t *testing.T) { c.Convey("Given a MockWriter", t, func() { writer := &MockWriter{} Writer = writer c.Convey("When Level is LevelCritical", func() { Level = LevelCritical c.So(func() { Fatal("fatal") }, c.ShouldPanic) c.So(writer.GetLastLog(), c.ShouldEqual, "fatal") }) }) }
func TestStructToJSON(t *testing.T) { type Account struct{ Name string } convey.Convey("Given I have an instance of a particular struct", t, func() { item := Account{"Diego"} convey.Convey("When I convert it to JSON", func() { converted := from.StructToJSON(item) bytes, _ := json.Marshal(item) convey.So(converted, should.Resemble, bytes) }) }) }
func TestFlags(t *testing.T) { c.Convey("Flags should be parsed and translated to log levels", t, func() { c.Convey("When flag is 'trace'", func() { os.Args = []string{"", "--log-level", "trace"} flag.Parse() c.So(Level.String(), c.ShouldEqual, "trace") c.So(Level, c.ShouldEqual, LevelTrace) }) c.Convey("When flag is 'debug'", func() { os.Args = []string{"", "--log-level", "debug"} flag.Parse() c.So(Level.String(), c.ShouldEqual, "debug") c.So(Level, c.ShouldEqual, LevelDebug) }) c.Convey("When flag is 'info'", func() { os.Args = []string{"", "--log-level", "info"} flag.Parse() c.So(Level.String(), c.ShouldEqual, "info") c.So(Level, c.ShouldEqual, LevelInfo) }) c.Convey("When flag is 'warning'", func() { os.Args = []string{"", "--log-level", "warning"} flag.Parse() c.So(Level.String(), c.ShouldEqual, "warning") c.So(Level, c.ShouldEqual, LevelWarning) }) c.Convey("When flag is 'error'", func() { os.Args = []string{"", "--log-level", "error"} flag.Parse() c.So(Level.String(), c.ShouldEqual, "error") c.So(Level, c.ShouldEqual, LevelError) }) c.Convey("When flag is 'fatal'", func() { os.Args = []string{"", "--log-level", "fatal"} flag.Parse() c.So(Level.String(), c.ShouldEqual, "fatal") c.So(Level, c.ShouldEqual, LevelFatal) }) }) c.Convey("Flags should yield an error", t, func() { Level = LevelInfo c.Convey("When flag is 'incorrect'", func() { args := []string{"--log-level", "incorrect"} flags := flag.NewFlagSet("testing", flag.ContinueOnError) flags.Var(&Level, "log-level", "Log level: trace|debug|info|warning|error|fatal") err := flags.Parse(args) c.So(err.Error(), c.ShouldContainSubstring, "Unknown logging level incorrect") c.So(LogLevel(0).String(), c.ShouldEqual, "unknown") c.So(Level, c.ShouldEqual, LevelInfo) }) }) }
func TestDataIs(t *testing.T) { type Account struct{ Name, Email string } convey.Convey("Given I have an instance of a particular struct", t, func() { item := &Account{"Diego", "*****@*****.**"} convey.Convey("Then subject is the same instance", func() { convey.So(where.DataIs(item)(item), should.BeTrue) }) convey.Convey("Then subject is not the same instace", func() { convey.So(where.DataIs(&Account{})(item), should.BeFalse) }) }) }
func TestJSONToStruct(t *testing.T) { type Account struct{ Name string } convey.Convey("Given I have an instance of a particular struct", t, func() { json := []byte(`{"Name":"Diego"}`) convey.Convey("When I convert it to Struct", func() { converted := from.JSONToStruct(Account{})(json) convey.So(converted, should.Resemble, Account{"Diego"}) converted = from.JSONToStruct(&Account{})(json) convey.So(converted, should.Resemble, &Account{"Diego"}) }) }) }
func TestWrap(t *testing.T) { c.Convey("Test Wrap a value", t, func() { r, err := Wrap(10).Get() c.So(r, c.ShouldEqual, 10) c.So(err, c.ShouldBeNil) }) }
func TestCreatingNewTickSession(t *testing.T) { c.Convey("Given I want to create a new Tick session", t, func() { c.Convey("When the NewTickSession is called with valid variables", func() { tick, _ := NewTickSession("mytoken", "subID", "thisUserAgent") c.Convey("The session should contain the APIToken", func() { c.So(tick.APIToken, c.ShouldEqual, "mytoken") }) c.Convey("The session should contain the SubscriptionID", func() { c.So(tick.SubscriptionID, c.ShouldEqual, "subID") }) c.Convey("The session should contain the UserAgent", func() { c.So(tick.UserAgent, c.ShouldEqual, "thisUserAgent") }) }) }) }
func TestSpec(t *testing.T) { var x int // Only pass t into top-level Convey calls cv.Convey("Given some integer with a starting value", t, func() { x = 1 cv.Convey("When the integer is incremented", func() { x++ cv.Convey("The value should be greater by one", func() { cv.So(x, cv.ShouldEqual, 2) }) }) }) }
func TestFrequency(t *testing.T) { convey.Convey("Given value", t, func() { actual := Note{Note: C, Octave: 5}.Frequency() convey.So(actual, convey.ShouldAlmostEqual, 523.251, 0.001) }) }
func TestHalfStepDistance(t *testing.T) { convey.Convey("Given value", t, func() { expected := 3 convey.So(HalfstepDistance(a4, Note{Note: C, Octave: 5}), convey.ShouldEqual, expected) }) }