使用 webtest.TestApp 时,我的 cookie 没有被传输

Ste*_*gle 2 python google-app-engine webtest

我对如何使用 python webtest 在请求中传递 cookie 感到困惑。

我有以下测试:

def test_commenting_and_voting(self):
    https = {'wsgi.url_scheme': 'https'}
    users = []
    for user in USERS:
      resp_post = self.testapp.post_json('/user', user)
      users.append(resp_post.json.get('id'))

    self.testapp.post_json('/login/%s' % users[0],
                           {'password' : USERS[0]['password']},
                           extra_environ=https)
    print "testapp's view of the cookiejar"
    print self.testapp.cookies
    print "END"
    resp_post = self.testapp.post_json('/comment', {'value': ""})
Run Code Online (Sandbox Code Playgroud)

和以下处理程序:

class CommentHandler(webapp2.RequestHandler):

    def get(self, id=None):
        get_from_urlsafe(self, id)

    @ndb.transactional
    def post(self, id=None):
        assert False, self.request.cookies
Run Code Online (Sandbox Code Playgroud)

我正在从处理程序函数中引发错误以查看 cookie。看起来cookies,虽然在webtest.TestApp事物端的cookiejar中,但在发出wsgi请求时并没有被传输。那么如何让cookies进行传输呢?

Using scent:
test_commenting_and_voting (test_models.test_Models) ... 
testapp's view of the cookiejar
{'secret': '58bd5cfd36e6f805de645e00f8bea9d70ae5398ff0606b7fde829e6732394bb7', 'session': 'agx0ZXN0YmVkLXRlc3RyIgsSD1VzZXJFbnRpdHlHcm91cBgBDAsSB1Nlc3Npb24YCww'}
END
WARNING:root:suspended generator transaction(context.py:941) raised AssertionError(<RequestCookies (dict-like) with values {}>)
ERROR:root:<RequestCookies (dict-like) with values {}>
Traceback (most recent call last):
  File "/home/stephen/bin/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  ... I removed some of the stacktrace here ....
  File "/home/stephen/work/seocomments/src/python/main.py", line 127, in post
    assert False, self.request.cookies
AssertionError: <RequestCookies (dict-like) with values {}>
----------------------------------------------------------------------
Ran 6 tests in 0.371s

FAILED (errors=1)
Failed - Back to work!
Run Code Online (Sandbox Code Playgroud)

Ste*_*gle 6

没关系。我没有看到 cookie 的原因是 cookie 被设置为安全 cookie,这意味着它们仅在使用安全连接时存在。我的测试使用的是不安全的连接。

要使其工作,请将请求更改为以下内容:

self.testapp.post_json('/comment', 
                       {'value': ""}, 
                       extra_environ={'wsgi.url_scheme': 'https'})
Run Code Online (Sandbox Code Playgroud)

  • 您可以在创建时将 extra_environ 传递给 testapp,因此您不必对每个请求都执行此操作。 (3认同)