Golang NewObjectId示例

说明

golang newobjectid示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: gopkg/in/mgo/v2/bson

示例#1
文件: mongo_cache_test.go 项目: koding/cache

func TestMongoCacheTTL(t *testing.T) {
	// duration specifies the time duration to hold the data in mongo
	// after the duration interval, data will be deleted from mongoDB
	duration := time.Millisecond * 100

	mgoCache := NewMongoCacheWithTTL(session, SetTTL(duration))
	defer mgoCache.StopGC()
	if mgoCache == nil {
		t.Fatal("config should not be nil")
	}
	defer mgoCache.StopGC()

	key, value := bson.NewObjectId().Hex(), bson.NewObjectId().Hex()

	if err := mgoCache.Set(key, value); err != nil {
		t.Fatalf("error should be nil: %q", err)
	}

	if data, err := mgoCache.Get(key); err != nil {
		t.Fatalf("error should be nil: %q", err)
	} else if data != value {
		t.Fatalf("data should equal: %v, but got: %v", value, data)
	}

	time.Sleep(duration)

	if _, err := mgoCache.Get(key); err != ErrNotFound {
		t.Fatalf("error should equal to %q but got: %q", ErrNotFound, err)
	}
}

示例#2
文件: mongo_cache_test.go 项目: koding/cache

func TestMongoCacheSetEx(t *testing.T) {
	mgoCache := NewMongoCacheWithTTL(session)
	defer mgoCache.StopGC()
	if mgoCache == nil {
		t.Fatal("config should not be nil")
	}
	// defaultExpireDuration is 1 Minute as default
	if mgoCache.TTL != defaultExpireDuration {
		t.Fatalf("mongoCache TTL should equal %v", defaultExpireDuration)
	}

	key := bson.NewObjectId().Hex()
	value := bson.NewObjectId().Hex()

	duration := time.Second * 10
	err := mgoCache.SetEx(key, duration, value)
	if err != nil {
		t.Fatalf("error should be nil: %q", err)
	}

	document, err := mgoCache.get(key)
	if err != nil {
		t.Fatal(err)
	}
	if !time.Now().Add(duration).After(document.ExpireAt) {
		t.Fatalf("expireAt should be greater than now + %v", duration)
	}

}

示例#3
文件: apply_test.go 项目: Clever/mongo-op-throttler

func TestUpdate(t *testing.T) {
	db := setupDb(t)

	// Update a doc and check that it's changed
	obj := bson.M{"_id": bson.NewObjectId(), "key": "value"}
	assert.NoError(t, db.C("test").Insert(obj))

	updatedObj := bson.M{"key": "value2"}

	op := operation.Op{
		ID:        obj["_id"].(bson.ObjectId).Hex(),
		Type:      "update",
		Namespace: "throttle.test",
		Obj:       updatedObj,
	}
	assert.NoError(t, applyOp(op, db.Session))

	var result bson.M
	assert.NoError(t, db.C("test").Find(bson.M{}).One(&result))
	assert.Equal(t, "value2", result["key"].(string))

	// Try with the $set syntax
	op.Obj = bson.M{"$set": bson.M{"key": "value3"}}

	assert.NoError(t, applyOp(op, db.Session))
	assert.NoError(t, db.C("test").Find(bson.M{}).One(&result))
	assert.Equal(t, "value3", result["key"].(string))

	// Updating a doc that doesn't exist doesn't fail
	op.ID = bson.NewObjectId().Hex()
	assert.NoError(t, applyOp(op, db.Session))
}

示例#4
文件: mongo_cache_test.go 项目: koding/cache

func TestMongoCacheDelete(t *testing.T) {
	mgoCache := NewMongoCacheWithTTL(session)
	defer mgoCache.StopGC()
	if mgoCache == nil {
		t.Fatal("config should not be nil")
	}
	key := bson.NewObjectId().Hex()
	value := bson.NewObjectId().Hex()

	err := mgoCache.Set(key, value)
	if err != nil {
		t.Fatalf("error should be nil: %q", err)
	}
	data, err := mgoCache.Get(key)
	if err != nil {
		t.Fatalf("error should be nil: %q", err)
	}
	if data != value {
		t.Fatalf("data should equal to %v, but got: %v", value, data)
	}

	if err = mgoCache.Delete(key); err != nil {
		t.Fatalf("err should be nil, but got %q", err)
	}

	if _, err := mgoCache.Get(key); err != ErrNotFound {
		t.Fatalf("error should equal to %q but got: %q", ErrNotFound, err)
	}
}

