當前位置: 首頁>>代碼示例>>Golang>>正文


Golang aetest.NewContext函數代碼示例

本文整理匯總了Golang中google/golang.org/appengine/aetest.NewContext函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewContext函數的具體用法?Golang NewContext怎麽用?Golang NewContext使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewContext函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestGetUser

// Should return the user with the given username, or throw an Entity not found error
func TestGetUser(t *testing.T) {
	ctx, done, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer done()
	key := datastore.NewKey(ctx, "User", "testertim", 0, nil)
	if _, err := datastore.Put(ctx, key, &models.User{FirstName: "Tim"}); err != nil {
		t.Fatal(err)
	}

	user := &models.User{Username: "nonexistent"}
	if err = repositories.GetUser(ctx, user); err == nil || err.Error() != "datastore: no such entity" {
		t.Errorf("Error: %v; want datastore: no such entity", err)
	}

	user.Username = "testertim"
	err = repositories.GetUser(ctx, user)
	if err != nil {
		t.Fatal(err)
	}

	if firstName, want := user.FirstName, "Tim"; firstName != want {
		t.Errorf("User First Name %d, want %d", firstName, want)
	}

	if username, want := user.Username, "testertim"; username != want {
		t.Errorf("Username %d, want %d", username, want)
	}
}
開發者ID:the-weekend-project,項目名稱:blogApi,代碼行數:31,代碼來源:users_test.go

示例2: TestStoreUser

// Should store the given user, after encrypting its password
func TestStoreUser(t *testing.T) {
	ctx, done, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer done()

	user := &models.User{Username: "testertim", FirstName: "Tim", Email: "[email protected]", Password: []byte("I <3 golang")}
	err = repositories.StoreUser(ctx, user)

	if err != nil {
		t.Fatal(err)
	}

	key := datastore.NewKey(ctx, "User", "testertim", 0, nil)
	var storedUser models.User
	err = datastore.Get(ctx, key, &storedUser)
	if err != nil {
		t.Fatal(err)
	}

	if storedUser.FirstName != user.FirstName {
		t.Errorf("FirstName %d, want %d", storedUser.FirstName, user.FirstName)
	}

	if storedUser.Username != "" {
		t.Errorf("Username %d should be derived from the key, not stored", storedUser.Username)
	}

	if string(storedUser.Password) == "I <3 golang" {
		t.Errorf("Password %d should be hashed and not %d", string(storedUser.Password), "I <3 golang")
	}
}
開發者ID:the-weekend-project,項目名稱:blogApi,代碼行數:34,代碼來源:users_test.go

示例3: TestHasRole

func TestHasRole(t *testing.T) {

	ctx, done, _ := aetest.NewContext()
	defer done()
	ctx = test.WithConfig(ctx, map[string]interface{}{"AuthSecret": "foo"})

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "/", nil)
	r.Header.Set("Authorization", "wrong")

	// Make up a fake user
	acct, _ := account.New(ctx, "[email protected]", "foobar")
	acct.Roles = append(acct.Roles, "tyrant")
	account.Save(ctx, acct)

	// Unretrievable user, because middleware hasn't been run.
	if err := HasRole("foo")(ctx, w, r); err != ErrCannotGetAccount {
		t.Errorf("Unexpected error, wanted ErrCannotGetAccount, got %s", err)
	}

	// User's set, but claimset isn't for some reason.
	ctx2 := context.WithValue(ctx, internal.AuthContextKey, &account.Nobody)
	if err := HasRole("foo")(ctx2, w, r); err != ErrCannotGetClaimSet {
		t.Errorf("Unexpected error, wanted ErrCannotGetClaimSet, got %s", err)
	}

	// Account doesn't have the role.
	r.Header.Set("Authorization", test.JWT(&jws.ClaimSet{Sub: "[email protected]", Scope: AllScope}, "foo"))
	ctx2 = Middleware(ctx, w, r)
	if err := HasRole("foo")(ctx2, w, r); err != ErrRoleMissing {
		t.Errorf("Unexpected error, wanted ErrRoleMissing, got %s", err)
	}

	// Token doesn't have the role in scope.
	r.Header.Set("Authorization", test.JWT(&jws.ClaimSet{Sub: "[email protected]", Scope: "somethingelse"}, "foo"))
	ctx2 = Middleware(ctx, w, r)
	if err := HasRole("tyrant")(ctx2, w, r); err != ErrRoleNotInScope {
		t.Errorf("Unexpected error, wanted ErrRoleNotInScope, got %s", err)
	}

	// Token is consumable, but hasn't been used yet.
	consumableToken := test.ConsumableJWT(&jws.ClaimSet{Sub: "[email protected]", Scope: "tyrant"}, "foo", 1)
	r.Header.Set("Authorization", consumableToken)
	ctx2 = Middleware(ctx, w, r)
	if err := HasRole("tyrant")(ctx2, w, r); err != nil {
		t.Errorf("Unexpected error, wanted nil, got %s", err)
	}

	// We used this token once already. Should be used up.
	ctx2 = Middleware(ctx, w, r)
	if err := HasRole("tyrant")(ctx2, w, r); err != ErrClaimSetUsedUp {
		t.Errorf("Unexpected error, wanted ErrClaimSetUsedUp, got %s", err)
	}

}
開發者ID:the-information,項目名稱:ori,代碼行數:55,代碼來源:middleware_test.go

