Exemple #1
1
// Gets all authors from the user's repository and prints them out as json
func IndexAuthors(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	ctx := appengine.NewContext(r)
	authors, err := repositories.GetUsersAboveLevel(ctx, models.UserAuthor)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	response, err := json.Marshal(authors)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(response)
}
// Should return users that are level 3 or above
func TestIndexAuthors(t *testing.T) {
	ctx, done, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer done()
	key := []*datastore.Key{
		datastore.NewKey(ctx, "User", "dranton", 0, nil),
		datastore.NewKey(ctx, "User", "testertim", 0, nil),
		datastore.NewKey(ctx, "User", "rookierook", 0, nil),
	}

	seededUsers := []*models.User{
		&models.User{FirstName: "Anton", Level: 5},
		&models.User{FirstName: "Tim", Level: 3},
		&models.User{FirstName: "Rookie", Level: 1},
	}

	if _, err := datastore.PutMulti(ctx, key, seededUsers); err != nil {
		t.Fatal(err)
	}

	time.Sleep(300 * time.Millisecond)

	var authors []models.User
	authors, err = repositories.GetUsersAboveLevel(ctx, 3)
	if err != nil {
		t.Errorf("Error: %v", err)
	}

	if len(authors) != 2 {
		t.Errorf("Got %d authors, want %d", len(authors), 2)
	}

	if authors[0].Username != "testertim" {
		t.Errorf("Got username %d, want %d", authors[1].Username, "testertim")
	}
}