示例#5
文件: mailThreadCache_test.go 项目: PradheepShrinivasan/mailbox

func createMail(subject string, body string) (mail mail.Mail) {

	var i int

	mail.Init()

	mail.From = bson.NewObjectId()
	for i = 0; i < 5; i++ {
		mail.To = append(mail.To, bson.NewObjectId())
	}

	for i = 0; i < 5; i++ {
		mail.Cc = append(mail.Cc, bson.NewObjectId())
	}

	for i = 0; i < 5; i++ {
		mail.Bcc = append(mail.Bcc, bson.NewObjectId())
	}

	mail.Subject = subject

	mail.Mailtext = body

	return mail
}

示例#6
文件: default_token_test.go 项目: phuc0302/go-oauth2

func Test_DefaultToken(t *testing.T) {
	defer os.Remove(debug)
	Cfg = LoadConfig(debug)

	token := DefaultToken{
		ID:      bson.NewObjectId(),
		User:    bson.NewObjectId(),
		Client:  bson.NewObjectId(),
		Created: time.Now(),
	}
	token.Expired = token.Created.Add(Cfg.RefreshTokenDuration)

	// Test token
	tokenString := token.Token()
	if len(tokenString) == 0 {
		t.Error(test.ExpectedNotNil)
	} else {
		jwtToken, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
			if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, fmt.Errorf("Unexpected signing method: %v", t.Header["alg"])
			}
			return &privateKey.PublicKey, nil
		})

		if err != nil || !jwtToken.Valid {
			t.Error("Expected token string should be able to decoded.")
		}
	}
}

示例#7
文件: mgo_test.go 项目: FIPress/fipmgo

func TestInsert(t *testing.T) {
	InitMgoWithAuth("localhost", "test", "dba", "[email protected]")
	tt := &Test{}
	tt.Id = bson.NewObjectId()
	tt.Name = "Abby"
	tt.Age = 33

	//testAccessor.Insert(tt)

	t2 := &Test{}
	t2.Id = bson.NewObjectId()
	t2.Name = "Tony"
	t2.Age = 35

	testAccessor.Insert(tt, t2)
	/*err := GetMgoConn().C("test").Insert(tt)
	if err != nil {
		t.Error(err)
	}*/

	t.Log("return id", tt.Id.Hex())
	//var v = &Test{}
	/*_, v := testAccessor.Get(tt.Id).(*Test)

	t.Log(v.Id)
	t.Log(v.Name)
	t.Log(v.Age)*/
}

示例#8
文件: main.go 项目: jamesmarva/practice

func main() {
	sess, err := mgo.Dial("127.0.0.1")
	if err != nil {
		panic(err)
	}
	defer sess.Close()

	c := sess.DB("test1").C("test1")
	m1 := Mail{bson.NewObjectId(), "user1", "[email protected]"}
	m2 := Mail{bson.NewObjectId(), "user2", "[email protected]"}
	m3 := Mail{bson.NewObjectId(), "user3", "[email protected]"}
	m4 := Mail{bson.NewObjectId(), "user4", "[email protected]"}
	err = c.Insert(&m1, &m2, &m3, &m4)
	if err != nil {
		panic(err)
	}

	ms := []Mail{}
	err = c.Find(&bson.M{"name": "user1"}).All(&ms)

	if err != nil {
		panic(err)
	}

	for i, m := range ms {
		fmt.Printf("%s, %d, %s\n", m.Id.Hex(), i, m.Email)
	}
}

示例#9
文件: comment.go 项目: rolandjudd/thingstodo

// Called on a POST to /events/:id/comments
// Assuming valid comment; Adds the comment under the given id
func AddComment(db *mgo.Database, r render.Render, comment models.Comment, p martini.Params) {
	var eventId bson.ObjectId

	// Create a unique id
	comment.Id = bson.NewObjectId()

	if bson.IsObjectIdHex(p["event_id"]) {
		eventId = bson.ObjectIdHex(p["event_id"])
	} else {
		r.JSON(400, "Bad Request: Invalid Event ID")
		return
	}

	comment.EventId = eventId

	// TODO Should be the user Id
	comment.CreatedBy = bson.NewObjectId()
	comment.CreatedAt = time.Now().UTC()

	err := db.C("comments").Insert(comment)
	if err != nil {
		panic(err)
	}

	r.JSON(201, comment)
}

