Skip to content

Instantly share code, notes, and snippets.

@cgallemore
Created February 27, 2012 18:49
Show Gist options
  • Save cgallemore/1926187 to your computer and use it in GitHub Desktop.
Save cgallemore/1926187 to your computer and use it in GitHub Desktop.
Potential Solution for testing with CSRF enabled
#In looking into the issue with being able to test with CSRF enabled,
#I've come up with a way to mock this out and wanted to see what you
#guys think before I move on. Here is a sample test of what this
#would look like:
@mock.patch.object(SessionStore, 'get_secure_cookie')
def test_can_add_order(self, mock_session):
mock_session.return_value = {'csrf_token': str(uuid4())}
self.login('[email protected]', admin = True)
response = self.app.get(build_url('order_add'))
form = response.form
form.set('customer', self.test_customer.key.urlsafe())
form.set('origin', self.fake_location.key.urlsafe())
form.set('destination', self.fake_location.key.urlsafe())
form.set('scheduled_pickup_time', '02/15/2012 00:00:00')
form.set('scheduled_delivery_time', '02/15/2012 00:00:00')
form.set('product', self.fake_product.key.urlsafe())
submit_response = form.submit().follow()
submit_response.mustcontain(self.fake_location.name, self.fake_product.name, '02/15/2012 00:00:00')
#Essentially what is going on is we are patching the get_secure_cookie function
#on the SessionStore object to return a value that we expect. The code would function
#exactly like it normally would, we are just stubbing out one function. Then inside our test
#we set the return value for the patched function. Running this test in it's current form
#will pass as long as the form has the CSRF hidden filed in the template, if not, this fails
#as expected.
#I'll have to go though each test case and apply the patch to the test cases that needs it,
#and going forward as you write your test, you'll need to apply the patch if applicable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment