1"""Unit tests for code in urllib.response.""" 2 3import socket 4import tempfile 5import urllib.response 6import unittest 7 8class TestResponse(unittest.TestCase): 9 10 def setUp(self): 11 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 12 self.fp = self.sock.makefile('rb') 13 self.test_headers = {"Host": "www.python.org", 14 "Connection": "close"} 15 16 def test_with(self): 17 addbase = urllib.response.addbase(self.fp) 18 19 self.assertIsInstance(addbase, tempfile._TemporaryFileWrapper) 20 21 def f(): 22 with addbase as spam: 23 pass 24 self.assertFalse(self.fp.closed) 25 f() 26 self.assertTrue(self.fp.closed) 27 self.assertRaises(ValueError, f) 28 29 def test_addclosehook(self): 30 closehook_called = False 31 32 def closehook(): 33 nonlocal closehook_called 34 closehook_called = True 35 36 closehook = urllib.response.addclosehook(self.fp, closehook) 37 closehook.close() 38 39 self.assertTrue(self.fp.closed) 40 self.assertTrue(closehook_called) 41 42 def test_addinfo(self): 43 info = urllib.response.addinfo(self.fp, self.test_headers) 44 self.assertEqual(info.info(), self.test_headers) 45 self.assertEqual(info.headers, self.test_headers) 46 47 def test_addinfourl(self): 48 url = "http://www.python.org" 49 code = 200 50 infourl = urllib.response.addinfourl(self.fp, self.test_headers, 51 url, code) 52 self.assertEqual(infourl.info(), self.test_headers) 53 self.assertEqual(infourl.geturl(), url) 54 self.assertEqual(infourl.getcode(), code) 55 self.assertEqual(infourl.headers, self.test_headers) 56 self.assertEqual(infourl.url, url) 57 self.assertEqual(infourl.status, code) 58 59 def tearDown(self): 60 self.sock.close() 61 62if __name__ == '__main__': 63 unittest.main() 64