Last Updated: February 25, 2016
·
5.743K
· Lorin Hochstein

Testing a PDF download with splinter and requests

Here's how I use Splinter and requests to test if a Django app is generating a PDF file:

import requests
from splinter.browser import Browser
from nose.tools import assert_equal

browser = Browser()
# Log in to the website with splinter
...
url = ... # pdf download url
cookies = {browser.cookies.all()[0]["name"]:browser.cookies.all()[0]["value"]}
result = requests.get(url, cookies=cookies)
assert_equal(result.headers['content-type'], 'application/pdf')
assert result.content.startswith('%PDF-')

# Bonus points: open the pdf in the browser
(fd, fname) = tempfile.mkstemp()
pdf = os.fdopen(fd, 'w')
pdf.write(result.content)
pdf.close()
browser.visit("file://" + fname)