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
46    def test_addinfourl(self):
47        url = "http://www.python.org"
48        code = 200
49        infourl = urllib.response.addinfourl(self.fp, self.test_headers,
50                                             url, code)
51        self.assertEqual(infourl.info(), self.test_headers)
52        self.assertEqual(infourl.geturl(), url)
53        self.assertEqual(infourl.getcode(), code)
54
55    def tearDown(self):
56        self.sock.close()
57
58if __name__ == '__main__':
59    unittest.main()
60