Пример #1
0
func TestCreateAndGetGroup(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

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

	g2, err := modelhelper.GetGroup(g.Slug)
	if err != nil {
		t.Errorf(err.Error())
	}

	if g2 == nil {
		t.Errorf("couldnt fetch group by its slug. Got nil, expected: %+v", g)
	}

	if g2.Id.Hex() != g.Id.Hex() {
		t.Errorf("groups are not same: expected: %+v, got: %+v ", g.Id.Hex(), g2.Id.Hex())
	}

	randomName := bson.NewObjectId().Hex()
	_, err = modelhelper.GetGroup(randomName)
	if err == nil {
		t.Errorf("we should not be able to find the group")
	}
}
Пример #2
0
func TestGetWorkspaceByChannelId(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	rand.Seed(time.Now().UnixNano())

	w, err := createWorkspace()
	if err != nil {
		t.Fatalf(err.Error())
	}

	w2, err := modelhelper.GetWorkspaceByChannelId(w.ChannelId)
	if err != nil {
		t.Errorf(err.Error())
	}

	if w2 == nil {
		t.Errorf("couldnt fetch workspace by channel id got nil, expected: %+v", w)
	}

	if w2.ObjectId.Hex() != w.ObjectId.Hex() {
		t.Errorf("workspaces are not same: expected: %+v, got: ", w)
	}

	_, err = modelhelper.GetWorkspaceByChannelId(strconv.FormatInt(rand.Int63(), 10))
	if err == nil {
		t.Errorf("we should not be able to find the WS")
	}
}
Пример #3
0
func TestUserLoginSessionCreation(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

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

	group, err := createGroup()
	if 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:         "member",
	}); err != nil {
		t.Error(err)
	}

	ses, err := modelhelper.UserLogin(acc2.Profile.Nickname, group.Slug)
	if err != nil {
		t.Errorf("expected nil error, but got %q!", err)
	}

	if ses == nil || ses.ClientId == "" {
		t.Error("expected ses.ClientId to be set, but got empty!")
	}
}
Пример #4
0
func TestUnsetSocialChannelFromWorkspace(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	rand.Seed(time.Now().UnixNano())

	w, err := createWorkspace()
	if err != nil {
		t.Fatalf(err.Error())
	}

	// first fetch it
	w2, err := modelhelper.GetWorkspaceByChannelId(w.ChannelId)
	if err != nil {
		t.Errorf(err.Error())
	}

	if w2 == nil {
		t.Errorf("couldnt fetch workspace by channel id got nil, expected: %+v", w)
	}

	if w2.ObjectId.Hex() != w.ObjectId.Hex() {
		t.Errorf("workspaces are not same: expected: %+v, got: ", w)
	}

	err = modelhelper.UnsetSocialChannelFromWorkspace(w.ObjectId)
	if err != nil {
		t.Errorf("we should be able to unset social channel id")
	}

	_, err = modelhelper.GetWorkspaceByChannelId(w.ChannelId)
	if err == nil {
		t.Errorf("we should not be able to find the WS")
	}
}
Пример #5
0
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))
	}
}
Пример #6
0
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))
	}
}
Пример #7
0
func TestGetCombinedAppStorageByAccountId(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	acc := createTestAccount(t)

	_, err := modelhelper.GetCombinedAppStorageByAccountId(acc.Id)
	if err == nil {
		t.Fatalf("error should be nil but got:", err)
	}

}
Пример #8
0
func TestBlockUser(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	username, blockedReason := "testuser", "testing"

	user := &models.User{
		Name: username, ObjectId: bson.NewObjectId(), Status: models.UserBlocked,
	}

	defer func() {
		modelhelper.RemoveUser(username)
	}()

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

	err = modelhelper.BlockUser(username, blockedReason, 1*time.Hour)
	if err != nil {
		t.Error(err)
	}

	user, err = modelhelper.GetUser(username)
	if err != nil {
		t.Error(err)
	}

	if user.Status != models.UserBlocked {
		t.Errorf("User status is not blocked")
	}

	if user.BlockedReason != blockedReason {
		t.Errorf("User blocked reason is not: %s", blockedReason)
	}

	if user.BlockedUntil.IsZero() {
		t.Errorf("User blocked until date is not set")
	}

	id, err := modelhelper.GetUserID(user.Name)
	if err != nil {
		t.Fatalf("GetUserID()=%s", err)
	}

	if id != user.ObjectId {
		t.Fatalf("got %q, want %q", id.Hex(), user.ObjectId.Hex())
	}
}
Пример #9
0
func TestSessionUpdateData(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()
	testUsername := "******"
	testGroupName := "testgroupname"
	ses, err := modelhelper.CreateSessionForAccount(testUsername, testGroupName)
	if err != nil {
		t.Error(err)
	}

	nonExistingKey := "nonExistingKey"
	val, err := ses.Data.GetString(nonExistingKey)
	if err != models.ErrDataKeyNotExists {
		t.Error("expected ErrDataKeyNotExists, got", err)
	}

	if val != "" {
		t.Error("expected empty string, got", val)
	}

	key := "chargeID"
	value := "chargeVal"

	data := map[string]interface{}{
		key: value,
	}

	if err := modelhelper.UpdateSessionData(ses.ClientId, data); err != nil {
		t.Error(err)
	}

	ses, err = modelhelper.GetSessionById(ses.Id.Hex())
	if err != nil {
		t.Error(err)
	}

	val, err = ses.Data.GetString(key)
	if err != nil {
		t.Error("expected nil, got", err)
	}

	if val != value {
		t.Error("expected", value, "got", val)
	}
}
Пример #10
0
func TestGetMostRecentSession(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()
	g, err := createGroup()
	if err != nil {
		t.Fatalf("createGroup()=%s", err)
	}

	newSession := func(long time.Duration) *models.Session {
		return &models.Session{
			Id:           bson.NewObjectId(),
			ClientId:     bson.NewObjectId().Hex(),
			Username:     "******",
			GroupName:    g.Slug,
			SessionBegan: time.Now().UTC().Add(long),
			LastAccess:   time.Now().UTC().Add(long),
		}
	}

	sessions := []*models.Session{
		newSession(0),
		newSession(10 * time.Minute),
		newSession(1 * time.Hour), // <- this is most recent
		newSession(15 * time.Second),
		newSession(58 * time.Minute),
		newSession(-1 * time.Hour),
	}

	for i, s := range sessions {
		if err := modelhelper.CreateSession(s); err != nil {
			t.Fatalf("%d: CreateSession()=%s", i, err)
		}
	}

	got, err := modelhelper.GetMostRecentSession("user")
	if err != nil {
		t.Fatalf("GetMostRecentSession()=%s", err)
	}

	if got.Id != sessions[2].Id {
		t.Fatalf("got %q, want %q", got.Id.Hex(), sessions[2].Id.Hex())
	}
}
Пример #11
0
func TestGetAllCombinedAppStorageByAccountId(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	acc := createTestAccount(t)

	cs1 := &models.CombinedAppStorage{
		Id:        bson.NewObjectId(),
		AccountId: acc.Id,
	}
	cs2 := &models.CombinedAppStorage{
		Id:        bson.NewObjectId(),
		AccountId: acc.Id,
	}

	if err := modelhelper.CreateCombinedAppStorage(cs1); err != nil {
		t.Fatalf("error should be nil but got:", err)
	}

	if err := modelhelper.CreateCombinedAppStorage(cs2); err != nil {
		t.Fatalf("error should be nil but got:", err)
	}

	if cs1 == nil {
		t.Fatal("CombinedAppStorage should not be nil")
	}

	if cs1.AccountId != acc.Id {
		t.Fatalf("CombinedAppStorage Account id should equal: but got:", acc.Id, cs1.AccountId)
	}

	css, err := modelhelper.GetAllCombinedAppStorageByAccountId(acc.Id)
	if err != nil {
		t.Fatalf("error should be nil but got:", err)
	}

	if len(css) != 2 {
		t.Fatalf("length of CombinedAppStorage should equal to 2, but got:", len(css))
	}

}
Пример #12
0
func TestGetAccountBySocialApiIds(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)

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

	accounts, err := modelhelper.GetAccountBySocialApiIds(acc1.SocialApiId, acc2.SocialApiId, acc3.SocialApiId)
	if err != nil {
		t.Error(err)
	}

	if len(accounts) != 3 {
		t.Errorf("accounts count should be 3, got: %d", len(accounts))
	}
}
Пример #13
0
func TestCreateCombinedAppStorage(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	acc := createTestAccount(t)

	cs := &models.CombinedAppStorage{
		Id:        bson.NewObjectId(),
		AccountId: acc.Id,
	}

	if err := modelhelper.CreateCombinedAppStorage(cs); err != nil {
		t.Fatalf("error should be nil but got:", err)
	}

	if cs == nil {
		t.Fatal("CombinedAppStorage should not be nil")
	}

	if cs.AccountId != acc.Id {
		t.Fatalf("CombinedAppStorage Account id should equal: but got:", acc.Id, cs.AccountId)
	}
}
Пример #14
0
func TestUnshareMachine(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	m := createMachine(t)
	defer modelhelper.DeleteMachine(m.ObjectId)

	if err := modelhelper.UnshareMachineByUid(m.Uid); err != nil {
		t.Error(err)
	}

	m2, err := modelhelper.GetMachineByUid(m.Uid)
	if err != nil {
		t.Error(err.Error())
	}

	if len(m2.Users) != 1 {
		t.Errorf("user count should be 1, got: %d", len(m2.Users))
	}

	if !(m2.Users[0].Sudo && m2.Users[0].Owner) {
		t.Errorf("only owner should have sudo and owner priv.")
	}
}
Пример #15
0
func TestRemoveUser(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	username := "******"
	user := &models.User{
		Name: username, ObjectId: bson.NewObjectId(),
	}

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

	err = modelhelper.RemoveUser(username)
	if err != nil {
		t.Error(err)
	}

	user, err = modelhelper.GetUser(username)
	if err == nil {
		t.Errorf("User should've been deleted, but wasn't")
	}
}
Пример #16
0
func TestCounter(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	if err := delCounters(); err != nil {
		t.Fatalf("delCounters()=%s", err)
	}

	counters := []*models.Counter{{
		ID:        bson.NewObjectId(),
		Namespace: "foo",
		Type:      "member_instaces",
		Current:   10,
	}, {
		ID:        bson.NewObjectId(),
		Namespace: "foo",
		Type:      "member_stacks",
		Current:   1,
	}, {
		ID:        bson.NewObjectId(),
		Namespace: "bar",
		Type:      "member_instances",
		Current:   2,
	}, {
		ID:        bson.NewObjectId(),
		Namespace: "bar",
		Type:      "member_stacks",
		Current:   5,
	}}

	sort.Sort(models.Counters(counters))

	if err := modelhelper.CreateCounters(counters...); err != nil {
		t.Fatalf("CreateCounters()=%s", err)
	}

	c, err := allCounters()
	if err != nil {
		t.Fatalf("counters()=%s", err)
	}

	if !reflect.DeepEqual(counters, c) {
		t.Fatalf("got %+v, want %+v", c, counters)
	}

	decCases := []struct {
		n    int
		want int
	}{
		{7, 3}, // i=0
		{1, 0}, // i=1
		{2, 0}, // i=2
		{3, 2}, // i=3
	}

	for i, cas := range decCases {
		c := counters[i]

		err := modelhelper.DecrementOrCreateCounter(c.Namespace, c.Type, cas.n)
		if err != nil {
			t.Errorf("%d (%s): DecrementOrCreateCounter()=%s", i, c.ID.Hex(), err)
			continue
		}

		got, err := modelhelper.CounterByID(c.ID)
		if err != nil {
			t.Errorf("%d (%s): CounterByID()=%d", i, c.ID.Hex(), err)
			continue
		}

		if got.Current != cas.want {
			t.Errorf("%d (%s): got %d, want %d", i, c.ID.Hex(), got.Current, cas.want)
		}
	}

	newCases := []struct {
		namespace string
		typ       string
		n         int
	}{
		{"qux", "member_stacks", 1},    // i=0
		{"qux", "member_instances", 3}, // i=0
	}

	for i, cas := range newCases {
		err := modelhelper.DecrementOrCreateCounter(cas.namespace, cas.typ, cas.n)
		if err != nil {
			t.Errorf("%d: DecrementOrCreateCounter()=%s", i, err)
		}
	}

	c, err = modelhelper.CountersByNamespace("qux")
	if err != nil {
		t.Fatalf("CountersByNamespace()=%s", err)
	}

	if len(c) != 2 {
		t.Fatalf("got len(c)=%d, want len(c)=2", len(c))
	}
}
Пример #17
0
func TestGetAnyUserTokenFromGroup(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	id := bson.NewObjectId()
	username := id.Hex()
	user := &models.User{
		ObjectId: id,
		Name:     username,
		Email:    username + "@" + username + ".com",
	}

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

	groupName := bson.NewObjectId().Hex()

	key := fmt.Sprintf("foreignAuth.slack.%s.token", groupName)
	token := "token-123qwe"
	selector := bson.M{"username": username}
	update := bson.M{key: token}

	if err := modelhelper.UpdateUser(selector, update); err != nil {
		t.Error("Error while updating user")
	}

	id2 := bson.NewObjectId()
	username2 := id2.Hex()
	user2 := &models.User{
		ObjectId: id2,
		Name:     username2,
		Email:    username2 + "@" + username2 + ".com",
	}

	err = modelhelper.CreateUser(user2)
	if err != nil {
		t.Error(err)
	}

	groupName2 := bson.NewObjectId().Hex()
	key2 := fmt.Sprintf("foreignAuth.slack.%s.token", groupName2)
	token2 := "token-123qwe11"
	selector2 := bson.M{"username": username2}
	update2 := bson.M{key2: token2}

	if err := modelhelper.UpdateUser(selector2, update2); err != nil {
		t.Error("Error while updating user")
	}

	users, err := modelhelper.GetAnySlackTokenWithGroup(groupName)
	if err != nil {
		t.Error("Error while getting user token")
	}

	if len(users) != 1 {
		t.Error("Length of user should be 1")
	}

	err = modelhelper.RemoveUser(username)
	if err != nil {
		t.Error(err)
	}
}
Пример #18
0
func TestHasRole(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)
	}

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

	tests := []struct {
		Title string
		Nick  string
		Slug  string
		Roles []string
		Has   bool
	}{
		{
			Title: "Member account",
			Nick:  acc1.Profile.Nickname,
			Slug:  group.Slug,
			Roles: []string{"member"},
			Has:   true,
		},
		{
			Title: "Member account with multi role",
			Nick:  acc1.Profile.Nickname,
			Slug:  group.Slug,
			Roles: []string{"member", "admin"},
			Has:   true,
		},
		{
			Title: "Member account with default roles",
			Nick:  acc1.Profile.Nickname,
			Slug:  group.Slug,
			Roles: modelhelper.DefaultRoles,
			Has:   true,
		},
		{
			Title: "Non-member account",
			Nick:  acc2.Profile.Nickname,
			Slug:  group.Slug,
			Roles: []string{"member"},
			Has:   false,
		},
		{
			Title: "Invalid role correct account",
			Nick:  acc1.Profile.Nickname,
			Slug:  group.Slug,
			Roles: []string{"admin"},
			Has:   false,
		},
		{
			Title: "Invalid role in-correct account",
			Nick:  acc2.Profile.Nickname,
			Slug:  group.Slug,
			Roles: []string{"admin"},
			Has:   false,
		},
	}

	for _, test := range tests {
		has, err := modelhelper.HasAnyRole(test.Nick, test.Slug, test.Roles...)
		if err != nil {
			t.Error(err)
		}
		if has != test.Has {
			t.Errorf("expected %q's \"has\" equal to %t, but it wasnt!", test.Title, test.Has)
		}
	}
}
Пример #19
0
func TestUserLogin(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)
	}

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

	ses, err := modelhelper.CreateSessionForAccount(acc1.Profile.Nickname, group.Slug)
	if err != nil {
		t.Error(err)
	}

	tests := []struct {
		Title    string
		Nick     string
		Slug     string
		ClientID string
		Err      error
	}{
		{
			Title:    "Member account",
			Nick:     acc1.Profile.Nickname,
			Slug:     group.Slug,
			ClientID: ses.ClientId,
			Err:      nil,
		},
		{
			Title:    "Re-testing with Member account",
			Nick:     acc1.Profile.Nickname,
			Slug:     group.Slug,
			ClientID: ses.ClientId,
			Err:      nil,
		},
		{
			Title:    "Non-member account",
			Nick:     acc2.Profile.Nickname,
			Slug:     group.Slug,
			ClientID: "",
			Err:      modelhelper.ErrNotParticipant,
		},
	}

	for _, test := range tests {
		t.Run(test.Title, func(t *testing.T) {
			ses, err := modelhelper.UserLogin(test.Nick, test.Slug)
			if err != test.Err {
				t.Errorf("expected Err equal to %q, but got %q!", test.Err, err)
			}

			if ses != nil && ses.ClientId != test.ClientID {
				t.Errorf("expected ClientID equal to %q, but got %q!", test.ClientID, ses.ClientId)
			}
		})
	}
}
Пример #20
0
func TestFetchAccountGroups(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

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

	groups, err := modelhelper.FetchAccountGroups(acc1.Profile.Nickname)
	if err != mgo.ErrNotFound {
		t.Fatalf("want err = %v; got %v", mgo.ErrNotFound, err)
	}

	if len(groups) != 0 {
		t.Fatalf("expected len(groups) to be 0, got groups: %+v", groups)
	}

	group1, err := createGroup()
	if err != nil {
		t.Fatal(err)
	}

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

	groups, err = modelhelper.FetchAccountGroups(acc1.Profile.Nickname)
	if err != nil {
		t.Fatal(err)
	}

	if len(groups) != 1 {
		t.Fatalf("expected len(groups) to be 1, got groups: %+v", groups)
	}

	// test having 2 relationsips in one group
	group2, err := createGroup()
	if err != nil {
		t.Error(err)
	}

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

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

	groups, err = modelhelper.FetchAccountGroups(acc1.Profile.Nickname)
	if err != nil {
		t.Fatal(err)
	}

	if len(groups) != 2 {
		t.Fatalf("expected len(groups) to be 2, got groups: %+v", groups)
	}
}
Пример #21
0
func TestLookupGroup(t *testing.T) {
	const N = 10

	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	user := &models.User{
		ObjectId: bson.NewObjectId(),
		Name:     bson.NewObjectId().Hex(),
		Email:    bson.NewObjectId().Hex(),
	}

	if err := modelhelper.CreateUser(user); err != nil {
		t.Fatalf("CreateUser()=%s", err)
	}

	groups, err := createGroups(N + 1)
	if err != nil {
		t.Fatalf("createGroups()=%s", err)
	}

	machines, err := createMachines(N, t)
	if err != nil {
		t.Fatalf("createMachines()=%s", err)
	}

	for i := range machines {
		machines[i].Groups = []models.MachineGroup{{Id: groups[i].Id}}

		update := bson.M{
			"$set": bson.M{
				"groups": machines[i].Groups,
				"users": []*models.MachineUser{{
					Id:       user.ObjectId,
					Username: user.Name,
				}},
			},
		}

		if i&2 == 0 {
			// force to lookup by registerUrl for machines with even index
			update["$set"].(bson.M)["ipAddress"] = ""
		}

		err := modelhelper.UpdateMachine(machines[i].ObjectId, update)
		if err != nil {
			t.Fatalf("UpdateMachine()=%s", err)
		}
	}

	session := &models.Session{
		Id:        bson.NewObjectId(),
		GroupName: groups[N].Slug,
		Username:  user.Name,
	}

	if err := modelhelper.CreateSession(session); err != nil {
		t.Fatalf("CreateSession()=%s")
	}

	cases := map[string]struct {
		opts *modelhelper.LookupGroupOptions
		id   bson.ObjectId
	}{
		"lookup by queryString": {
			&modelhelper.LookupGroupOptions{
				Username: user.Name,
				KiteID:   mustKiteID(machines[0].QueryString),
			},
			groups[0].Id,
		},
		"lookup by ipAddress": {
			&modelhelper.LookupGroupOptions{
				Username:  user.Name,
				ClientURL: machines[1].RegisterURL,
			},
			groups[1].Id,
		},
		"lookup by registerUrl": {
			&modelhelper.LookupGroupOptions{
				Username:  user.Name,
				ClientURL: machines[4].RegisterURL,
			},
			groups[4].Id,
		},
		"lookup by most recent session for KD": {
			&modelhelper.LookupGroupOptions{
				Username:    user.Name,
				Environment: "managed",
			},
			groups[N].Id,
		},
	}

	for name, cas := range cases {
		t.Run(name, func(t *testing.T) {
			team, err := modelhelper.LookupGroup(cas.opts)
			if err != nil {
				t.Fatalf("LookupGroup()=%s", err)
			}

			if team.Id != cas.id {
				t.Fatalf("got %q, want %q", team.Id.Hex(), cas.id.Hex())
			}
		})
	}
}
Пример #22
0
func TestAddAndRemoveFromStack(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	user, group, machine, account, clean := testFixture(t)
	defer clean()

	sd := &modelhelper.StackDetails{
		UserID:    user.ObjectId,
		GroupID:   group.Id,
		MachineID: machine.ObjectId,

		UserName:  user.Name,
		GroupSlug: group.Slug,

		AccountID: account.Id,
		BaseID:    bson.ObjectIdHex("53fe557af052f8e9435a04fa"),
	}

	// Add for a first time.

	err := modelhelper.AddToStack(sd)
	if err != nil {
		t.Fatalf("error adding machine %q to stack: %s", machine.ObjectId.Hex(), err)
	}

	s, err := modelhelper.GetComputeStackByGroup(group.Slug, account.Id)
	if err != nil {
		t.Fatalf("error getting stack for koding, %q: %s", account.Id.Hex(), err)
	}

	if len(s.Machines) != 1 {
		t.Fatalf("want 1 machine, got %d", len(s.Machines))
	}

	if s.Machines[0] != machine.ObjectId {
		t.Fatalf("want machine %q to be added to stack, got %q instead", machine.ObjectId.Hex(), s.Machines[0].Hex())
	}

	m, err := modelhelper.GetMachine(machine.ObjectId.Hex())
	if err != nil {
		t.Fatalf("error getting machine %q: %s", machine.ObjectId.Hex(), err)
	}

	if len(m.Groups) != 1 {
		t.Fatalf("want 1 group, got %d", len(m.Groups))
	}

	if m.Groups[0].Id != group.Id {
		t.Fatalf("want group %q, got %q", group.Id.Hex(), m.Groups[0].Id.Hex())
	}

	// Adding for a second time must be idempotent.

	err = modelhelper.AddToStack(sd)
	if err != nil {
		t.Fatalf("error adding machine %q to stack: %s", machine.ObjectId.Hex(), err)
	}

	s2, err := modelhelper.GetComputeStackByGroup(group.Slug, account.Id)
	if err != nil {
		t.Fatalf("error getting stack for koding, %q: %s", account.Id.Hex(), err)
	}

	if s.Id != s2.Id {
		t.Errorf("want jComputeStack.ObjetId %q; got %q", s.Id.Hex(), s2.Id.Hex())
	}

	if len(s.Machines) != 1 {
		t.Fatalf("want 1 machine, got %d", len(s.Machines))
	}

	if s.Machines[0] != machine.ObjectId {
		t.Fatalf("want machine %q to be added to stack, got %q instead", machine.ObjectId.Hex(), s.Machines[0].Hex())
	}

	m, err = modelhelper.GetMachine(machine.ObjectId.Hex())
	if err != nil {
		t.Fatalf("error getting machine %q: %s", machine.ObjectId.Hex(), err)
	}

	if len(m.Groups) != 1 {
		t.Fatalf("want 1 group, got %d", len(m.Groups))
	}

	if m.Groups[0].Id != group.Id {
		t.Fatalf("want group %q, got %q", group.Id.Hex(), m.Groups[0].Id.Hex())
	}

	// Remove from stack.
	err = modelhelper.RemoveFromStack(sd)
	if err != nil {
		t.Fatalf("error removing %q from stack: %s", machine.ObjectId.Hex(), err)
	}

	s3, err := modelhelper.GetComputeStackByGroup(group.Slug, account.Id)
	if err != nil {
		t.Fatalf("error getting stack for koding, %q: %s", account.Id.Hex(), err)
	}

	if len(s3.Machines) != 0 {
		t.Fatalf("want 0 machine, got %d", len(s.Machines))
	}

	m, err = modelhelper.GetMachine(machine.ObjectId.Hex())
	if err != nil {
		t.Fatalf("error getting machine %q: %s", machine.ObjectId.Hex(), err)
	}

	if len(m.Groups) != 0 {
		t.Fatalf("want 0 group, got %d", len(m.Groups))
	}
}
Пример #23
0
func TestMongoDatabase(t *testing.T) {
	tests := []struct {
		Name     string
		Filter   *Filter
		IsValid  bool
		Machines []*Machine
	}{
		{
			Name: "bober machine list",
			Filter: &Filter{
				Username:     bober,
				Owners:       true,
				OnlyApproved: true,
			},
			IsValid: true,
			Machines: []*Machine{
				&Machine{
					ID:       boberAws0.Hex(),
					Team:     "orange",
					Stack:    "boberStack",
					Provider: "aws",
					Label:    "bober-aws-0",
					IP:       "127.0.0.1",
					Status: Status{
						State:  "running",
						Reason: "because it can",
					},
					Users: []User{
						{
							Sudo:     true,
							Owner:    true,
							Username: bober,
						},
					},
				},
				&Machine{
					ID:    boberAws1.Hex(),
					Team:  "orange",
					Stack: "boberStack",
					Label: "bober-aws-1",
					Users: []User{
						{
							Sudo:     true,
							Owner:    true,
							Username: bober,
						},
					},
				},
				&Machine{
					ID:    johnGoogle0.Hex(),
					Team:  "orange",
					Stack: "johnStack",
					Label: "john-google-0",
					Users: []User{
						{
							Sudo:     true,
							Owner:    true,
							Username: john,
						},
						{
							Approved: true,
							Username: bober,
						},
					},
				},
			},
		},
		{
			Name: "john machine list",
			Filter: &Filter{
				Username:     john,
				Owners:       true,
				OnlyApproved: true,
			},
			IsValid: true,
			Machines: []*Machine{
				&Machine{
					ID:    boberAws1.Hex(),
					Team:  "orange",
					Stack: "boberStack",
					Label: "bober-aws-1",
					Users: []User{
						{
							Sudo:     true,
							Owner:    true,
							Username: bober,
						},
						{
							Approved: true,
							Username: john,
						},
					},
				},
				&Machine{
					ID:    johnGoogle0.Hex(),
					Team:  "orange",
					Stack: "johnStack",
					Label: "john-google-0",
					Users: []User{
						{
							Sudo:     true,
							Owner:    true,
							Username: john,
						},
					},
				},
			},
		},
		{
			Name: "blaster machine list",
			Filter: &Filter{
				Username:     blaster,
				Owners:       true,
				OnlyApproved: true,
			},
			IsValid: true,
			Machines: []*Machine{
				&Machine{
					ID:    boberAws1.Hex(),
					Team:  "orange",
					Stack: "boberStack",
					Label: "bober-aws-1",
					Users: []User{
						{
							Sudo:     true,
							Owner:    true,
							Username: bober,
						},
						{
							Approved: true,
							Username: blaster,
						},
					},
				},
				&Machine{
					ID:    blasterAws0.Hex(),
					Team:  "orange",
					Stack: "blasterStack",
					Label: "blaster-aws-0",
					Users: []User{
						{
							Sudo:     true,
							Owner:    true,
							Username: blaster,
						},
					},
				},
			},
		},
		{
			Name: "unknown user machine list",
			Filter: &Filter{
				Username:     "******",
				Owners:       true,
				OnlyApproved: true,
			},
			IsValid:  false,
			Machines: nil,
		},
	}

	// Prepare database.
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	if err := prepareMongoMachines(); err != nil {
		t.Fatalf("want err == nil; got %v", err)
	}

	if err := prepareMongoStackTmpls(); err != nil {
		t.Fatalf("want err == nil; got %v", err)
	}

	mongoDB := NewMongoDatabase()
	for _, test := range tests {
		t.Run(test.Name, func(t *testing.T) {
			machines, err := mongoDB.Machines(test.Filter)
			if (err == nil) != test.IsValid {
				t.Fatalf("want valid test = %t; got err: %v", test.IsValid, err)
			}

			if len(machines) != len(test.Machines) {
				t.Fatalf("want slice length = %d; got %d", len(test.Machines), len(machines))
			}

			for i := range test.Machines {
				if !reflect.DeepEqual(machines[i], test.Machines[i]) {
					t.Fatalf("want machine[%d] = \n%# v\ngot:\n%# v\n", i, test.Machines[i], machines[i])
				}
			}
		})
	}
}