pythonpython-3.xpyramidwebtestcookiejar

Getting cookies from a form submit and using them with a webtest


So I'm trying to do some test cases with webtest library, the problem is that my site has access control which requires a user to login. It seems that the form post is successful, but the result do not have any cookies (that I could find at least), and the cookiejar is empty after the login.

Test setup:

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())

Test:

    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 returns 200 OK, and the HTML content of the login page, after the form submit, but no redirect is happening, is that a problem? or is that working as intended? Before the any access control other form submits worked just fine. The cookies will change every time when the user clicks a link or reloads the page. I'm using session cookies. I tried to set a unsecure flag for cookies.

and the last return of the my login view:

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

I would be using the normal unittest but since unittest module looses its nuts when the view tries to do redirect, someone suggested webtest library.


Solution

  • Problem was that the form.submit() didn't actually mimic the basic use-case of mine, where the user clicks the submit button. In normal case the browser adds the username, password and the ('form.submitted', '') in side of the request.POST. But the form.submit() only adds the username and password, and only those that are defined in the form, so I couldn't define my own values to go with the request. (at least I didn't found out how)

    Problem was solved inside of the login view. by changing the if 'form.submitted' in request.POST: -> if 'username' in request.POST and 'password' in request.POST:

    Cookies are working just fine, as show above, login failed to support my test.