【问题标题】:Getting cookies from a form submit and using them with a webtest从表单提交中获取 cookie 并将它们与 webtest 一起使用
【发布时间】:2016-06-16 06:00:19
【问题描述】:

所以我试图用 webtest 库做一些测试用例,问题是我的网站有访问控制,需要用户登录。似乎表单发布成功,但结果没有任何cookie(我至少可以找到),并且登录后cookiejar是空的。

测试设置:

class TestMyViewSuccessCondition(unittest.TestCase):

    def setUp(self):
        self.config = testing.setUp()

        from myapp import main

        settings = {'sqlalchemy.url': postgresqlURL}
        app = main({}, **settings)
        from webtest import TestApp

        self.testapp = TestApp(app, cookiejar=CookieJar())

测试:

    page = self.testapp.get('/login', status=200)

    self.assertIn('Please login', page)

    form = page.forms['loginForm']
    form['username'] = 'user'
    form['password'] = 'userpw'

    result = form.submit(status=200)

    # self.testapp.cookies is empty dictionary at this point
    # it fails here, login page is shown again
    page = self.testapp.get('/home', status=200)

result 返回 200 OK,并且登录页面的 HTML 内容,在表单提交之后,但没有发生重定向,是不是有问题?还是按预期工作?在其他表单提交的任何访问控制之前工作得很好。每次用户单击链接或重新加载页面时,cookie 都会更改。我正在使用会话 cookie。我试图为 cookie 设置一个不安全的标志。

和我的登录视图的最后返回:

if 'form.submitted' in request.POST:
# do stuff
    return HTTPFound(location=request.route_url('home'))

我会使用普通的 unittest,但由于 unittest 模块在视图尝试重定向时会松动,有人建议使用 webtest 库。

【问题讨论】:

    标签: python python-3.x pyramid webtest cookiejar


    【解决方案1】:

    问题是form.submit() 实际上并没有模仿我的基本用例,即用户单击提交按钮。在正常情况下,浏览器会在request.POST 旁边添加用户名、密码和('form.submitted', '')。但是form.submit() 只添加了用户名和密码,并且只添加了表单中定义的那些,所以我无法定义自己的值来配合请求。 (至少我没有发现如何)

    问题已在登录视图中解决。通过更改 if 'form.submitted' in request.POST: -> if 'username' in request.POST and 'password' in request.POST:

    Cookie 工作正常,如上所示,登录失败支持我的测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 2014-10-27
      • 2011-08-28
      • 2022-09-23
      • 1970-01-01
      相关资源
      最近更新 更多