示例#10
文件: quality_reports_test.go 项目: mitre/ecqm

func (q *QualityReportSuite) SetUpSuite(c *C) {
	//set up dbtest server
	q.DBServer = &dbtest.DBServer{}
	q.DBServer.SetPath(c.MkDir())
	session := q.DBServer.Session()
	q.Database = session.DB("qme-test")
	qr := &models.QualityReport{MeasureID: "efg", EffectiveDate: 5678}
	qrID := bson.ObjectIdHex("56bd06841cd462774f2af485")
	qr.ID = qrID
	q.Database.C("query_cache").Insert(qr)
	ir := models.IndividualResult{MeasureID: "abcd", EffectiveDate: 1234, PatientID: "1234", InitialPatientPopulation: 1, Last: "Jones"}
	id := bson.NewObjectId()
	rw := &models.ResultWrapper{ID: id, IndividualResult: ir}
	q.Database.C("patient_cache").Insert(rw)
	ir2 := models.IndividualResult{MeasureID: "efg", EffectiveDate: 5678, PatientID: "1234", InitialPatientPopulation: 1, Last: "B"}
	id2 := bson.NewObjectId()
	rw2 := &models.ResultWrapper{ID: id2, IndividualResult: ir2}
	q.Database.C("patient_cache").Insert(rw2)
	ir3 := models.IndividualResult{MeasureID: "efg", EffectiveDate: 5678, PatientID: "5678", InitialPatientPopulation: 1, Denominator: 1, Last: "A"}
	id3 := bson.NewObjectId()
	rw3 := &models.ResultWrapper{ID: id3, IndividualResult: ir3}
	q.Database.C("patient_cache").Insert(rw3)
	e := gin.New()
	e.GET("/QualityReport/:id", ShowQualityReportHandler(q.Database))
	e.POST("/QualityReport", CreateQualityReportHandler(q.Database))
	e.GET("/QualityReport/:id/PatientResults", ShowQualityReportPatientsHandler(q.Database))
	q.Engine = e
}

示例#11
文件: alerts_test.go 项目: tychoish/evergreen

func TestAlertQueue(t *testing.T) {
	Convey("After queueing a few alerts", t, func() {
		db.Clear(alert.Collection)
		now := time.Now()

		// a bunch of alerts, in order of oldest to newest
		testAlerts := []*alert.AlertRequest{
			{Id: bson.NewObjectId(), Display: "test1", CreatedAt: now.Add(time.Millisecond)},
			{Id: bson.NewObjectId(), Display: "test2", CreatedAt: now.Add(2 * time.Millisecond)},
			{Id: bson.NewObjectId(), Display: "test3", CreatedAt: now.Add(3 * time.Millisecond)},
		}

		for _, a := range testAlerts {
			err := alert.EnqueueAlertRequest(a)
			So(err, ShouldBeNil)
		}

		Convey("dequeuing should return them in order, oldest first", func() {
			found := 0
			for {
				nextAlert, err := alert.DequeueAlertRequest()
				So(err, ShouldBeNil)
				if nextAlert == nil {
					break
				}
				So(nextAlert.Display, ShouldEqual, testAlerts[found].Display)
				So(nextAlert.QueueStatus, ShouldEqual, alert.InProgress)
				found++
			}
			So(found, ShouldEqual, len(testAlerts))
		})
	})
}

示例#12
文件: main.go 项目: mfs409/golang-webapp-tutorial

