本文整理汇总了Golang中google/golang.org/appengine/aetest.NewContext函数的典型用法代码示例。如果您正苦于以下问题:Golang NewContext函数的具体用法?Golang NewContext怎么用?Golang NewContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewContext函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: TestBasicUsage2
func TestBasicUsage2(t *testing.T) {
c, closer, err := aetest.NewContext()
if err != nil {
t.Fatal(err)
}
defer closer()
src := &a.Sample{"Foo!"}
key := datastore.NewIncompleteKey(c, "Sample", nil)
_, err = datastore.Put(c, key, src)
if err != nil {
t.Fatal(err)
}
builder := a.NewSampleQueryBuilder()
builder.Foo.GreaterThan("Foo").KeysOnly().Limit(3)
iter := builder.Query().Run(c)
for {
key, err = iter.Next(nil)
if err == datastore.Done {
break
} else if err != nil {
t.Fatal(err)
}
src := &a.Sample{}
err = datastore.Get(c, key, src)
if err != nil {
t.Fatal(err)
}
t.Logf("key: %#v, entity: %#v", key, src)
}
}
开发者ID:favclip,项目名称:qbg,代码行数:33,代码来源:usage_test.go
示例17: TestNone
func TestNone(t *testing.T) {
c, done, err := aetest.NewContext()
if err != nil {
t.Fatal(err)
}
defer done()
tests := []struct {
name string
count int
contiguous bool
canQuery bool
ranges []NamespaceRange
}{
{"testSplitWithNoNamespacesInDatastore", 10, false, true, []NamespaceRange{}},
}
for _, test := range tests {
results, _ := namespaceSplit(c, test.count, test.contiguous, test.canQuery)
if len(results) != len(test.ranges) {
t.Fatalf("%s expected %d ranges got %d", test.name, len(test.ranges), len(results))
}
for i, r := range results {
if r.Start != test.ranges[i].Start || r.End != test.ranges[i].End {
t.Fatalf("%s expected range %d %s-%s got %s-%s", test.name, i, test.ranges[i].Start, test.ranges[i].End, r.Start, r.End)
}
}
}
}
开发者ID:CaptainCodeman,项目名称:go-appengine-mapper,代码行数:28,代码来源:namespace_range_test.go
示例18: SetupEnv
func SetupEnv(t *testing.T) TestContext {
c, clean, err := aetest.NewContext()
if err != nil {
t.Fatal(err)
}
err = aetools.Load(c, strings.NewReader(SampleEntities), aetools.LoadSync)
if err != nil {
defer clean()
t.Fatal(err)
}
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := httputil.DumpRequest(r, true)
log.Printf("Received request:\n%s\n", string(b))
enc := json.NewEncoder(w)
err := enc.Encode(&bigquery.TableDataInsertAllResponse{})
log.Printf("Error writing response: %v\n", err)
}))
// TODO(ronoaldo): enable parallel testing.
bigquerysync.InsertAllURL = fmt.Sprintf("%s/%%s/%%s/%%s", s.URL)
bigquerysync.NewClient = func(c context.Context) (*http.Client, error) {
return &http.Client{}, nil
}
tc := &testContext{
Context: c,
clean: clean,
server: s,
}
return tc
}
开发者ID:ronoaldo,项目名称:aetools,代码行数:33,代码来源:utilities_test.go
示例19: NewContext
func NewContext(t *testing.T) (context.Context, func()) {
c, closeFunc, err := aetest.NewContext()
if err != nil {
t.Fatal(err)
}
return c, closeFunc
}
开发者ID:jongillham,项目名称:nds,代码行数:7,代码来源:nds_test.go
示例20: TestInferTableSchema
func TestInferTableSchema(t *testing.T) {
c, clean, err := aetest.NewContext()
if err != nil {
t.Fatal(err)
}
defer clean()
err = aetools.LoadJSON(c, datastoreStats, aetools.LoadSync)
s, err := bigquerysync.SchemaForKind(c, "Account")
if err != nil {
t.Fatal(err)
}
j, _ := json.Marshal(s)
t.Logf("Decoded schema: '%s'", string(j))
if len(s.Fields) != 4 {
t.Errorf("Unexpected field len: %d, expected 4", len(s.Fields))
}
for i, f := range s.Fields {
if f.Name == "" {
t.Errorf("Name of field %d is empty", i)
}
if f.Type == "" {
t.Errorf("Type of field %d is empty", i)
}
}
}
开发者ID:ronoaldo,项目名称:aetools,代码行数:27,代码来源:schema_test.go
注:本文中的google/golang.org/appengine/aetest.NewContext函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论