예제 #1
0
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) })

}
예제 #2
0
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)
		}
	}
}
예제 #3
0
파일: parser_test.go 프로젝트: guileen/xbp
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)
}
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)
}
예제 #5
0
파일: store_test.go 프로젝트: levcom/csfw
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())
}
예제 #6
0
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())
}
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)
}
예제 #8
0
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"])
}
예제 #9
0
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)
}
예제 #10
0
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 := &sectionedParser{}
	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)
}
예제 #11
0
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)
}
예제 #12
0
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())
	}
}
예제 #13
0
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))
}
예제 #14
0
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)
}
예제 #15
0
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)

}
예제 #16
0
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#4@CountUsingMaster"}
	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()
}
예제 #17
0
func TestStatusProperties(t *testing.T) {
	props := map[string]interface{}{"message": "ok", "size": 3, "sync": true}
	uh := health.StatusHealthyWithProperties(props)
	assert.Equal(t, props, uh.Properties)
	assert.EqualValues(t, 3, uh.Properties["size"])
	assert.EqualValues(t, true, uh.Properties["sync"])
}
예제 #18
0
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))
}
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},"getShardMap":{"failed":0,"total":0},"getShardVersion":{"failed":0,"total":0},"getnonce":{"failed":0,"total":1},"grantPrivilegesToRole":{"failed":0,"total":0},"grantRolesToRole":{"failed":0,"total":0},"grantRolesToUser":{"failed":0,"total":0},"group":{"failed":0,"total":0},"handshake":{"failed":0,"total":0},"hostInfo":{"failed":0,"total":0},"insert":{"failed":0,"total":0},"invalidateUserCache":{"failed":0,"total":0},"isMaster":{"failed":0,"total":1},"listCollections":{"failed":0,"total":0},"listCommands":{"failed":0,"total":0},"listDatabases":{"failed":0,"total":0},"listIndexes":{"failed":0,"total":0},"logRotate":{"failed":0,"total":0},"logout":{"failed":0,"total":0},"mapReduce":{"failed":0,"total":0},"mapreduce":{"shardedfinish":{"failed":0,"total":0}},"medianKey":{"failed":0,"total":0},"mergeChunks":{"failed":0,"total":0},"moveChunk":{"failed":0,"total":0},"parallelCollectionScan":{"failed":0,"total":0},"ping":{"failed":0,"total":2},"planCacheClear":{"failed":0,"total":0},"planCacheClearFilters":{"failed":0,"total":0},"planCacheListFilters":{"failed":0,"total":0},"planCacheListPlans":{"failed":0,"total":0},"planCacheListQueryShapes":{"failed":0,"total":0},"planCacheSetFilter":{"failed":0,"total":0},"profile":{"failed":0,"total":0},"reIndex":{"failed":0,"total":0},"renameCollection":{"failed":0,"total":0},"repairCursor":{"failed":0,"total":0},"repairDatabase":{"failed":0,"total":0},"replSetElect":{"failed":0,"total":0},"replSetFreeze":{"failed":0,"total":0},"replSetFresh":{"failed":0,"total":0},"replSetGetConfig":{"failed":0,"total":0},"replSetGetRBID":{"failed":0,"total":0},"replSetGetStatus":{"failed":0,"total":0},"replSetHeartbeat":{"failed":0,"total":0},"replSetInitiate":{"failed":0,"total":0},"replSetMaintenance":{"failed":0,"total":0},"replSetReconfig":{"failed":0,"total":0},"replSetStepDown":{"failed":0,"total":0},"replSetSyncFrom":{"failed":0,"total":0},"replSetUpdatePosition":{"failed":0,"total":0},"resetError":{"failed":0,"total":0},"resync":{"failed":0,"total":0},"revokePrivilegesFromRole":{"failed":0,"total":0},"revokeRolesFromRole":{"failed":0,"total":0},"revokeRolesFromUser":{"failed":0,"total":0},"rolesInfo":{"failed":0,"total":0},"saslContinue":{"failed":0,"total":0},"saslStart":{"failed":0,"total":0},"serverStatus":{"failed":0,"total":1},"setParameter":{"failed":0,"total":0},"setShardVersion":{"failed":0,"total":0},"shardConnPoolStats":{"failed":0,"total":0},"shardingState":{"failed":0,"total":0},"shutdown":{"failed":0,"total":0},"splitChunk":{"failed":0,"total":0},"splitVector":{"failed":0,"total":0},"top":{"failed":0,"total":0},"touch":{"failed":0,"total":0},"unsetSharding":{"failed":0,"total":0},"update":{"failed":0,"total":0},"updateRole":{"failed":0,"total":0},"updateUser":{"failed":0,"total":0},"usersInfo":{"failed":0,"total":0},"validate":{"failed":0,"total":0},"whatsmyuri":{"failed":0,"total":0},"writebacklisten":{"failed":0,"total":0}},"cursor":{"open":{"noTimeout":0,"pinned":0,"total":0},"timedOut":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":{"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":8,"scanned":0}}},"ttl":{"deletedDocuments":0,"passes":0}},"network":{"bytesIn":224,"bytesOut":381,"numRequests":4},"ok":1,"opcounters":{"command":5,"delete":0,"getmore":0,"insert":0,"query":1,"update":0},"opcountersRepl":{"command":0,"delete":0,"getmore":0,"insert":0,"query":0,"update":0},"pid":1,"process":"mongod","storageEngine":{"name":"mmapv1"},"uptime":5,"uptimeEstimate":5,"uptimeMillis":5616,"version":"3.0.5","writeBacksQueued":false}
`

	var v interface{}
	err := json.Unmarshal([]byte(stub3_0_5), &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["duration_ms"]).String(), "float64")
	assert.EqualValues(t, stat["duration_ms"], 3.0)
}
예제 #20
0
func TestGetSNMPConnection_v3(t *testing.T) {
	s := &Snmp{
		Version:        3,
		MaxRepetitions: 20,
		ContextName:    "mycontext",
		SecLevel:       "authPriv",
		SecName:        "myuser",
		AuthProtocol:   "md5",
		AuthPassword:   "******",
		PrivProtocol:   "des",
		PrivPassword:   "******",
		EngineID:       "myengineid",
		EngineBoots:    1,
		EngineTime:     2,
	}

	gsc, err := s.getConnection("1.2.3.4")
	require.NoError(t, err)
	gs := gsc.(gosnmpWrapper)
	assert.Equal(t, gs.Version, gosnmp.Version3)
	sp := gs.SecurityParameters.(*gosnmp.UsmSecurityParameters)
	assert.Equal(t, "1.2.3.4", gsc.Host())
	assert.EqualValues(t, 20, gs.MaxRepetitions)
	assert.Equal(t, "mycontext", gs.ContextName)
	assert.Equal(t, gosnmp.AuthPriv, gs.MsgFlags&gosnmp.AuthPriv)
	assert.Equal(t, "myuser", sp.UserName)
	assert.Equal(t, gosnmp.MD5, sp.AuthenticationProtocol)
	assert.Equal(t, "password123", sp.AuthenticationPassphrase)
	assert.Equal(t, gosnmp.DES, sp.PrivacyProtocol)
	assert.Equal(t, "321drowssap", sp.PrivacyPassphrase)
	assert.Equal(t, "myengineid", sp.AuthoritativeEngineID)
	assert.EqualValues(t, 1, sp.AuthoritativeEngineBoots)
	assert.EqualValues(t, 2, sp.AuthoritativeEngineTime)
}
func TestParse22(t *testing.T) {
	var mongodb MongoDBPlugin
	stub2_2_7 := `
{"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":0},"connections":{"available":818,"current":1},"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":25585584,"note":"fields vary by platform","page_faults":136},"globalLock":{"activeClients":{"readers":0,"total":0,"writers":0},"currentQueue":{"readers":0,"total":0,"writers":0},"lockTime":1638,"totalTime":35489000},"host":"58a1c98acba3","indexCounters":{"btree":{"accesses":0,"hits":5,"missRatio":0,"misses":0,"resets":0}},"localTime":"2015-08-17T15:08:02.677+09:00","locks":{".":{"timeAcquiringMicros":{"R":1593,"W":279},"timeLockedMicros":{"R":1906,"W":1638}},"admin":{"timeAcquiringMicros":{},"timeLockedMicros":{}},"local":{"timeAcquiringMicros":{"r":9,"w":0},"timeLockedMicros":{"r":44,"w":0}}},"mem":{"bits":64,"mapped":0,"mappedWithJournal":0,"resident":30,"supported":true,"virtual":128},"network":{"bytesIn":510,"bytesOut":2319,"numRequests":9},"ok":1,"opcounters":{"command":10,"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":35,"uptimeEstimate":34,"uptimeMillis":35489,"version":"2.2.7","writeBacksQueued":false}
`

	var v interface{}
	err := json.Unmarshal([]byte(stub2_2_7), &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)
}
예제 #22
0
func TestProtocolReal(t *testing.T) {
	listener, err := net.Listen("tcp", "127.0.0.1:17777")
	assert.Nil(t, err)

	conn1, err1 := net.Dial("tcp", "127.0.0.1:17777")
	assert.Nil(t, err1)
	p1 := NewTcpProtocol(conn1)

	conn2, err2 := listener.Accept()
	assert.Nil(t, err2)
	p2 := NewTcpProtocol(conn2)

	err = p1.SendPacket(&Packet{
		Flag:    FlagResponse,
		Text:    "222",
		Seq:     123,
		Payload: []byte{1, 2, 3, 4, 5, 6},
	})
	assert.Nil(t, err)

	pkt, err := p2.ReadPacket()

	assert.Nil(t, err)
	assert.Equal(t, FlagResponse, pkt.Flag&FlagResponse)
	assert.Equal(t, "222", pkt.Text)
	assert.EqualValues(t, 123, pkt.Seq)
	assert.EqualValues(t, 6, len(pkt.Payload))
	assert.EqualValues(t, byte(6), pkt.Payload[5])
	err = conn1.Close()
	assert.Nil(t, err)
}
func TestParse26(t *testing.T) {
	var mongodb MongoDBPlugin
	stub2_6_11 := `
{"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":0},"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":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":62512008,"note":"fields vary by platform","page_faults":228},"globalLock":{"activeClients":{"readers":0,"total":0,"writers":0},"currentQueue":{"readers":0,"total":0,"writers":0},"lockTime":68622,"totalTime":6583000},"host":"08ea07b5a8fd","indexCounters":{"accesses":2,"hits":5,"missRatio":0,"misses":0,"resets":0},"localTime":"2015-08-17T15:08:44.187+09:00","locks":{".":{"timeAcquiringMicros":{"R":254,"W":94},"timeLockedMicros":{"R":520,"W":68622}},"admin":{"timeAcquiringMicros":{"r":28,"w":0},"timeLockedMicros":{"r":338,"w":0}},"local":{"timeAcquiringMicros":{"r":22,"w":0},"timeLockedMicros":{"r":46,"w":0}}},"mem":{"bits":64,"mapped":80,"mappedWithJournal":160,"resident":36,"supported":true,"virtual":342},"metrics":{"cursor":{"open":{"noTimeout":0,"pinned":0,"total":0},"timedOut":0},"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,"scannedObjects":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},"preload":{"docs":{"num":0,"totalMillis":0},"indexes":{"num":0,"totalMillis":0}}},"storage":{"freelist":{"search":{"bucketExhausted":0,"requests":6,"scanned":11}}},"ttl":{"deletedDocuments":0,"passes":0}},"network":{"bytesIn":224,"bytesOut":380,"numRequests":4},"ok":1,"opcounters":{"command":6,"delete":0,"getmore":0,"insert":1,"query":1,"update":0},"opcountersRepl":{"command":0,"delete":0,"getmore":0,"insert":0,"query":0,"update":0},"pid":1,"process":"mongod","recordStats":{"accessesNotInMemory":0,"admin":{"accessesNotInMemory":0,"pageFaultExceptionsThrown":0},"local":{"accessesNotInMemory":0,"pageFaultExceptionsThrown":0},"pageFaultExceptionsThrown":0},"uptime":7,"uptimeEstimate":6,"uptimeMillis":6581,"version":"2.6.11","writeBacksQueued":false}
`

	var v interface{}
	err := json.Unmarshal([]byte(stub2_6_11), &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)
}
예제 #24
0
파일: spec_test.go 프로젝트: vmware/vic
func TestCollectSlotNumbers(t *testing.T) {
	s := &VirtualMachineConfigSpec{
		config: &VirtualMachineConfigSpecConfig{
			ID: "foo",
		},
		VirtualMachineConfigSpec: &types.VirtualMachineConfigSpec{},
	}

	slots := s.CollectSlotNumbers(nil)
	assert.Empty(t, slots)

	s.AddVirtualVmxnet3(NewVirtualVmxnet3())
	s.DeviceChange[0].GetVirtualDeviceConfigSpec().Device.GetVirtualDevice().SlotInfo = &types.VirtualDevicePciBusSlotInfo{PciSlotNumber: 32}
	slots = s.CollectSlotNumbers(nil)
	assert.EqualValues(t, map[int32]bool{32: true}, slots)

	// add a device without a slot number
	s.AddVirtualVmxnet3(NewVirtualVmxnet3())
	slots = s.CollectSlotNumbers(nil)
	assert.EqualValues(t, map[int32]bool{32: true}, slots)

	// add another device with slot number
	s.AddVirtualVmxnet3(NewVirtualVmxnet3())
	s.DeviceChange[len(s.DeviceChange)-1].GetVirtualDeviceConfigSpec().Device.GetVirtualDevice().SlotInfo = &types.VirtualDevicePciBusSlotInfo{PciSlotNumber: 33}
	slots = s.CollectSlotNumbers(slots)
	assert.EqualValues(t, map[int32]bool{32: true, 33: true}, slots)

}
예제 #25
0
func TestNewGroupSetStores(t *testing.T) {

	g := store.NewGroup(
		&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "DACH Group", RootCategoryID: 2, DefaultStoreID: 2},
		nil,
	)
	g.SetStores(
		store.TableStoreSlice{
			&store.TableStore{StoreID: 0, Code: dbr.NullString{NullString: sql.NullString{String: "admin", Valid: true}}, WebsiteID: 0, GroupID: 0, Name: "Admin", SortOrder: 0, IsActive: true},
			&store.TableStore{StoreID: 5, Code: dbr.NullString{NullString: sql.NullString{String: "au", Valid: true}}, WebsiteID: 2, GroupID: 3, Name: "Australia", SortOrder: 10, IsActive: true},
			&store.TableStore{StoreID: 1, Code: dbr.NullString{NullString: sql.NullString{String: "de", Valid: true}}, WebsiteID: 1, GroupID: 1, Name: "Germany", SortOrder: 10, IsActive: true},
			&store.TableStore{StoreID: 4, Code: dbr.NullString{NullString: sql.NullString{String: "uk", Valid: true}}, WebsiteID: 1, GroupID: 2, Name: "UK", SortOrder: 10, IsActive: true},
			&store.TableStore{StoreID: 2, Code: dbr.NullString{NullString: sql.NullString{String: "at", Valid: true}}, WebsiteID: 1, GroupID: 1, Name: "Österreich", SortOrder: 20, IsActive: true},
			&store.TableStore{StoreID: 6, Code: dbr.NullString{NullString: sql.NullString{String: "nz", Valid: true}}, WebsiteID: 2, GroupID: 3, Name: "Kiwi", SortOrder: 30, IsActive: true},
			&store.TableStore{StoreID: 3, Code: dbr.NullString{NullString: sql.NullString{String: "ch", Valid: true}}, WebsiteID: 1, GroupID: 1, Name: "Schweiz", SortOrder: 30, IsActive: true},
		},
		&store.TableWebsite{WebsiteID: 1, Code: dbr.NullString{NullString: sql.NullString{String: "euro", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "Europe", Valid: true}}, SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: true, Valid: true}}},
	)
	gStores, err := g.Stores()
	assert.NoError(t, err)
	assert.EqualValues(t, utils.StringSlice{"de", "at", "ch"}, gStores.Codes())

	gDefaultStore, err := g.DefaultStore()
	assert.NoError(t, err)
	assert.EqualValues(t, "euro", gDefaultStore.Website().Data().Code.String)
	assert.EqualValues(t, "DACH Group", gDefaultStore.Group().Data().Name)
	assert.EqualValues(t, "at", gDefaultStore.Data().Code.String)
}
예제 #26
0
func TestHandler(t *testing.T) {
	i := IncrHandler{}
	expectAfter := 0
	expectBefore := 2
	destination := HandlerFunc(func(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
		assert.Equal(t, "value", ctx.Value("key"))
		assert.EqualValues(t, expectAfter, i.after)
		assert.EqualValues(t, expectBefore, i.before)
	})
	ctx := context.Background()
	h := NewHandler(ctx, destination)
	v1 := VarAdder{
		Key:   "key",
		Value: "value",
	}

	h.Add(ConstructorFunc(v1.Generate), HTTPConstructor(i.makeHTTP), NextHTTP(i.ServeHTTP))
	rw := httptest.NewRecorder()
	req, _ := http.NewRequest("POST", "/", nil)
	h.ServeHTTP(rw, req)
	assert.EqualValues(t, 2, i.after)

	expectAfter = 2
	expectBefore = 4
	h.ServeHTTPC(ctx, rw, req)
	assert.EqualValues(t, 4, i.after)

	bodyTest := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		rw.Write([]byte("test"))
	})

	ToHTTP(ctx, FromHTTP(bodyTest)).ServeHTTP(rw, req)
	assert.Equal(t, "test", rw.Body.String())
}
예제 #27
0
파일: routes_test.go 프로젝트: jak-atx/vic
func assertOperation(t *testing.T, op *spec.Operation, id, summary, description string, tags []string) {
	assert.NotNil(t, op)
	assert.Equal(t, summary, op.Summary)
	assert.Equal(t, description, op.Description)
	assert.Equal(t, id, op.ID)
	assert.EqualValues(t, tags, op.Tags)
	assert.EqualValues(t, []string{"application/json", "application/x-protobuf"}, op.Consumes)
	assert.EqualValues(t, []string{"application/json", "application/x-protobuf"}, op.Produces)
	assert.EqualValues(t, []string{"http", "https", "ws", "wss"}, op.Schemes)
	assert.Len(t, op.Security, 2)
	_, ok := op.Security[0]["api_key"]
	assert.True(t, ok)

	vv, ok := op.Security[1]["oauth"]
	assert.True(t, ok)
	assert.EqualValues(t, []string{"read", "write"}, vv)

	assert.NotNil(t, op.Responses.Default)
	assert.Equal(t, "#/responses/genericError", op.Responses.Default.Ref.String())

	rsp, ok := op.Responses.StatusCodeResponses[200]
	assert.True(t, ok)
	assert.Equal(t, "#/responses/someResponse", rsp.Ref.String())
	rsp, ok = op.Responses.StatusCodeResponses[422]
	assert.True(t, ok)
	assert.Equal(t, "#/responses/validationError", rsp.Ref.String())
}
예제 #28
0
func TestInstanceIDMarshalText(t *testing.T) {

	i1 := &InstanceID{ID: "1234", Driver: "vfs"}
	assert.Equal(t, "vfs=1234", i1.String())
	t.Logf("instanceID=%s", i1)

	i2 := &InstanceID{}
	assert.NoError(t, i2.UnmarshalText([]byte(i1.String())))
	assert.EqualValues(t, i1, i2)

	assert.NoError(t, i1.MarshalMetadata(newMetadata()))
	assert.Equal(t, expectedI1String, i1.String())
	t.Logf("instanceID=%s", i1)

	i3 := &InstanceID{}
	assert.NoError(t, i3.UnmarshalText([]byte(expectedI1String)))
	assert.EqualValues(t, i1, i3)

	i4 := &InstanceID{
		ID:     "1234",
		Driver: "vfs",
		Fields: map[string]string{"region": "west"},
	}
	assert.Equal(t, "vfs=1234,region=west", i4.String())
}
예제 #29
0
func TestUnCompressed(t *testing.T) {
	assert := assert.New(t)
	// SELECT repeat("a", 50)
	before := `