示例4: TestIndexHandler

func TestIndexHandler(t *testing.T) {
	_, done, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer done()

	inst, err := aetest.NewInstance(nil)
	if err != nil {
		t.Errorf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	request, err := inst.NewRequest("GET", "/", nil)
	if err != nil {
		t.Errorf("Error creating new instance %v", err)
	}

	response := httptest.NewRecorder()
	IndexHandler(response, request)
	if response.Code != http.StatusFound {
		t.Errorf("Did not get StatusFound(302) got %v", response.Code)
	}
	if response.Header().Get("Location") != "/index.html" {
		t.Errorf("Expected Location: /index.html but instead got %v", response.Header().Get("Location"))
	}
}
開發者ID:dherbst,項目名稱:go-appengine-example,代碼行數:27,代碼來源:handlers_test.go

示例5: TestProcess

func TestProcess(t *testing.T) {

	ctx, done, _ := aetest.NewContext()
	defer done()

	smallTest := strings.NewReader(`{
		"User/jsmith": {
			"Name": "John Smith",
			"LotteryNumbers": [1,2,3,4,5],
			"CreatedAt": {
				"Type": "time",
				"Value": "1993-05-01T12:31:00.000Z"
			}
		},
		"User/jdoe": {
			"Name": "Jane Doe",
			"LotteryNumbers": [2,4,6,8,10],
			"CreatedAt": {
				"Type": "time",
				"Value": "1992-01-30T08:01:00.000Z"
			}
		}
	}`)

	if err := Process(ctx, smallTest); err != nil {
		t.Errorf("Unexpected error %s", err)
	}

	key1 := datastore.NewKey(ctx, "User", "jdoe", 0, nil)
	key2 := datastore.NewKey(ctx, "User", "jsmith", 0, nil)

	value1 := fakeUser{}
	value2 := fakeUser{}

	if err := nds.Get(ctx, key1, &value1); err != nil {
		t.Errorf("Unexpected error %s retrieving value1", err)
	} else if err := nds.Get(ctx, key2, &value2); err != nil {
		t.Errorf("Unexpected error %s retrieving value2", err)
	}

	value1.CreatedAt = value1.CreatedAt.UTC()
	value2.CreatedAt = value2.CreatedAt.UTC()

	if !reflect.DeepEqual(value1, fakeUser{
		Name:           "Jane Doe",
		LotteryNumbers: []int64{2, 4, 6, 8, 10},
		CreatedAt:      time.Date(1992, 1, 30, 8, 1, 0, 0, time.UTC),
	}) {
		t.Errorf("Unexpected value in value1: %+v", value1)
	}

	if !reflect.DeepEqual(value2, fakeUser{
		Name:           "John Smith",
		LotteryNumbers: []int64{1, 2, 3, 4, 5},
		CreatedAt:      time.Date(1993, 5, 1, 12, 31, 0, 0, time.UTC),
	}) {
		t.Errorf("Unexpected value in value2: %+v", value1)
	}

}
開發者ID:the-information,項目名稱:ori,代碼行數:60,代碼來源:process_test.go

示例6: TestParseWormhole2

func TestParseWormhole2(t *testing.T) {
	c, err := aetest.NewContext(nil)
	if err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	wh, rpl := parseWormhole(`[[.Moke  もけ]]`)
	if wh == nil {
		t.Errorf("wh is nil")
	}

	if !reflect.DeepEqual(*wh, Wormhole{
		"Moke",
		"もけ",
		true,
		PROPERTY,
	}) {
		t.Errorf("illegal wh: %#v\n", wh)
	}

	if rpl != `{{index .Properties "Moke"}}` {
		t.Errorf("illegal rpl: %s\n", rpl)
	}
}
開發者ID:gcpug-shonan,項目名稱:gcpug-shonan-cms,代碼行數:25,代碼來源:caterpillar_test.go

示例7: TestParseWormhole1

//func parseWormhole(s string) (*Wormhole, string) {
func TestParseWormhole1(t *testing.T) {
	c, err := aetest.NewContext(nil)
	if err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	wh, rpl := parseWormhole(`[[hoge]]`)
	if wh == nil {
		t.Errorf("wh is nil")
	}

	if !reflect.DeepEqual(*wh, Wormhole{
		"hoge",
		"",
		false,
		AREA,
	}) {
		t.Errorf("illegal wh: %#v\n", wh)
	}

	if rpl != `{{index .Areas "hoge"}}` {
		t.Errorf("illegal rpl: %s\n", rpl)
	}
}
開發者ID:gcpug-shonan,項目名稱:gcpug-shonan-cms,代碼行數:26,代碼來源:caterpillar_test.go

示例8: TestEndToEndTest

func TestEndToEndTest(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}

	c, clean, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer clean()

	err = createSampleEntities(c, 3)
	if err != nil {
		t.Fatal(err)
	}

	w := new(bytes.Buffer)
	err = Dump(c, w, &Options{Kind: "User", GetAfterPut: true})
	if err != nil {
		t.Fatal(err)
	}
	t.Log("Dump output: ", w)

	err = Load(c, w, &Options{
		GetAfterPut: true,
		BatchSize:   50,
	})
	if err != nil {
		t.Fatal(err)
	}
}
開發者ID:ronoaldo,項目名稱:aetools,代碼行數:31,代碼來源:funcs_test.go

