/usr/lib/python2.7/dist-packages/twisted/web/test/test_webclient.py is in python-twisted-web 13.2.0-1ubuntu1.2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for the old L{twisted.web.client} APIs, C{getPage} and friends.
"""
from __future__ import division, absolute_import
import os
from errno import ENOSPC
try:
from urlparse import urlparse, urljoin
except ImportError:
from urllib.parse import urlparse, urljoin
from twisted.python.compat import _PY3, networkString, nativeString, intToBytes
from twisted.trial import unittest
from twisted.web import server, client, error, resource
from twisted.internet import reactor, defer, interfaces
from twisted.python.filepath import FilePath
from twisted.python.log import msg
from twisted.protocols.policies import WrappingFactory
from twisted.test.proto_helpers import StringTransport
try:
from twisted.internet import ssl
except:
ssl = None
from twisted import test
serverPEM = FilePath(test.__file__.encode("utf-8")).sibling(b'server.pem')
serverPEMPath = nativeString(serverPEM.path)
# Remove this in #6177, when static is ported to Python 3:
if _PY3:
from twisted.web.test.test_web import Data
else:
from twisted.web.static import Data
# Remove this in #6178, when util is ported to Python 3:
if _PY3:
class Redirect(resource.Resource):
isLeaf = 1
def __init__(self, url):
resource.Resource.__init__(self)
self.url = url
def render(self, request):
request.redirect(self.url)
return b""
def getChild(self, name, request):
return self
else:
from twisted.web.util import Redirect
_PY3DownloadSkip = "downloadPage will be ported to Python 3 in ticket #6197."
class ExtendedRedirect(resource.Resource):
"""
Redirection resource.
The HTTP status code is set according to the C{code} query parameter.
@type lastMethod: C{str}
@ivar lastMethod: Last handled HTTP request method
"""
isLeaf = 1
lastMethod = None
def __init__(self, url):
resource.Resource.__init__(self)
self.url = url
def render(self, request):
if self.lastMethod:
self.lastMethod = request.method
return b"OK Thnx!"
else:
self.lastMethod = request.method
code = int(request.args[b'code'][0])
return self.redirectTo(self.url, request, code)
def getChild(self, name, request):
return self
def redirectTo(self, url, request, code):
request.setResponseCode(code)
request.setHeader(b"location", url)
return b"OK Bye!"
class ForeverTakingResource(resource.Resource):
"""
L{ForeverTakingResource} is a resource which never finishes responding
to requests.
"""
def __init__(self, write=False):
resource.Resource.__init__(self)
self._write = write
def render(self, request):
if self._write:
request.write(b'some bytes')
return server.NOT_DONE_YET
class CookieMirrorResource(resource.Resource):
def render(self, request):
l = []
for k,v in sorted(list(request.received_cookies.items())):
l.append((nativeString(k), nativeString(v)))
l.sort()
return networkString(repr(l))
class RawCookieMirrorResource(resource.Resource):
def render(self, request):
header = request.getHeader(b'cookie')
if header is None:
return b'None'
return networkString(repr(nativeString(header)))
class ErrorResource(resource.Resource):
def render(self, request):
request.setResponseCode(401)
if request.args.get(b"showlength"):
request.setHeader(b"content-length", b"0")
return b""
class NoLengthResource(resource.Resource):
def render(self, request):
return b"nolength"
class HostHeaderResource(resource.Resource):
"""
A testing resource which renders itself as the value of the host header
from the request.
"""
def render(self, request):
return request.requestHeaders.getRawHeaders(b"host")[0]
class PayloadResource(resource.Resource):
"""
A testing resource which renders itself as the contents of the request body
as long as the request body is 100 bytes long, otherwise which renders
itself as C{"ERROR"}.
"""
def render(self, request):
data = request.content.read()
contentLength = request.requestHeaders.getRawHeaders(b"content-length")[0]
if len(data) != 100 or int(contentLength) != 100:
return b"ERROR"
return data
class DelayResource(resource.Resource):
def __init__(self, seconds):
self.seconds = seconds
def render(self, request):
def response():
request.write(b'some bytes')
request.finish()
reactor.callLater(self.seconds, response)
return server.NOT_DONE_YET
class BrokenDownloadResource(resource.Resource):
def render(self, request):
# only sends 3 bytes even though it claims to send 5
request.setHeader(b"content-length", b"5")
request.write(b'abc')
return b''
class CountingRedirect(Redirect):
"""
A L{Redirect} resource that keeps track of the number of times the
resource has been accessed.
"""
def __init__(self, *a, **kw):
Redirect.__init__(self, *a, **kw)
self.count = 0
def render(self, request):
self.count += 1
return Redirect.render(self, request)
class CountingResource(resource.Resource):
"""
A resource that keeps track of the number of times it has been accessed.
"""
def __init__(self):
resource.Resource.__init__(self)
self.count = 0
def render(self, request):
self.count += 1
return b"Success"
class URLJoinTests(unittest.TestCase):
"""
Tests for L{client._urljoin}.
"""
def test_noFragments(self):
"""
L{client._urljoin} does not include a fragment identifier in the
resulting URL if neither the base nor the new path include a fragment
identifier.
"""
self.assertEqual(
client._urljoin(b'http://foo.com/bar', b'/quux'),
b'http://foo.com/quux')
self.assertEqual(
client._urljoin(b'http://foo.com/bar#', b'/quux'),
b'http://foo.com/quux')
self.assertEqual(
client._urljoin(b'http://foo.com/bar', b'/quux#'),
b'http://foo.com/quux')
def test_preserveFragments(self):
"""
L{client._urljoin} preserves the fragment identifier from either the
new path or the base URL respectively, as specified in the HTTP 1.1 bis
draft.
@see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#section-7.1.2}
"""
self.assertEqual(
client._urljoin(b'http://foo.com/bar#frag', b'/quux'),
b'http://foo.com/quux#frag')
self.assertEqual(
client._urljoin(b'http://foo.com/bar', b'/quux#frag2'),
b'http://foo.com/quux#frag2')
self.assertEqual(
client._urljoin(b'http://foo.com/bar#frag', b'/quux#frag2'),
b'http://foo.com/quux#frag2')
class HTTPPageGetterTests(unittest.TestCase):
"""
Tests for L{HTTPPagerGetter}, the HTTP client protocol implementation
used to implement L{getPage}.
"""
def test_earlyHeaders(self):
"""
When a connection is made, L{HTTPPagerGetter} sends the headers from
its factory's C{headers} dict. If I{Host} or I{Content-Length} is
present in this dict, the values are not sent, since they are sent with
special values before the C{headers} dict is processed. If
I{User-Agent} is present in the dict, it overrides the value of the
C{agent} attribute of the factory. If I{Cookie} is present in the
dict, its value is added to the values from the factory's C{cookies}
attribute.
"""
factory = client.HTTPClientFactory(
b'http://foo/bar',
agent=b"foobar",
cookies={b'baz': b'quux'},
postdata=b"some data",
headers={
b'Host': b'example.net',
b'User-Agent': b'fooble',
b'Cookie': b'blah blah',
b'Content-Length': b'12981',
b'Useful': b'value'})
transport = StringTransport()
protocol = client.HTTPPageGetter()
protocol.factory = factory
protocol.makeConnection(transport)
result = transport.value()
for expectedHeader in [
b"Host: example.net\r\n",
b"User-Agent: foobar\r\n",
b"Content-Length: 9\r\n",
b"Useful: value\r\n",
b"connection: close\r\n",
b"Cookie: blah blah; baz=quux\r\n"]:
self.assertIn(expectedHeader, result)
class WebClientTestCase(unittest.TestCase):
def _listen(self, site):
return reactor.listenTCP(0, site, interface="127.0.0.1")
def setUp(self):
self.agent = None # for twisted.web.client.Agent test
self.cleanupServerConnections = 0
r = resource.Resource()
r.putChild(b"file", Data(b"0123456789", b"text/html"))
r.putChild(b"redirect", Redirect(b"/file"))
self.infiniteRedirectResource = CountingRedirect(b"/infiniteRedirect")
r.putChild(b"infiniteRedirect", self.infiniteRedirectResource)
r.putChild(b"wait", ForeverTakingResource())
r.putChild(b"write-then-wait", ForeverTakingResource(write=True))
r.putChild(b"error", ErrorResource())
r.putChild(b"nolength", NoLengthResource())
r.putChild(b"host", HostHeaderResource())
r.putChild(b"payload", PayloadResource())
r.putChild(b"broken", BrokenDownloadResource())
r.putChild(b"cookiemirror", CookieMirrorResource())
r.putChild(b'delay1', DelayResource(1))
r.putChild(b'delay2', DelayResource(2))
self.afterFoundGetCounter = CountingResource()
r.putChild(b"afterFoundGetCounter", self.afterFoundGetCounter)
r.putChild(b"afterFoundGetRedirect", Redirect(b"/afterFoundGetCounter"))
miscasedHead = Data(b"miscased-head GET response content", b"major/minor")
miscasedHead.render_Head = lambda request: b"miscased-head content"
r.putChild(b"miscased-head", miscasedHead)
self.extendedRedirect = ExtendedRedirect(b'/extendedRedirect')
r.putChild(b"extendedRedirect", self.extendedRedirect)
self.site = server.Site(r, timeout=None)
self.wrapper = WrappingFactory(self.site)
self.port = self._listen(self.wrapper)
self.portno = self.port.getHost().port
def tearDown(self):
if self.agent:
# clean up connections for twisted.web.client.Agent test.
self.agent.closeCachedConnections()
self.agent = None
# If the test indicated it might leave some server-side connections
# around, clean them up.
connections = list(self.wrapper.protocols.keys())
# If there are fewer server-side connections than requested,
# that's okay. Some might have noticed that the client closed
# the connection and cleaned up after themselves.
for n in range(min(len(connections), self.cleanupServerConnections)):
proto = connections.pop()
msg("Closing %r" % (proto,))
proto.transport.loseConnection()
if connections:
msg("Some left-over connections; this test is probably buggy.")
return self.port.stopListening()
def getURL(self, path):
host = "http://127.0.0.1:%d/" % self.portno
return networkString(urljoin(host, nativeString(path)))
def testPayload(self):
s = b"0123456789" * 10
return client.getPage(self.getURL("payload"), postdata=s
).addCallback(self.assertEqual, s
)
def test_getPageBrokenDownload(self):
"""
If the connection is closed before the number of bytes indicated by
I{Content-Length} have been received, the L{Deferred} returned by
L{getPage} fails with L{PartialDownloadError}.
"""
d = client.getPage(self.getURL("broken"))
d = self.assertFailure(d, client.PartialDownloadError)
d.addCallback(lambda exc: self.assertEqual(exc.response, b"abc"))
return d
def test_downloadPageBrokenDownload(self):
"""
If the connection is closed before the number of bytes indicated by
I{Content-Length} have been received, the L{Deferred} returned by
L{downloadPage} fails with L{PartialDownloadError}.
"""
# test what happens when download gets disconnected in the middle
path = FilePath(self.mktemp())
d = client.downloadPage(self.getURL("broken"), path.path)
d = self.assertFailure(d, client.PartialDownloadError)
def checkResponse(response):
"""
The HTTP status code from the server is propagated through the
C{PartialDownloadError}.
"""
self.assertEqual(response.status, b"200")
self.assertEqual(response.message, b"OK")
return response
d.addCallback(checkResponse)
def cbFailed(ignored):
self.assertEqual(path.getContent(), b"abc")
d.addCallback(cbFailed)
return d
def test_downloadPageLogsFileCloseError(self):
"""
If there is an exception closing the file being written to after the
connection is prematurely closed, that exception is logged.
"""
class BrokenFile:
def write(self, bytes):
pass
def close(self):
raise IOError(ENOSPC, "No file left on device")
d = client.downloadPage(self.getURL("broken"), BrokenFile())
d = self.assertFailure(d, client.PartialDownloadError)
def cbFailed(ignored):
self.assertEqual(len(self.flushLoggedErrors(IOError)), 1)
d.addCallback(cbFailed)
return d
def testHostHeader(self):
# if we pass Host header explicitly, it should be used, otherwise
# it should extract from url
return defer.gatherResults([
client.getPage(self.getURL("host")).addCallback(
self.assertEqual, b"127.0.0.1:" + intToBytes(self.portno)),
client.getPage(self.getURL("host"),
headers={b"Host": b"www.example.com"}).addCallback(
self.assertEqual, b"www.example.com")])
def test_getPage(self):
"""
L{client.getPage} returns a L{Deferred} which is called back with
the body of the response if the default method B{GET} is used.
"""
d = client.getPage(self.getURL("file"))
d.addCallback(self.assertEqual, b"0123456789")
return d
def test_getPageHEAD(self):
"""
L{client.getPage} returns a L{Deferred} which is called back with
the empty string if the method is I{HEAD} and there is a successful
response code.
"""
d = client.getPage(self.getURL("file"), method=b"HEAD")
d.addCallback(self.assertEqual, b"")
return d
def test_getPageNotQuiteHEAD(self):
"""
If the request method is a different casing of I{HEAD} (ie, not all
capitalized) then it is not a I{HEAD} request and the response body
is returned.
"""
d = client.getPage(self.getURL("miscased-head"), method=b'Head')
d.addCallback(self.assertEqual, b"miscased-head content")
return d
def test_timeoutNotTriggering(self):
"""
When a non-zero timeout is passed to L{getPage} and the page is
retrieved before the timeout period elapses, the L{Deferred} is
called back with the contents of the page.
"""
d = client.getPage(self.getURL("host"), timeout=100)
d.addCallback(self.assertEqual,
networkString("127.0.0.1:%s" % (self.portno,)))
return d
def test_timeoutTriggering(self):
"""
When a non-zero timeout is passed to L{getPage} and that many
seconds elapse before the server responds to the request. the
L{Deferred} is errbacked with a L{error.TimeoutError}.
"""
# This will probably leave some connections around.
self.cleanupServerConnections = 1
return self.assertFailure(
client.getPage(self.getURL("wait"), timeout=0.000001),
defer.TimeoutError)
def testDownloadPage(self):
downloads = []
downloadData = [(b"file", self.mktemp(), b"0123456789"),
(b"nolength", self.mktemp(), b"nolength")]
for (url, name, data) in downloadData:
d = client.downloadPage(self.getURL(url), name)
d.addCallback(self._cbDownloadPageTest, data, name)
downloads.append(d)
return defer.gatherResults(downloads)
def _cbDownloadPageTest(self, ignored, data, name):
bytes = file(name, "rb").read()
self.assertEqual(bytes, data)
def testDownloadPageError1(self):
class errorfile:
def write(self, data):
raise IOError("badness happened during write")
def close(self):
pass
ef = errorfile()
return self.assertFailure(
client.downloadPage(self.getURL("file"), ef),
IOError)
def testDownloadPageError2(self):
class errorfile:
def write(self, data):
pass
def close(self):
raise IOError("badness happened during close")
ef = errorfile()
return self.assertFailure(
client.downloadPage(self.getURL("file"), ef),
IOError)
def testDownloadPageError3(self):
# make sure failures in open() are caught too. This is tricky.
# Might only work on posix.
tmpfile = open("unwritable", "wb")
tmpfile.close()
os.chmod("unwritable", 0) # make it unwritable (to us)
d = self.assertFailure(
client.downloadPage(self.getURL("file"), "unwritable"),
IOError)
d.addBoth(self._cleanupDownloadPageError3)
return d
def _cleanupDownloadPageError3(self, ignored):
os.chmod("unwritable", 0o700)
os.unlink("unwritable")
return ignored
def _downloadTest(self, method):
dl = []
for (url, code) in [("nosuchfile", b"404"), ("error", b"401"),
("error?showlength=1", b"401")]:
d = method(url)
d = self.assertFailure(d, error.Error)
d.addCallback(lambda exc, code=code: self.assertEqual(exc.args[0], code))
dl.append(d)
return defer.DeferredList(dl, fireOnOneErrback=True)
def testServerError(self):
return self._downloadTest(lambda url: client.getPage(self.getURL(url)))
def testDownloadServerError(self):
return self._downloadTest(lambda url: client.downloadPage(self.getURL(url), url.split('?')[0]))
def testFactoryInfo(self):
url = self.getURL('file')
uri = client._URI.fromBytes(url)
factory = client.HTTPClientFactory(url)
reactor.connectTCP(nativeString(uri.host), uri.port, factory)
return factory.deferred.addCallback(self._cbFactoryInfo, factory)
def _cbFactoryInfo(self, ignoredResult, factory):
self.assertEqual(factory.status, b'200')
self.assert_(factory.version.startswith(b'HTTP/'))
self.assertEqual(factory.message, b'OK')
self.assertEqual(factory.response_headers[b'content-length'][0], b'10')
def test_followRedirect(self):
"""
By default, L{client.getPage} follows redirects and returns the content
of the target resource.
"""
d = client.getPage(self.getURL("redirect"))
d.addCallback(self.assertEqual, b"0123456789")
return d
def test_noFollowRedirect(self):
"""
If C{followRedirect} is passed a false value, L{client.getPage} does not
follow redirects and returns a L{Deferred} which fails with
L{error.PageRedirect} when it encounters one.
"""
d = self.assertFailure(
client.getPage(self.getURL("redirect"), followRedirect=False),
error.PageRedirect)
d.addCallback(self._cbCheckLocation)
return d
def _cbCheckLocation(self, exc):
self.assertEqual(exc.location, b"/file")
def test_infiniteRedirection(self):
"""
When more than C{redirectLimit} HTTP redirects are encountered, the
page request fails with L{InfiniteRedirection}.
"""
def checkRedirectCount(*a):
self.assertEqual(f._redirectCount, 13)
self.assertEqual(self.infiniteRedirectResource.count, 13)
f = client._makeGetterFactory(
self.getURL('infiniteRedirect'),
client.HTTPClientFactory,
redirectLimit=13)
d = self.assertFailure(f.deferred, error.InfiniteRedirection)
d.addCallback(checkRedirectCount)
return d
def test_isolatedFollowRedirect(self):
"""
C{client.HTTPPagerGetter} instances each obey the C{followRedirect}
value passed to the L{client.getPage} call which created them.
"""
d1 = client.getPage(self.getURL('redirect'), followRedirect=True)
d2 = client.getPage(self.getURL('redirect'), followRedirect=False)
d = self.assertFailure(d2, error.PageRedirect
).addCallback(lambda dummy: d1)
return d
def test_afterFoundGet(self):
"""
Enabling unsafe redirection behaviour overwrites the method of
redirected C{POST} requests with C{GET}.
"""
url = self.getURL('extendedRedirect?code=302')
f = client.HTTPClientFactory(url, followRedirect=True, method=b"POST")
self.assertFalse(
f.afterFoundGet,
"By default, afterFoundGet must be disabled")
def gotPage(page):
self.assertEqual(
self.extendedRedirect.lastMethod,
b"GET",
"With afterFoundGet, the HTTP method must change to GET")
d = client.getPage(
url, followRedirect=True, afterFoundGet=True, method=b"POST")
d.addCallback(gotPage)
return d
def test_downloadAfterFoundGet(self):
"""
Passing C{True} for C{afterFoundGet} to L{client.downloadPage} invokes
the same kind of redirect handling as passing that argument to
L{client.getPage} invokes.
"""
url = self.getURL('extendedRedirect?code=302')
def gotPage(page):
self.assertEqual(
self.extendedRedirect.lastMethod,
b"GET",
"With afterFoundGet, the HTTP method must change to GET")
d = client.downloadPage(url, "downloadTemp",
followRedirect=True, afterFoundGet=True, method="POST")
d.addCallback(gotPage)
return d
def test_afterFoundGetMakesOneRequest(self):
"""
When C{afterFoundGet} is C{True}, L{client.getPage} only issues one
request to the server when following the redirect. This is a regression
test, see #4760.
"""
def checkRedirectCount(*a):
self.assertEqual(self.afterFoundGetCounter.count, 1)
url = self.getURL('afterFoundGetRedirect')
d = client.getPage(
url, followRedirect=True, afterFoundGet=True, method=b"POST")
d.addCallback(checkRedirectCount)
return d
def testPartial(self):
name = self.mktemp()
f = open(name, "wb")
f.write(b"abcd")
f.close()
partialDownload = [(True, b"abcd456789"),
(True, b"abcd456789"),
(False, b"0123456789")]
d = defer.succeed(None)
for (partial, expectedData) in partialDownload:
d.addCallback(self._cbRunPartial, name, partial)
d.addCallback(self._cbPartialTest, expectedData, name)
return d
testPartial.skip = "Cannot test until webserver can serve partial data properly"
def _cbRunPartial(self, ignored, name, partial):
return client.downloadPage(self.getURL("file"), name, supportPartial=partial)
def _cbPartialTest(self, ignored, expectedData, filename):
bytes = file(filename, "rb").read()
self.assertEqual(bytes, expectedData)
def test_downloadTimeout(self):
"""
If the timeout indicated by the C{timeout} parameter to
L{client.HTTPDownloader.__init__} elapses without the complete response
being received, the L{defer.Deferred} returned by
L{client.downloadPage} fires with a L{Failure} wrapping a
L{defer.TimeoutError}.
"""
self.cleanupServerConnections = 2
# Verify the behavior if no bytes are ever written.
first = client.downloadPage(
self.getURL("wait"),
self.mktemp(), timeout=0.01)
# Verify the behavior if some bytes are written but then the request
# never completes.
second = client.downloadPage(
self.getURL("write-then-wait"),
self.mktemp(), timeout=0.01)
return defer.gatherResults([
self.assertFailure(first, defer.TimeoutError),
self.assertFailure(second, defer.TimeoutError)])
def test_downloadHeaders(self):
"""
After L{client.HTTPDownloader.deferred} fires, the
L{client.HTTPDownloader} instance's C{status} and C{response_headers}
attributes are populated with the values from the response.
"""
def checkHeaders(factory):
self.assertEqual(factory.status, b'200')
self.assertEqual(factory.response_headers[b'content-type'][0], b'text/html')
self.assertEqual(factory.response_headers[b'content-length'][0], b'10')
os.unlink(factory.fileName)
factory = client._makeGetterFactory(
self.getURL('file'),
client.HTTPDownloader,
fileOrName=self.mktemp())
return factory.deferred.addCallback(lambda _: checkHeaders(factory))
def test_downloadCookies(self):
"""
The C{cookies} dict passed to the L{client.HTTPDownloader}
initializer is used to populate the I{Cookie} header included in the
request sent to the server.
"""
output = self.mktemp()
factory = client._makeGetterFactory(
self.getURL('cookiemirror'),
client.HTTPDownloader,
fileOrName=output,
cookies={b'foo': b'bar'})
def cbFinished(ignored):
self.assertEqual(
FilePath(output).getContent(),
"[('foo', 'bar')]")
factory.deferred.addCallback(cbFinished)
return factory.deferred
def test_downloadRedirectLimit(self):
"""
When more than C{redirectLimit} HTTP redirects are encountered, the
page request fails with L{InfiniteRedirection}.
"""
def checkRedirectCount(*a):
self.assertEqual(f._redirectCount, 7)
self.assertEqual(self.infiniteRedirectResource.count, 7)
f = client._makeGetterFactory(
self.getURL('infiniteRedirect'),
client.HTTPDownloader,
fileOrName=self.mktemp(),
redirectLimit=7)
d = self.assertFailure(f.deferred, error.InfiniteRedirection)
d.addCallback(checkRedirectCount)
return d
if _PY3:
for method in (
test_downloadPageBrokenDownload,
test_downloadPageLogsFileCloseError,
testDownloadPage,
testDownloadPageError1,
testDownloadPageError2,
testDownloadPageError3,
testDownloadServerError,
test_downloadAfterFoundGet,
testPartial,
test_downloadTimeout,
test_downloadHeaders,
test_downloadCookies,
test_downloadRedirectLimit):
method.skip = _PY3DownloadSkip
del method
def test_setURL(self):
"""
L{client.HTTPClientFactory.setURL} alters the scheme, host, port and
path for absolute URLs.
"""
url = b'http://example.com'
f = client.HTTPClientFactory(url)
self.assertEqual(
(url, b'http', b'example.com', 80, b'/'),
(f.url, f.scheme, f.host, f.port, f.path))
def test_setURLRemovesFragment(self):
"""
L{client.HTTPClientFactory.setURL} removes the fragment identifier from
the path component.
"""
f = client.HTTPClientFactory(b'http://example.com')
url = b'https://foo.com:8443/bar;123?a#frag'
f.setURL(url)
self.assertEqual(
(url, b'https', b'foo.com', 8443, b'/bar;123?a'),
(f.url, f.scheme, f.host, f.port, f.path))
def test_setURLRelativePath(self):
"""
L{client.HTTPClientFactory.setURL} alters the path in a relative URL.
"""
f = client.HTTPClientFactory(b'http://example.com')
url = b'/hello'
f.setURL(url)
self.assertEqual(
(url, b'http', b'example.com', 80, b'/hello'),
(f.url, f.scheme, f.host, f.port, f.path))
def test_setURLRelativeScheme(self):
"""
L{client.HTTPClientFactory.setURL} alters the host and port in
a scheme-relative URL.
"""
f = client.HTTPClientFactory(b'http://example.com')
url = b'//foo.com:81/bar'
f.setURL(url)
self.assertEqual(
(url, b'http', b'foo.com', 80, b'/bar'),
(f.url, f.scheme, f.host, f.port, f.path))
test_setURLRelativeScheme.todo = \
'HTTPClientFactory.setURL does not support scheme-relative URLs.'
class WebClientSSLTestCase(WebClientTestCase):
def _listen(self, site):
return reactor.listenSSL(
0, site,
contextFactory=ssl.DefaultOpenSSLContextFactory(
serverPEMPath, serverPEMPath),
interface="127.0.0.1")
def getURL(self, path):
return networkString("https://127.0.0.1:%d/%s" % (self.portno, path))
def testFactoryInfo(self):
url = self.getURL('file')
uri = client._URI.fromBytes(url)
factory = client.HTTPClientFactory(url)
reactor.connectSSL(nativeString(uri.host), uri.port, factory,
ssl.ClientContextFactory())
# The base class defines _cbFactoryInfo correctly for this
return factory.deferred.addCallback(self._cbFactoryInfo, factory)
class WebClientRedirectBetweenSSLandPlainText(unittest.TestCase):
def getHTTPS(self, path):
return networkString("https://127.0.0.1:%d/%s" % (self.tlsPortno, path))
def getHTTP(self, path):
return networkString("http://127.0.0.1:%d/%s" % (self.plainPortno, path))
def setUp(self):
plainRoot = Data(b'not me', b'text/plain')
tlsRoot = Data(b'me neither', b'text/plain')
plainSite = server.Site(plainRoot, timeout=None)
tlsSite = server.Site(tlsRoot, timeout=None)
self.tlsPort = reactor.listenSSL(
0, tlsSite,
contextFactory=ssl.DefaultOpenSSLContextFactory(
serverPEMPath, serverPEMPath),
interface="127.0.0.1")
self.plainPort = reactor.listenTCP(0, plainSite, interface="127.0.0.1")
self.plainPortno = self.plainPort.getHost().port
self.tlsPortno = self.tlsPort.getHost().port
plainRoot.putChild(b'one', Redirect(self.getHTTPS('two')))
tlsRoot.putChild(b'two', Redirect(self.getHTTP('three')))
plainRoot.putChild(b'three', Redirect(self.getHTTPS('four')))
tlsRoot.putChild(b'four', Data(b'FOUND IT!', b'text/plain'))
def tearDown(self):
ds = list(
map(defer.maybeDeferred,
[self.plainPort.stopListening, self.tlsPort.stopListening]))
return defer.gatherResults(ds)
def testHoppingAround(self):
return client.getPage(self.getHTTP("one")
).addCallback(self.assertEqual, b"FOUND IT!"
)
class CookieTestCase(unittest.TestCase):
def _listen(self, site):
return reactor.listenTCP(0, site, interface="127.0.0.1")
def setUp(self):
root = Data(b'El toro!', b'text/plain')
root.putChild(b"cookiemirror", CookieMirrorResource())
root.putChild(b"rawcookiemirror", RawCookieMirrorResource())
site = server.Site(root, timeout=None)
self.port = self._listen(site)
self.portno = self.port.getHost().port
def tearDown(self):
return self.port.stopListening()
def getHTTP(self, path):
return networkString("http://127.0.0.1:%d/%s" % (self.portno, path))
def testNoCookies(self):
return client.getPage(self.getHTTP("cookiemirror")
).addCallback(self.assertEqual, b"[]"
)
def testSomeCookies(self):
cookies = {b'foo': b'bar', b'baz': b'quux'}
return client.getPage(self.getHTTP("cookiemirror"), cookies=cookies
).addCallback(self.assertEqual, b"[('baz', 'quux'), ('foo', 'bar')]"
)
def testRawNoCookies(self):
return client.getPage(self.getHTTP("rawcookiemirror")
).addCallback(self.assertEqual, b"None"
)
def testRawSomeCookies(self):
cookies = {b'foo': b'bar', b'baz': b'quux'}
return client.getPage(self.getHTTP("rawcookiemirror"), cookies=cookies
).addCallback(self.assertIn,
(b"'foo=bar; baz=quux'", b"'baz=quux; foo=bar'")
)
def testCookieHeaderParsing(self):
factory = client.HTTPClientFactory(b'http://foo.example.com/')
proto = factory.buildProtocol('127.42.42.42')
transport = StringTransport()
proto.makeConnection(transport)
for line in [
b'200 Ok',
b'Squash: yes',
b'Hands: stolen',
b'Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT',
b'Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/',
b'Set-Cookie: SHIPPING=FEDEX; path=/foo',
b'',
b'body',
b'more body',
]:
proto.dataReceived(line + b'\r\n')
self.assertEqual(transport.value(),
b'GET / HTTP/1.0\r\n'
b'Host: foo.example.com\r\n'
b'User-Agent: Twisted PageGetter\r\n'
b'\r\n')
self.assertEqual(factory.cookies,
{
b'CUSTOMER': b'WILE_E_COYOTE',
b'PART_NUMBER': b'ROCKET_LAUNCHER_0001',
b'SHIPPING': b'FEDEX',
})
class TestHostHeader(unittest.TestCase):
"""
Test that L{HTTPClientFactory} includes the port in the host header
if needed.
"""
def _getHost(self, bytes):
"""
Retrieve the value of the I{Host} header from the serialized
request given by C{bytes}.
"""
for line in bytes.split(b'\r\n'):
try:
name, value = line.split(b':', 1)
if name.strip().lower() == b'host':
return value.strip()
except ValueError:
pass
def test_HTTPDefaultPort(self):
"""
No port should be included in the host header when connecting to the
default HTTP port.
"""
factory = client.HTTPClientFactory(b'http://foo.example.com/')
proto = factory.buildProtocol(b'127.42.42.42')
proto.makeConnection(StringTransport())
self.assertEqual(self._getHost(proto.transport.value()),
b'foo.example.com')
def test_HTTPPort80(self):
"""
No port should be included in the host header when connecting to the
default HTTP port even if it is in the URL.
"""
factory = client.HTTPClientFactory(b'http://foo.example.com:80/')
proto = factory.buildProtocol('127.42.42.42')
proto.makeConnection(StringTransport())
self.assertEqual(self._getHost(proto.transport.value()),
b'foo.example.com')
def test_HTTPNotPort80(self):
"""
The port should be included in the host header when connecting to the
a non default HTTP port.
"""
factory = client.HTTPClientFactory(b'http://foo.example.com:8080/')
proto = factory.buildProtocol('127.42.42.42')
proto.makeConnection(StringTransport())
self.assertEqual(self._getHost(proto.transport.value()),
b'foo.example.com:8080')
def test_HTTPSDefaultPort(self):
"""
No port should be included in the host header when connecting to the
default HTTPS port.
"""
factory = client.HTTPClientFactory(b'https://foo.example.com/')
proto = factory.buildProtocol('127.42.42.42')
proto.makeConnection(StringTransport())
self.assertEqual(self._getHost(proto.transport.value()),
b'foo.example.com')
def test_HTTPSPort443(self):
"""
No port should be included in the host header when connecting to the
default HTTPS port even if it is in the URL.
"""
factory = client.HTTPClientFactory(b'https://foo.example.com:443/')
proto = factory.buildProtocol('127.42.42.42')
proto.makeConnection(StringTransport())
self.assertEqual(self._getHost(proto.transport.value()),
b'foo.example.com')
def test_HTTPSNotPort443(self):
"""
The port should be included in the host header when connecting to the
a non default HTTPS port.
"""
factory = client.HTTPClientFactory(b'http://foo.example.com:8080/')
proto = factory.buildProtocol('127.42.42.42')
proto.makeConnection(StringTransport())
self.assertEqual(self._getHost(proto.transport.value()),
b'foo.example.com:8080')
if ssl is None or not hasattr(ssl, 'DefaultOpenSSLContextFactory'):
for case in [WebClientSSLTestCase, WebClientRedirectBetweenSSLandPlainText]:
case.skip = "OpenSSL not present"
if not interfaces.IReactorSSL(reactor, None):
for case in [WebClientSSLTestCase, WebClientRedirectBetweenSSLandPlainText]:
case.skip = "Reactor doesn't support SSL"
class URITests(unittest.TestCase):
"""
Tests for L{twisted.web.client._URI}.
"""
def assertURIEquals(self, uri, scheme, netloc, host, port, path,
params=b'', query=b'', fragment=b''):
"""
Assert that all of a L{client._URI}'s components match the expected
values.
@param uri: U{client._URI} instance whose attributes will be checked
for equality.
@type scheme: L{bytes}
@param scheme: URI scheme specifier.
@type netloc: L{bytes}
@param netloc: Network location component.
@type host: L{bytes}
@param host: Host name.
@type port: L{int}
@param port: Port number.
@type path: L{bytes}
@param path: Hierarchical path.
@type params: L{bytes}
@param params: Parameters for last path segment, defaults to C{b''}.
@type query: L{bytes}
@param query: Query string, defaults to C{b''}.
@type fragment: L{bytes}
@param fragment: Fragment identifier, defaults to C{b''}.
"""
self.assertEqual(
(scheme, netloc, host, port, path, params, query, fragment),
(uri.scheme, uri.netloc, uri.host, uri.port, uri.path, uri.params,
uri.query, uri.fragment))
def test_parseDefaultPort(self):
"""
L{client._URI.fromBytes} by default assumes port 80 for the I{http}
scheme and 443 for the I{https} scheme.
"""
uri = client._URI.fromBytes(b'http://example.com')
self.assertEqual(80, uri.port)
# Weird (but commonly accepted) structure uses default port.
uri = client._URI.fromBytes(b'http://example.com:')
self.assertEqual(80, uri.port)
uri = client._URI.fromBytes(b'https://example.com')
self.assertEqual(443, uri.port)
def test_parseCustomDefaultPort(self):
"""
L{client._URI.fromBytes} accepts a C{defaultPort} parameter that
overrides the normal default port logic.
"""
uri = client._URI.fromBytes(b'http://example.com', defaultPort=5144)
self.assertEqual(5144, uri.port)
uri = client._URI.fromBytes(b'https://example.com', defaultPort=5144)
self.assertEqual(5144, uri.port)
def test_netlocHostPort(self):
"""
Parsing a I{URI} splits the network location component into I{host} and
I{port}.
"""
uri = client._URI.fromBytes(b'http://example.com:5144')
self.assertEqual(5144, uri.port)
self.assertEqual(b'example.com', uri.host)
self.assertEqual(b'example.com:5144', uri.netloc)
# Spaces in the hostname are trimmed, the default path is /.
uri = client._URI.fromBytes(b'http://example.com ')
self.assertEqual(b'example.com', uri.netloc)
def test_path(self):
"""
Parse the path from a I{URI}.
"""
uri = b'http://example.com/foo/bar'
parsed = client._URI.fromBytes(uri)
self.assertURIEquals(
parsed,
scheme=b'http',
netloc=b'example.com',
host=b'example.com',
port=80,
path=b'/foo/bar')
self.assertEqual(uri, parsed.toBytes())
def test_noPath(self):
"""
The path of a I{URI} that has no path is the empty string.
"""
uri = b'http://example.com'
parsed = client._URI.fromBytes(uri)
self.assertURIEquals(
parsed,
scheme=b'http',
netloc=b'example.com',
host=b'example.com',
port=80,
path=b'')
self.assertEqual(uri, parsed.toBytes())
def test_emptyPath(self):
"""
The path of a I{URI} with an empty path is C{b'/'}.
"""
uri = b'http://example.com/'
self.assertURIEquals(
client._URI.fromBytes(uri),
scheme=b'http',
netloc=b'example.com',
host=b'example.com',
port=80,
path=b'/')
def test_param(self):
"""
Parse I{URI} parameters from a I{URI}.
"""
uri = b'http://example.com/foo/bar;param'
parsed = client._URI.fromBytes(uri)
self.assertURIEquals(
parsed,
scheme=b'http',
netloc=b'example.com',
host=b'example.com',
port=80,
path=b'/foo/bar',
params=b'param')
self.assertEqual(uri, parsed.toBytes())
def test_query(self):
"""
Parse the query string from a I{URI}.
"""
uri = b'http://example.com/foo/bar;param?a=1&b=2'
parsed = client._URI.fromBytes(uri)
self.assertURIEquals(
parsed,
scheme=b'http',
netloc=b'example.com',
host=b'example.com',
port=80,
path=b'/foo/bar',
params=b'param',
query=b'a=1&b=2')
self.assertEqual(uri, parsed.toBytes())
def test_fragment(self):
"""
Parse the fragment identifier from a I{URI}.
"""
uri = b'http://example.com/foo/bar;param?a=1&b=2#frag'
parsed = client._URI.fromBytes(uri)
self.assertURIEquals(
parsed,
scheme=b'http',
netloc=b'example.com',
host=b'example.com',
port=80,
path=b'/foo/bar',
params=b'param',
query=b'a=1&b=2',
fragment=b'frag')
self.assertEqual(uri, parsed.toBytes())
def test_originForm(self):
"""
L{client._URI.originForm} produces an absolute I{URI} path including
the I{URI} path.
"""
uri = client._URI.fromBytes(b'http://example.com/foo')
self.assertEqual(b'/foo', uri.originForm)
def test_originFormComplex(self):
"""
L{client._URI.originForm} produces an absolute I{URI} path including
the I{URI} path, parameters and query string but excludes the fragment
identifier.
"""
uri = client._URI.fromBytes(b'http://example.com/foo;param?a=1#frag')
self.assertEqual(b'/foo;param?a=1', uri.originForm)
def test_originFormNoPath(self):
"""
L{client._URI.originForm} produces a path of C{b'/'} when the I{URI}
specifies no path.
"""
uri = client._URI.fromBytes(b'http://example.com')
self.assertEqual(b'/', uri.originForm)
def test_originFormEmptyPath(self):
"""
L{client._URI.originForm} produces a path of C{b'/'} when the I{URI}
specifies an empty path.
"""
uri = client._URI.fromBytes(b'http://example.com/')
self.assertEqual(b'/', uri.originForm)
def test_externalUnicodeInterference(self):
"""
L{client._URI.fromBytes} parses the scheme, host, and path elements
into L{bytes}, even when passed an URL which has previously been passed
to L{urlparse} as a L{unicode} string.
"""
goodInput = b'http://example.com/path'
badInput = goodInput.decode('ascii')
urlparse(badInput)
uri = client._URI.fromBytes(goodInput)
self.assertIsInstance(uri.scheme, bytes)
self.assertIsInstance(uri.host, bytes)
self.assertIsInstance(uri.path, bytes)
|