在没有客户端的情况下在flask请求unittest中设置cookie

时间:2015-10-23 10:54:57

标签: unit-testing flask

我正在为我的烧瓶应用程序编写单元测试。我有几种方法不是为了返回响应,而是积极使用cookie。例如:

def get_timezone():
  try:
    return int(request.cookies.get('timezone_offset', 0))
  except (RuntimeError, ValueError):
    pass

  return 0

我的测试看起来像:

from my_main import my_flask_app
with my_flask_app.test_Request_context(**request_environ_params):
  tz_value = 4
  # HERE. How to setup cookie value to `tz_value`?

  tz = myapp.utils.get_timezone()
  self.assertEqual(tz, tz_value)

所以,我想设置cookie(如何设置我已经想到的其他请求参数)用于测试目的。怎么做?

3 个答案:

答案 0 :(得分:0)

测试客户端有一个set_cookie方法,做这样的工作吗?

with app.test_client() as c:
    c.set_cookie('localhost', 'COOKIE_NAME', 'cookie_value')
    resp = c.get('/my_url')

答案 1 :(得分:0)

我认为这很有用:

with app.app_context():
    with app.test_request_context():
        resp = make_response(redirect('your_url'))
        resp.set_cookie('Cookie_name', 'Cookie_Value')

答案 2 :(得分:0)

我认为这可以帮到你。 Cookie应位于headers **request_environ_params

的关键字中
cookie = http.dump_cookie("Cookie_name",'Cookie_value')
with app.test_request_context(path="/", method="GET", headers={"COOKIE":cookie}):
    # do_something...

我想你可以知道我的答案。

:P(我不擅长英语)