Exemplo n.º 1
0
func Test_GetMulti_Cache(t *testing.T) {
	assert := gaetest.NewAssert(t)
	gaetest.CleanupDatastore(ts.Context)
	gaetest.FixtureFromMap(ts.Context, []map[string]interface{}{
		map[string]interface{}{"_kind": testEntity.String(), "_key": "1", "ID": "1"},
	})

	driver := memcache.NewDriver(ts.Context, wcg.NewLogger(nil))

	_, list, err := testEntity.GetMulti().Keys("1", "3").Cache(true).List(ts.GET("/").Request)
	got := list.([]*TEntity)
	assert.Nil(err)
	assert.EqInt(2, len(got))
	assert.EqStr("1", got[0].ID)
	assert.Nil(got[1])

	assert.OK(driver.Exists("ent.TestEntity.1"))
	assert.OK(driver.Exists("ent.TestEntity.3"))

	var t1, t3 TEntity
	driver.Get("ent.TestEntity.1", &t1)
	driver.Get("ent.TestEntity.3", &t3)
	assert.EqStr("1", t1.ID)
	assert.EqStr("", t3.ID)

	got = make([]*TEntity, 2)
	driver.GetMulti([]string{"ent.TestEntity.1", "ent.TestEntity.3"}, got)
	assert.EqStr("1", got[0].ID)
	assert.Nil(got[1])
}
Exemplo n.º 2
0
func Test_Put_Update(t *testing.T) {
	assert := gaetest.NewAssert(t)
	gaetest.CleanupDatastore(ts.Context)
	gaetest.FixtureFromMap(ts.Context, []map[string]interface{}{
		map[string]interface{}{"_kind": testEntity.String(), "_key": "1", "ID": "1"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "2", "ID": "2"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "3", "ID": "3"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "4", "ID": "4"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "5", "ID": "5"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "6", "ID": "6"},
	})

	var ent, err = testEntity.CreateEntityFromForm(url.Values{
		"desc":          []string{"hogehoge"},
		"digit":         []string{"2"},
		"content_bytes": []string{"abcdef"},
	})

	_, _ent, err := testEntity.Put().Key("1").Update(ts.PUTForm("/1", nil).Request, ent)
	got := _ent.(*TEntity)
	assert.Nil(err)
	assert.EqStr("1", got.ID)
	assert.EqInt(2, got.Digit)
	assert.EqStr("hogehoge", got.Desc)
	assert.EqStr("abcdef", string(got.ContentBytes))
	assert.OK(got.BeforeSaveProcessed, "BeforeSave triggerd")
	assert.OK(got.AfterSaveProcessed, "AfterSave triggerd")
}
Exemplo n.º 3
0
func Test_API_SystemStats_Query(t *testing.T) {
	assert := gaetest.NewAssert(t)
	assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_API_SystemStats_Query.json", nil, "intern.home"), "fixture")

	app := NewApp()
	req := ts.GET("/api/intern/home/stats/servers/dummy/system/")
	res := req.RouteTo(app.Routes())
	assert.HTTPStatus(200, res)
	var got []home.SystemStats
	assert.JSONResponse(&got, res)
	assert.EqInt(0, len(got), string(res.Body))

	req = ts.GET("/api/intern/home/stats/servers/dummy/system/?until=2014-12-01T11:00:00Z")
	res = req.RouteTo(app.Routes())
	assert.HTTPStatus(200, res)
	assert.JSONResponse(&got, res)
	assert.EqInt(2, len(got), string(res.Body))

	tempnow, _ := wcg.ParseDateTime("2014-12-01T11:00:00Z")
	lib.TemporarySetNow(tempnow, func() {
		req := ts.GET("/api/intern/home/stats/servers/dummy/system/")
		res := req.RouteTo(app.Routes())
		assert.HTTPStatus(200, res)
		var got []home.SystemStats
		assert.JSONResponse(&got, res)
		assert.EqInt(2, len(got), string(res.Body))
	})

}
Exemplo n.º 4
0
func Test_API_Tasks_Crawlers_Ameblo_EntryLists(t *testing.T) {
	assert := gaetest.NewAssert(t)
	assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_API_Tasks_Crawlers_Ameblo_EntryLists.json", nil, "hplink"), "fixture")

	httptest.StartMockServer(func(mock *httptest.MockServer) {
		mock.Routes().GET("/morningmusume-9ki/entrylist.html", middleware.ServeFile("./fixtures/mocks/ameblo.jp//morningmusume-9ki/entrylist.html"))
		crawler.MockExternalResource(map[string]string{
			"http://ameblo.jp/morningmusume-9ki/entrylist.html": fmt.Sprintf("%s//morningmusume-9ki/entrylist.html", mock.BaseURL()),
		}, func() {
			runner := testhelper.NewAsyncTaskTestRunner(t, instance.Routes(), ts)
			runner.OnMonitor(func(testreq *httptest.TestRequest, f func()) {
				testhelper.TemporaryAllow(testreq, "hplink.admin", f)
			})
			runner.OnTrigger(func(testreq *httptest.TestRequest, f func()) {
				testhelper.TemporaryAllow(testreq, "hplink.admin", f)
			})
			runner.Run("/api/hplink/tasks/crawlers/ameblo/entrylists/", url.Values{})

			p := entities.AmebloPost.Query().Order("-PostAt").MustExecute(ts.GET("/").Request)
			postList := p.Data.([]hplink.AmebloPost)
			assert.EqInt(20, len(postList))
			assert.EqStr("ノーメイク☆譜久村聖", postList[0].Title)
			assert.EqStr("", postList[0].Theme)
			assert.EqStr("morningmusume.mizuki_fukumura", postList[0].MemberKey)
			assert.EqStr("http://ameblo.jp/morningmusume-9ki/", postList[0].SettingsURL)

			p = entities.CrawlerSettings.Query().Filter("URL=", "http://ameblo.jp/morningmusume-9ki/").MustExecute(ts.GET("/").Request)
			assert.EqInt(1, p.Length())
			settings := p.Head().(*hplink.CrawlerSettings)
			assert.EqInt(int(hplink.CrawlerStatusSuccess), int(settings.Status))
		})
	})
}
Exemplo n.º 5
0
func Test_Kind_CreateEntityFromJSON(t *testing.T) {
	assert := gaetest.NewAssert(t)
	jsonString := `{
		"digit": 34225940,
		"desc": "foo",
		"slice_type": ["1", "2", "3"],
		"slice_float_type": [1.1, 2.5, 3.4],
		"bool_type": true,
		"float_type": 1.4,
		"id": "1"
	}`
	ent, _ := testEntity.CreateEntityFromJSON([]byte(jsonString))
	got := ent.(*TEntity)
	assert.EqInt(34225940, got.Digit)
	assert.EqStr("foo", got.Desc)
	assert.EqStr("1", got.SliceType[0])
	assert.EqStr("2", got.SliceType[1])
	assert.EqStr("3", got.SliceType[2])
	assert.EqFloat64(1.1, got.SliceFloatType[0])
	assert.EqFloat64(2.5, got.SliceFloatType[1])
	assert.EqFloat64(3.4, got.SliceFloatType[2])
	assert.OK(got.BoolType)
	assert.EqFloat64(1.4, got.FloatType)
	assert.EqStr("", got.ID, "id field should not be parsed")
}
Exemplo n.º 6
0
func Test_APITokenOnly(t *testing.T) {
	assert := gaetest.NewAssert(t)
	router := wcg.NewRouter()
	router.GET("/",
		APITokenOnly(),
		wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
			res.WriteString("OK")
		}),
	)
	req := ts.GET("/")
	res := req.RouteTo(router)
	assert.HTTPStatus(401, res)

	req = ts.GET("/")
	req.Request.User = &request.APITokenUser{
		&models.APIToken{
			Token:       "testuser",
			Description: "test api token user",
			CreatedAt:   time.Now(),
			AlertOn:     time.Duration(0),
			LastAccess:  time.Now(),
		},
	}
	res = req.RouteTo(router)
	assert.HTTPStatus(200, res)
}
Exemplo n.º 7
0
func Test_Query_WithCache(t *testing.T) {
	assert := gaetest.NewAssert(t)
	gaetest.CleanupDatastore(ts.Context)
	gaetest.FixtureFromMap(ts.Context, []map[string]interface{}{
		map[string]interface{}{"_kind": testEntity.String(), "_key": "1", "ID": "1"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "2", "ID": "2"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "3", "ID": "3"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "4", "ID": "4"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "5", "ID": "5"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "6", "ID": "6"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "7", "ID": "7"},
	})
	page, err := testEntity.Query().Cache("123").Execute(ts.GET("/").Request)
	got := page.Data.([]TEntity)
	assert.Nil(err)
	assert.EqInt(7, len(got), "len(Pagination.Data)")

	driver := memcache.NewDriver(ts.Context, wcg.NewLogger(nil))
	assert.OK(driver.Exists("query.TestEntity.123"))

	// cache still exists even after removing data.
	gaetest.CleanupDatastore(ts.Context)
	page, err = testEntity.Query().Cache("123").Execute(ts.GET("/").Request)
	got = page.Data.([]TEntity)
	assert.Nil(err)
	assert.EqInt(7, len(got))
	assert.EqStr("1", got[0].ID)
}
Exemplo n.º 8
0
func Test_API_POST_Me_Gates(t *testing.T) {
	assert := gaetest.NewAssert(t)
	app := NewApp()

	req := ts.POSTForm("/api/users/me/gates/", url.Values{
		"keys": []string{"foo"},
	})
	res := req.RouteTo(app.Routes())
	assert.HTTPStatus(200, res)

	var got map[string]bool
	assert.JSONResponse(&got, res)
	assert.EqInt(1, len(got))
	assert.Not(got["foo"])

	req = ts.POSTForm("/api/users/me/gates/", url.Values{
		"keys": []string{"foo"},
	})
	testhelper.TemporaryAllow(req, "foo", func() {
		res := req.RouteTo(app.Routes())
		assert.HTTPStatus(200, res)

		var got map[string]bool
		assert.JSONResponse(&got, res)
		assert.EqInt(1, len(got))
		assert.OK(got["foo"])
	})
}
Exemplo n.º 9
0
func Test_Query(t *testing.T) {
	assert := gaetest.NewAssert(t)
	gaetest.CleanupDatastore(ts.Context)
	gaetest.FixtureFromMap(ts.Context, []map[string]interface{}{
		map[string]interface{}{"_kind": testEntity.String(), "_key": "1", "ID": "1"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "2", "ID": "2"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "3", "ID": "3"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "4", "ID": "4"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "5", "ID": "5"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "6", "ID": "6"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "7", "ID": "7"},
	})

	// no pagination parameter specified -> returns all entities
	page := testEntity.Query().MustExecute(ts.GET("/").Request)
	got := page.Data.([]TEntity)
	assert.EqInt(7, len(got), "len(Pagination.Data)")
	assert.Nil(page.Next, "Pagination.Next")
	assert.Nil(page.Previous, "Pagination.Previous")
	assert.EqStr("1", got[0].ID, "Pagination.Data[0].ID")
	assert.EqStr("2", got[1].ID, "Pagination.Data[1].ID")
	assert.EqStr("3", got[2].ID, "Pagination.Data[2].ID")
	assert.EqStr("4", got[3].ID, "Pagination.Data[3].ID")
	assert.EqStr("5", got[4].ID, "Pagination.Data[4].ID")
	assert.EqStr("6", got[5].ID, "Pagination.Data[5].ID")
	assert.EqStr("7", got[6].ID, "Pagination.Data[6].ID")
}
Exemplo n.º 10
0
func Test_Query_NoData(t *testing.T) {
	assert := gaetest.NewAssert(t)
	gaetest.CleanupDatastore(ts.Context)
	page := testEntity.Query().MustExecute(ts.GET("/").Request)
	got := page.Data.([]TEntity)
	assert.EqInt(0, len(got))
}
Exemplo n.º 11
0
func Test_API_CronStatsCleanup(t *testing.T) {
	assert := gaetest.NewAssert(t)
	assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_API_SystemStats_Query.json", nil, "intern.home"), "fixture")

	sk, _ := Server.Get().Key("dummy").MustOne(ts.GET("/").Request)
	c := SystemStats.Query().Ancestor(sk).MustCount(ts.GET("/").Request)
	assert.EqInt(2, c)

	tempnow, _ := wcg.ParseDateTime("2014-12-01T11:00:00Z")
	lib.TemporarySetNow(tempnow, func() {
		app := NewApp()
		req := ts.GET("/cron/intern/home/stats/cleanup/")
		res := req.RouteTo(app.Routes())
		assert.HTTPStatus(200, res)

		// confirm nothing deleted
		c = SystemStats.Query().Ancestor(sk).MustCount(ts.GET("/").Request)
		assert.EqInt(2, c)
	})

	app := NewApp()
	req := ts.GET("/cron/intern/home/stats/cleanup/")
	res := req.RouteTo(app.Routes())
	assert.HTTPStatus(200, res)

	// everything deleted since it's old
	c = SystemStats.Query().Ancestor(sk).MustCount(ts.GET("/").Request)
	assert.EqInt(0, c)
}
Exemplo n.º 12
0
func Test_Session(t *testing.T) {
	assert := gaetest.NewAssert(t)

	handler := wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
		if req.Session == nil {
			res.WriteString("No Session")
		} else {
			res.WriteString("Has Session")
		}
	})

	router := wcg.NewRouter()
	Use(router, func() {
		router.GET("/api/foo", handler)
		router.GET("/static/foo", handler)
		router.GET("/cron/foo", handler)
	})
	req := ts.GET("/api/foo")
	assert.EqStr("Has Session", string(req.RouteTo(router).Body), "Has Session")

	req = ts.GET("/api/foo")
	req.AddHeader(request.APITokenHeader, "FOO")
	assert.EqStr("No Session", string(req.RouteTo(router).Body), "No Session")

	req = ts.GET("/api/foo")
	req.AddHeader(request.TaskQueueHeader, "true")
	assert.EqStr("No Session", string(req.RouteTo(router).Body), "No Session")

	req = ts.GET("/static/foo")
	assert.EqStr("No Session", string(req.RouteTo(router).Body), "No Session")

	req = ts.GET("/cron/foo")
	req.AddHeader(request.CronHeader, "true")
	assert.EqStr("No Session", string(req.RouteTo(router).Body), "No Session")
}
Exemplo n.º 13
0
func Test_Delete_CacheInvalidation(t *testing.T) {
	assert := gaetest.NewAssert(t)
	driver := memcache.NewDriver(ts.Context, wcg.NewLogger(nil))

	gaetest.CleanupDatastore(ts.Context)
	gaetest.FixtureFromMap(ts.Context, []map[string]interface{}{
		map[string]interface{}{"_kind": testEntity.String(), "_key": "1", "ID": "1"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "2", "ID": "2"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "3", "ID": "3"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "4", "ID": "4"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "5", "ID": "5"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "6", "ID": "6"},
	})

	// create caches
	testEntity.Query().Cache("123").MustExecute(ts.GET("/").Request)
	testEntity.Get().Key("1").Cache(true).MustOne(ts.GET("/").Request)

	assert.OK(driver.Exists("ent.TestEntity.1"), "An entyty cache should exist")
	assert.OK(driver.Exists("query.TestEntity.123"), "A query cache should exist")

	testEntity.Delete().Key("1").Cache("123").MustCommit(ts.GET("/").Request)

	assert.Not(driver.Exists("ent.TestEntity.1"), "Entity cache should be invalidated")
	assert.Not(driver.Exists("query.TestEntity.123"), "Query cache should be invalidated")
}
Exemplo n.º 14
0
func Test_API_Tasks_Crawlers_Ameblo_Posts(t *testing.T) {
	assert := gaetest.NewAssert(t)
	assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_API_Tasks_Crawlers_Ameblo_Posts.json", nil, "hplink"), "fixture")

	p := entities.AmebloPost.Query().MustExecute(ts.GET("/").Request)
	postList := p.Data.([]hplink.AmebloPost)
	assert.EqInt(1, len(postList))

	httptest.StartMockServer(func(mock *httptest.MockServer) {
		mock.Routes().GET("/morningmusume-9ki/post.html", middleware.ServeFile("./fixtures/mocks/ameblo.jp//morningmusume-9ki/post.html"))
		crawler.MockExternalResource(map[string]string{
			"http://ameblo.jp/morningmusume-9ki/entry-12201946654.html": fmt.Sprintf("%s//morningmusume-9ki/post.html", mock.BaseURL()),
		}, func() {
			runner := testhelper.NewAsyncTaskTestRunner(t, instance.Routes(), ts)
			runner.OnMonitor(func(testreq *httptest.TestRequest, f func()) {
				testhelper.TemporaryAllow(testreq, "hplink.admin", f)
			})
			runner.OnTrigger(func(testreq *httptest.TestRequest, f func()) {
				testhelper.TemporaryAllow(testreq, "hplink.admin", f)
			})
			runner.Run("/api/hplink/tasks/crawlers/ameblo/posts/", url.Values{})

			p := entities.AmebloPost.Query().MustExecute(ts.GET("/").Request)
			postList := p.Data.([]hplink.AmebloPost)
			assert.EqInt(1, len(postList))
			assert.EqStr("ノーメイク☆譜久村聖", postList[0].Title)
			assert.EqStr("譜久村聖", postList[0].Theme)
			assert.EqStr("morningmusume.mizuki_fukumura", postList[0].MemberKey)

			// It also creates a URL cache
			assert.EqInt(1, entities.URLCache.Query().MustCount(ts.GET("/").Request))
		})
	})
}
Exemplo n.º 15
0
func Test_Kind_CreateEntitiesFromJSON(t *testing.T) {
	assert := gaetest.NewAssert(t)
	jsonString := `[
	{"digit": 34225940},
	{"desc": "foo"},
	{"slice_type": ["1", "2", "3"]},
	{"slice_float_type": [1.1, 2.5, 3.4]},
	{"bool_type": true},
	{"float_type": 1.4},
	{"id": "1"}
]`
	ent, err := testEntity.CreateEntitiesFromJSON(bytes.NewBuffer([]byte(jsonString)))
	assert.Nil(err)
	got := ent.([]*TEntity)
	assert.EqInt(7, len(got))
	assert.EqInt(34225940, got[0].Digit)
	assert.EqStr("foo", got[1].Desc)
	assert.EqInt(3, len(got[2].SliceType))
	assert.EqStr("1", got[2].SliceType[0])
	assert.EqStr("2", got[2].SliceType[1])
	assert.EqStr("3", got[2].SliceType[2])
	assert.EqFloat64(1.1, got[3].SliceFloatType[0])
	assert.EqFloat64(2.5, got[3].SliceFloatType[1])
	assert.EqFloat64(3.4, got[3].SliceFloatType[2])
	assert.OK(got[4].BoolType)
	assert.EqFloat64(1.4, got[5].FloatType)
	assert.EqStr("", got[6].ID, "id field should not be parsed")
}
Exemplo n.º 16
0
func Test_ParseForm(t *testing.T) {
	assert := gaetest.NewAssert(t)
	router := wcg.NewRouter()
	router.POST("/*",
		ParseForm(func(v *validators.FormValidator) {
			v.IntField("foo").Required()
		}),
		wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
			res.WriteString("OK")
		}),
	)
	req := ts.POSTForm("/api/", nil)
	res := req.RouteTo(router)

	var got map[string]interface{}
	assert.HTTPStatus(400, res)
	assert.JSONResponse(&got, res)
	assert.OK(len(got["fields"].(map[string]interface{})) > 0, "'fields' field")

	req = ts.POSTForm("/api/", url.Values{
		"foo": []string{"a"},
	})
	res = req.RouteTo(router)
	assert.HTTPStatus(200, res)
}
Exemplo n.º 17
0
func Test_API_Task_List(t *testing.T) {
	assert := gaetest.NewAssert(t)
	assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_API_Task_List.json", nil), "fixture")

	now, _ := wcg.ParseDateTime("2016-01-10T00:00:00Z")

	lib.TemporarySetNow(now, func() {
		req := ts.GET("/api/admin/tasks/")
		res := req.RouteTo(instance.Routes())
		assert.HTTPStatus(200, res)

		var got entities.Pagination
		assert.JSONResponse(&got, res)
		assert.EqInt(0, got.Length())
	})

	now, _ = wcg.ParseDateTime("2016-01-09T00:00:00Z")

	lib.TemporarySetNow(now, func() {
		req := ts.GET("/api/admin/tasks/")
		res := req.RouteTo(instance.Routes())
		assert.HTTPStatus(200, res)

		var got entities.Pagination
		assert.JSONResponse(&got, res)
		assert.EqInt(1, got.Length())
	})
}
Exemplo n.º 18
0
func Test_API_ServerConfig_Put(t *testing.T) {
	assert := gaetest.NewAssert(t)

	// Create a new key
	req := ts.PUTForm("/api/admin/configs/facebook_app_id.json", url.Values{
		"value": []string{"12345"},
	})
	res := req.RouteTo(instance.Routes())
	assert.HTTPStatus(200, res)

	req = ts.GET("/api/admin/configs/facebook_app_id.json")
	res = req.RouteTo(instance.Routes())
	assert.HTTPStatus(200, res)

	var got models.ServerConfig
	assert.JSONResponse(&got, res)
	assert.EqStr("facebook_app_id", got.Key, "ServerConfig.Key")
	assert.EqStr("12345", got.Value, "ServerConfig.Value")

	// Try to update not defined key the key value
	req = ts.PUTForm("/api/admin/configs/mykey.json", url.Values{
		"value": []string{"myvalue_updated"},
	})
	res = req.RouteTo(instance.Routes())
	assert.HTTPStatus(404, res)
}
Exemplo n.º 19
0
func Test_AsyncAPI_Define(t *testing.T) {
	assert := gaetest.NewAssert(t)
	app := NewApp("testapp")
	async := app.AsyncAPI()

	var processed = false
	var q1 = ""
	config := async.Define("/async/")
	config.OnProcess(AsyncTaskHandler(func(req *wcg.Request, _ *models.AsyncAPITask) (*models.AsyncAPITaskProgress, error) {
		processed = true
		q1 = req.Query("q1")
		return nil, nil
	}))
	assert.EqStr("api-testapp-async", config.Queue.Name)

	var path = "/api/testapp/async/"
	var params = url.Values{
		"q1": []string{"a"},
	}

	runner := testhelper.NewAsyncTaskTestRunner(t, app.Routes(), ts)
	runner.Run(fmt.Sprintf("%s", path), params)

	assert.OK(processed)
	assert.EqStr("a", q1)
}
Exemplo n.º 20
0
func Test_EntityPut(t *testing.T) {
	assert := gaetest.NewAssert(t)
	router := wcg.NewRouter()
	router.PUT("/api/:key.json",
		ParseForm(nil),
		EntityPut(testEntity.Put(), "key"),
	)
	gaetest.CleanupDatastore(ts.Context)
	gaetest.FixtureFromMap(ts.Context, []map[string]interface{}{
		map[string]interface{}{"_kind": testEntity.String(), "_key": "1", "ID": "1"},
	})

	var got TEntity
	req := ts.PUTForm("/api/1.json", url.Values{
		"value": []string{"1"},
	})
	res := req.RouteTo(router)
	assert.HTTPStatus(200, res)
	assert.JSONResponse(&got, res)
	assert.EqStr("1", got.ID)
	assert.EqInt(1, got.Value)

	_, one := testEntity.Get().Key(got.ID).MustOne(ts.GET("/").Request)
	assert.EqStr(got.ID, one.(*TEntity).ID)
	assert.EqInt(1, one.(*TEntity).Value)
}
Exemplo n.º 21
0
func Test_ByHeader(t *testing.T) {
	assert := gaetest.NewAssert(t)
	assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_HeaderAuth.json", nil), "fixture")

	router := wcg.NewRouter()
	handler := wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
		res.WriteString(req.User.ID())
	})
	byHeader(router, func() {
		router.GET("/api/foo", handler)
		router.GET("/cron/foo", handler)
	})
	req := ts.GET("/api/foo")
	assert.EqStr("-", string(req.RouteTo(router).Body), "Guest")

	req = ts.GET("/api/foo")
	req.AddHeader(request.APITokenHeader, "2e489f08-3be9-4d28-af86-b14841b2181a")
	assert.EqStr("api:2e489f08-3be9-4d28-af86-b14841b2181a", string(req.RouteTo(router).Body), "APITokenUser")

	req = ts.GET("/api/foo")
	req.AddHeader(request.APITokenHeader, "invalidtoken")
	assert.EqStr("-", string(req.RouteTo(router).Body), "Guest")

	req = ts.GET("/api/foo")
	req.AddHeader(request.TaskQueueHeader, "true")
	assert.EqStr(fmt.Sprintf("api:%s", request.APITokenForTask), string(req.RouteTo(router).Body), "Guest")

	req = ts.GET("/cron/foo")
	req.AddHeader(request.CronHeader, "true")
	assert.EqStr(fmt.Sprintf("api:%s", request.APITokenForCron), string(req.RouteTo(router).Body), "CronUser")

}
Exemplo n.º 22
0
func Test_EntityQuery(t *testing.T) {
	assert := gaetest.NewAssert(t)
	router := wcg.NewRouter()
	router.GET("/api/",
		EntityQuery(testEntity.Query().Limit(2)),
	)
	gaetest.CleanupDatastore(ts.Context)
	gaetest.FixtureFromMap(ts.Context, []map[string]interface{}{
		map[string]interface{}{"_kind": testEntity.String(), "_key": "1", "ID": "1"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "2", "ID": "2"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "3", "ID": "3"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "4", "ID": "4"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "5", "ID": "5"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "6", "ID": "6"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "7", "ID": "7"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "8", "ID": "8"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "9", "ID": "9"},
	})

	var got entities.Pagination
	req := ts.GET("/api/")
	res := req.RouteTo(router)
	assert.HTTPStatus(200, res)
	assert.JSONResponse(&got, res)
	assert.EqInt(2, got.Length())
	assert.EqInt(2, got.Next.N)
	assert.EqInt(1, got.Next.P)
	assert.Nil(got.Previous)
	// TODO: got does not has []TEntity, but has []map[string]interface{}.
	// Need  to provide a way to make got have []TEntity or []*TEntity
}
Exemplo n.º 23
0
func Test_EntityStreaming(t *testing.T) {
	assert := gaetest.NewAssert(t)
	router := wcg.NewRouter()
	router.GET("/api/",
		EntityStreaming(testEntity.Query(), false),
	)
	gaetest.CleanupDatastore(ts.Context)
	gaetest.FixtureFromMap(ts.Context, []map[string]interface{}{
		map[string]interface{}{"_kind": testEntity.String(), "_key": "1", "ID": "1"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "2", "ID": "2"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "3", "ID": "3"},
		map[string]interface{}{"_kind": testEntity.String(), "_key": "4", "ID": "4"},
	})
	req := ts.GET("/api/")
	res := req.RouteTo(router)
	assert.HTTPStatus(200, res)
	assert.HTTPBodyString(
		`{"id":"1","value":0,"updated_at":"0001-01-01T00:00:00Z"}
{"id":"2","value":0,"updated_at":"0001-01-01T00:00:00Z"}
{"id":"3","value":0,"updated_at":"0001-01-01T00:00:00Z"}
{"id":"4","value":0,"updated_at":"0001-01-01T00:00:00Z"}
`,
		res,
	)
}
Exemplo n.º 24
0
func Test_API_Config_Get_Default(t *testing.T) {
	assert := gaetest.NewAssert(t)
	assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_API_Config_Get.json", nil), "fixture")
	testUser := httptest.NewTestUser().SetID("facebook:6789")
	dummy := ts.GET("/")

	configs.TemporarySetConfig(dummy.Request,
		"facebook_page_id", "12345",
		func() {
			messenger.TemporaryOptIn(dummy.Request,
				"12345", testUser.ID(),
				func() {
					var notif pt.MessengerNotification
					req := ts.GET("/api/intern/pt/configs/facebook%3A6789/messenger.json")
					req.Request.User = testUser
					helper.TemporaryAllow(req, "family", func() {
						res := req.RouteTo(instance.Routes())
						assert.HTTPStatus(200, res)
						assert.JSONResponse(&notif, res)
						assert.EqStr("facebook:6789", notif.UserID, "MessengerNotification.UserID")
						assert.OK(!notif.Summary, "MessengerNotification.Summary")
						assert.OK(!notif.OnStart, "MessengerNotification.OnStart")
						assert.OK(!notif.OnEnd, "MessengerNotification.OnEnd")
					})
				},
			)
		},
	)
}
Exemplo n.º 25
0
func Test_API_Config_Put(t *testing.T) {
	assert := gaetest.NewAssert(t)
	testUser := httptest.NewTestUser().SetID("facebook:12345")
	dummy := ts.GET("/")

	configs.TemporarySetConfig(dummy.Request,
		"facebook_page_id", "12345",
		func() {
			messenger.TemporaryOptIn(dummy.Request,
				"12345", testUser.ID(),
				func() {
					var notif pt.MessengerNotification
					req := ts.PUTForm("/api/intern/pt/configs/facebook%3A12345/messenger.json", url.Values{
						"id":       []string{"messenger"},
						"user_id":  []string{"testuser"},
						"summary":  []string{"true"},
						"on_start": []string{"true"},
						"on_end":   []string{"false"},
					})
					req.Request.User = testUser
					helper.TemporaryAllow(req, "family", func() {
						res := req.RouteTo(instance.Routes())
						assert.HTTPStatus(200, res)
						assert.JSONResponse(&notif, res)
						assert.EqStr("testuser", notif.UserID, "MessengerNotification.UserID")
						assert.OK(notif.Summary, "MessengerNotification.Summary")
						assert.OK(notif.OnStart, "MessengerNotification.OnStart")
						assert.OK(!notif.OnEnd, "MessengerNotification.OnEnd")
					})
				},
			)
		},
	)
}
Exemplo n.º 26
0
func Test_API_IEPGRecord_OptInOut_Excluded(t *testing.T) {
	assert := gaetest.NewAssert(t)
	assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_API_IEPGRecord_OptInOut.json", nil, "intern.pt"), "fixture")

	req := ts.PUTForm(fmt.Sprintf("/api/intern/pt/iepg/records/%s/opt-in/", "excluded"), url.Values{
		"opt_in": []string{"1"},
	})
	helper.TemporaryAllow(req, "family", func() {
		var got pt.IEPG
		res := req.RouteTo(instance.Routes())
		assert.HTTPStatus(200, res)
		assert.JSONResponse(&got, res)
		assert.OK(got.OptIn, "OptIn")
		assert.OK(!got.OptOut, "OptOut")
	})

	req = ts.PUTForm(fmt.Sprintf("/api/intern/pt/iepg/records/%s/opt-in/", "excluded"), url.Values{
		"opt_in": []string{"0"},
	})
	helper.TemporaryAllow(req, "family", func() {
		var got pt.IEPG
		res := req.RouteTo(instance.Routes())
		assert.HTTPStatus(200, res)
		assert.JSONResponse(&got, res)
		assert.OK(!got.OptIn, "OptIn")
		assert.OK(!got.OptOut, "OptOut")
	})
}
Exemplo n.º 27
0
func Test_Kind_CreateEntityFromForm(t *testing.T) {
	assert := gaetest.NewAssert(t)

	n := lib.Now()
	lib.TemporarySetNow(n, func() {
		var ent, err = testEntity.CreateEntityFromForm(url.Values{
			"content_bytes": []string{"abcdef"},
			"slice_type":    []string{"1", "2", "3"},
		})
		assert.Nil(err)
		assert.EqStr("This is defualt value", ent.(*TEntity).Desc)
		assert.EqInt(10, ent.(*TEntity).Digit)
		assert.EqStr("abcdef", string(ent.(*TEntity).ContentBytes))
		assert.EqInt(3, len(ent.(*TEntity).SliceType))
		assert.EqStr("1", ent.(*TEntity).SliceType[0])
		assert.EqStr("2", ent.(*TEntity).SliceType[1])
		assert.EqStr("3", ent.(*TEntity).SliceType[2])
		assert.EqTime(n, ent.(*TEntity).CreatedAt)
	})

	var ent, err = testEntity.CreateEntityFromForm(url.Values{
		"digit": []string{"2"},
		"desc":  []string{"specific desc"},
	})
	assert.Nil(err)
	assert.EqInt(2, ent.(*TEntity).Digit)
	assert.EqStr("specific desc", ent.(*TEntity).Desc)
}
Exemplo n.º 28
0
func Test_API_IEPGExclusion_Delete(t *testing.T) {
	assert := gaetest.NewAssert(t)
	req := ts.DELETE("/api/intern/pt/channels/test1.json")
	helper.TemporaryAllow(req, "family", func() {
		res := req.RouteTo(instance.Routes())
		assert.HTTPStatus(200, res)
	})
}
Exemplo n.º 29
0
func Test_API_Gate_List(t *testing.T) {
	assert := gaetest.NewAssert(t)

	var got []models.Gate
	req := ts.GET("/api/admin/gates/")
	res := req.RouteTo(instance.Routes())
	assert.HTTPStatus(200, res)
	assert.JSONResponse(&got, res)
}
Exemplo n.º 30
0
func Test_Kind_NewRemote(t *testing.T) {
	if os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") == "" {
		t.Skip("GOOGLE_APPLICATION_CREDENTIALS is not defined for remote API test")
	}
	const testHost = "speedland-ng-dev.appspot.com"
	assert := gaetest.NewAssert(t)
	_, err := ServerConfig.NewRemote(testHost).Query().Count(ts.GET("/").Request)
	assert.Nil(err)
}