示例9: TestBasicUsage1

func TestBasicUsage1(t *testing.T) {
	c, closer, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer closer()

	src := &a.Sample{"Foo!"}
	index := a.NewSampleSearch()
	_, err = index.Put(c, src)
	if err != nil {
		t.Fatal(err)
	}

	index.Foo.Match("Foo")
	index.Opts().Limit(3)
	iter, err := index.Search(c)
	if err != nil {
		t.Fatal(err)
	}

	for {
		_, doc, err := iter.Next(c)
		if err == search.Done {
			break
		}
		t.Logf("%#v", doc)
	}
}
開發者ID:favclip,項目名稱:smg,代碼行數:29,代碼來源:usage_test.go

示例10: TestReadAfterWrite

func TestReadAfterWrite(t *testing.T) {
	ctx, done, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}

	dueDate := time.Date(2016, 2, 29, 13, 0, 0, 0, time.UTC)
	itemId := writeTodoItem(ctx, "finish writing these tests", dueDate, false, &testUser, false)
	switch (*itemId).(type) {
	case TodoID:
		theTodo := readTodoItem(ctx, (*itemId).(TodoID))
		switch (*theTodo).(type) {
		case TodoItem:
			theItem := (*theTodo).(TodoItem)
			assertEquals(t, theItem.Description, "finish writing these tests")
			assertEquals(t, theItem.DueDate.String(), dueDate.Local().String())
		case E, TodoID:
			t.Fatal("Expected read to return a todo item, got ", *theTodo)
		}
	case E, TodoItem:
		t.Fatal("Expected write to return a todo ID, got something else")
	}

	defer done()

}
開發者ID:catamorphism,項目名稱:tada,代碼行數:26,代碼來源:tada_test.go

示例11: TestUpdate

func TestUpdate(t *testing.T) {
	ctx, done, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	dueDate := time.Date(2016, 2, 29, 13, 0, 0, 0, time.UTC)

	id := writeTodoItem(ctx, "phone up my friend", dueDate, false, &testUser, false)
	switch (*id).(type) {
	case TodoID:
		id1 := ((datastore.Key)((*id).(TodoID)))
		result := updateTodoItem(ctx, testUser.Email, "phone up my friend", dueDate, true, id1.IntID())
		switch (*result).(type) {
		case Ok:
		case Matches, E, TodoID, TodoItem:
			t.Fatal("Non-OK result from updateTodoItem")
		}
		item := readTodoItem(ctx, TodoID(id1))
		switch (*item).(type) {
		case TodoItem:
			item1 := (*item).(TodoItem)
			assert(t, item1.Description == "phone up my friend", "wrong description")
			assert(t, item1.DueDate == dueDate, fmt.Sprintf("wrong date: expected %s, found %s [%s] {%s}", dueDate, item1.DueDate, dueDate.Sub(item1.DueDate), dueDate == item1.DueDate))
			assert(t, item1.State == "completed", "expected to be completed, saw incompleted")
		case E, TodoID, Matches:
			t.Fatal("Didn't get a TodoItem result from readTodoItem")
		}
	case E, TodoItem, Matches:
		t.Fatal("Didn't get a TodoID result from writeTodoItem")
	}
	defer done()
}
開發者ID:catamorphism,項目名稱:tada,代碼行數:32,代碼來源:tada_test.go

