[Jython-checkins] jython: from:
frank.wierzbicki
jython-checkins at python.org
Tue Jan 1 02:27:19 CET 2013
http://hg.python.org/jython/rev/23145318aabf
changeset: 6924:23145318aabf
user: Frank Wierzbicki <fwierzbicki at gmail.com>
date: Mon Dec 31 17:27:01 2012 -0800
summary:
from:
http://hg.python.org/cpython/Lib/test/test_httplib.py@22db03646d9b
http://hg.python.org/cpython/Lib/test/test_httpservers.py@22db03646d9b
files:
Lib/test/test_httplib.py | 471 ++++++++++++++++++++
Lib/test/test_httpservers.py | 535 +++++++++++++++++++++++
2 files changed, 1006 insertions(+), 0 deletions(-)
diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py
new file mode 100644
--- /dev/null
+++ b/Lib/test/test_httplib.py
@@ -0,0 +1,471 @@
+import httplib
+import array
+import httplib
+import StringIO
+import socket
+import errno
+
+import unittest
+TestCase = unittest.TestCase
+
+from test import test_support
+
+HOST = test_support.HOST
+
+class FakeSocket:
+ def __init__(self, text, fileclass=StringIO.StringIO):
+ self.text = text
+ self.fileclass = fileclass
+ self.data = ''
+
+ def sendall(self, data):
+ self.data += ''.join(data)
+
+ def makefile(self, mode, bufsize=None):
+ if mode != 'r' and mode != 'rb':
+ raise httplib.UnimplementedFileMode()
+ return self.fileclass(self.text)
+
+class EPipeSocket(FakeSocket):
+
+ def __init__(self, text, pipe_trigger):
+ # When sendall() is called with pipe_trigger, raise EPIPE.
+ FakeSocket.__init__(self, text)
+ self.pipe_trigger = pipe_trigger
+
+ def sendall(self, data):
+ if self.pipe_trigger in data:
+ raise socket.error(errno.EPIPE, "gotcha")
+ self.data += data
+
+ def close(self):
+ pass
+
+class NoEOFStringIO(StringIO.StringIO):
+ """Like StringIO, but raises AssertionError on EOF.
+
+ This is used below to test that httplib doesn't try to read
+ more from the underlying file than it should.
+ """
+ def read(self, n=-1):
+ data = StringIO.StringIO.read(self, n)
+ if data == '':
+ raise AssertionError('caller tried to read past EOF')
+ return data
+
+ def readline(self, length=None):
+ data = StringIO.StringIO.readline(self, length)
+ if data == '':
+ raise AssertionError('caller tried to read past EOF')
+ return data
+
+
+class HeaderTests(TestCase):
+ def test_auto_headers(self):
+ # Some headers are added automatically, but should not be added by
+ # .request() if they are explicitly set.
+
+ class HeaderCountingBuffer(list):
+ def __init__(self):
+ self.count = {}
+ def append(self, item):
+ kv = item.split(':')
+ if len(kv) > 1:
+ # item is a 'Key: Value' header string
+ lcKey = kv[0].lower()
+ self.count.setdefault(lcKey, 0)
+ self.count[lcKey] += 1
+ list.append(self, item)
+
+ for explicit_header in True, False:
+ for header in 'Content-length', 'Host', 'Accept-encoding':
+ conn = httplib.HTTPConnection('example.com')
+ conn.sock = FakeSocket('blahblahblah')
+ conn._buffer = HeaderCountingBuffer()
+
+ body = 'spamspamspam'
+ headers = {}
+ if explicit_header:
+ headers[header] = str(len(body))
+ conn.request('POST', '/', body, headers)
+ self.assertEqual(conn._buffer.count[header.lower()], 1)
+
+ def test_putheader(self):
+ conn = httplib.HTTPConnection('example.com')
+ conn.sock = FakeSocket(None)
+ conn.putrequest('GET','/')
+ conn.putheader('Content-length',42)
+ self.assertTrue('Content-length: 42' in conn._buffer)
+
+ def test_ipv6host_header(self):
+ # Default host header on IPv6 transaction should wrapped by [] if
+ # its actual IPv6 address
+ expected = 'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
+ 'Accept-Encoding: identity\r\n\r\n'
+ conn = httplib.HTTPConnection('[2001::]:81')
+ sock = FakeSocket('')
+ conn.sock = sock
+ conn.request('GET', '/foo')
+ self.assertTrue(sock.data.startswith(expected))
+
+ expected = 'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
+ 'Accept-Encoding: identity\r\n\r\n'
+ conn = httplib.HTTPConnection('[2001:102A::]')
+ sock = FakeSocket('')
+ conn.sock = sock
+ conn.request('GET', '/foo')
+ self.assertTrue(sock.data.startswith(expected))
+
+
+class BasicTest(TestCase):
+ def test_status_lines(self):
+ # Test HTTP status lines
+
+ body = "HTTP/1.1 200 Ok\r\n\r\nText"
+ sock = FakeSocket(body)
+ resp = httplib.HTTPResponse(sock)
+ resp.begin()
+ self.assertEqual(resp.read(), 'Text')
+ self.assertTrue(resp.isclosed())
+
+ body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
+ sock = FakeSocket(body)
+ resp = httplib.HTTPResponse(sock)
+ self.assertRaises(httplib.BadStatusLine, resp.begin)
+
+ def test_bad_status_repr(self):
+ exc = httplib.BadStatusLine('')
+ self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
+
+ def test_partial_reads(self):
+ # if we have a lenght, the system knows when to close itself
+ # same behaviour than when we read the whole thing with read()
+ body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
+ sock = FakeSocket(body)
+ resp = httplib.HTTPResponse(sock)
+ resp.begin()
+ self.assertEqual(resp.read(2), 'Te')
+ self.assertFalse(resp.isclosed())
+ self.assertEqual(resp.read(2), 'xt')
+ self.assertTrue(resp.isclosed())
+
+ def test_host_port(self):
+ # Check invalid host_port
+
+ # Note that httplib does not accept user:password@ in the host-port.
+ for hp in ("www.python.org:abc", "user:password at www.python.org"):
+ self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp)
+
+ for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b",
+ 8000),
+ ("www.python.org:80", "www.python.org", 80),
+ ("www.python.org", "www.python.org", 80),
+ ("www.python.org:", "www.python.org", 80),
+ ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80)):
+ http = httplib.HTTP(hp)
+ c = http._conn
+ if h != c.host:
+ self.fail("Host incorrectly parsed: %s != %s" % (h, c.host))
+ if p != c.port:
+ self.fail("Port incorrectly parsed: %s != %s" % (p, c.host))
+
+ def test_response_headers(self):
+ # test response with multiple message headers with the same field name.
+ text = ('HTTP/1.1 200 OK\r\n'
+ 'Set-Cookie: Customer="WILE_E_COYOTE";'
+ ' Version="1"; Path="/acme"\r\n'
+ 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
+ ' Path="/acme"\r\n'
+ '\r\n'
+ 'No body\r\n')
+ hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
+ ', '
+ 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
+ s = FakeSocket(text)
+ r = httplib.HTTPResponse(s)
+ r.begin()
+ cookies = r.getheader("Set-Cookie")
+ if cookies != hdr:
+ self.fail("multiple headers not combined properly")
+
+ def test_read_head(self):
+ # Test that the library doesn't attempt to read any data
+ # from a HEAD request. (Tickles SF bug #622042.)
+ sock = FakeSocket(
+ 'HTTP/1.1 200 OK\r\n'
+ 'Content-Length: 14432\r\n'
+ '\r\n',
+ NoEOFStringIO)
+ resp = httplib.HTTPResponse(sock, method="HEAD")
+ resp.begin()
+ if resp.read() != "":
+ self.fail("Did not expect response from HEAD request")
+
+ def test_send_file(self):
+ expected = 'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
+ 'Accept-Encoding: identity\r\nContent-Length:'
+
+ body = open(__file__, 'rb')
+ conn = httplib.HTTPConnection('example.com')
+ sock = FakeSocket(body)
+ conn.sock = sock
+ conn.request('GET', '/foo', body)
+ self.assertTrue(sock.data.startswith(expected))
+
+ def test_send(self):
+ expected = 'this is a test this is only a test'
+ conn = httplib.HTTPConnection('example.com')
+ sock = FakeSocket(None)
+ conn.sock = sock
+ conn.send(expected)
+ self.assertEqual(expected, sock.data)
+ sock.data = ''
+ conn.send(array.array('c', expected))
+ self.assertEqual(expected, sock.data)
+ sock.data = ''
+ conn.send(StringIO.StringIO(expected))
+ self.assertEqual(expected, sock.data)
+
+ def test_chunked(self):
+ chunked_start = (
+ 'HTTP/1.1 200 OK\r\n'
+ 'Transfer-Encoding: chunked\r\n\r\n'
+ 'a\r\n'
+ 'hello worl\r\n'
+ '1\r\n'
+ 'd\r\n'
+ )
+ sock = FakeSocket(chunked_start + '0\r\n')
+ resp = httplib.HTTPResponse(sock, method="GET")
+ resp.begin()
+ self.assertEqual(resp.read(), 'hello world')
+ resp.close()
+
+ for x in ('', 'foo\r\n'):
+ sock = FakeSocket(chunked_start + x)
+ resp = httplib.HTTPResponse(sock, method="GET")
+ resp.begin()
+ try:
+ resp.read()
+ except httplib.IncompleteRead, i:
+ self.assertEqual(i.partial, 'hello world')
+ self.assertEqual(repr(i),'IncompleteRead(11 bytes read)')
+ self.assertEqual(str(i),'IncompleteRead(11 bytes read)')
+ else:
+ self.fail('IncompleteRead expected')
+ finally:
+ resp.close()
+
+ def test_chunked_head(self):
+ chunked_start = (
+ 'HTTP/1.1 200 OK\r\n'
+ 'Transfer-Encoding: chunked\r\n\r\n'
+ 'a\r\n'
+ 'hello world\r\n'
+ '1\r\n'
+ 'd\r\n'
+ )
+ sock = FakeSocket(chunked_start + '0\r\n')
+ resp = httplib.HTTPResponse(sock, method="HEAD")
+ resp.begin()
+ self.assertEqual(resp.read(), '')
+ self.assertEqual(resp.status, 200)
+ self.assertEqual(resp.reason, 'OK')
+ self.assertTrue(resp.isclosed())
+
+ def test_negative_content_length(self):
+ sock = FakeSocket('HTTP/1.1 200 OK\r\n'
+ 'Content-Length: -1\r\n\r\nHello\r\n')
+ resp = httplib.HTTPResponse(sock, method="GET")
+ resp.begin()
+ self.assertEqual(resp.read(), 'Hello\r\n')
+ resp.close()
+
+ def test_incomplete_read(self):
+ sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
+ resp = httplib.HTTPResponse(sock, method="GET")
+ resp.begin()
+ try:
+ resp.read()
+ except httplib.IncompleteRead as i:
+ self.assertEqual(i.partial, 'Hello\r\n')
+ self.assertEqual(repr(i),
+ "IncompleteRead(7 bytes read, 3 more expected)")
+ self.assertEqual(str(i),
+ "IncompleteRead(7 bytes read, 3 more expected)")
+ else:
+ self.fail('IncompleteRead expected')
+ finally:
+ resp.close()
+
+ def test_epipe(self):
+ sock = EPipeSocket(
+ "HTTP/1.0 401 Authorization Required\r\n"
+ "Content-type: text/html\r\n"
+ "WWW-Authenticate: Basic realm=\"example\"\r\n",
+ b"Content-Length")
+ conn = httplib.HTTPConnection("example.com")
+ conn.sock = sock
+ self.assertRaises(socket.error,
+ lambda: conn.request("PUT", "/url", "body"))
+ resp = conn.getresponse()
+ self.assertEqual(401, resp.status)
+ self.assertEqual("Basic realm=\"example\"",
+ resp.getheader("www-authenticate"))
+
+ def test_filenoattr(self):
+ # Just test the fileno attribute in the HTTPResponse Object.
+ body = "HTTP/1.1 200 Ok\r\n\r\nText"
+ sock = FakeSocket(body)
+ resp = httplib.HTTPResponse(sock)
+ self.assertTrue(hasattr(resp,'fileno'),
+ 'HTTPResponse should expose a fileno attribute')
+
+ # Test lines overflowing the max line size (_MAXLINE in http.client)
+
+ def test_overflowing_status_line(self):
+ self.skipTest("disabled for HTTP 0.9 support")
+ body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
+ resp = httplib.HTTPResponse(FakeSocket(body))
+ self.assertRaises((httplib.LineTooLong, httplib.BadStatusLine), resp.begin)
+
+ def test_overflowing_header_line(self):
+ body = (
+ 'HTTP/1.1 200 OK\r\n'
+ 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
+ )
+ resp = httplib.HTTPResponse(FakeSocket(body))
+ self.assertRaises(httplib.LineTooLong, resp.begin)
+
+ def test_overflowing_chunked_line(self):
+ body = (
+ 'HTTP/1.1 200 OK\r\n'
+ 'Transfer-Encoding: chunked\r\n\r\n'
+ + '0' * 65536 + 'a\r\n'
+ 'hello world\r\n'
+ '0\r\n'
+ )
+ resp = httplib.HTTPResponse(FakeSocket(body))
+ resp.begin()
+ self.assertRaises(httplib.LineTooLong, resp.read)
+
+
+class OfflineTest(TestCase):
+ def test_responses(self):
+ self.assertEqual(httplib.responses[httplib.NOT_FOUND], "Not Found")
+
+
+class SourceAddressTest(TestCase):
+ def setUp(self):
+ self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.port = test_support.bind_port(self.serv)
+ self.source_port = test_support.find_unused_port()
+ self.serv.listen(5)
+ self.conn = None
+
+ def tearDown(self):
+ if self.conn:
+ self.conn.close()
+ self.conn = None
+ self.serv.close()
+ self.serv = None
+
+ def testHTTPConnectionSourceAddress(self):
+ self.conn = httplib.HTTPConnection(HOST, self.port,
+ source_address=('', self.source_port))
+ self.conn.connect()
+ self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
+
+ @unittest.skipIf(not hasattr(httplib, 'HTTPSConnection'),
+ 'httplib.HTTPSConnection not defined')
+ def testHTTPSConnectionSourceAddress(self):
+ self.conn = httplib.HTTPSConnection(HOST, self.port,
+ source_address=('', self.source_port))
+ # We don't test anything here other the constructor not barfing as
+ # this code doesn't deal with setting up an active running SSL server
+ # for an ssl_wrapped connect() to actually return from.
+
+
+class TimeoutTest(TestCase):
+ PORT = None
+
+ def setUp(self):
+ self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ TimeoutTest.PORT = test_support.bind_port(self.serv)
+ self.serv.listen(5)
+
+ def tearDown(self):
+ self.serv.close()
+ self.serv = None
+
+ def testTimeoutAttribute(self):
+ '''This will prove that the timeout gets through
+ HTTPConnection and into the socket.
+ '''
+ # default -- use global socket timeout
+ self.assertTrue(socket.getdefaulttimeout() is None)
+ socket.setdefaulttimeout(30)
+ try:
+ httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT)
+ httpConn.connect()
+ finally:
+ socket.setdefaulttimeout(None)
+ self.assertEqual(httpConn.sock.gettimeout(), 30)
+ httpConn.close()
+
+ # no timeout -- do not use global socket default
+ self.assertTrue(socket.getdefaulttimeout() is None)
+ socket.setdefaulttimeout(30)
+ try:
+ httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT,
+ timeout=None)
+ httpConn.connect()
+ finally:
+ socket.setdefaulttimeout(None)
+ self.assertEqual(httpConn.sock.gettimeout(), None)
+ httpConn.close()
+
+ # a value
+ httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
+ httpConn.connect()
+ self.assertEqual(httpConn.sock.gettimeout(), 30)
+ httpConn.close()
+
+
+class HTTPSTimeoutTest(TestCase):
+# XXX Here should be tests for HTTPS, there isn't any right now!
+
+ def test_attributes(self):
+ # simple test to check it's storing it
+ if hasattr(httplib, 'HTTPSConnection'):
+ h = httplib.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
+ self.assertEqual(h.timeout, 30)
+
+ @unittest.skipIf(not hasattr(httplib, 'HTTPS'), 'httplib.HTTPS not available')
+ def test_host_port(self):
+ # Check invalid host_port
+
+ # Note that httplib does not accept user:password@ in the host-port.
+ for hp in ("www.python.org:abc", "user:password at www.python.org"):
+ self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp)
+
+ for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b",
+ 8000),
+ ("pypi.python.org:443", "pypi.python.org", 443),
+ ("pypi.python.org", "pypi.python.org", 443),
+ ("pypi.python.org:", "pypi.python.org", 443),
+ ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443)):
+ http = httplib.HTTPS(hp)
+ c = http._conn
+ if h != c.host:
+ self.fail("Host incorrectly parsed: %s != %s" % (h, c.host))
+ if p != c.port:
+ self.fail("Port incorrectly parsed: %s != %s" % (p, c.host))
+
+
+def test_main(verbose=None):
+ test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
+ HTTPSTimeoutTest, SourceAddressTest)
+
+if __name__ == '__main__':
+ test_main()
diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py
new file mode 100644
--- /dev/null
+++ b/Lib/test/test_httpservers.py
@@ -0,0 +1,535 @@
+"""Unittests for the various HTTPServer modules.
+
+Written by Cody A.W. Somerville <cody-somerville at ubuntu.com>,
+Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest.
+"""
+
+from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
+from SimpleHTTPServer import SimpleHTTPRequestHandler
+from CGIHTTPServer import CGIHTTPRequestHandler
+import CGIHTTPServer
+
+import os
+import sys
+import re
+import base64
+import shutil
+import urllib
+import httplib
+import tempfile
+
+import unittest
+
+from StringIO import StringIO
+
+from test import test_support
+threading = test_support.import_module('threading')
+
+
+class NoLogRequestHandler:
+ def log_message(self, *args):
+ # don't write log messages to stderr
+ pass
+
+class SocketlessRequestHandler(SimpleHTTPRequestHandler):
+ def __init__(self):
+ self.get_called = False
+ self.protocol_version = "HTTP/1.1"
+
+ def do_GET(self):
+ self.get_called = True
+ self.send_response(200)
+ self.send_header('Content-Type', 'text/html')
+ self.end_headers()
+ self.wfile.write(b'<html><body>Data</body></html>\r\n')
+
+ def log_message(self, format, *args):
+ pass
+
+
+class TestServerThread(threading.Thread):
+ def __init__(self, test_object, request_handler):
+ threading.Thread.__init__(self)
+ self.request_handler = request_handler
+ self.test_object = test_object
+
+ def run(self):
+ self.server = HTTPServer(('', 0), self.request_handler)
+ self.test_object.PORT = self.server.socket.getsockname()[1]
+ self.test_object.server_started.set()
+ self.test_object = None
+ try:
+ self.server.serve_forever(0.05)
+ finally:
+ self.server.server_close()
+
+ def stop(self):
+ self.server.shutdown()
+
+
+class BaseTestCase(unittest.TestCase):
+ def setUp(self):
+ self._threads = test_support.threading_setup()
+ os.environ = test_support.EnvironmentVarGuard()
+ self.server_started = threading.Event()
+ self.thread = TestServerThread(self, self.request_handler)
+ self.thread.start()
+ self.server_started.wait()
+
+ def tearDown(self):
+ self.thread.stop()
+ os.environ.__exit__()
+ test_support.threading_cleanup(*self._threads)
+
+ def request(self, uri, method='GET', body=None, headers={}):
+ self.connection = httplib.HTTPConnection('localhost', self.PORT)
+ self.connection.request(method, uri, body, headers)
+ return self.connection.getresponse()
+
+class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
+ """Test the functionality of the BaseHTTPServer focussing on
+ BaseHTTPRequestHandler.
+ """
+
+ HTTPResponseMatch = re.compile('HTTP/1.[0-9]+ 200 OK')
+
+ def setUp (self):
+ self.handler = SocketlessRequestHandler()
+
+ def send_typical_request(self, message):
+ input = StringIO(message)
+ output = StringIO()
+ self.handler.rfile = input
+ self.handler.wfile = output
+ self.handler.handle_one_request()
+ output.seek(0)
+ return output.readlines()
+
+ def verify_get_called(self):
+ self.assertTrue(self.handler.get_called)
+
+ def verify_expected_headers(self, headers):
+ for fieldName in 'Server: ', 'Date: ', 'Content-Type: ':
+ self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
+
+ def verify_http_server_response(self, response):
+ match = self.HTTPResponseMatch.search(response)
+ self.assertTrue(match is not None)
+
+ def test_http_1_1(self):
+ result = self.send_typical_request('GET / HTTP/1.1\r\n\r\n')
+ self.verify_http_server_response(result[0])
+ self.verify_expected_headers(result[1:-1])
+ self.verify_get_called()
+ self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
+
+ def test_http_1_0(self):
+ result = self.send_typical_request('GET / HTTP/1.0\r\n\r\n')
+ self.verify_http_server_response(result[0])
+ self.verify_expected_headers(result[1:-1])
+ self.verify_get_called()
+ self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
+
+ def test_http_0_9(self):
+ result = self.send_typical_request('GET / HTTP/0.9\r\n\r\n')
+ self.assertEqual(len(result), 1)
+ self.assertEqual(result[0], '<html><body>Data</body></html>\r\n')
+ self.verify_get_called()
+
+ def test_with_continue_1_0(self):
+ result = self.send_typical_request('GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
+ self.verify_http_server_response(result[0])
+ self.verify_expected_headers(result[1:-1])
+ self.verify_get_called()
+ self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
+
+ def test_request_length(self):
+ # Issue #10714: huge request lines are discarded, to avoid Denial
+ # of Service attacks.
+ result = self.send_typical_request(b'GET ' + b'x' * 65537)
+ self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
+ self.assertFalse(self.handler.get_called)
+
+
+class BaseHTTPServerTestCase(BaseTestCase):
+ class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
+ protocol_version = 'HTTP/1.1'
+ default_request_version = 'HTTP/1.1'
+
+ def do_TEST(self):
+ self.send_response(204)
+ self.send_header('Content-Type', 'text/html')
+ self.send_header('Connection', 'close')
+ self.end_headers()
+
+ def do_KEEP(self):
+ self.send_response(204)
+ self.send_header('Content-Type', 'text/html')
+ self.send_header('Connection', 'keep-alive')
+ self.end_headers()
+
+ def do_KEYERROR(self):
+ self.send_error(999)
+
+ def do_CUSTOM(self):
+ self.send_response(999)
+ self.send_header('Content-Type', 'text/html')
+ self.send_header('Connection', 'close')
+ self.end_headers()
+
+ def setUp(self):
+ BaseTestCase.setUp(self)
+ self.con = httplib.HTTPConnection('localhost', self.PORT)
+ self.con.connect()
+
+ def test_command(self):
+ self.con.request('GET', '/')
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 501)
+
+ def test_request_line_trimming(self):
+ self.con._http_vsn_str = 'HTTP/1.1\n'
+ self.con.putrequest('GET', '/')
+ self.con.endheaders()
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 501)
+
+ def test_version_bogus(self):
+ self.con._http_vsn_str = 'FUBAR'
+ self.con.putrequest('GET', '/')
+ self.con.endheaders()
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 400)
+
+ def test_version_digits(self):
+ self.con._http_vsn_str = 'HTTP/9.9.9'
+ self.con.putrequest('GET', '/')
+ self.con.endheaders()
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 400)
+
+ def test_version_none_get(self):
+ self.con._http_vsn_str = ''
+ self.con.putrequest('GET', '/')
+ self.con.endheaders()
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 501)
+
+ def test_version_none(self):
+ self.con._http_vsn_str = ''
+ self.con.putrequest('PUT', '/')
+ self.con.endheaders()
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 400)
+
+ def test_version_invalid(self):
+ self.con._http_vsn = 99
+ self.con._http_vsn_str = 'HTTP/9.9'
+ self.con.putrequest('GET', '/')
+ self.con.endheaders()
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 505)
+
+ def test_send_blank(self):
+ self.con._http_vsn_str = ''
+ self.con.putrequest('', '')
+ self.con.endheaders()
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 400)
+
+ def test_header_close(self):
+ self.con.putrequest('GET', '/')
+ self.con.putheader('Connection', 'close')
+ self.con.endheaders()
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 501)
+
+ def test_head_keep_alive(self):
+ self.con._http_vsn_str = 'HTTP/1.1'
+ self.con.putrequest('GET', '/')
+ self.con.putheader('Connection', 'keep-alive')
+ self.con.endheaders()
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 501)
+
+ def test_handler(self):
+ self.con.request('TEST', '/')
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 204)
+
+ def test_return_header_keep_alive(self):
+ self.con.request('KEEP', '/')
+ res = self.con.getresponse()
+ self.assertEqual(res.getheader('Connection'), 'keep-alive')
+ self.con.request('TEST', '/')
+ self.addCleanup(self.con.close)
+
+ def test_internal_key_error(self):
+ self.con.request('KEYERROR', '/')
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 999)
+
+ def test_return_custom_status(self):
+ self.con.request('CUSTOM', '/')
+ res = self.con.getresponse()
+ self.assertEqual(res.status, 999)
+
+
+class SimpleHTTPServerTestCase(BaseTestCase):
+ class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
+ pass
+
+ def setUp(self):
+ BaseTestCase.setUp(self)
+ self.cwd = os.getcwd()
+ basetempdir = tempfile.gettempdir()
+ os.chdir(basetempdir)
+ self.data = 'We are the knights who say Ni!'
+ self.tempdir = tempfile.mkdtemp(dir=basetempdir)
+ self.tempdir_name = os.path.basename(self.tempdir)
+ temp = open(os.path.join(self.tempdir, 'test'), 'wb')
+ temp.write(self.data)
+ temp.close()
+
+ def tearDown(self):
+ try:
+ os.chdir(self.cwd)
+ try:
+ shutil.rmtree(self.tempdir)
+ except:
+ pass
+ finally:
+ BaseTestCase.tearDown(self)
+
+ def check_status_and_reason(self, response, status, data=None):
+ body = response.read()
+ self.assertTrue(response)
+ self.assertEqual(response.status, status)
+ self.assertIsNotNone(response.reason)
+ if data:
+ self.assertEqual(data, body)
+
+ def test_get(self):
+ #constructs the path relative to the root directory of the HTTPServer
+ response = self.request(self.tempdir_name + '/test')
+ self.check_status_and_reason(response, 200, data=self.data)
+ response = self.request(self.tempdir_name + '/')
+ self.check_status_and_reason(response, 200)
+ response = self.request(self.tempdir_name)
+ self.check_status_and_reason(response, 301)
+ response = self.request('/ThisDoesNotExist')
+ self.check_status_and_reason(response, 404)
+ response = self.request('/' + 'ThisDoesNotExist' + '/')
+ self.check_status_and_reason(response, 404)
+ f = open(os.path.join(self.tempdir_name, 'index.html'), 'w')
+ response = self.request('/' + self.tempdir_name + '/')
+ self.check_status_and_reason(response, 200)
+
+ # chmod() doesn't work as expected on Windows, and filesystem
+ # permissions are ignored by root on Unix.
+ if os.name == 'posix' and os.geteuid() != 0:
+ os.chmod(self.tempdir, 0)
+ response = self.request(self.tempdir_name + '/')
+ self.check_status_and_reason(response, 404)
+ os.chmod(self.tempdir, 0755)
+
+ def test_head(self):
+ response = self.request(
+ self.tempdir_name + '/test', method='HEAD')
+ self.check_status_and_reason(response, 200)
+ self.assertEqual(response.getheader('content-length'),
+ str(len(self.data)))
+ self.assertEqual(response.getheader('content-type'),
+ 'application/octet-stream')
+
+ def test_invalid_requests(self):
+ response = self.request('/', method='FOO')
+ self.check_status_and_reason(response, 501)
+ # requests must be case sensitive,so this should fail too
+ response = self.request('/', method='get')
+ self.check_status_and_reason(response, 501)
+ response = self.request('/', method='GETs')
+ self.check_status_and_reason(response, 501)
+
+
+cgi_file1 = """\
+#!%s
+
+print "Content-type: text/html"
+print
+print "Hello World"
+"""
+
+cgi_file2 = """\
+#!%s
+import cgi
+
+print "Content-type: text/html"
+print
+
+form = cgi.FieldStorage()
+print "%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
+ form.getfirst("bacon"))
+"""
+
+
+ at unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
+ "This test can't be run reliably as root (issue #13308).")
+class CGIHTTPServerTestCase(BaseTestCase):
+ class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
+ pass
+
+ def setUp(self):
+ BaseTestCase.setUp(self)
+ self.parent_dir = tempfile.mkdtemp()
+ self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
+ os.mkdir(self.cgi_dir)
+
+ # The shebang line should be pure ASCII: use symlink if possible.
+ # See issue #7668.
+ if hasattr(os, 'symlink'):
+ self.pythonexe = os.path.join(self.parent_dir, 'python')
+ os.symlink(sys.executable, self.pythonexe)
+ else:
+ self.pythonexe = sys.executable
+
+ self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
+ with open(self.file1_path, 'w') as file1:
+ file1.write(cgi_file1 % self.pythonexe)
+ os.chmod(self.file1_path, 0777)
+
+ self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
+ with open(self.file2_path, 'w') as file2:
+ file2.write(cgi_file2 % self.pythonexe)
+ os.chmod(self.file2_path, 0777)
+
+ self.cwd = os.getcwd()
+ os.chdir(self.parent_dir)
+
+ def tearDown(self):
+ try:
+ os.chdir(self.cwd)
+ if self.pythonexe != sys.executable:
+ os.remove(self.pythonexe)
+ os.remove(self.file1_path)
+ os.remove(self.file2_path)
+ os.rmdir(self.cgi_dir)
+ os.rmdir(self.parent_dir)
+ finally:
+ BaseTestCase.tearDown(self)
+
+ def test_url_collapse_path_split(self):
+ test_vectors = {
+ '': ('/', ''),
+ '..': IndexError,
+ '/.//..': IndexError,
+ '/': ('/', ''),
+ '//': ('/', ''),
+ '/\\': ('/', '\\'),
+ '/.//': ('/', ''),
+ 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
+ '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
+ '/cgi-bin/file1.py/PATH-INFO': ('/cgi-bin', 'file1.py/PATH-INFO'),
+ 'a': ('/', 'a'),
+ '/a': ('/', 'a'),
+ '//a': ('/', 'a'),
+ './a': ('/', 'a'),
+ './C:/': ('/C:', ''),
+ '/a/b': ('/a', 'b'),
+ '/a/b/': ('/a/b', ''),
+ '/a/b/c/..': ('/a/b', ''),
+ '/a/b/c/../d': ('/a/b', 'd'),
+ '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
+ '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
+ '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
+ '../a/b/c/../d/e/.././././..//f': IndexError,
+ '/a/b/c/../d/e/../../../f': ('/a', 'f'),
+ '/a/b/c/../d/e/../../../../f': ('/', 'f'),
+ '/a/b/c/../d/e/../../../../../f': IndexError,
+ '/a/b/c/../d/e/../../../../f/..': ('/', ''),
+ }
+ for path, expected in test_vectors.iteritems():
+ if isinstance(expected, type) and issubclass(expected, Exception):
+ self.assertRaises(expected,
+ CGIHTTPServer._url_collapse_path_split, path)
+ else:
+ actual = CGIHTTPServer._url_collapse_path_split(path)
+ self.assertEqual(expected, actual,
+ msg='path = %r\nGot: %r\nWanted: %r' %
+ (path, actual, expected))
+
+ def test_headers_and_content(self):
+ res = self.request('/cgi-bin/file1.py')
+ self.assertEqual(('Hello World\n', 'text/html', 200),
+ (res.read(), res.getheader('Content-type'), res.status))
+
+ def test_post(self):
+ params = urllib.urlencode({'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
+ headers = {'Content-type' : 'application/x-www-form-urlencoded'}
+ res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
+
+ self.assertEqual(res.read(), '1, python, 123456\n')
+
+ def test_invaliduri(self):
+ res = self.request('/cgi-bin/invalid')
+ res.read()
+ self.assertEqual(res.status, 404)
+
+ def test_authorization(self):
+ headers = {'Authorization' : 'Basic %s' %
+ base64.b64encode('username:pass')}
+ res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
+ self.assertEqual(('Hello World\n', 'text/html', 200),
+ (res.read(), res.getheader('Content-type'), res.status))
+
+ def test_no_leading_slash(self):
+ # http://bugs.python.org/issue2254
+ res = self.request('cgi-bin/file1.py')
+ self.assertEqual(('Hello World\n', 'text/html', 200),
+ (res.read(), res.getheader('Content-type'), res.status))
+
+ def test_os_environ_is_not_altered(self):
+ signature = "Test CGI Server"
+ os.environ['SERVER_SOFTWARE'] = signature
+ res = self.request('/cgi-bin/file1.py')
+ self.assertEqual((b'Hello World\n', 'text/html', 200),
+ (res.read(), res.getheader('Content-type'), res.status))
+ self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
+
+
+class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
+ """ Test url parsing """
+ def setUp(self):
+ self.translated = os.getcwd()
+ self.translated = os.path.join(self.translated, 'filename')
+ self.handler = SocketlessRequestHandler()
+
+ def test_query_arguments(self):
+ path = self.handler.translate_path('/filename')
+ self.assertEqual(path, self.translated)
+ path = self.handler.translate_path('/filename?foo=bar')
+ self.assertEqual(path, self.translated)
+ path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
+ self.assertEqual(path, self.translated)
+
+ def test_start_with_double_slash(self):
+ path = self.handler.translate_path('//filename')
+ self.assertEqual(path, self.translated)
+ path = self.handler.translate_path('//filename?foo=bar')
+ self.assertEqual(path, self.translated)
+
+
+def test_main(verbose=None):
+ try:
+ cwd = os.getcwd()
+ test_support.run_unittest(BaseHTTPRequestHandlerTestCase,
+ SimpleHTTPRequestHandlerTestCase,
+ BaseHTTPServerTestCase,
+ SimpleHTTPServerTestCase,
+ CGIHTTPServerTestCase
+ )
+ finally:
+ os.chdir(cwd)
+
+if __name__ == '__main__':
+ test_main()
--
Repository URL: http://hg.python.org/jython
More information about the Jython-checkins
mailing list