See the unittest below (especially the connectWithDigestAuth function).
import unittest
import urllib2
def connectWithDigestAuth(url, username, pw, realm):
authhandler = urllib2.HTTPDigestAuthHandler()
authhandler.add_password(realm, url, username, pw)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
pagehandle = urllib2.urlopen(url)
lines = pagehandle.readlines()
return lines
class testLinebreak(unittest.TestCase):
def testAuth(self):
url = "http://localhost/authTest/index.html"
username = "matt"
password = "password"
realm = "/home/spike"
contents = connectWithDigestAuth(url, username, password, realm)
self.failUnless('You should be authenticated!\n' in contents)
def testBadAuth(self):
url = "http://localhost/authTest/index.html"
username = "BadUser"
password = "password"
realm = "/home/spike"
self.assertRaises(urllib2.HTTPError, connectWithDigestAuth,url, username, password, realm)
def testNoAuth(self):
"a test to make sure this location is protected"
url = "http://localhost/authTest/index.html"
req = urllib2.Request(url)
self.assertRaises(urllib2.HTTPError, urllib2.urlopen, req)
if __name__=="__main__":
unittest.main()
username&password