09 00 00 00 03 53 45 4c 45 43 54 20 31                ....SELECT 1
`
	after := `
0d 00 00 00 00 00 00 09    00 00 00 03 53 45 4c 45    ............SELE
43 54 20 31                                           CT 1
`
	_, _ = before, after

	buf := bytes.NewBufferString("")
	buf.Write(DecodeDump(after))

	r := NewCompressedReader(buf)
	b, err := ioutil.ReadAll(r)
	assert.NoError(err)
	assert.EqualValues(DecodeDump(before), b)

	// write and read again
	w := NewCompressedWriter(buf)
	_, err = w.Write(DecodeDump(before))
	assert.NoError(err)
	b, err = ioutil.ReadAll(r)
	assert.NoError(err)
	assert.EqualValues(DecodeDump(before), b)
}
func TestAutoTransaction(t *testing.T) {
	assert := assert.New(t)
	wiz := testCreateWizard()
	orm := New(wiz)
	xsm := orm.XormSessionManager
	sl := xsm.getOrCreateSessionList(testID)
	assert.Len(sl.getTransactions(), 0)

	user1 := testUser{ID: 1}

	s, _ := orm.NewMasterSession(user1)

	err := orm.AutoTransaction(testID, user1, s)
	assert.Nil(err)
	assert.Len(sl.getTransactions(), 0, "transaction is not added")

	orm.SetAutoTransaction(testID, true)
	err = orm.AutoTransaction(testID, user1, s)
	assert.Nil(err)
	assert.Len(sl.getTransactions(), 1, "transaction is added")

	assert.EqualValues(3, countUserBySession(s), "initial users count")
	s.Insert(&testUser{ID: 4})
	assert.EqualValues(4, countUserBySession(s), "users count after insert in the transaction")
	assert.EqualValues(4, countUserMaster(orm), "users count after insert in the transaction")

	s2, _ := newSession(orm.Master(user1), user1)
	assert.EqualValues(3, countUserBySession(s2), "users count after insert in another session")

	err = s.Rollback()
	assert.Nil(err)
	s.Init()
	assert.EqualValues(3, countUserBySession(s), "users count after rollback")

}