使用webtest.TestApp时我的Cookie未被传输

2 投票
1 回答
1179 浏览
提问于 2025-04-17 23:43

我对如何在使用Python的webtest发送请求时传递cookies感到困惑。

我有以下测试:

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': ""})

还有以下处理程序:

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

我在处理函数中抛出一个错误,以便查看cookies。看起来虽然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!

1 个回答

6

没关系。我之前看不到那些 cookies 的原因是因为它们被设置为安全 cookies,这意味着只有在使用安全连接时它们才会存在。而我测试的时候使用的是不安全的连接。

要让这个正常工作,改成下面的请求:

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

撰写回答