本文整理汇总了Golang中lib/wcg.NewAssert函数的典型用法代码示例。如果您正苦于以下问题:Golang NewAssert函数的具体用法?Golang NewAssert怎么用?Golang NewAssert使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewAssert函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Test_PT1Recorder_Retry
func Test_PT1Recorder_Retry(t *testing.T) {
assert := wcg.NewAssert(t)
iepg := &pt.IEPG{}
iepg.ProgramTitle = "test"
iepg.StartAt = lib.Now()
iepg.EndAt = lib.Now().Add(3 * time.Second)
cfg := newPT1RecorderConfig()
cfg.Recpt1Path = "./fixtures/pt1commands/fail.sh"
notifier := &testNotifier{}
recorder := NewPT1Recorder(iepg, cfg, notifier)
go recorder.Start()
time.Sleep(500 * time.Millisecond)
stats := recorder.GetStats()
assert.EqInt(
int(pt.IEPGProcessing), int(stats.Status),
"recorder status should be pt.IEPGCanceled",
)
// change the recpt1path to the correct one to succeed.
cfg.Recpt1Path = "./fixtures/pt1commands/simple.sh"
time.Sleep(2800 * time.Millisecond)
assert.EqInt(
int(pt.IEPGCompleted), int(stats.Status),
"recorder status should be pt.IEPGCompleted",
)
assert.EqInt(3, int(stats.EndAt.Sub(stats.StartAt).Seconds()), "recorder should be cancled in about 3 seconds (actual=%f)", stats.EndAt.Sub(stats.StartAt).Seconds())
assert.GtInt(0, stats.Retries, "recorder should retry the command")
assert.OK(notifier.StartNotified, "notifier should be notified on start.")
assert.OK(notifier.EndNotified, "notifier should be notified on end.")
}
示例2: Test_Do_MaxRetries
func Test_Do_MaxRetries(t *testing.T) {
assert := wcg.NewAssert(t)
var interval = Interval(100 * time.Millisecond)
var i = 0
var max = MaxRetries(15)
err := Do(func() error {
i++
if i < 10 {
return fmt.Errorf("Need retry")
}
return nil
}, interval, max)
assert.Nil(err)
assert.EqInt(10, i)
i = 0
max = MaxRetries(3)
err = Do(func() error {
i++
if i < 10 {
return fmt.Errorf("Need retry")
}
return nil
}, interval, max)
assert.NotNil(err)
assert.OK(i == 3)
}
示例3: TestSessionSupport
func TestSessionSupport(t *testing.T) {
assert := wcg.NewAssert(t)
// default configugration
cfg := SessionConfigIni
load, save := SessionSupport()
r, _ := http.NewRequest("GET", "http://example.com/foo", nil)
req := wcg.NewRequest(r)
w := httptest.NewRecorder()
res := wcg.NewResponse(w, req)
load.Process(res, req)
assert.NotNil(req.Session, "req.Session with SessionSupport")
// application set the sessoin data.
req.Session.Set("foo", "bar")
// Check set-cookie header on response, which should include signed session id.
c := wcg.ParseCookie(w.Header().Get("set-cookie"))
assert.EqStr(cfg.CookieName, c.Name, "Issued cookie name")
assert.NotZero(c.Value, "Issued cookie value")
// Run save handler.
save.Process(res, req)
// Another request is coming with the same session id.
r, _ = http.NewRequest("GET", "http://example.com/foo", nil)
r.Header.Set("cookie", c.String())
req = wcg.NewRequest(r)
w = httptest.NewRecorder()
res = wcg.NewResponse(w, req)
load.Process(res, req)
val, _ := req.Session.Get("foo")
assert.EqStr("bar", val, "Stored value check")
}
示例4: TestSessionSupport_Expire
func TestSessionSupport_Expire(t *testing.T) {
assert := wcg.NewAssert(t)
// default configugration
cfg := &SessionConfig{
StoreFactory: nil,
Key: "wcgsess",
MaxAge: 1, // 3 seconds
CookieName: "wcgsess",
Domain: "",
HTTPOnly: true,
Path: "/",
}
load, save := SessionSupportWithConfig(cfg)
r, _ := http.NewRequest("GET", "http://example.com/foo", nil)
req := wcg.NewRequest(r)
w := httptest.NewRecorder()
res := wcg.NewResponse(w, req)
load.Process(res, req)
req.Session.Set("foo", "bar")
save.Process(res, req)
sid1 := req.Session.ID
time.Sleep(1 * time.Second)
// Another request is coming with the same cookie.
c := wcg.ParseCookie(w.Header().Get("set-cookie"))
r, _ = http.NewRequest("GET", "http://example.com/foo", nil)
r.Header.Set("cookie", c.String())
req = wcg.NewRequest(r)
w = httptest.NewRecorder()
res = wcg.NewResponse(w, req)
load.Process(res, req)
sid2 := req.Session.ID
assert.Not(sid1 == sid2, "Keep session")
}
示例5: Test_parseUserFeed
func Test_parseUserFeed(t *testing.T) {
assert := wcg.NewAssert(t)
f, err := os.Open("./fixtures/Test_parseUserFeed.xml")
assert.Nil(err, "Open fixture file")
defer f.Close()
albums, err := parseUserFeed(f)
assert.Nil(err, "parseAlbums should return no error.")
assert.EqInt(2, len(albums), "len(albums)")
assert.EqStr("1000000487409559", albums[0].ID, "albums[0].ID")
assert.EqStr("自動バックアップ", albums[0].Title, "albums[0].Title")
assert.EqStr("109784491874587409559", albums[0].AuthorID, "albums[0].AuthorID")
assert.EqStr("Yohei Sasaki", albums[0].AuthorName, "albums[0].AuthorName")
publishedAt, _ := wcg.ParseDateTime("2015-11-29T11:03:42.000Z")
updatedAt, _ := wcg.ParseDateTime("2015-11-29T15:32:17.582Z")
assert.EqTime(publishedAt, *albums[0].PublishedAt, "albums[0].PublishedAt")
assert.EqTime(updatedAt, *albums[0].UpdatedAt, "albums[0].UpdatedAt")
assert.EqStr("6173825975323480657", albums[1].ID, "albums[0].ID")
assert.EqStr("2015/07/21", albums[1].Title, "albums[0].Title")
assert.EqStr("109784491874587409559", albums[1].AuthorID, "albums[0].AuthorID")
assert.EqStr("Yohei Sasaki", albums[1].AuthorName, "albums[0].AuthorName")
publishedAt, _ = wcg.ParseDateTime("2015-07-21T05:17:55.000Z")
updatedAt, _ = wcg.ParseDateTime("2015-07-21T05:38:48.016Z")
assert.EqTime(publishedAt, *albums[1].PublishedAt, "albums[0].PublishedAt")
assert.EqTime(updatedAt, *albums[1].UpdatedAt, "albums[0].UpdatedAt")
}
示例6: TestMax
func TestMax(t *testing.T) {
type TestObject struct {
Str string
Int int
Float float32
Array []string
}
assert := wcg.NewAssert(t)
obj := &TestObject{}
v := NewObjectValidator()
v.Field("Str").Max(1)
v.Field("Int").Max(1)
v.Field("Float").Max(1)
v.Field("Array").Max(1)
obj.Str = "Foo"
obj.Int = 5
obj.Float = 5
obj.Array = []string{"a", "b", "c", "d"}
result := v.Eval(obj)
assert.NotNil(result.Errors["Str"], "ValidationError should claims on 'Str'")
assert.NotNil(result.Errors["Int"], "ValidationError should claims on 'Int'")
assert.NotNil(result.Errors["Float"], "ValidationError should claims on 'Float'")
assert.NotNil(result.Errors["Array"], "ValidationError should claims on 'Arrau'")
assert.EqStr("must be less than or equal to 1", result.Errors["Str"][0].String(), "ValidationError Error message")
assert.EqStr("must be less than or equal to 1", result.Errors["Int"][0].String(), "ValidationError Error message")
assert.EqStr("must be less than or equal to 1", result.Errors["Float"][0].String(), "ValidationError Error message")
assert.EqStr("must be less than or equal to 1", result.Errors["Array"][0].String(), "ValidationError Error message")
obj.Str = "F"
obj.Int = 1
obj.Float = 1
obj.Array = []string{"a"}
assert.Nil(v.Eval(obj), "Eval(obj) should return nil when validation passed.")
}
示例7: Test_CollectFilesystemStats
func Test_CollectFilesystemStats(t *testing.T) {
assert := wcg.NewAssert(t)
stats, err := CollectFileSystemStats("./fixtures/df.sh")
assert.Nil(err, "CollectFileSystemStats should not return an error")
assert.EqInt(2, len(stats), "CollectFileSystemStats should return 2 stats")
}
示例8: TestIOLogSinkFormat
func TestIOLogSinkFormat(t *testing.T) {
assert := wcg.NewAssert(t)
record := NewTestRecord()
storage := NewTestLogStorage()
s := NewIOLogSink("", storage, false)
s.Write(record)
assert.NotZero(len(storage.GetLines()), "sink.Write should write a log record")
line := storage.GetLines()[0]
expect := fmt.Sprintf(
"1984/09/22 12:01:28 +0000 [TRACE] [1|user1|%s|%s] This is a test (sourec.go#1)",
record.SessionID.Shorten(),
record.RequestID.Shorten(),
)
assert.EqStr(expect, line, "LogRecord format")
// custom format
storage = NewTestLogStorage()
s = NewIOLogSink("$TIMESTAMP $INVALIDVAR $TEXT", storage, false)
s.Write(record)
assert.NotZero(len(storage.GetLines()), "sink.Write should write a log record")
line = storage.GetLines()[0]
expect = "1984/09/22 12:01:28 +0000 !UNDEFINED This is a test"
assert.EqStr(expect, line, "LogRecord format")
// Data record case.
storage = NewTestLogStorage()
s = NewIOLogSink("", storage, false)
record.Data = wcg.DataBag{}
s.Write(record)
assert.Zero(len(storage.GetLines()), "sink.Write should not write anything if the record has DataBag")
}
示例9: Test_Do_Until
func Test_Do_Until(t *testing.T) {
assert := wcg.NewAssert(t)
var interval = Interval(100 * time.Millisecond)
var i = 0
var ut = time.Now().Add(3 * time.Second)
var until = Until(ut)
err := Do(func() error {
i++
if i < 10 {
return fmt.Errorf("Need retry")
}
return nil
}, interval, until)
assert.Nil(err)
assert.OK(time.Now().Before(ut))
assert.EqInt(10, i)
i = 0
ut = time.Now().Add(500 * time.Millisecond)
until = Until(ut)
err = Do(func() error {
i++
if i < 10 {
return fmt.Errorf("Need retry")
}
return nil
}, interval, until)
assert.NotNil(err)
assert.OK(time.Now().After(ut))
assert.OK(i > 1)
assert.OK(i < 10)
}
示例10: TestMatch
func TestMatch(t *testing.T) {
type TestObject struct {
Str string
Bytes []byte
}
assert := wcg.NewAssert(t)
obj := &TestObject{}
v := NewObjectValidator()
v.Field("Str").Match("a+")
v.Field("Bytes").Match("a+")
result := v.Eval(obj)
assert.NotNil(result.Errors["Str"], "ValidationError should claims on 'Str'")
assert.NotNil(result.Errors["Bytes"], "ValidationError should claims on 'Bytes'")
assert.EqStr("not match with 'a+'", result.Errors["Str"][0].String(), "ValidationError Error message")
assert.EqStr("not match with 'a+'", result.Errors["Bytes"][0].String(), "ValidationError Error message")
obj.Str = "bbb"
obj.Bytes = []byte(obj.Str)
result = v.Eval(obj)
assert.NotNil(result, "Eval(obj) should return ValidationError")
assert.NotNil(result.Errors["Str"], "ValidationError should claims on 'Str'")
assert.NotNil(result.Errors["Bytes"], "ValidationError should claims on 'Bytes'")
assert.EqStr("not match with 'a+'", result.Errors["Str"][0].String(), "ValidationError Error message")
assert.EqStr("not match with 'a+'", result.Errors["Bytes"][0].String(), "ValidationError Error message")
obj.Str = "aaa"
obj.Bytes = []byte(obj.Str)
assert.Nil(v.Eval(obj), "Eval(obj) should return nil when validation passed.")
}
示例11: Test_PT1Recorder_ShortenTime
func Test_PT1Recorder_ShortenTime(t *testing.T) {
assert := wcg.NewAssert(t)
iepg := &pt.IEPG{}
iepg.ProgramTitle = "test"
iepg.StartAt = lib.Now()
iepg.EndAt = lib.Now().Add(10 * time.Second)
iepg2 := &pt.IEPG{}
iepg2.ProgramTitle = "test"
iepg2.StartAt = iepg.StartAt
iepg2.EndAt = iepg.EndAt.Add(-8 * time.Second)
notifier := &testNotifier{}
recorder := NewPT1Recorder(iepg, newPT1RecorderConfig(), notifier)
go recorder.Start()
stats := recorder.GetStats()
time.Sleep(500 * time.Millisecond)
recorder.Update(iepg2)
time.Sleep(500 * time.Millisecond)
assert.EqInt(
int(pt.IEPGProcessing), int(stats.Status),
"recorder status should be pt.IEPGCanceled",
)
time.Sleep(2 * time.Second)
assert.EqInt(
int(pt.IEPGCompleted), int(stats.Status),
"recorder status should be pt.IEPGCompleted",
)
assert.EqInt(2, int(stats.EndAt.Sub(stats.StartAt).Seconds()), "recorder should be cancled in about 4 seconds (actual=%f)", stats.EndAt.Sub(stats.StartAt).Seconds())
assert.OK(notifier.StartNotified, "notifier should be notified on start.")
assert.OK(notifier.EndNotified, "notifier should be notified on end.")
}
示例12: TestObjectValidation
func TestObjectValidation(t *testing.T) {
type TestObject struct {
Str1 string
Str2 string
}
assert := wcg.NewAssert(t)
obj := &TestObject{}
v := NewObjectValidator()
v.Func(func(v interface{}) *FieldValidationError {
obj := v.(*TestObject)
if obj.Str1 == obj.Str2 {
return NewFieldValidationError(
"Same!!", nil,
)
}
return nil
})
obj.Str1 = "foo"
obj.Str2 = "foo"
result := v.Eval(obj)
assert.NotNil(result.Errors["."], "ValidationError should claims on 'Str'")
assert.EqStr("Same!!", result.Errors["."][0].String(), "ValidationError Error message")
obj.Str2 = "bar"
assert.Nil(v.Eval(obj), "Eval(obj) should return nil when validation passed.")
}
示例13: Test_Agent_Recorder_Cancel
func Test_Agent_Recorder_Cancel(t *testing.T) {
var agent *Agent
var r Recorder
assert := wcg.NewAssert(t)
now, _ := wcg.ParseDateTime("2016-05-15T16:05:00Z")
httptest.StartMockServer(func(mock *httptest.MockServer) {
mock.Routes().GET("/api/intern/pt/iepg/records/", middleware.ServeFile("./fixtures/mocks/agent_tests.json"))
agent = NewAgent(mock.BaseURL(), "test-token", nil)
agent.recorderFactory = func(iepg *pt.IEPG) Recorder {
return NewMockRecorder(iepg)
}
lib.TemporarySetNow(now, func() {
agent.RunOnce()
time.Sleep(100 * time.Millisecond)
r = agent.recorders["200171201605160105"]
assert.EqInt(1, len(agent.recorders), "agent should have a recorder thread.")
assert.EqInt(int(pt.IEPGProcessing), int(r.GetStats().Status), "the recorder status should be pt.IEPGProcessing.")
})
})
httptest.StartMockServer(func(mock *httptest.MockServer) {
// preparation for dummy entry
mock.Routes().GET("/api/intern/pt/iepg/records/", middleware.ServeFile("./fixtures/mocks/agent_tests_no_data.json"))
agent.subscriber = NewSubscriber(mock.BaseURL(), "test-token")
lib.TemporarySetNow(now, func() {
agent.RunOnce()
time.Sleep(100 * time.Millisecond)
assert.EqInt(0, len(agent.recorders), "agent should have no recorder thread.")
assert.EqInt(int(r.GetStats().Status), int(pt.IEPGCanceled), "the recorder status should be pt.IEPGPRocessing.")
})
})
}
示例14: Test_parsePhotoFeed
func Test_parsePhotoFeed(t *testing.T) {
assert := wcg.NewAssert(t)
f, err := os.Open("./fixtures/Test_parsePhotoFeed.xml")
assert.Nil(err, "Open fixture file")
defer f.Close()
media, err := parsePhotoFeed(f)
assert.Nil(err, "parseMedia should return no error.")
assert.EqInt(4, len(media.Contents), "len(media[0].Contents)")
}
示例15: Test_TodayInLocation
func Test_TodayInLocation(t *testing.T) {
assert := wcg.NewAssert(t)
TemporarySetNow(nowValue, func() {
now := TodayInLocation(JST)
assert.EqInt(2015, now.Year(), "Year")
assert.EqInt(2, int(now.Month()), "Month")
assert.EqInt(13, now.Day(), "Day")
assert.EqInt(0, now.Hour(), "Hour")
assert.EqInt(0, now.Minute(), "Mintues")
assert.EqStr("JST", now.Location().String(), "Location")
})
}