示例12: TestListWriteList

// write 1 todo item
// list todo items: should be 1 item
// write another todo item
// list todo items again: should be 2 items
func TestListWriteList(t *testing.T) {
	ctx, done, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	dueDate := time.Date(2016, 2, 29, 13, 0, 0, 0, time.UTC)

	writeTodoItem(ctx, "phone up my friend", dueDate, false, &testUser, false)
	listResults := listTodoItems(ctx, &testUser)
	switch (*listResults).(type) {
	case Matches:
		items := ([]Match)((*listResults).(Matches))
		assert(t, len(items) == 1, fmt.Sprintf("wrong number of todo items: expected 1, saw %d", len(items)))
		writeTodoItem(ctx, "buy a new phone", dueDate, false, &testUser, false)
		listResults1 := listTodoItems(ctx, &testUser)
		switch (*listResults1).(type) {
		case Matches:
			items1 := ([]Match)((*listResults1).(Matches))
			assert(t, len(items1) == 2, fmt.Sprintf("wrong number of todo items: expected 2, saw %d", len(items1)))
		default:
			t.Fatal(fmt.Sprintf("weird result from second listTodoItems: %s", *listResults1))
		}
	default:
		t.Fatal("weird result from listTodoItems")
	}

	defer done()

}
開發者ID:catamorphism,項目名稱:tada,代碼行數:33,代碼來源:tada_test.go

示例13: TestBatchSizeOnDump

func TestBatchSizeOnDump(t *testing.T) {
	c, clean, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer clean()

	for _, i := range []int{10, 20, 50, 99, 100, 101} {
		t.Logf("Testing %d entities ...", i)
		if err := createSampleEntities(c, i); err != nil {
			t.Fatal(err)
		}
		w := new(bytes.Buffer)
		err := Dump(c, w, &Options{Kind: "User", PrettyPrint: false})
		if err != nil {
			t.Fatal(err)
		}
		count := strings.Count(w.String(), "__key__")
		if count != i {
			t.Errorf("Unexpected number of __key__'s %d: expected %d", count, i)
		}
		// t.Logf(w.String())
		// Check if we have all keys
		for id := 1; id <= i; id++ {
			sep := fmt.Sprintf(`["User",%d]`, id)
			occ := strings.Count(w.String(), sep)
			if occ != 1 {
				t.Errorf("Unexpected ocorrences of entity id %d: %d, expected 1", id, occ)
			}
		}
	}
}
開發者ID:ronoaldo,項目名稱:aetools,代碼行數:32,代碼來源:funcs_test.go

示例14: TestIndexPage

func TestIndexPage(t *testing.T) {
	inst, err := aetest.NewInstance(nil)
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()
	req, err := inst.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatalf("Failed to create request: %v", err)
	}
	w := httptest.NewRecorder()
	var vars map[string]string
	var settings Settings
	file, err := ioutil.ReadFile("./settings_test.json")
	if err == nil {
		json.Unmarshal(file, &settings)
	}
	ctx, _, _ := aetest.NewContext()
	index(&Context{
		AE:       ctx,
		Request:  req,
		Response: w,
		Settings: &settings,
		Vars:     vars,
	})
	if w.Code != 200 {
		t.Errorf("Index did not return 200. Returned type was %d", w.Code)
	}
}
開發者ID:rctl,項目名稱:rasmusj.se,代碼行數:29,代碼來源:index_test.go

示例15: TestUsecaseSample

func TestUsecaseSample(t *testing.T) {
	c, closer, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err.Error())
	}
	defer closer()

	sample := &Sample{
		A: []int64{1, 2, 3},
	}

	index := NewSampleSearch()
	_, err = index.Put(c, sample)
	if err != nil {
		t.Fatal(err.Error())
	}

	index = NewSampleSearch()
	index.A.Match("3")
	iter, err := index.Search(c)
	if err != nil {
		t.Fatal(err)
	}
	for {
		docID, s, err := iter.Next(c)
		if err == search.Done {
			break
		}
		if err != nil {
			t.Fatal(err.Error())
		}
		t.Logf("%s %#v", docID, s)
	}
}
開發者ID:favclip,項目名稱:smg,代碼行數:34,代碼來源:model_test.go


注:本文中的google/golang.org/appengine/aetest.NewContext函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。