Debian Codegraph @

Lib/test/test_robotparser.py

raw
1 import io
2 import os
3 import threading
4 import unittest
5 import urllib.robotparser
6 from test import support
7 from test.support import socket_helper
8 from test.support import threading_helper
9 from http.server import BaseHTTPRequestHandler, HTTPServer
10
11
12 class BaseRobotTest:
13 robots_txt = ''
14 agent = 'test_robotparser'
15 good = []
16 bad = []
17 site_maps = None
18
19 def __init_subclass__(cls):
20 super().__init_subclass__()
21 # Remove tests that do nothing.
22 if not cls.good:
23 cls.test_good_urls = None
24 if not cls.bad:
25 cls.test_bad_urls = None
26
27 def setUp(self):
28 lines = io.StringIO(self.robots_txt).readlines()
29 self.parser = urllib.robotparser.RobotFileParser()
30 self.parser.parse(lines)
31
32 def get_agent_and_url(self, url):
33 if isinstance(url, tuple):
34 agent, url = url
35 return agent, url
36 return self.agent, url
37
38 def test_good_urls(self):
39 for url in self.good:
40 agent, url = self.get_agent_and_url(url)
41 with self.subTest(url=url, agent=agent):
42 self.assertTrue(self.parser.can_fetch(agent, url))
43
44 def test_bad_urls(self):
45 for url in self.bad:
46 agent, url = self.get_agent_and_url(url)
47 with self.subTest(url=url, agent=agent):
48 self.assertFalse(self.parser.can_fetch(agent, url))
49
50 def test_site_maps(self):
51 self.assertEqual(self.parser.site_maps(), self.site_maps)
52
53
54 class UserAgentWildcardTest(BaseRobotTest, unittest.TestCase):
55 robots_txt = """\
56 User-agent: *
57 Disallow: /cyberworld/map/ # This is an infinite virtual URL space
58 Disallow: /tmp/ # these will soon disappear
59 Disallow: /foo.html
60 """
61 good = ['/', '/test.html']
62 bad = ['/cyberworld/map/index.html', '/tmp/xxx', '/foo.html']
63
64
65 class CrawlDelayAndCustomAgentTest(BaseRobotTest, unittest.TestCase):
66 robots_txt = """\
67 # robots.txt for http://www.example.com/
68
69 User-agent: *
70 Crawl-delay: 1
71 Request-rate: 3/15
72 Disallow: /cyberworld/map/ # This is an infinite virtual URL space
73
74 # Cybermapper knows where to go.
75 User-agent: cybermapper
76 Disallow:
77 """
78 good = ['/', '/test.html', ('cybermapper', '/cyberworld/map/index.html')]
79 bad = ['/cyberworld/map/index.html']
80
81
82 class SitemapTest(BaseRobotTest, unittest.TestCase):
83 robots_txt = """\
84 # robots.txt for http://www.example.com/
85
86 User-agent: *
87 Sitemap: http://www.gstatic.com/s2/sitemaps/profiles-sitemap.xml
88 Sitemap: http://www.google.com/hostednews/sitemap_index.xml
89 Request-rate: 3/15
90 Disallow: /cyberworld/map/ # This is an infinite virtual URL space
91
92 """
93 good = ['/', '/test.html']
94 bad = ['/cyberworld/map/index.html']
95 site_maps = ['http://www.gstatic.com/s2/sitemaps/profiles-sitemap.xml',
96 'http://www.google.com/hostednews/sitemap_index.xml']
97
98
99 class RejectAllRobotsTest(BaseRobotTest, unittest.TestCase):
100 robots_txt = """\
101 # go away
102 User-agent: *
103 Disallow: /
104 """
105 good = []
106 bad = ['/cyberworld/map/index.html', '/', '/tmp/']
107
108
109 class BaseRequestRateTest(BaseRobotTest):
110 request_rate = None
111 crawl_delay = None
112
113 def test_request_rate(self):
114 parser = self.parser
115 for url in self.good + self.bad:
116 agent, url = self.get_agent_and_url(url)
117 with self.subTest(url=url, agent=agent):
118 self.assertEqual(parser.crawl_delay(agent), self.crawl_delay)
119
120 parsed_request_rate = parser.request_rate(agent)
121 self.assertEqual(parsed_request_rate, self.request_rate)
122 if self.request_rate is not None:
123 self.assertIsInstance(
124 parsed_request_rate,
125 urllib.robotparser.RequestRate
126 )
127 self.assertEqual(
128 parsed_request_rate.requests,
129 self.request_rate.requests
130 )
131 self.assertEqual(
132 parsed_request_rate.seconds,
133 self.request_rate.seconds
134 )
135
136
137 class EmptyFileTest(BaseRequestRateTest, unittest.TestCase):
138 robots_txt = ''
139 good = ['/foo']
140
141
142 class CrawlDelayAndRequestRateTest(BaseRequestRateTest, unittest.TestCase):
143 robots_txt = """\
144 User-agent: figtree
145 Crawl-delay: 3
146 Request-rate: 9/30
147 Disallow: /tmp
148 Disallow: /a%3cd.html
149 Disallow: /a%2fb.html
150 Disallow: /%7ejoe/index.html
151 """
152 agent = 'figtree'
153 request_rate = urllib.robotparser.RequestRate(9, 30)
154 crawl_delay = 3
155 good = [('figtree', '/foo.html')]
156 bad = ['/tmp', '/tmp.html', '/tmp/a.html', '/a%3cd.html', '/a%3Cd.html',
157 '/a%2fb.html', '/~joe/index.html']
158
159
160 class DifferentAgentTest(CrawlDelayAndRequestRateTest):
161 agent = 'FigTree Robot libwww-perl/5.04'
162
163
164 class InvalidRequestRateTest(BaseRobotTest, unittest.TestCase):
165 robots_txt = """\
166 User-agent: *
167 Disallow: /tmp/
168 Disallow: /a%3Cd.html
169 Disallow: /a/b.html
170 Disallow: /%7ejoe/index.html
171 Crawl-delay: 3
172 Request-rate: 9/banana
173 """
174 good = ['/tmp']
175 bad = ['/tmp/', '/tmp/a.html', '/a%3cd.html', '/a%3Cd.html', '/a/b.html',
176 '/%7Ejoe/index.html']
177 crawl_delay = 3
178
179
180 class InvalidCrawlDelayTest(BaseRobotTest, unittest.TestCase):
181 # From bug report #523041
182 robots_txt = """\
183 User-Agent: *
184 Disallow: /.
185 Crawl-delay: pears
186 """
187 good = ['/foo.html']
188 # bug report says "/" should be denied, but that is not in the RFC
189 bad = []
190
191
192 class AnotherInvalidRequestRateTest(BaseRobotTest, unittest.TestCase):
193 # also test that Allow and Diasallow works well with each other
194 robots_txt = """\
195 User-agent: Googlebot
196 Allow: /folder1/myfile.html
197 Disallow: /folder1/
198 Request-rate: whale/banana
199 """
200 agent = 'Googlebot'
201 good = ['/folder1/myfile.html']
202 bad = ['/folder1/anotherfile.html']
203
204
205 class UserAgentOrderingTest(BaseRobotTest, unittest.TestCase):
206 # the order of User-agent should be correct. note
207 # that this file is incorrect because "Googlebot" is a
208 # substring of "Googlebot-Mobile"
209 robots_txt = """\
210 User-agent: Googlebot
211 Disallow: /
212
213 User-agent: Googlebot-Mobile
214 Allow: /
215 """
216 agent = 'Googlebot'
217 bad = ['/something.jpg']
218
219
220 class UserAgentGoogleMobileTest(UserAgentOrderingTest):
221 agent = 'Googlebot-Mobile'
222
223
224 class GoogleURLOrderingTest(BaseRobotTest, unittest.TestCase):
225 # Google also got the order wrong. You need
226 # to specify the URLs from more specific to more general
227 robots_txt = """\
228 User-agent: Googlebot
229 Allow: /folder1/myfile.html
230 Disallow: /folder1/
231 """
232 agent = 'googlebot'
233 good = ['/folder1/myfile.html']
234 bad = ['/folder1/anotherfile.html']
235
236
237 class DisallowQueryStringTest(BaseRobotTest, unittest.TestCase):
238 # see issue #6325 for details
239 robots_txt = """\
240 User-agent: *
241 Disallow: /some/path?name=value
242 Disallow: /another/path?
243 Disallow: /yet/one/path?name=value&more
244 """
245 good = ['/some/path', '/some/path?',
246 '/some/path%3Fname=value', '/some/path?name%3Dvalue',
247 '/another/path', '/another/path%3F',
248 '/yet/one/path?name=value%26more']
249 bad = ['/some/path?name=value'
250 '/another/path?', '/another/path?name=value',
251 '/yet/one/path?name=value&more']
252
253
254 class UseFirstUserAgentWildcardTest(BaseRobotTest, unittest.TestCase):
255 # obey first * entry (#4108)
256 robots_txt = """\
257 User-agent: *
258 Disallow: /some/path
259
260 User-agent: *
261 Disallow: /another/path
262 """
263 good = ['/another/path']
264 bad = ['/some/path']
265
266
267 class PercentEncodingTest(BaseRobotTest, unittest.TestCase):
268 robots_txt = """\
269 User-agent: *
270 Disallow: /a1/Z-._~ # unreserved characters
271 Disallow: /a2/%5A%2D%2E%5F%7E # percent-encoded unreserved characters
272 Disallow: /u1/%F0%9F%90%8D # percent-encoded ASCII Unicode character
273 Disallow: /u2/%f0%9f%90%8d
274 Disallow: /u3/\U0001f40d # raw non-ASCII Unicode character
275 Disallow: /v1/%F0 # percent-encoded non-ASCII octet
276 Disallow: /v2/%f0
277 Disallow: /v3/\udcf0 # raw non-ASCII octet
278 Disallow: /p1%xy # raw percent
279 Disallow: /p2%
280 Disallow: /p3%25xy # percent-encoded percent
281 Disallow: /p4%2525xy # double percent-encoded percent
282 Disallow: /john%20smith # space
283 Disallow: /john doe
284 Disallow: /trailingspace%20
285 Disallow: /question%3Fq=v # not query
286 Disallow: /hash%23f # not fragment
287 Disallow: /dollar%24
288 Disallow: /asterisk%2A
289 Disallow: /sub/dir
290 Disallow: /slash%2F
291 Disallow: /query/question?q=%3F
292 Disallow: /query/raw/question?q=?
293 Disallow: /query/eq?q%3Dv
294 Disallow: /query/amp?q=v%26a
295 """
296 good = [
297 '/u1/%F0', '/u1/%f0',
298 '/u2/%F0', '/u2/%f0',
299 '/u3/%F0', '/u3/%f0',
300 '/p1%2525xy', '/p2%f0', '/p3%2525xy', '/p4%xy', '/p4%25xy',
301 '/question?q=v',
302 '/dollar', '/asterisk',
303 '/query/eq?q=v',
304 '/query/amp?q=v&a',
305 ]
306 bad = [
307 '/a1/Z-._~', '/a1/%5A%2D%2E%5F%7E',
308 '/a2/Z-._~', '/a2/%5A%2D%2E%5F%7E',
309 '/u1/%F0%9F%90%8D', '/u1/%f0%9f%90%8d', '/u1/\U0001f40d',
310 '/u2/%F0%9F%90%8D', '/u2/%f0%9f%90%8d', '/u2/\U0001f40d',
311 '/u3/%F0%9F%90%8D', '/u3/%f0%9f%90%8d', '/u3/\U0001f40d',
312 '/v1/%F0', '/v1/%f0', '/v1/\udcf0', '/v1/\U0001f40d',
313 '/v2/%F0', '/v2/%f0', '/v2/\udcf0', '/v2/\U0001f40d',
314 '/v3/%F0', '/v3/%f0', '/v3/\udcf0', '/v3/\U0001f40d',
315 '/p1%xy', '/p1%25xy',
316 '/p2%', '/p2%25', '/p2%2525', '/p2%xy',
317 '/p3%xy', '/p3%25xy',
318 '/p4%2525xy',
319 '/john%20smith', '/john smith',
320 '/john%20doe', '/john doe',
321 '/trailingspace%20', '/trailingspace ',
322 '/question%3Fq=v',
323 '/hash#f', '/hash%23f',
324 '/dollar$', '/dollar%24',
325 '/asterisk*', '/asterisk%2A',
326 '/sub/dir', '/sub%2Fdir',
327 '/slash%2F', '/slash/',
328 '/query/question?q=?', '/query/question?q=%3F',
329 '/query/raw/question?q=?', '/query/raw/question?q=%3F',
330 '/query/eq?q%3Dv',
331 '/query/amp?q=v%26a',
332 ]
333 # other reserved characters
334 for c in ":/[]@!$&'()*+,;=":
335 robots_txt += f'Disallow: /raw{c}\nDisallow: /pc%{ord(c):02X}\n'
336 bad.append(f'/raw{c}')
337 bad.append(f'/raw%{ord(c):02X}')
338 bad.append(f'/pc{c}')
339 bad.append(f'/pc%{ord(c):02X}')
340
341
342 class DefaultEntryTest(BaseRequestRateTest, unittest.TestCase):
343 robots_txt = """\
344 User-agent: *
345 Crawl-delay: 1
346 Request-rate: 3/15
347 Disallow: /cyberworld/map/
348 """
349 request_rate = urllib.robotparser.RequestRate(3, 15)
350 crawl_delay = 1
351 good = ['/', '/test.html']
352 bad = ['/cyberworld/map/index.html']
353
354
355 class StringFormattingTest(BaseRobotTest, unittest.TestCase):
356 robots_txt = """\
357 User-agent: *
358 Crawl-delay: 1
359 Request-rate: 3/15
360 Disallow: /cyberworld/map/ # This is an infinite virtual URL space
361
362 # Cybermapper knows where to go.
363 User-agent: cybermapper
364 Disallow: /some/path
365 """
366
367 expected_output = """\
368 User-agent: cybermapper
369 Disallow: /some/path
370
371 User-agent: *
372 Crawl-delay: 1
373 Request-rate: 3/15
374 Disallow: /cyberworld/map/\
375 """
376
377 def test_string_formatting(self):
378 self.assertEqual(str(self.parser), self.expected_output)
379
380
381 @unittest.skipUnless(
382 support.has_socket_support,
383 "Socket server requires working socket."
384 )
385 class BaseLocalNetworkTestCase:
386
387 def setUp(self):
388 # clear _opener global variable
389 self.addCleanup(urllib.request.urlcleanup)
390
391 self.server = HTTPServer((socket_helper.HOST, 0), self.RobotHandler)
392
393 self.t = threading.Thread(
394 name='HTTPServer serving',
395 target=self.server.serve_forever,
396 # Short poll interval to make the test finish quickly.
397 # Time between requests is short enough that we won't wake
398 # up spuriously too many times.
399 kwargs={'poll_interval':0.01})
400 self.t.daemon = True # In case this function raises.
401 self.t.start()
402
403 def tearDown(self):
404 self.server.shutdown()
405 self.t.join()
406 self.server.server_close()
407
408
409 SAMPLE_ROBOTS_TXT = b'''\
410 User-agent: test_robotparser
411 Disallow: /utf8/\xf0\x9f\x90\x8d
412 Disallow: /non-utf8/\xf0
413 Disallow: //[spam]/path
414 '''
415
416
417 class LocalNetworkTestCase(BaseLocalNetworkTestCase, unittest.TestCase):
418 class RobotHandler(BaseHTTPRequestHandler):
419
420 def do_GET(self):
421 self.send_response(200)
422 self.end_headers()
423 self.wfile.write(SAMPLE_ROBOTS_TXT)
424
425 def log_message(self, format, *args):
426 pass
427
428 @threading_helper.reap_threads
429 def testRead(self):
430 # Test that reading a weird robots.txt doesn't fail.
431 addr = self.server.server_address
432 url = f'http://{socket_helper.HOST}:{addr[1]}'
433 robots_url = url + '/robots.txt'
434 parser = urllib.robotparser.RobotFileParser()
435 parser.set_url(robots_url)
436 parser.read()
437 # And it can even interpret the weird paths in some reasonable way.
438 agent = 'test_robotparser'
439 self.assertTrue(parser.can_fetch(agent, robots_url))
440 self.assertTrue(parser.can_fetch(agent, url + '/utf8/'))
441 self.assertFalse(parser.can_fetch(agent, url + '/utf8/\U0001f40d'))
442 self.assertFalse(parser.can_fetch(agent, url + '/utf8/%F0%9F%90%8D'))
443 self.assertFalse(parser.can_fetch(agent, url + '/utf8/\U0001f40d'))
444 self.assertTrue(parser.can_fetch(agent, url + '/non-utf8/'))
445 self.assertFalse(parser.can_fetch(agent, url + '/non-utf8/%F0'))
446 self.assertFalse(parser.can_fetch(agent, url + '/non-utf8/\U0001f40d'))
447 self.assertFalse(parser.can_fetch(agent, url + '/%2F[spam]/path'))
448
449
450 class PasswordProtectedSiteTestCase(BaseLocalNetworkTestCase, unittest.TestCase):
451 class RobotHandler(BaseHTTPRequestHandler):
452
453 def do_GET(self):
454 self.send_error(403, "Forbidden access")
455
456 def log_message(self, format, *args):
457 pass
458
459 @threading_helper.reap_threads
460 def testPasswordProtectedSite(self):
461 addr = self.server.server_address
462 url = 'http://' + socket_helper.HOST + ':' + str(addr[1])
463 robots_url = url + "/robots.txt"
464 parser = urllib.robotparser.RobotFileParser()
465 parser.set_url(url)
466 parser.read()
467 self.assertFalse(parser.can_fetch("*", robots_url))
468
469
470 @support.requires_working_socket()
471 class NetworkTestCase(unittest.TestCase):
472
473 base_url = 'http://www.pythontest.net/'
474 robots_txt = '{}elsewhere/robots.txt'.format(base_url)
475
476 @classmethod
477 def setUpClass(cls):
478 support.requires('network')
479 with socket_helper.transient_internet(cls.base_url):
480 cls.parser = urllib.robotparser.RobotFileParser(cls.robots_txt)
481 cls.parser.read()
482
483 def url(self, path):
484 return '{}{}{}'.format(
485 self.base_url, path, '/' if not os.path.splitext(path)[1] else ''
486 )
487
488 def test_basic(self):
489 self.assertFalse(self.parser.disallow_all)
490 self.assertFalse(self.parser.allow_all)
491 self.assertGreater(self.parser.mtime(), 0)
492 self.assertFalse(self.parser.crawl_delay('*'))
493 self.assertFalse(self.parser.request_rate('*'))
494
495 def test_can_fetch(self):
496 self.assertTrue(self.parser.can_fetch('*', self.url('elsewhere')))
497 self.assertFalse(self.parser.can_fetch('Nutch', self.base_url))
498 self.assertFalse(self.parser.can_fetch('Nutch', self.url('brian')))
499 self.assertFalse(self.parser.can_fetch('Nutch', self.url('webstats')))
500 self.assertFalse(self.parser.can_fetch('*', self.url('webstats')))
501 self.assertTrue(self.parser.can_fetch('*', self.base_url))
502
503 def test_read_404(self):
504 parser = urllib.robotparser.RobotFileParser(self.url('i-robot.txt'))
505 parser.read()
506 self.assertTrue(parser.allow_all)
507 self.assertFalse(parser.disallow_all)
508 self.assertEqual(parser.mtime(), 0)
509 self.assertIsNone(parser.crawl_delay('*'))
510 self.assertIsNone(parser.request_rate('*'))
511
512 if __name__=='__main__':
513 unittest.main()