| 1 |
import unittest |
| 2 |
from test import support |
| 3 |
from test.support import os_helper |
| 4 |
from test.support import socket_helper |
| 5 |
|
| 6 |
import contextlib |
| 7 |
import socket |
| 8 |
import urllib.error |
| 9 |
import urllib.parse |
| 10 |
import urllib.request |
| 11 |
import os |
| 12 |
import email.message |
| 13 |
import time |
| 14 |
|
| 15 |
|
| 16 |
support.requires('network') |
| 17 |
|
| 18 |
|
| 19 |
class URLTimeoutTest(unittest.TestCase): |
| 20 |
# XXX this test doesn't seem to test anything useful. |
| 21 |
|
| 22 |
def setUp(self): |
| 23 |
socket.setdefaulttimeout(support.INTERNET_TIMEOUT) |
| 24 |
|
| 25 |
def tearDown(self): |
| 26 |
socket.setdefaulttimeout(None) |
| 27 |
|
| 28 |
def testURLread(self): |
| 29 |
# clear _opener global variable |
| 30 |
self.addCleanup(urllib.request.urlcleanup) |
| 31 |
|
| 32 |
domain = urllib.parse.urlparse(support.TEST_HTTP_URL).netloc |
| 33 |
with socket_helper.transient_internet(domain): |
| 34 |
f = urllib.request.urlopen(support.TEST_HTTP_URL) |
| 35 |
f.read() |
| 36 |
|
| 37 |
|
| 38 |
class urlopenNetworkTests(unittest.TestCase): |
| 39 |
"""Tests urllib.request.urlopen using the network. |
| 40 |
|
| 41 |
These tests are not exhaustive. Assuming that testing using files does a |
| 42 |
good job overall of some of the basic interface features. There are no |
| 43 |
tests exercising the optional 'data' and 'proxies' arguments. No tests |
| 44 |
for transparent redirection have been written. |
| 45 |
|
| 46 |
setUp is not used for always constructing a connection to |
| 47 |
http://www.pythontest.net/ since there a few tests that don't use that address |
| 48 |
and making a connection is expensive enough to warrant minimizing unneeded |
| 49 |
connections. |
| 50 |
|
| 51 |
""" |
| 52 |
|
| 53 |
url = 'http://www.pythontest.net/' |
| 54 |
|
| 55 |
def setUp(self): |
| 56 |
# clear _opener global variable |
| 57 |
self.addCleanup(urllib.request.urlcleanup) |
| 58 |
|
| 59 |
@contextlib.contextmanager |
| 60 |
def urlopen(self, *args, **kwargs): |
| 61 |
resource = args[0] |
| 62 |
with socket_helper.transient_internet(resource): |
| 63 |
r = urllib.request.urlopen(*args, **kwargs) |
| 64 |
try: |
| 65 |
yield r |
| 66 |
finally: |
| 67 |
r.close() |
| 68 |
|
| 69 |
def test_basic(self): |
| 70 |
# Simple test expected to pass. |
| 71 |
with self.urlopen(self.url) as open_url: |
| 72 |
for attr in ("read", "readline", "readlines", "fileno", "close", |
| 73 |
"info", "geturl"): |
| 74 |
self.assertHasAttr(open_url, attr) |
| 75 |
self.assertTrue(open_url.read(), "calling 'read' failed") |
| 76 |
|
| 77 |
def test_readlines(self): |
| 78 |
# Test both readline and readlines. |
| 79 |
with self.urlopen(self.url) as open_url: |
| 80 |
self.assertIsInstance(open_url.readline(), bytes, |
| 81 |
"readline did not return a string") |
| 82 |
self.assertIsInstance(open_url.readlines(), list, |
| 83 |
"readlines did not return a list") |
| 84 |
|
| 85 |
def test_info(self): |
| 86 |
# Test 'info'. |
| 87 |
with self.urlopen(self.url) as open_url: |
| 88 |
info_obj = open_url.info() |
| 89 |
self.assertIsInstance(info_obj, email.message.Message, |
| 90 |
"object returned by 'info' is not an " |
| 91 |
"instance of email.message.Message") |
| 92 |
self.assertEqual(info_obj.get_content_subtype(), "html") |
| 93 |
|
| 94 |
def test_geturl(self): |
| 95 |
# Make sure same URL as opened is returned by geturl. |
| 96 |
with self.urlopen(self.url) as open_url: |
| 97 |
gotten_url = open_url.geturl() |
| 98 |
self.assertEqual(gotten_url, self.url) |
| 99 |
|
| 100 |
def test_getcode(self): |
| 101 |
# test getcode() with the fancy opener to get 404 error codes |
| 102 |
URL = self.url + "XXXinvalidXXX" |
| 103 |
with socket_helper.transient_internet(URL): |
| 104 |
with self.assertRaises(urllib.error.URLError) as e: |
| 105 |
with urllib.request.urlopen(URL): |
| 106 |
pass |
| 107 |
self.assertEqual(e.exception.code, 404) |
| 108 |
e.exception.close() |
| 109 |
|
| 110 |
@support.requires_resource('walltime') |
| 111 |
def test_bad_address(self): |
| 112 |
# Make sure proper exception is raised when connecting to a bogus |
| 113 |
# address. |
| 114 |
|
| 115 |
# Given that both VeriSign and various ISPs have in |
| 116 |
# the past or are presently hijacking various invalid |
| 117 |
# domain name requests in an attempt to boost traffic |
| 118 |
# to their own sites, finding a domain name to use |
| 119 |
# for this test is difficult. RFC2606 leads one to |
| 120 |
# believe that '.invalid' should work, but experience |
| 121 |
# seemed to indicate otherwise. Single character |
| 122 |
# TLDs are likely to remain invalid, so this seems to |
| 123 |
# be the best choice. The trailing '.' prevents a |
| 124 |
# related problem: The normal DNS resolver appends |
| 125 |
# the domain names from the search path if there is |
| 126 |
# no '.' the end and, and if one of those domains |
| 127 |
# implements a '*' rule a result is returned. |
| 128 |
# However, none of this will prevent the test from |
| 129 |
# failing if the ISP hijacks all invalid domain |
| 130 |
# requests. The real solution would be to be able to |
| 131 |
# parameterize the framework with a mock resolver. |
| 132 |
bogus_domain = "sadflkjsasf.i.nvali.d." |
| 133 |
try: |
| 134 |
socket.gethostbyname(bogus_domain) |
| 135 |
except OSError: |
| 136 |
# socket.gaierror is too narrow, since getaddrinfo() may also |
| 137 |
# fail with EAI_SYSTEM and ETIMEDOUT (seen on Ubuntu 13.04), |
| 138 |
# i.e. Python's TimeoutError. |
| 139 |
pass |
| 140 |
else: |
| 141 |
# This happens with some overzealous DNS providers such as OpenDNS |
| 142 |
self.skipTest("%r should not resolve for test to work" % bogus_domain) |
| 143 |
failure_explanation = ('opening an invalid URL did not raise OSError; ' |
| 144 |
'can be caused by a broken DNS server ' |
| 145 |
'(e.g. returns 404 or hijacks page)') |
| 146 |
with self.assertRaises(OSError, msg=failure_explanation): |
| 147 |
urllib.request.urlopen("http://{}/".format(bogus_domain)) |
| 148 |
|
| 149 |
|
| 150 |
class urlretrieveNetworkTests(unittest.TestCase): |
| 151 |
"""Tests urllib.request.urlretrieve using the network.""" |
| 152 |
|
| 153 |
def setUp(self): |
| 154 |
# remove temporary files created by urlretrieve() |
| 155 |
self.addCleanup(urllib.request.urlcleanup) |
| 156 |
|
| 157 |
@contextlib.contextmanager |
| 158 |
def urlretrieve(self, *args, **kwargs): |
| 159 |
resource = args[0] |
| 160 |
with socket_helper.transient_internet(resource): |
| 161 |
file_location, info = urllib.request.urlretrieve(*args, **kwargs) |
| 162 |
try: |
| 163 |
yield file_location, info |
| 164 |
finally: |
| 165 |
os_helper.unlink(file_location) |
| 166 |
|
| 167 |
def test_basic(self): |
| 168 |
# Test basic functionality. |
| 169 |
with self.urlretrieve(self.logo) as (file_location, info): |
| 170 |
self.assertTrue(os.path.exists(file_location), "file location returned by" |
| 171 |
" urlretrieve is not a valid path") |
| 172 |
with open(file_location, 'rb') as f: |
| 173 |
self.assertTrue(f.read(), "reading from the file location returned" |
| 174 |
" by urlretrieve failed") |
| 175 |
|
| 176 |
def test_specified_path(self): |
| 177 |
# Make sure that specifying the location of the file to write to works. |
| 178 |
with self.urlretrieve(self.logo, |
| 179 |
os_helper.TESTFN) as (file_location, info): |
| 180 |
self.assertEqual(file_location, os_helper.TESTFN) |
| 181 |
self.assertTrue(os.path.exists(file_location)) |
| 182 |
with open(file_location, 'rb') as f: |
| 183 |
self.assertTrue(f.read(), "reading from temporary file failed") |
| 184 |
|
| 185 |
def test_header(self): |
| 186 |
# Make sure header returned as 2nd value from urlretrieve is good. |
| 187 |
with self.urlretrieve(self.logo) as (file_location, info): |
| 188 |
self.assertIsInstance(info, email.message.Message, |
| 189 |
"info is not an instance of email.message.Message") |
| 190 |
|
| 191 |
logo = "http://www.pythontest.net/" |
| 192 |
|
| 193 |
@support.requires_resource('walltime') |
| 194 |
def test_data_header(self): |
| 195 |
with self.urlretrieve(self.logo) as (file_location, fileheaders): |
| 196 |
datevalue = fileheaders.get('Date') |
| 197 |
dateformat = '%a, %d %b %Y %H:%M:%S GMT' |
| 198 |
try: |
| 199 |
time.strptime(datevalue, dateformat) |
| 200 |
except ValueError: |
| 201 |
self.fail('Date value not in %r format' % dateformat) |
| 202 |
|
| 203 |
def test_reporthook(self): |
| 204 |
records = [] |
| 205 |
|
| 206 |
def recording_reporthook(blocks, block_size, total_size): |
| 207 |
records.append((blocks, block_size, total_size)) |
| 208 |
|
| 209 |
with self.urlretrieve(self.logo, reporthook=recording_reporthook) as ( |
| 210 |
file_location, fileheaders): |
| 211 |
expected_size = int(fileheaders['Content-Length']) |
| 212 |
|
| 213 |
records_repr = repr(records) # For use in error messages. |
| 214 |
self.assertGreater(len(records), 1, msg="There should always be two " |
| 215 |
"calls; the first one before the transfer starts.") |
| 216 |
self.assertEqual(records[0][0], 0) |
| 217 |
self.assertGreater(records[0][1], 0, |
| 218 |
msg="block size can't be 0 in %s" % records_repr) |
| 219 |
self.assertEqual(records[0][2], expected_size) |
| 220 |
self.assertEqual(records[-1][2], expected_size) |
| 221 |
|
| 222 |
block_sizes = {block_size for _, block_size, _ in records} |
| 223 |
self.assertEqual({records[0][1]}, block_sizes, |
| 224 |
msg="block sizes in %s must be equal" % records_repr) |
| 225 |
self.assertGreaterEqual(records[-1][0]*records[0][1], expected_size, |
| 226 |
msg="number of blocks * block size must be" |
| 227 |
" >= total size in %s" % records_repr) |
| 228 |
|
| 229 |
|
| 230 |
if __name__ == "__main__": |
| 231 |
unittest.main() |