本文整理汇总了Golang中github.com/stretchr/testify/assert.EqualValues函数的典型用法代码示例。如果您正苦于以下问题:Golang EqualValues函数的具体用法?Golang EqualValues怎么用?Golang EqualValues使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了EqualValues函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: TestExtentCompleteRequiredLengths
func TestExtentCompleteRequiredLengths(t *testing.T) {
info := &metainfo.InfoEx{
Info: metainfo.Info{
Files: []metainfo.FileInfo{
{Path: []string{"a"}, Length: 2},
{Path: []string{"b"}, Length: 3},
},
},
}
assert.Empty(t, extentCompleteRequiredLengths(&info.Info, 0, 0))
assert.EqualValues(t, []metainfo.FileInfo{
{Path: []string{"a"}, Length: 1},
}, extentCompleteRequiredLengths(&info.Info, 0, 1))
assert.EqualValues(t, []metainfo.FileInfo{
{Path: []string{"a"}, Length: 2},
}, extentCompleteRequiredLengths(&info.Info, 0, 2))
assert.EqualValues(t, []metainfo.FileInfo{
{Path: []string{"a"}, Length: 2},
{Path: []string{"b"}, Length: 1},
}, extentCompleteRequiredLengths(&info.Info, 0, 3))
assert.EqualValues(t, []metainfo.FileInfo{
{Path: []string{"b"}, Length: 2},
}, extentCompleteRequiredLengths(&info.Info, 2, 2))
assert.EqualValues(t, []metainfo.FileInfo{
{Path: []string{"b"}, Length: 3},
}, extentCompleteRequiredLengths(&info.Info, 4, 1))
assert.Len(t, extentCompleteRequiredLengths(&info.Info, 5, 0), 0)
assert.Panics(t, func() { extentCompleteRequiredLengths(&info.Info, 6, 1) })
}
开发者ID:ymonk,项目名称:torrent,代码行数:30,代码来源:file_misc_test.go
示例2: TestSpecialFileAttrs
func (suite *FsTestSuite) TestSpecialFileAttrs() {
assert := suite.assert
cases := []struct {
filename string
size int
mode int
}{
{"", 4096, 0755 | fuse.S_IFDIR},
{".version", len(keywhizfs.VERSION), 0444 | fuse.S_IFREG},
{".running", -1, 0444 | fuse.S_IFREG},
{".clear_cache", 0, 0440 | fuse.S_IFREG},
{".json", 4096, 0700 | fuse.S_IFDIR},
{".json/secret", 4096, 0700 | fuse.S_IFDIR},
{".json/secrets", -1, 0400 | fuse.S_IFREG},
}
for _, c := range cases {
attr, status := suite.fs.GetAttr(c.filename, nil)
assert.Equal(fuse.OK, status, "Expected %v attr status to be fuse.OK", c.filename)
assert.EqualValues(c.mode, attr.Mode, "Expected %v mode %#o, was %#o", c.filename, c.mode, attr.Mode)
if c.size >= 0 {
assert.EqualValues(c.size, attr.Size, "Expected %v size %d, was %d", c.filename, c.size, attr.Size)
}
}
}
开发者ID:mcpherrinm,项目名称:keywhiz-fs,代码行数:26,代码来源:fs_test.go
示例3: testSize
func testSize(t *testing.T, size int) {
var b bytes.Buffer
text := string(bytes.Repeat([]byte("a"), size))
payload := bytes.Repeat([]byte{1}, size)
w := bufio.NewWriter(&b)
err := WritePacket(w, &Packet{
Text: text,
Seq: 1234,
Payload: payload,
})
assert.Nil(t, err)
// log.Println("size:", size)
// for i := 0; i < len(b.Bytes()) && i < 255; i++ {
// fmt.Printf("%02x ", b.Bytes()[i])
// }
// fmt.Println("")
var pkt Packet
r := bufio.NewReader(&b)
err = ReadPacket(r, &pkt)
assert.Nil(t, err)
assert.EqualValues(t, len([]byte(text)), pkt.LengthText)
assert.EqualValues(t, len(payload), pkt.LengthPayload)
assert.EqualValues(t, 1234, pkt.Seq)
assert.EqualValues(t, text, pkt.Text)
assert.EqualValues(t, payload, pkt.Payload)
}
开发者ID:guileen,项目名称:xbp,代码行数:27,代码来源:parser_test.go
示例4: TestParse24
func TestParse24(t *testing.T) {
var mongodb MongoDBPlugin
stub2_4_14 := `
{"asserts":{"msg":0,"regular":0,"rollovers":0,"user":0,"warning":0},"backgroundFlushing":{"average_ms":0.6153846153846154,"flushes":26,"last_finished":"2015-08-17T14:55:58.622+09:00","last_ms":0,"total_ms":16},"connections":{"available":818,"current":1,"totalCreated":10},"cursors":{"clientCursors_size":0,"timedOut":0,"totalOpen":0},"dur":{"commits":30,"commitsInWriteLock":0,"compression":0,"earlyCommits":0,"journaledMB":0,"timeMs":{"dt":3074,"prepLogBuffer":0,"remapPrivateView":0,"writeToDataFiles":0,"writeToJournal":0},"writeToDataFilesMB":0},"extra_info":{"heap_usage_bytes":62256840,"note":"fields vary by platform","page_faults":181},"globalLock":{"activeClients":{"readers":0,"total":0,"writers":0},"currentQueue":{"readers":0,"total":0,"writers":0},"lockTime":143869,"totalTime":1603601000},"host":"bcd5355930ff","indexCounters":{"accesses":0,"hits":5,"missRatio":0,"misses":0,"resets":0},"localTime":"2015-08-17T14:56:42.209+09:00","locks":{".":{"timeAcquiringMicros":{"R":66884,"W":12244},"timeLockedMicros":{"R":86058,"W":143869}},"admin":{"timeAcquiringMicros":{},"timeLockedMicros":{}},"local":{"timeAcquiringMicros":{"r":513,"w":0},"timeLockedMicros":{"r":11886,"w":0}}},"mem":{"bits":64,"mapped":80,"mappedWithJournal":160,"resident":38,"supported":true,"virtual":341},"metrics":{"document":{"deleted":0,"inserted":1,"returned":0,"updated":0},"getLastError":{"wtime":{"num":0,"totalMillis":0},"wtimeouts":0},"operation":{"fastmod":0,"idhack":0,"scanAndOrder":0},"queryExecutor":{"scanned":0},"record":{"moves":0},"repl":{"apply":{"batches":{"num":0,"totalMillis":0},"ops":0},"buffer":{"count":0,"maxSizeBytes":268435456,"sizeBytes":0},"network":{"bytes":0,"getmores":{"num":0,"totalMillis":0},"ops":0,"readersCreated":0},"oplog":{"insert":{"num":0,"totalMillis":0},"insertBytes":0},"preload":{"docs":{"num":0,"totalMillis":0},"indexes":{"num":0,"totalMillis":0}}},"ttl":{"deletedDocuments":0,"passes":26}},"network":{"bytesIn":1940,"bytesOut":18064,"numRequests":33},"ok":1,"opcounters":{"command":35,"delete":0,"getmore":0,"insert":1,"query":26,"update":0},"opcountersRepl":{"command":0,"delete":0,"getmore":0,"insert":0,"query":0,"update":0},"pid":1,"process":"mongod","recordStats":{"accessesNotInMemory":0,"local":{"accessesNotInMemory":0,"pageFaultExceptionsThrown":0},"pageFaultExceptionsThrown":0},"uptime":1604,"uptimeEstimate":1581,"uptimeMillis":1603600,"version":"2.4.14","writeBacksQueued":false}
`
var v interface{}
err := json.Unmarshal([]byte(stub2_4_14), &v)
if err != nil {
t.Errorf("Error: %s", err.Error())
}
bsonStats, err := bson.Marshal(v)
if err != nil {
t.Errorf("Error: %s", err.Error())
}
var m bson.M
err = bson.Unmarshal(bsonStats, &m)
if err != nil {
t.Errorf("Error: %s", err.Error())
}
stat, err := mongodb.parseStatus(m)
fmt.Println(stat)
assert.Nil(t, err)
// Mongodb Stats
assert.EqualValues(t, reflect.TypeOf(stat["btree_hits"]).String(), "float64")
assert.EqualValues(t, stat["btree_hits"], 5.0)
}
开发者ID:supercaracal,项目名称:mackerel-agent-plugins,代码行数:28,代码来源:mongodb_test.go
示例5: TestStoreSlice
func TestStoreSlice(t *testing.T) {
storeSlice := store.StoreSlice{
store.MustNewStore(
&store.TableStore{StoreID: 1, Code: dbr.NewNullString("de"), WebsiteID: 1, GroupID: 1, Name: "Germany", SortOrder: 10, IsActive: true},
&store.TableWebsite{WebsiteID: 1, Code: dbr.NewNullString("admin"), Name: dbr.NewNullString("Admin"), SortOrder: 0, DefaultGroupID: 0, IsDefault: dbr.NewNullBool(false)},
&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "Default", RootCategoryID: 0, DefaultStoreID: 0},
),
nil,
store.MustNewStore(
&store.TableStore{StoreID: 5, Code: dbr.NewNullString("au"), WebsiteID: 2, GroupID: 3, Name: "Australia", SortOrder: 10, IsActive: true},
&store.TableWebsite{WebsiteID: 2, Code: dbr.NewNullString("oz"), Name: dbr.NewNullString("OZ"), SortOrder: 20, DefaultGroupID: 3, IsDefault: dbr.NewNullBool(false)},
&store.TableGroup{GroupID: 3, WebsiteID: 2, Name: "Australia", RootCategoryID: 2, DefaultStoreID: 5},
),
}
assert.True(t, storeSlice.Len() == 3)
assert.EqualValues(t, utils.Int64Slice{1, 5}, storeSlice.IDs())
assert.EqualValues(t, utils.StringSlice{"de", "au"}, storeSlice.Codes())
assert.EqualValues(t, 5, storeSlice.LastItem().Data.StoreID)
assert.Nil(t, (store.StoreSlice{}).LastItem())
storeSlice2 := storeSlice.Filter(func(s *store.Store) bool {
return s.Website.Data.WebsiteID == 2
})
assert.True(t, storeSlice2.Len() == 1)
assert.Equal(t, "au", storeSlice2[0].Data.Code.String)
assert.EqualValues(t, utils.Int64Slice{5}, storeSlice2.IDs())
assert.EqualValues(t, utils.StringSlice{"au"}, storeSlice2.Codes())
assert.Nil(t, (store.StoreSlice{}).IDs())
assert.Nil(t, (store.StoreSlice{}).Codes())
}
开发者ID:levcom,项目名称:csfw,代码行数:32,代码来源:store_test.go
示例6: TestReadDirTrailingSlash
func TestReadDirTrailingSlash(t *testing.T) {
client := getClient(t)
mkdirp(t, "/_test/fulldir2")
mkdirp(t, "/_test/fulldir2/dir")
touch(t, "/_test/fulldir2/1")
touch(t, "/_test/fulldir2/2")
touch(t, "/_test/fulldir2/3")
res, err := client.ReadDir("/_test/fulldir2/")
require.NoError(t, err)
require.Equal(t, len(res), 4)
assert.EqualValues(t, "1", res[0].Name())
assert.False(t, res[0].IsDir())
assert.EqualValues(t, "2", res[1].Name())
assert.False(t, res[1].IsDir())
assert.EqualValues(t, "3", res[2].Name())
assert.False(t, res[2].IsDir())
assert.EqualValues(t, "dir", res[3].Name())
assert.True(t, res[3].IsDir())
}
开发者ID:erimatnor,项目名称:hdfs,代码行数:25,代码来源:readdir_test.go
示例7: TestParse32
func TestParse32(t *testing.T) {
var mongodb MongoDBPlugin
stub3_2_0 := `
{"host":"mbp13.local","advisoryHostFQDNs":["mbp13.local"],"version":"3.2.0","process":"mongod","pid":20843,"uptime":725,"uptimeMillis":724266,"uptimeEstimate":625,"localTime":"2016-01-06T08:02:12.187Z","asserts":{"regular":0,"warning":0,"msg":0,"user":0,"rollovers":0},"connections":{"current":1,"available":2047,"totalCreated":26},"extra_info":{"note":"fieldsvarybyplatform","page_faults":457},"globalLock":{"totalTime":724259000,"currentQueue":{"total":0,"readers":0,"writers":0},"activeClients":{"total":8,"readers":0,"writers":0}},"locks":{"Global":{"acquireCount":{"r":400,"w":2,"W":4}},"Database":{"acquireCount":{"r":197,"W":2}},"Collection":{"acquireCount":{"r":197}},"Metadata":{"acquireCount":{"w":1}}},"network":{"bytesIn":11962,"bytesOut":419980,"numRequests":174},"opcounters":{"insert":0,"query":1,"update":0,"delete":0,"getmore":0,"command":175},"opcountersRepl":{"insert":0,"query":0,"update":0,"delete":0,"getmore":0,"command":0},"storageEngine":{"name":"wiredTiger","supportsCommittedReads":true},"wiredTiger":{"uri":"statistics:","LSM":{"sleepforLSMcheckpointthrottle":0,"sleepforLSMmergethrottle":0,"rowsmergedinanLSMtree":0,"applicationworkunitscurrentlyqueued":0,"mergeworkunitscurrentlyqueued":0,"treequeuehitmaximum":0,"switchworkunitscurrentlyqueued":0,"treemaintenanceoperationsscheduled":0,"treemaintenanceoperationsdiscarded":0,"treemaintenanceoperationsexecuted":0},"async":{"numberofallocationstateraces":0,"numberofoperationslotsviewedforallocation":0,"currentworkqueuelength":0,"numberofflushcalls":0,"numberoftimesoperationallocationfailed":0,"maximumworkqueuelength":0,"numberoftimesworkerfoundnowork":0,"totalallocations":0,"totalcompactcalls":0,"totalinsertcalls":0,"totalremovecalls":0,"totalsearchcalls":0,"totalupdatecalls":0},"block-manager":{"mappedbytesread":0,"bytesread":4096,"byteswritten":86016,"mappedblocksread":0,"blockspre-loaded":0,"blocksread":1,"blockswritten":19},"cache":{"trackeddirtybytesinthecache":0,"trackedbytesbelongingtointernalpagesinthecache":1398,"bytescurrentlyinthecache":16143,"trackedbytesbelongingtoleafpagesinthecache":14745,"maximumbytesconfigured":9663676416,"trackedbytesbelongingtooverflowpagesinthecache":0,"bytesreadintocache":0,"byteswrittenfromcache":13061,"pagesevictedbyapplicationthreads":0,"checkpointblockedpageeviction":0,"unmodifiedpagesevicted":0,"pagesplitduringevictiondeepenedthetree":0,"modifiedpagesevicted":0,"pagesselectedforevictionunabletobeevicted":0,"pagesevictedbecausetheyexceededthein-memorymaximum":0,"pagesevictedbecausetheyhadchainsofdeleteditems":0,"failedevictionofpagesthatexceededthein-memorymaximum":0,"hazardpointerblockedpageeviction":0,"internalpagesevicted":0,"maximumpagesizeateviction":0,"evictionservercandidatequeueemptywhentoppingup":0,"evictionservercandidatequeuenotemptywhentoppingup":0,"evictionserverevictingpages":0,"evictionserverpopulatingqueue,butnotevictingpages":0,"evictionserverunabletoreachevictiongoal":0,"internalpagessplitduringeviction":0,"leafpagessplitduringeviction":0,"pageswalkedforeviction":0,"evictionworkerthreadevictingpages":0,"in-memorypagesplits":0,"in-memorypagepassedcriteriatobesplit":0,"lookasidetableinsertcalls":0,"lookasidetableremovecalls":0,"percentageoverhead":8,"trackeddirtypagesinthecache":0,"pagescurrentlyheldinthecache":11,"pagesreadintocache":0,"pagesreadintocacherequiringlookasideentries":0,"pageswrittenfromcache":12,"pagewrittenrequiringlookasiderecords":0,"pageswrittenrequiringin-memoryrestoration":0},"connection":{"pthreadmutexconditionwaitcalls":90553,"filescurrentlyopen":9,"memoryallocations":12590,"memoryfrees":12013,"memoryre-allocations":2360,"totalreadI/Os":8,"pthreadmutexsharedlockread-lockcalls":951,"pthreadmutexsharedlockwrite-lockcalls":706,"totalwriteI/Os":44},"cursor":{"cursorcreatecalls":131,"cursorinsertcalls":25,"cursornextcalls":13,"cursorprevcalls":3,"cursorremovecalls":0,"cursorresetcalls":56,"cursorrestartedsearches":0,"cursorsearchcalls":145,"cursorsearchnearcalls":1,"truncatecalls":0,"cursorupdatecalls":0},"data-handle":{"connectiondatahandlescurrentlyactive":6,"sessiondhandlesswept":0,"sessionsweepattempts":20,"connectionsweepdhandlesclosed":0,"connectionsweepcandidatebecamereferenced":0,"connectionsweepdhandlesremovedfromhashlist":1,"connectionsweeptime-of-deathsets":1,"connectionsweeps":72},"log":{"totallogbuffersize":33554432,"logbytesofpayloaddata":7566,"logbyteswritten":9856,"yieldswaitingforpreviouslogfileclose":0,"totalsizeofcompressedrecords":5927,"totalin-memorysizeofcompressedrecords":10292,"logrecordstoosmalltocompress":10,"logrecordsnotcompressed":7,"logrecordscompressed":8,"logflushoperations":7037,"maximumlogfilesize":104857600,"pre-allocatedlogfilesprepared":2,"numberofpre-allocatedlogfilestocreate":2,"pre-allocatedlogfilesnotreadyandmissed":1,"pre-allocatedlogfilesused":0,"logreleaseadvanceswriteLSN":8,"recordsprocessedbylogscan":0,"logscanrecordsrequiringtworeads":0,"logscanoperations":0,"consolidatedslotclosures":20847,"writtenslotscoalesced":0,"loggingbytesconsolidated":9472,"consolidatedslotjoins":25,"consolidatedslotjoinraces":0,"busyreturnsattemptingtoswitchslots":0,"consolidatedslotjointransitions":20847,"consolidatedslotunbufferedwrites":0,"logsyncoperations":12,"logsync_diroperations":1,"logserverthreadadvanceswriteLSN":5,"logwriteoperations":25,"logfilesmanuallyzero-filled":0},"reconciliation":{"pagesdeleted":0,"fast-pathpagesdeleted":0,"pagereconciliationcalls":12,"pagereconciliationcallsforeviction":0,"splitbytescurrentlyawaitingfree":0,"splitobjectscurrentlyawaitingfree":0},"session":{"opencursorcount":13,"opensessioncount":15},"thread-yield":{"pageacquirebusyblocked":0,"pageacquireevictionblocked":0,"pageacquirelockedblocked":0,"pageacquirereadblocked":0,"pageacquiretimesleeping(usecs)":0},"transaction":{"transactionbegins":16,"transactioncheckpoints":12,"transactioncheckpointgeneration":12,"transactioncheckpointcurrentlyrunning":0,"transactioncheckpointmaxtime(msecs)":77,"transactioncheckpointmintime(msecs)":0,"transactioncheckpointmostrecenttime(msecs)":0,"transactioncheckpointtotaltime(msecs)":138,"transactionscommitted":3,"transactionfailuresduetocacheoverflow":0,"transactionrangeofIDscurrentlypinnedbyacheckpoint":0,"transactionrangeofIDscurrentlypinned":0,"transactionrangeofIDscurrentlypinnedbynamedsnapshots":0,"transactionsrolledback":13,"numberofnamedsnapshotscreated":0,"numberofnamedsnapshotsdropped":0,"transactionsynccalls":0},"concurrentTransactions":{"write":{"out":0,"available":128,"totalTickets":128},"read":{"out":0,"available":128,"totalTickets":128}}},"writeBacksQueued":false,"mem":{"bits":64,"resident":52,"virtual":2511,"supported":true,"mapped":0,"mappedWithJournal":0},"metrics":{"commands":{"buildInfo":{"failed":0,"total":23},"getLog":{"failed":0,"total":2},"getnonce":{"failed":0,"total":3},"isMaster":{"failed":0,"total":71},"ping":{"failed":0,"total":6},"replSetGetStatus":{"failed":23,"total":23},"serverStatus":{"failed":0,"total":24},"whatsmyuri":{"failed":0,"total":23}},"cursor":{"timedOut":0,"open":{"noTimeout":0,"pinned":0,"total":0}},"document":{"deleted":0,"inserted":0,"returned":0,"updated":0},"getLastError":{"wtime":{"num":0,"totalMillis":0},"wtimeouts":0},"operation":{"fastmod":0,"idhack":0,"scanAndOrder":0,"writeConflicts":0},"queryExecutor":{"scanned":0,"scannedObjects":0},"record":{"moves":0},"repl":{"executor":{"counters":{"eventCreated":0,"eventWait":0,"cancels":0,"waits":0,"scheduledNetCmd":0,"scheduledDBWork":0,"scheduledXclWork":0,"scheduledWorkAt":0,"scheduledWork":0,"schedulingFailures":0},"queues":{"networkInProgress":0,"dbWorkInProgress":0,"exclusiveInProgress":0,"sleepers":0,"ready":0,"free":0},"unsignaledEvents":0,"eventWaiters":0,"shuttingDown":false,"networkInterface":"NetworkInterfaceASIOinShutdown:0"},"apply":{"batches":{"num":0,"totalMillis":0},"ops":0},"buffer":{"count":0,"maxSizeBytes":268435456,"sizeBytes":0},"network":{"bytes":0,"getmores":{"num":0,"totalMillis":0},"ops":0,"readersCreated":0},"preload":{"docs":{"num":0,"totalMillis":0},"indexes":{"num":0,"totalMillis":0}}},"storage":{"freelist":{"search":{"bucketExhausted":0,"requests":0,"scanned":0}}},"ttl":{"deletedDocuments":0,"passes":12}},"ok":1}
`
var v interface{}
err := json.Unmarshal([]byte(stub3_2_0), &v)
if err != nil {
t.Errorf("Error: %s", err.Error())
}
bsonStats, err := bson.Marshal(v)
if err != nil {
t.Errorf("Error: %s", err.Error())
}
var m bson.M
err = bson.Unmarshal(bsonStats, &m)
if err != nil {
t.Errorf("Error: %s", err.Error())
}
stat, err := mongodb.parseStatus(m)
fmt.Println(stat)
assert.Nil(t, err)
// Mongodb Stats
assert.EqualValues(t, reflect.TypeOf(stat["opcounters_command"]).String(), "float64")
assert.EqualValues(t, stat["opcounters_command"], 175)
}
开发者ID:supercaracal,项目名称:mackerel-agent-plugins,代码行数:28,代码来源:mongodb_test.go
示例8: TestGetNote
func TestGetNote(t *testing.T) {
assert := assert.New(t)
dbMap := initDb()
defer dbMap.Db.Close()
ctx := context.Background()
ctx = context.WithValue(ctx, "db", dbMap)
ctx = context.WithValue(ctx, "auth", &auth.AuthContext{})
dbMap.Insert(&model.Note{
Id: 0,
Title: "Test Title 1",
Content: "lorem ipsum dolor sit amet consetetur.",
OwnerId: 0,
CreatedAt: 1442284669000,
UpdatedAt: 1442292926000,
})
kami.Reset()
kami.Context = ctx
kami.Post("/api/notes/:noteId", GetNote)
server := httptest.NewServer(kami.Handler())
defer server.Close()
resp := request(t, server.URL+"/api/notes/1", http.StatusOK, nil)
assert.NotNil(resp)
note := resp.(map[string]interface{})
assert.Equal("Test Title 1", note["title"])
assert.Equal("lorem ipsum dolor sit amet consetetur.", note["content"])
assert.EqualValues(0, note["ownerId"])
assert.EqualValues(1442284669000, note["createdAt"])
assert.EqualValues(1442292926000, note["updatedAt"])
}
开发者ID:keichi,项目名称:scribble,代码行数:34,代码来源:note_handler_test.go
示例9: TestDeleteNote
func TestDeleteNote(t *testing.T) {
assert := assert.New(t)
dbMap := initDb()
defer dbMap.Db.Close()
ctx := context.Background()
ctx = context.WithValue(ctx, "db", dbMap)
ctx = context.WithValue(ctx, "auth", &auth.AuthContext{})
dbMap.Insert(&model.Note{
Id: 0,
Title: "Test Title 1",
Content: "lorem ipsum dolor sit amet consetetur.",
OwnerId: 0,
CreatedAt: 1442284669000,
UpdatedAt: 1442292926000,
})
count, err := dbMap.SelectInt("SELECT COUNT(id) FROM notes")
assert.Nil(err)
assert.EqualValues(1, count)
kami.Reset()
kami.Context = ctx
kami.Post("/api/notes/:noteId", DeleteNote)
server := httptest.NewServer(kami.Handler())
defer server.Close()
request(t, server.URL+"/api/notes/1", http.StatusOK, nil)
count, err = dbMap.SelectInt("SELECT COUNT(id) FROM notes")
assert.Nil(err)
assert.EqualValues(0, count)
}
开发者ID:keichi,项目名称:scribble,代码行数:34,代码来源:note_handler_test.go
示例10: TestSectionedParser_TerminateOnNewAnnotation
func TestSectionedParser_TerminateOnNewAnnotation(t *testing.T) {
block := `swagger:model someModel
This has a title without whitespace.
The punctuation here does indeed matter. But it won't for go.
minimum: 10
swagger:meta
maximum: 20
`
st := §ionedParser{}
st.setTitle = func(lines []string) {}
ap := newSchemaAnnotationParser("SomeModel")
st.annotation = ap
st.taggers = []tagParser{
{"Maximum", false, nil, &setMaximum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMaximumFmt, ""))}},
{"Minimum", false, nil, &setMinimum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMinimumFmt, ""))}},
{"MultipleOf", false, nil, &setMultipleOf{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMultipleOfFmt, ""))}},
}
st.Parse(ascg(block))
assert.EqualValues(t, []string{"This has a title without whitespace."}, st.Title())
assert.EqualValues(t, []string{"The punctuation here does indeed matter. But it won't for go."}, st.Description())
assert.Len(t, st.matched, 1)
_, ok := st.matched["Maximum"]
assert.False(t, ok)
_, ok = st.matched["Minimum"]
assert.True(t, ok)
assert.Equal(t, "SomeModel", ap.GoName)
assert.Equal(t, "someModel", ap.Name)
}
开发者ID:jason-xxl,项目名称:go-swagger,代码行数:31,代码来源:scanner_test.go
示例11: TestAddNote
func TestAddNote(t *testing.T) {
assert := assert.New(t)
dbMap := initDb()
defer dbMap.Db.Close()
ctx := context.Background()
ctx = context.WithValue(ctx, "db", dbMap)
ctx = context.WithValue(ctx, "auth", &auth.AuthContext{})
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
AddNote(ctx, w, r)
},
))
defer server.Close()
resp := request(t, server.URL, http.StatusOK, map[string]interface{}{
"title": "Test Title",
"content": "lorem ipsum dolor sit amet consetetur.",
"ownerId": 0,
})
assert.NotNil(resp)
note := resp.(map[string]interface{})
assert.Equal("Test Title", note["title"])
assert.Equal("lorem ipsum dolor sit amet consetetur.", note["content"])
assert.EqualValues(0, note["ownerId"])
assert.NotZero(note["createdAt"])
assert.NotZero(note["updatedAt"])
count, err := dbMap.SelectInt("SELECT COUNT(id) FROM notes")
assert.Nil(err)
assert.EqualValues(1, count)
}
开发者ID:keichi,项目名称:scribble,代码行数:34,代码来源:note_handler_test.go
示例12: TestStorageWebsites
func TestStorageWebsites(t *testing.T) {
websites, err := testStorage.Websites()
assert.NoError(t, err)
assert.EqualValues(t, utils.StringSlice{"admin", "euro", "oz"}, websites.Codes())
assert.EqualValues(t, utils.Int64Slice{0, 1, 2}, websites.IDs())
var ids = []struct {
g utils.Int64Slice
s utils.Int64Slice
}{
{utils.Int64Slice{0}, utils.Int64Slice{0}}, //admin
{utils.Int64Slice{1, 2}, utils.Int64Slice{1, 4, 2, 3}}, // dach
{utils.Int64Slice{3}, utils.Int64Slice{5, 6}}, // oz
}
for i, w := range websites {
groups, err := w.Groups()
assert.NoError(t, err)
assert.EqualValues(t, ids[i].g, groups.IDs())
stores, err := w.Stores()
assert.NoError(t, err)
assert.EqualValues(t, ids[i].s, stores.IDs())
}
}
开发者ID:bom-d-van,项目名称:csfw,代码行数:25,代码来源:storage_test.go
示例13: TestFileReadAt
func TestFileReadAt(t *testing.T) {
client := getClient(t)
file, err := client.Open("/_test/mobydick.txt")
require.NoError(t, err)
buf := make([]byte, len(testStr))
off := 0
for off < len(buf) {
n, err := file.ReadAt(buf[off:], int64(testStrOff+off))
assert.NoError(t, err)
assert.True(t, n > 0)
off += n
}
assert.EqualValues(t, string(buf), testStr)
buf = make([]byte, len(testStr2))
off = 0
for off < len(buf) {
n, err := file.ReadAt(buf[off:], int64(testStr2Off+off))
assert.NoError(t, err)
assert.True(t, n > 0)
off += n
}
assert.EqualValues(t, testStr2, string(buf))
}
开发者ID:erimatnor,项目名称:hdfs,代码行数:28,代码来源:file_reader_test.go
示例14: TestGenerateStatisticsInputParams
func TestGenerateStatisticsInputParams(t *testing.T) {
d := &cloudwatch.Dimension{
Name: aws.String("LoadBalancerName"),
Value: aws.String("p-example"),
}
m := &cloudwatch.Metric{
MetricName: aws.String("Latency"),
Dimensions: []*cloudwatch.Dimension{d},
}
duration, _ := time.ParseDuration("1m")
internalDuration := internal.Duration{
Duration: duration,
}
c := &CloudWatch{
Namespace: "AWS/ELB",
Delay: internalDuration,
Period: internalDuration,
}
c.initializeCloudWatch()
now := time.Now()
params := c.getStatisticsInput(m, now)
assert.EqualValues(t, *params.EndTime, now.Add(-c.Delay.Duration))
assert.EqualValues(t, *params.StartTime, now.Add(-c.Period.Duration).Add(-c.Delay.Duration))
assert.Len(t, params.Dimensions, 1)
assert.Len(t, params.Statistics, 5)
assert.EqualValues(t, *params.Period, 60)
}
开发者ID:jeichorn,项目名称:telegraf,代码行数:34,代码来源:cloudwatch_test.go
示例15: TestConnectionReference
func TestConnectionReference(t *testing.T) {
h, err := newTestHub()
assert.NoError(t, err)
defer h.Close()
assert.True(t, h.IsRunning(time.Millisecond))
conn := NewMockConnection()
/* Unregistered connection test */
o, err := h.ConnectionReference(conn)
assert.Error(t, err)
assert.EqualValues(t, o, "")
err = h.Register(conn)
assert.NoError(t, err)
r, err := h.IsRegistered(conn)
assert.NoError(t, err)
assert.True(t, r)
/* registered connection test */
o, err = h.ConnectionReference(conn)
assert.NoError(t, err)
assert.EqualValues(t, "Mock Test", o)
/* registered connection test with empty origin */
conn.SetReference("")
o, err = h.ConnectionReference(conn)
assert.NoError(t, err)
assert.EqualValues(t, "unknown", o)
}
开发者ID:SonOfBytes,项目名称:interfacehub,代码行数:32,代码来源:hub_connection_test.go
示例16: TestCountUsingMaster
func TestCountUsingMaster(t *testing.T) {
assert := assert.New(t)
wiz := testCreateWizard()
orm := New(wiz)
var foobar = testFoobar{}
var count int64
var err error
fn := func(s Session) (int64, error) {
return s.Count(&foobar)
}
orm.SetAutoTransaction(testID, true)
row := &testFoobar{ID: 4, Name: "foobar#[email protected]"}
s, _ := orm.Transaction(testID, row)
s.Insert(row)
count, err = orm.Count(foobar, fn)
assert.Nil(err)
assert.EqualValues(3, count)
count, err = orm.CountUsingMaster(testID, foobar, fn)
assert.Nil(err)
assert.EqualValues(4, count)
s.Rollback()
}
开发者ID:evalphobia,项目名称:wizard,代码行数:28,代码来源:xorm_function_test.go
示例17: TestAnnounceLocalhost
func TestAnnounceLocalhost(t *testing.T) {
t.Parallel()
srv := server{
t: map[[20]byte]torrent{
[20]byte{0xa3, 0x56, 0x41, 0x43, 0x74, 0x23, 0xe6, 0x26, 0xd9, 0x38, 0x25, 0x4a, 0x6b, 0x80, 0x49, 0x10, 0xa6, 0x67, 0xa, 0xc1}: {
Seeders: 1,
Leechers: 2,
Peers: []util.CompactPeer{
{[]byte{1, 2, 3, 4}, 5},
{[]byte{6, 7, 8, 9}, 10},
},
},
},
}
var err error
srv.pc, err = net.ListenPacket("udp", ":0")
require.NoError(t, err)
defer srv.pc.Close()
go func() {
require.NoError(t, srv.serveOne())
}()
req := AnnounceRequest{
NumWant: -1,
Event: Started,
}
rand.Read(req.PeerId[:])
copy(req.InfoHash[:], []uint8{0xa3, 0x56, 0x41, 0x43, 0x74, 0x23, 0xe6, 0x26, 0xd9, 0x38, 0x25, 0x4a, 0x6b, 0x80, 0x49, 0x10, 0xa6, 0x67, 0xa, 0xc1})
go func() {
require.NoError(t, srv.serveOne())
}()
ar, err := Announce(fmt.Sprintf("udp://%s/announce", srv.pc.LocalAddr().String()), &req)
require.NoError(t, err)
assert.EqualValues(t, 1, ar.Seeders)
assert.EqualValues(t, 2, len(ar.Peers))
}
开发者ID:CaptainIlu,项目名称:cloud-torrent,代码行数:35,代码来源:udp_test.go
示例18: TestParse30
func TestParse30(t *testing.T) {
var mongodb MongoDBPlugin
stub3_0_5 := `
{"asserts":{"msg":0,"regular":0,"rollovers":0,"user":0,"warning":0},"backgroundFlushing":{"average_ms":0,"flushes":0,"last_finished":"1970-01-01T09:00:00+09:00","last_ms":0,"total_ms":3},"connections":{"available":818,"current":1,"totalCreated":1},"cursors":{"clientCursors_size":0,"note":"deprecated, use server status metrics","pinned":0,"timedOut":0,"totalNoTimeout":0,"totalOpen":0},"dur":{"commits":31,"commitsInWriteLock":0,"compression":1.1555931725208068,"earlyCommits":0,"journaledMB":0.024576,"timeMs":{"commits":1,"commitsInWriteLock":0,"dt":3037,"prepLogBuffer":0,"remapPrivateView":0,"writeToDataFiles":0,"writeToJournal":3},"writeToDataFilesMB":0.020941},"extra_info":{"heap_usage_bytes":62891464,"note":"fields vary by platform","page_faults":189},"globalLock":{"activeClients":{"readers":0,"total":9,"writers":0},"currentQueue":{"readers":0,"total":0,"writers":0},"totalTime":5609000},"host":"db625bac64b5","localTime":"2015-08-17T15:09:12.821+09:00","locks":{"Collection":{"acquireCount":{"R":7}},"Database":{"acquireCount":{"W":2,"r":7}},"Global":{"acquireCount":{"W":5,"r":21,"w":2}},"MMAPV1Journal":{"acquireCount":{"R":54,"r":5,"w":10}},"Metadata":{"acquireCount":{"W":4}}},"mem":{"bits":64,"mapped":80,"mappedWithJournal":160,"resident":52,"supported":true,"virtual":358},"metrics":{"commands":{"\u003cUNKNOWN\u003e":0,"_getUserCacheGeneration":{"failed":0,"total":0},"_isSelf":{"failed":0,"total":0},"_mergeAuthzCollections":{"failed":0,"total":0},"_migrateClone":{"failed":0,"total":0},"_recvChunkAbort":{"failed":0,"total":0},"_recvChunkCommit":{"failed":0,"total":0},"_recvChunkStart":{"failed":0,"total":0},"_recvChunkStatus":{"failed":0,"total":0},"_transferMods":{"failed":0,"total":0},"aggregate":{"failed":0,"total":0},"appendOplogNote":{"failed":0,"total":0},"applyOps":{"failed":0,"total":0},"authSchemaUpgrade":{"failed":0,"total":0},"authenticate":{"failed":0,"total":0},"availableQueryOptions":{"failed":0,"total":0},"buildInfo":{"failed":0,"total":0},"checkShardingIndex":{"failed":0,"total":0},"cleanupOrphaned":{"failed":0,"total":0},"clone":{"failed":0,"total":0},"cloneCollection":{"failed":0,"total":0},"cloneCollectionAsCapped":{"failed":0,"total":0},"collMod":{"failed":0,"total":0},"collStats":{"failed":0,"total":0},"compact":{"failed":0,"total":0},"connPoolStats":{"failed":0,"total":0},"connPoolSync":{"failed":0,"total":0},"connectionStatus":{"failed":0,"total":0},"convertToCapped":{"failed":0,"total":0},"copydb":{"failed":0,"total":0},"copydbgetnonce":{"failed":0,"total":0},"copydbsaslstart":{"failed":0,"total":0},"count":{"failed":0,"total":0},"create":{"failed":0,"total":0},"createIndexes":{"failed":0,"total":0},"createRole":{"failed":0,"total":0},"createUser":{"failed":0,"total":0},"currentOpCtx":{"failed":0,"total":0},"cursorInfo":{"failed":0,"total":0},"dataSize":{"failed":0,"total":0},"dbHash":{"failed":0,"total":0},"dbStats":{"failed":0,"total":0},"delete":{"failed":0,"total":0},"diagLogging":{"failed":0,"total":0},"distinct":{"failed":0,"total":0},"driverOIDTest":{"failed":0,"total":0},"drop":{"failed":0,"total":0},"dropAllRolesFromDatabase":{"failed":0,"total":0},"dropAllUsersFromDatabase":{"failed":0,"total":0},"dropDatabase":{"failed":0,"total":0},"dropIndexes":{"failed":0,"total":0},"dropRole":{"failed":0,"total":0},"dropUser":{"failed":0,"total":0},"eval":{"failed":0,"total":0},"explain":{"failed":0,"total":0},"features":{"failed":0,"total":0},"filemd5":{"failed":0,"total":0},"find":{"failed":0,"total":0},"findAndModify":{"failed":0,"total":0},"forceerror":{"failed":0,"total":0},"fsync":{"failed":0,"total":0},"geoNear":{"failed":0,"total":0},"geoSearch":{"failed":0,"total":0},"getCmdLineOpts":{"failed":0,"total":0},"getLastError":{"failed":0,"total":0},"getLog":{"failed":0,"total":0},"getParameter":{"failed":0,"total":0},"getPrevError":{"failed":0,"total":0},"get
|
请发表评论