// Reset the database by dropping the entire database, re-creating it, and
// then creating the collections
//
// NB: since the schemas for the collections are determined by the
//     insertions, this isn't very exciting
func resetDb() {
	// Connect or fail
	db, err := mgo.Dial(cfg.DbHost)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// We'll use monotonic mode for now...
	db.SetMode(mgo.Monotonic, true)

	// drop the database
	err = db.DB(cfg.DbName).DropDatabase()
	if err != nil {
		log.Fatal(err)
	}

	// create the database by putting the collections into it
	//
	// NB: we must insert and then remove a row in order for the
	//     collection to actually exist
	u := db.DB(cfg.DbName).C("users")
	id := bson.NewObjectId()
	err = u.Insert(
		&UserEntry{
			ID:       id,
			State:    0,
			Googleid: "",
			Name:     "",
			Email:    "",
			Create:   time.Now()})
	if err != nil {
		log.Fatal(err)
	}
	q := bson.M{"_id": id}
	err = u.Remove(q)
	if err != nil {
		log.Fatal(err)
	}

	d := db.DB(cfg.DbName).C("data")
	id = bson.NewObjectId()
	err = d.Insert(
		&DataEntry{
			ID:         id,
			SmallNote:  "",
			BigNote:    "",
			FavInt:     72,
			FavFloat:   2.23,
			TrickFloat: nil,
			Create:     time.Now()})
	if err != nil {
		log.Fatal(err)
	}
	q = bson.M{"_id": id}
	err = d.Remove(q)
	if err != nil {
		log.Fatal(err)
	}
}

示例#13
文件: server.go 项目: sanjaysagarp/Co-Aud

