2016-07-19 10:36
浏览 46

使用Gorilla MUX的单元测试App Engine

I want to write tests for handlers in Google App Engine that use Gorilla mux to read variables from the request URL.

I understand from the documentation that you can create a fake context and request to use with testing.

I'm calling the handler directly in the test but the handler isn't seeing the path parameter as expected.

func TestRouter(t *testing.T) {
  inst, _ := aetest.NewInstance(nil) //ignoring error for brevity
  defer inst.Close()
  //tried adding this line because the test would not work with or without it
  req, _ := inst.NewRequest("GET", "/user/", nil)
  req.Header.Add("X-Requested-With", "XMLHttpRequest")
  resp := httptest.NewRecorder()
  restHandler(resp, req)

func restHandler(w http.ResponseWriter, r *http.Request) {
  ctx := appengine.NewContext(r)
  params := mux.Vars(r)
  email := params["email"]
  //`email` is always empty

The problem is that the handler always sees an empty "email" parameter because the path is not interpreted by Gorilla mux.

The router is as below:

func makeRouter() *mux.Router {
  r := mux.Router()
  rest := mux.NewRouter().Headers("Authorization", "").

  app := r.Headers("X-Requested-With", "XMLHttpRequest").Subrouter()
  app.HandleFunc("/user/{email}/{id}", restHandler).Methods(http.MethodGet)

  //using negroni for path prefix /api
    negroni.HandlerFunc(authCheck), //for access control
  return r

All my searches have not gotten anything specific to App Engine unit testing with Gorilla mux.

图片转代码服务由CSDN问答提供 功能建议

我想为Google App Engine中使用Gorilla mux从请求URL读取变量的处理程序编写测试。 / p>

我从文档< / a>,您可以创建一个伪造的上下文并请求与测试一起使用。</ p>

我正在测试中直接调用处理程序,但是处理程序未按预期看到path参数 </ p>

  func TestRouter(t * testing.T){
 inst,_:= aetest.NewInstance(nil)//忽略简短的错误
延迟inst.Close  ()
 req,_:= inst.NewRequest(“ GET”,“ / user / john  @ / id-123“,零)
 req.Header.Add(” X-Requested-With“,” XMLHttpRequest“)
 resp:= httptest.NewRecorder()
func restHandler(w http  .ResponseWriter,r * http.Request){
 ctx:= appengine.NewContext(r)
 params:= mux.Vars(r)
 email:= params [“ email”] 
 //`email` 始终为空
 </ code> </ pre> 

问题在于处理程序始终会看到一个空的“电子邮件”参数,因为该路径未被大猩猩多路复用器解释。</ p >

路由器如下:</ p>

  func makeRouter()* mux.Router {
r:= mux.Router()
 rest:  = mux.NewRouter()。Headers(“ Authorization”,“”)。
 PathPrefix(“ / api”)。Subrouter()
应用程序:= r.Headers(“ X-Requested-With”,“  XMLHttpRequest“)。Subrouter()
 app.HandleFunc(” / user / {email} / {id}“,restHandler).Methods(http.MethodGet)
 //使用negroni作为路径前缀/ api 
  r.PathPrefx(“ / api”)。Handler(negroni.New(
 </ code> </ pre> 

我所有的搜索都没有得到针对大猩猩多路复用器进行App Engine单元测试的特定信息。</ p> </ div>

1条回答 默认 最新

相关推荐 更多相似问题