func submitContestProjectHandler(w http.ResponseWriter, r *http.Request) {
	s := redis_session.Session(w, r)
	currentUser := user.FindUser(s.Get("Email"))

	r.ParseForm()
	castsAttendees := r.Form["castEmail[]"]
	castRoles := r.Form["castRole[]"]

	newContest := role.FindContests()
	currentContest := newContest[0]

	var castContainer []*project.Cast
	var newCast *project.Cast
	for i := 0; i < len(castsAttendees); i++ {
		castId := bson.NewObjectId()
		castUser := user.FindUser(castsAttendees[i])
		newCast = project.NewCast(castUser, castRoles[i], castId)
		project.InsertCast(newCast)
		castContainer = append(castContainer, newCast)
	}

	description := []string{r.FormValue("teamName") + ": \n", r.FormValue("description")}
	combinedDescription := strings.Join(description, "")

	projectId := bson.NewObjectId()
	newProject := project.NewContestProject(r.FormValue("title"), r.FormValue("url"), r.FormValue("shortDescription"), combinedDescription, castContainer, currentUser, projectId, currentContest)
	project.InsertProject(newProject)

	urlParts := []string{"/projects/?id=", projectId.Hex()}
	url := strings.Join(urlParts, "")
	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

示例#14
文件: server.go 项目: sanjaysagarp/Co-Aud

//api call for submitting project
func submitProjectHandler(w http.ResponseWriter, r *http.Request) {
	//data := setDefaultData(w, r)
	//submission := make(map[string]interface{})
	// **TOP
	s := redis_session.Session(w, r)
	currentUser := user.FindUser(s.Get("Email"))

	r.ParseForm()
	castsAttendees := r.Form["castEmail[]"]
	castRoles := r.Form["castRole[]"]

	var castContainer []*project.Cast
	var newCast *project.Cast
	for i := 0; i < len(castsAttendees); i++ {
		castId := bson.NewObjectId()
		castUser := user.FindUser(castsAttendees[i])
		newCast = project.NewCast(castUser, castRoles[i], castId)
		project.InsertCast(newCast)
		castContainer = append(castContainer, newCast)
	}

	projectId := bson.NewObjectId()
	fmt.Println("ID :::: ", projectId)
	//s := redis_session.Session(w, r)
	newProject := project.NewProject(r.FormValue("title"), r.FormValue("url"), r.FormValue("shortDescription"), r.FormValue("description"), castContainer, currentUser, projectId)
	//fmt.Println("new project: ", newProject.Id)
	project.InsertProject(newProject)

	urlParts := []string{"/projects/?id=", projectId.Hex()}
	url := strings.Join(urlParts, "")
	// redirect to project page
	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

示例#15
文件: tododao_test.go 项目: bgdsh/playground

func TestAll(t *testing.T) {

	ts := todo.Todos{}

	td0 := todo.Todo{bson.NewObjectId(), "12345560", time.Now()}
	td1 := todo.Todo{bson.NewObjectId(), "12345561", time.Now()}
	td2 := todo.Todo{bson.NewObjectId(), "12345562", time.Now()}
	td3 := todo.Todo{bson.NewObjectId(), "12345563", time.Now()}
	td4 := todo.Todo{bson.NewObjectId(), "12345564", time.Now()}

	createTodo(&td0)
	createTodo(&td1)
	createTodo(&td2)
	createTodo(&td3)
	createTodo(&td4)

	ts, _ = All()

	assert.Equal(t, td0.TodoMessage, ts[0].TodoMessage)
	assert.Equal(t, td1.TodoMessage, ts[1].TodoMessage)
	assert.Equal(t, td2.TodoMessage, ts[2].TodoMessage)
	assert.Equal(t, td3.TodoMessage, ts[3].TodoMessage)
	assert.Equal(t, td4.TodoMessage, ts[4].TodoMessage)

	clearDB()
}

示例#16
文件: validate_test.go 项目: wxf4150/bongo

func TestValidation(t *testing.T) {
	Convey("Validation", t, func() {
		Convey("ValidateRequired()", func() {
			So(ValidateRequired("foo"), ShouldEqual, true)
			So(ValidateRequired(""), ShouldEqual, false)
			So(ValidateRequired(0), ShouldEqual, false)
			So(ValidateRequired(1), ShouldEqual, true)
		})

		Convey("ValidateInclusionIn()", func() {
			So(ValidateInclusionIn("foo", []string{"foo", "bar", "baz"}), ShouldEqual, true)
			So(ValidateInclusionIn("bing", []string{"foo", "bar", "baz"}), ShouldEqual, false)
		})

		Convey("ValidateMongoIdRef()", func() {
			connection := getConnection()

			defer func() {
				connection.Session.DB("bongotest").DropDatabase()
			}()

			// Make the doc

			doc := &noHookDocument{}

			err := connection.Collection("docs").Save(doc)

			So(err, ShouldEqual, nil)
			So(ValidateMongoIdRef(doc.Id, connection.Collection("docs")), ShouldEqual, true)
			So(ValidateMongoIdRef(bson.NewObjectId(), connection.Collection("docs")), ShouldEqual, false)
			So(ValidateMongoIdRef(bson.NewObjectId(), connection.Collection("other_collection")), ShouldEqual, false)

		})
	})
}

示例#17
文件: order.go 项目: ninnemana/API

func (o *Order) Create() error {
	o.Token = bson.NewObjectId()
	o.CreatedAt = time.Now()
	o.ProcessedAt = time.Now()
	o.UpdatedAt = time.Now()

	if err := o.validate(); err != nil {
		return err
	}

	count, err := getOrderCount(o.ShopId)
	if err != nil {
		return err
	}
	o.OrderNumber = count + 1

	o.bindCustomer()

	if o.Id.Hex() == "" {
		o.Id = bson.NewObjectId()
	}

	sess, err := mgo.DialWithInfo(database.MongoConnectionString())
	if err != nil {
		return err
	}
	defer sess.Close()

	col := sess.DB("CurtCart").C("order")
	_, err = col.UpsertId(o.Id, o)

	return err
}

示例#18
文件: mongo_test.go 项目: koding/koding

func prepareMongoStackTmpls() error {
	stackTmpls := []*models.StackTemplate{
		&models.StackTemplate{
			Id:       boberStack,
			Group:    "orange",
			Title:    "boberStack",
			OriginID: bson.NewObjectId(),
		},
		&models.StackTemplate{
			Id:       johnStack,
			Group:    "orange",
			Title:    "johnStack",
			OriginID: bson.NewObjectId(),
		},
		&models.StackTemplate{
			Id:       blasterStack,
			Group:    "orange",
			Title:    "blasterStack",
			OriginID: bson.NewObjectId(),
		},
	}

	for _, st := range stackTmpls {
		if err := modelhelper.CreateStackTemplate(st); err != nil {
			return err
		}
	}

	return nil
}

示例#19
文件: buildManager.go 项目: EckoEdc/gogobuild

//NewBuild create a build and gives it to WorkerManager
func (b *BuildManager) newBuild(projectName string, sys string, commit string, deploy bool) *Build {
	project := PMInstance().GetProjectByName(projectName)
	project.Reload()
	var build Build
	if sys == "all" {
		for sysToBuild := range project.Configuration.BuildInstructions {
			build = Build{ID: bson.NewObjectId(),
				Date:           time.Now(),
				ProjectToBuild: project,
				TargetSys:      sysToBuild,
				State:          Created,
				Commit:         commit,
				Deploy:         deploy,
				GitCommitID:    project.GetHeadCommitID(),
			}
			WMInstance().Build(&build)
			b.saveBuild(&build)
		}
	} else {
		build = Build{
			ID:             bson.NewObjectId(),
			Date:           time.Now(),
			ProjectToBuild: project,
			TargetSys:      sys,
			State:          Created,
			Commit:         commit,
			Deploy:         deploy,
			GitCommitID:    project.GetHeadCommitID(),
		}
		WMInstance().Build(&build)
		b.saveBuild(&build)
	}
	return &build
}

示例#20
文件: main.go 项目: otsimo/listener

func main() {
	connect()
	defer closeConn()
	userId := bson.NewObjectId().Hex()
	subId := bson.NewObjectId().Hex()
	stream, err := client.CustomEvent(context.Background())
	if err != nil {
		panic(err)
	}
	start := time.Now()
	n := 0
	for {
		err := stream.Send(newEvent(userId, subId))
		if err != nil {
			panic(err)
		}
		n++
		now := time.Now()
		if now.Sub(start).Seconds() >= 5 {
			fmt.Println("finished at", now.Sub(start).Seconds(), "seconds", n, "requests")
			resp, err := stream.Recv()
			if err != nil {
				panic(err)
			}
			fmt.Println("response", resp)
			err = stream.CloseSend()
			if err != nil {
				panic(err)
			}
			break
		}
	}
}

示例#21
文件: main.go 项目: dongkui0712/golang-web-db

func initData(coll *mgo.Collection) {
	blogs := []interface{}{
		Blog{
			Id:        bson.NewObjectId(),
			Title:     "我的第一篇博客",
			Content:   "这是我的第一篇博客",
			CreatedAt: time.Now(),
		},
		Blog{
			Id:        bson.NewObjectId(),
			Title:     "今天天气不错",
			Content:   "今天天气虽然冷,但是很晴朗",
			CreatedAt: time.Now(),
		},
		Blog{
			Id:        bson.NewObjectId(),
			Title:     "周末参加创业松鼠聚会",
			Content:   "周末要去参加创业松鼠的聚会,可以认识很多朋友",
			CreatedAt: time.Now(),
		},
	}

	err := coll.Insert(blogs...)
	if err != nil {
		log.Printf("insert blogs with error: %s\n", err)
	}

	err = coll.EnsureIndexKey("title")
	if err != nil {
		log.Printf("ensure index with error: %s\n", err)
	}

	fmt.Println("初始化博客数据成功!")
}

示例#22
文件: AuthService.go 项目: intZz/leanote

func (this *AuthService) register(user info.User) (bool, string) {
	if userService.AddUser(user) {
		// 添加笔记本, 生活, 学习, 工作
		userId := user.UserId.Hex()
		notebook := info.Notebook{
			Seq:    -1,
			UserId: user.UserId}
		title2Id := map[string]bson.ObjectId{"life": bson.NewObjectId(), "study": bson.NewObjectId(), "work": bson.NewObjectId()}
		for title, objectId := range title2Id {
			notebook.Title = title
			notebook.NotebookId = objectId
			notebook.UserId = user.UserId
			notebookService.AddNotebook(notebook)
		}

		// 添加leanote -> 该用户的共享
		registerSharedUserId := configService.GetGlobalStringConfig("registerSharedUserId")
		if registerSharedUserId != "" {
			registerSharedNotebooks := configService.GetGlobalArrMapConfig("registerSharedNotebooks")
			registerSharedNotes := configService.GetGlobalArrMapConfig("registerSharedNotes")
			registerCopyNoteIds := configService.GetGlobalArrayConfig("registerCopyNoteIds")

			// 添加共享笔记本
			for _, notebook := range registerSharedNotebooks {
				perm, _ := strconv.Atoi(notebook["perm"])
				shareService.AddShareNotebookToUserId(notebook["notebookId"], perm, registerSharedUserId, userId)
			}

			// 添加共享笔记
			for _, note := range registerSharedNotes {
				perm, _ := strconv.Atoi(note["perm"])
				shareService.AddShareNoteToUserId(note["noteId"], perm, registerSharedUserId, userId)
			}

			// 复制笔记
			for _, noteId := range registerCopyNoteIds {
				note := noteService.CopySharedNote(noteId, title2Id["life"].Hex(), registerSharedUserId, user.UserId.Hex())
				//				Log(noteId)
				//				Log("Copy")
				//				LogJ(note)
				noteUpdate := bson.M{"IsBlog": false} // 不要是博客
				noteService.UpdateNote(user.UserId.Hex(), note.NoteId.Hex(), noteUpdate, -1)
			}
		}

		//---------------
		// 添加一条userBlog
		blogService.UpdateUserBlog(info.UserBlog{UserId: user.UserId,
			Title:      user.Username + " 's Blog",
			SubTitle:   "Love Leanote!",
			AboutMe:    "Hello, I am (^_^)",
			CanComment: true,
		})
		// 添加一个单页面
		blogService.AddOrUpdateSingle(user.UserId.Hex(), "", "About Me", "Hello, I am (^_^)")
	}

	return true, ""
}

示例#23
文件: transactionapi_test.go 项目: coddo/gost

func testPostTransactionNotIntegral(t *testing.T) {
	transaction := &models.Transaction{
		ID:       bson.NewObjectId(),
		Payer:    identity.ApplicationUser{ID: bson.NewObjectId()},
		Currency: "USD",
	}

	tests.PerformTestRequest(endpointPath, ActionCreate, api.POST, http.StatusBadRequest, nil, transaction, t)
}

示例#24
文件: plag_test.go 项目: sohlich/go-plag

func (f *FakeDataStorage) FindAllSubmissionsByAssignment(assignmentID string) ([]SubmissionFile, error) {

	return []SubmissionFile{
		SubmissionFile{Submission: "1", ID: bson.NewObjectId()},
		SubmissionFile{Submission: "2", ID: bson.NewObjectId()},
		SubmissionFile{Submission: "3", ID: bson.NewObjectId()},
		SubmissionFile{Submission: "4", ID: bson.NewObjectId()},
		SubmissionFile{Submission: "5", ID: bson.NewObjectId()},
	}, nil
}

示例#25
文件: roles_test.go 项目: koding/koding

func TestFetchAdminAccounts(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	acc1 := createTestAccount(t)
	defer modelhelper.RemoveAccount(acc1.Id)

	acc2 := createTestAccount(t)
	defer modelhelper.RemoveAccount(acc2.Id)

	group, err := createGroup()
	if err != nil {
		t.Error(err)
	}

	accounts, err := modelhelper.FetchAdminAccounts(group.Slug)
	if err != nil {
		t.Error(err)
	}

	if len(accounts) != 0 {
		t.Errorf("accounts count should be 0, got: %d", len(accounts))
	}

	if err := modelhelper.AddRelationship(&models.Relationship{
		Id:         bson.NewObjectId(),
		TargetId:   acc1.Id,
		TargetName: "JAccount",
		SourceId:   group.Id,
		SourceName: "JGroup",
		As:         "admin",
	}); err != nil {
		t.Error(err)
	}

	if err := modelhelper.AddRelationship(&models.Relationship{
		Id:         bson.NewObjectId(),
		TargetId:   acc2.Id,
		TargetName: "JAccount",
		SourceId:   group.Id,
		SourceName: "JGroup",
		As:         "admin",
	}); err != nil {
		t.Error(err)
	}

	accounts, err = modelhelper.FetchAdminAccounts(group.Slug)
	if err != nil {
		t.Error(err)
	}

	if len(accounts) != 2 {
		t.Errorf("accounts count should be 2, got: %d", len(accounts))
	}
}

示例#26
文件: feature.go 项目: yuzhiyue/3rd_data_import

func SaveFeatureV2(session *mgo.Session, f1 Feature, f2 Feature) error {
	if f1.Type == f2.Type && f1.Value == f2.Value {
		log.Println("SaveFeature: f1 == f2")
		return errors.New("f1 == f2")
	}

	c := session.DB("feature").C("feature")
	oldFeature1 := Feature{}
	oldFeature2 := Feature{}
	err1 := c.Find(bson.M{"value": f1.Value, "type": f1.Type}).One(&oldFeature1)
	err2 := c.Find(bson.M{"value": f2.Value, "type": f2.Type}).One(&oldFeature2)
	if err1 != nil {
		f1.ID = bson.NewObjectId().Hex()
	} else {
		f1.ID = oldFeature1.ID
		f1.Relate = oldFeature1.Relate
	}

	if err2 != nil {
		f2.ID = bson.NewObjectId().Hex()
	} else {
		f2.ID = oldFeature2.ID
		f2.Relate = oldFeature2.Relate
	}

	hasRelate := false
	for i := range f1.Relate {
		r := &f1.Relate[i]
		if r.Target == f2.ID {
			hasRelate = true
			r.Count++
		}
	}
	if !hasRelate {
		r := FeatureRelate{f2.ID, 1}
		f1.Relate = append(f1.Relate, r)
	}

	hasRelate = false
	for i := range f2.Relate {
		r := &f2.Relate[i]
		if r.Target == f1.ID {
			hasRelate = true
			r.Count++
		}
	}
	if !hasRelate {
		r := FeatureRelate{f1.ID, 1}
		f2.Relate = append(f2.Relate, r)
	}

	c.UpsertId(f1.ID, f1)
	c.UpsertId(f2.ID, f2)
	return nil
}

示例#27
文件: mocks.go 项目: Cristofori/kmud

func NewMockPC() *MockPC {
	return &MockPC{
		MockCharacter: MockCharacter{
			MockObject: MockObject{
				MockIdentifiable: MockIdentifiable{Id: bson.NewObjectId()},
			},
			MockNameable: MockNameable{Name: "Mock PC"},
		},
		RoomId: bson.NewObjectId(),
	}
}

示例#28
文件: mail_test.go 项目: PradheepShrinivasan/mailbox

func (s *MySuite) TestGetReferenceWithMultipleTo(c *C) {

	var mail Mail

	mail.Init()
	mail.To = append(mail.To, bson.NewObjectId())
	mail.To = append(mail.To, bson.NewObjectId())

	c.Assert(len(mail.To), Equals, 2)
	c.Assert(mail.GetReferenceCount(), Equals, 2)
}

示例#29
文件: transactions_service_CRUD_test.go 项目: coddo/gost

func changeAndUpdateTransaction(t *testing.T, transaction *dbmodels.Transaction) {
	transaction.PayerID = bson.NewObjectId()
	transaction.ReceiverID = bson.NewObjectId()
	transaction.Type = models.TransactionTypeCard
	transaction.Currency = "USD"

	err := UpdateTransaction(transaction)

	if err != nil {
		t.Fatal("The transaction document could not be updated!")
	}
}

示例#30
文件: machine_test.go 项目: koding/koding

func TestGetMachinesByUsernameAndProvider(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	user := &models.User{Name: "testuser", ObjectId: bson.NewObjectId()}
	defer modelhelper.RemoveUser(user.Name)

	if err := modelhelper.CreateUser(user); err != nil {
		t.Error(err)
	}

	// koding provider machine
	m1 := &models.Machine{
		ObjectId: bson.NewObjectId(),
		Uid:      bson.NewObjectId().Hex(),
		Provider: "koding",
		Users: []models.MachineUser{
			{Id: user.ObjectId, Owner: true},
		},
	}

	if err := modelhelper.CreateMachine(m1); err != nil {
		t.Errorf(err.Error())
	}

	defer modelhelper.DeleteMachine(m1.ObjectId)

	// non koding provider machine
	m2 := &models.Machine{
		ObjectId: bson.NewObjectId(),
		Uid:      bson.NewObjectId().Hex(),
		Provider: "amazon",
		Users: []models.MachineUser{
			{Id: user.ObjectId, Owner: true},
		},
	}

	if err := modelhelper.CreateMachine(m2); err != nil {
		t.Errorf(err.Error())
	}

	defer modelhelper.DeleteMachine(m2.ObjectId)

	// should only get koding provider machine
	machines, err := modelhelper.GetMachinesByUsernameAndProvider(user.Name, m1.Provider)
	if err != nil {
		t.Error(err.Error())
	}

	if len(machines) != 1 {
		t.Errorf("machine count should be 2, got: %d", len(machines))
	}
}

展开阅读全文