diff options
author | Chris McDonough <chrism@plope.com> | 2011-12-26 05:24:16 -0500 |
---|---|---|
committer | Chris McDonough <chrism@plope.com> | 2011-12-26 05:24:16 -0500 |
commit | 8ef78195e215a4abf8136b657c68010944f8e1be (patch) | |
tree | 70f3180fafb8f95c4632d669dffc71f3371965b5 | |
parent | 62c44bf3b5314aa407360fd72e809749f93d6f76 (diff) | |
download | waitress-8ef78195e215a4abf8136b657c68010944f8e1be.tar.gz |
pep8
-rw-r--r-- | TODO.txt | 1 | ||||
-rw-r--r-- | waitress/__init__.py | 2 | ||||
-rw-r--r-- | waitress/channel.py | 4 | ||||
-rw-r--r-- | waitress/interfaces.py | 4 | ||||
-rw-r--r-- | waitress/server.py | 6 | ||||
-rw-r--r-- | waitress/task.py | 34 | ||||
-rw-r--r-- | waitress/tests/test_channel.py | 2 | ||||
-rw-r--r-- | waitress/tests/test_init.py | 2 | ||||
-rw-r--r-- | waitress/tests/test_integration.py_aside | 1033 | ||||
-rw-r--r-- | waitress/tests/test_server.py | 8 | ||||
-rw-r--r-- | waitress/tests/test_task.py | 96 |
11 files changed, 80 insertions, 1112 deletions
@@ -20,4 +20,3 @@ - SERVER_IDENT -> ident -- PEP-8. diff --git a/waitress/__init__.py b/waitress/__init__.py index 57ff8fe..203e0b6 100644 --- a/waitress/__init__.py +++ b/waitress/__init__.py @@ -33,7 +33,7 @@ def serve( port = int(port) threads = int(threads) task_dispatcher = dispatcher() - task_dispatcher.setThreadCount(threads) + task_dispatcher.set_thread_count(threads) adj = Adjustments() adj.url_scheme = url_scheme adj.connection_limit = int(connection_limit) diff --git a/waitress/channel.py b/waitress/channel.py index 45862e2..b09733b 100644 --- a/waitress/channel.py +++ b/waitress/channel.py @@ -308,7 +308,7 @@ class HTTPServerChannel(asyncore.dispatcher, object): self.task_lock.release() if start: self.set_sync() - self.server.addTask(self) + self.server.add_task(self) # # ITask implementation. Delegates to the queued tasks. @@ -333,7 +333,7 @@ class HTTPServerChannel(asyncore.dispatcher, object): task.service() except: # propagate the exception, but keep executing tasks - self.server.addTask(self) + self.server.add_task(self) raise def cancel(self): diff --git a/waitress/interfaces.py b/waitress/interfaces.py index f57bd1a..4dd83a4 100644 --- a/waitress/interfaces.py +++ b/waitress/interfaces.py @@ -88,11 +88,11 @@ class ITaskDispatcher(Interface): """An object that accepts tasks and dispatches them to threads. """ - def setThreadCount(count): + def set_thread_count(count): """Sets the number of handler threads. """ - def addTask(task): + def add_task(task): """Receives a task and dispatches it to a thread. Note that, depending on load, a task may have to wait a diff --git a/waitress/server.py b/waitress/server.py index b2ee13e..fba49f9 100644 --- a/waitress/server.py +++ b/waitress/server.py @@ -25,7 +25,7 @@ class WSGIHTTPServer(asyncore.dispatcher, object): if __name__ == '__main__': from waitress.task import ThreadedTaskDispatcher td = ThreadedTaskDispatcher() - td.setThreadCount(4) + td.set_thread_count(4) server = WSGIHTTPServer(app, '', 8080, task_dispatcher=td) server.run() """ @@ -96,9 +96,9 @@ class WSGIHTTPServer(asyncore.dispatcher, object): self.accepting = True self.socket.listen(self.adj.backlog) # Get around asyncore NT limit - def addTask(self, task): + def add_task(self, task): """See waitress.interfaces.ITaskDispatcher""" - self.task_dispatcher.addTask(task) + self.task_dispatcher.add_task(task) def readable(self): """See waitress.interfaces.IDispatcher""" diff --git a/waitress/task.py b/waitress/task.py index b634377..92e48df 100644 --- a/waitress/task.py +++ b/waitress/task.py @@ -53,7 +53,7 @@ class ThreadedTaskDispatcher(object): self.queue = Queue() self.thread_mgmt_lock = thread.allocate_lock() - def handlerThread(self, thread_no): + def handler_thread(self, thread_no): threads = self.threads try: while threads.get(thread_no): @@ -77,7 +77,7 @@ class ThreadedTaskDispatcher(object): finally: mlock.release() - def setThreadCount(self, count): + def set_thread_count(self, count): """See waitress.interfaces.ITaskDispatcher""" mlock = self.thread_mgmt_lock mlock.acquire() @@ -91,7 +91,7 @@ class ThreadedTaskDispatcher(object): thread_no = thread_no + 1 threads[thread_no] = 1 running += 1 - self.start_new_thread(self.handlerThread, (thread_no,)) + self.start_new_thread(self.handler_thread, (thread_no,)) thread_no = thread_no + 1 if running > count: # Stop threads. @@ -103,7 +103,7 @@ class ThreadedTaskDispatcher(object): finally: mlock.release() - def addTask(self, task): + def add_task(self, task): """See waitress.interfaces.ITaskDispatcher""" try: task.defer() @@ -114,7 +114,7 @@ class ThreadedTaskDispatcher(object): def shutdown(self, cancel_pending=True, timeout=5): """See waitress.interfaces.ITaskDispatcher""" - self.setThreadCount(0) + self.set_thread_count(0) # Ensure the threads shut down. threads = self.threads expiration = time.time() + timeout @@ -191,7 +191,7 @@ class HTTPTask(object): pass def execute(self): - env = self.getEnvironment() + env = self.get_environment() def start_response(status, headers, exc_info=None): self.start_response_called = True @@ -204,7 +204,7 @@ class HTTPTask(object): # higher levels will catch and handle raised exception: # 1. "service" method in task.py # 2. "service" method in channel.py - # 3. "handlerThread" method in task.py + # 3. "handler_thread" method in task.py reraise(exc_info[0], exc_info[1], exc_info[2]) else: # As per WSGI spec existing headers must be cleared @@ -233,7 +233,7 @@ class HTTPTask(object): self.content_length = int(v) # Return the write method used to write the response data. - return fakeWrite + return fake_write # Call the application to handle the request and write a response app_iter = self.channel.server.application(env, start_response) @@ -244,16 +244,17 @@ class HTTPTask(object): # Set a Content-Length header if one is not supplied. cl = self.content_length - if cl is None: + if cl == -1: app_iter_len = len(app_iter) if app_iter_len == 1: - self.content_length = len(app_iter[0]) + cl = self.content_length = len(app_iter[0]) - # By iterating manually at this point, we execute task.write() - # multiple times, allowing partial data to be sent. has_content_length = cl != -1 bytes_written = 0 + try: + # By iterating manually at this point, we execute task.write() + # multiple times, allowing partial data to be sent. for value in app_iter: towrite = value if has_content_length: @@ -265,6 +266,7 @@ class HTTPTask(object): 'warning: app_iter content exceeded the number ' 'of bytes specified by Content-Length header (%s)' % cl) break + if has_content_length: if bytes_written != cl: self.log_info('warning: app_iter returned a number of ' @@ -275,7 +277,7 @@ class HTTPTask(object): app_iter.close() - def buildResponseHeader(self): + def build_response_header(self): version = self.version # Figure out whether the connection should be closed. connection = self.request_data.headers.get('CONNECTION', '').lower() @@ -351,7 +353,7 @@ class HTTPTask(object): res = '%s\r\n\r\n' % '\r\n'.join(lines) return tobytes(res) - def getEnvironment(self): + def get_environment(self): """Returns a WSGI environment.""" environ = self.environ if environ is not None: @@ -409,13 +411,13 @@ class HTTPTask(object): def write(self, data): channel = self.channel if not self.wrote_header: - rh = self.buildResponseHeader() + rh = self.build_response_header() channel.write(rh) self.wrote_header = True if data: channel.write(data) -def fakeWrite(body): +def fake_write(body): raise NotImplementedError( "the waitress HTTP Server does not support the WSGI write() function.") diff --git a/waitress/tests/test_channel.py b/waitress/tests/test_channel.py index 5d3c13c..5f99a4b 100644 --- a/waitress/tests/test_channel.py +++ b/waitress/tests/test_channel.py @@ -540,7 +540,7 @@ class DummyServer(object): trigger_pulled = False def __init__(self): self.tasks = [] - def addTask(self, task): + def add_task(self, task): self.tasks.append(task) def pull_trigger(self): self.trigger_pulled = True diff --git a/waitress/tests/test_init.py b/waitress/tests/test_init.py index 95f2e26..9427b1c 100644 --- a/waitress/tests/test_init.py +++ b/waitress/tests/test_init.py @@ -86,6 +86,6 @@ class DummyServerFactory(object): self.ran = True class DummyTaskDispatcher(object): - def setThreadCount(self, num): + def set_thread_count(self, num): self.threads = num diff --git a/waitress/tests/test_integration.py_aside b/waitress/tests/test_integration.py_aside deleted file mode 100644 index 367f790..0000000 --- a/waitress/tests/test_integration.py_aside +++ /dev/null @@ -1,1033 +0,0 @@ -import unittest -import asyncore -from asyncore import socket_map, poll -from time import sleep, time -import StringIO -import socket -import sys -import traceback -from threading import Thread, Event -from httplib import HTTPConnection -from httplib import HTTPResponse as ClientHTTPResponse - -from zope.component.testing import PlacelessSetup -import zope.component - -from zope.i18n.interfaces import IUserPreferredCharsets - -from zope.publisher.publish import publish -from zope.publisher.http import IHTTPRequest -from zope.publisher.http import HTTPCharsets -from zope.publisher.browser import BrowserRequest - -from zope.publisher.base import DefaultPublication -from zope.publisher.interfaces import Redirect, Retry -from zope.publisher.http import HTTPRequest - -from waitress.task import ThreadedTaskDispatcher -from waitress.adjustments import Adjustments - - -td = ThreadedTaskDispatcher() - -LOCALHOST = '127.0.0.1' - -HTTPRequest.STAGGER_RETRIES = 0 # Don't pause. - -LOCALHOST = '127.0.0.1' -SERVER_PORT = 0 # Set these port numbers to 0 to auto-bind, or -CONNECT_TO_PORT = 0 # use specific numbers to inspect using TCPWatch. - -my_adj = Adjustments() -# Reduce overflows to make testing easier. -my_adj.outbuf_overflow = 10000 -my_adj.inbuf_overflow = 10000 - - -class TestWSGIHTTPEchoServer(unittest.TestCase): - - def hook_asyncore_error(self): - self._asyncore_traceback = asyncore.compact_traceback - asyncore.compact_traceback = self.handle_asyncore_error - - def unhook_asyncore_error(self): - asyncore.compact_traceback = self._asyncore_traceback - - def handle_asyncore_error(self): # pragma: no cover - L = traceback.format_exception(*sys.exc_info()) - self.fail("".join(L)) - - def setUp(self): - # import only now to prevent the testrunner from importing it too early - # Otherwise dualmodechannel.the_trigger is closed by the ZEO tests - from waitress.server import WSGIHTTPServer - class EchoHTTPServer(WSGIHTTPServer): - - def executeRequest(self, task): - headers = task.request_data.headers - if 'CONTENT_LENGTH' in headers: - cl = headers['CONTENT_LENGTH'] - task.response_headers['Content-Length'] = cl - instream = task.request_data.getBodyStream() - while 1: - data = instream.read(8192) - if not data: - break - task.write(data) - - td.setThreadCount(4) - if len(socket_map) != 1: - # Let sockets die off. - # TODO tests should be more careful to clear the socket map. - poll(0.1) - self.orig_map_size = len(socket_map) - self.hook_asyncore_error() - self.server = EchoHTTPServer(None, LOCALHOST, SERVER_PORT, - task_dispatcher=td, adj=my_adj) - if CONNECT_TO_PORT == 0: - self.port = self.server.socket.getsockname()[1] - else: - self.port = CONNECT_TO_PORT - self.run_loop = 1 - self.counter = 0 - self.thread_started = Event() - self.thread = Thread(target=self.loop) - self.thread.setDaemon(True) - self.thread.start() - self.thread_started.wait(10.0) - self.assert_(self.thread_started.isSet()) - - def tearDown(self): - self.run_loop = 0 - self.thread.join() - td.shutdown() - self.server.close() - # Make sure all sockets get closed by asyncore normally. - timeout = time() + 5 - while 1: - if len(socket_map) == self.orig_map_size: - # Clean! - break - if time() >= timeout: - self.fail('Leaked a socket: %s' % `socket_map`) - poll(0.1) - self.unhook_asyncore_error() - - def loop(self): - self.thread_started.set() - while self.run_loop: - self.counter = self.counter + 1 - #print 'loop', self.counter - poll(0.1) - - def testEchoResponse(self, h=None, add_headers=None, body=''): - if h is None: - h = HTTPConnection(LOCALHOST, self.port) - headers = {} - if add_headers: - headers.update(add_headers) - headers["Accept"] = "text/plain" - # Content-Length header automatically added by HTTPConnection.request - #if body: - # headers["Content-Length"] = str(int(len(body))) - h.request("GET", "/", body, headers) - response = h.getresponse() - self.failUnlessEqual(int(response.status), 200) - length = int(response.getheader('Content-Length', '0')) - response_body = response.read() - self.failUnlessEqual(length, len(response_body)) - self.failUnlessEqual(response_body, body) - # HTTP 1.1 requires the server and date header. - self.assertEqual(response.getheader('server'), 'waitress') - self.assert_(response.getheader('date') is not None) - - def testMultipleRequestsWithoutBody(self): - # Tests the use of multiple requests in a single connection. - h = HTTPConnection(LOCALHOST, self.port) - for n in range(3): - self.testEchoResponse(h) - self.testEchoResponse(h, {'Connection': 'close'}) - - def testMultipleRequestsWithBody(self): - # Tests the use of multiple requests in a single connection. - h = HTTPConnection(LOCALHOST, self.port) - for n in range(3): - self.testEchoResponse(h, body='Hello, world!') - self.testEchoResponse(h, {'Connection': 'close'}) - - def testPipelining(self): - # Tests the use of several requests issued at once. - s = ("GET / HTTP/1.0\r\n" - "Connection: %s\r\n" - "Content-Length: %d\r\n" - "\r\n" - "%s") - to_send = '' - count = 25 - for n in range(count): - body = "Response #%d\r\n" % (n + 1) - if n + 1 < count: - conn = 'keep-alive' - else: - conn = 'close' - to_send += s % (conn, len(body), body) - - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((LOCALHOST, self.port)) - sock.send(to_send) - for n in range(count): - expect_body = "Response #%d\r\n" % (n + 1) - response = ClientHTTPResponse(sock) - response.begin() - self.failUnlessEqual(int(response.status), 200) - length = int(response.getheader('Content-Length', '0')) - response_body = response.read(length) - self.failUnlessEqual(length, len(response_body)) - self.failUnlessEqual(response_body, expect_body) - - def testWithoutCRLF(self): - # Tests the use of just newlines rather than CR/LFs. - data = "Echo\nthis\r\nplease" - s = ("GET / HTTP/1.0\n" - "Connection: close\n" - "Content-Length: %d\n" - "\n" - "%s") % (len(data), data) - - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((LOCALHOST, self.port)) - sock.send(s) - response = ClientHTTPResponse(sock) - response.begin() - self.failUnlessEqual(int(response.status), 200) - length = int(response.getheader('Content-Length', '0')) - response_body = response.read(length) - self.failUnlessEqual(length, len(data)) - self.failUnlessEqual(response_body, data) - - def testLargeBody(self): - # Tests the use of multiple requests in a single connection. - h = HTTPConnection(LOCALHOST, self.port) - s = 'This string has 32 characters.\r\n' * 32 # 1024 characters. - self.testEchoResponse(h, body=(s * 1024)) # 1 MB - self.testEchoResponse(h, {'Connection': 'close'}, - body=(s * 100)) # 100 KB - - def testManyClients(self): - # Set the number of connections to make. A previous comment said - # Linux kernel (2.4.8) doesn't like > 128. - # The test used to use 50. Win98SE can't handle that many, dying - # with - # File "C:\PYTHON23\Lib\httplib.py", line 548, in connect - # raise socket.error, msg - # error: (10055, 'No buffer space available') - nconn = 50 - if sys.platform == 'win32': - platform = sys.getwindowsversion()[3] - if platform < 2: - # 0 is Win32s on Windows 3.1 - # 1 is 95/98/ME - # 2 is NT/2000/XP - - # Pre-NT. 20 should work. The exact number you can get away - # with depends on what you're running at the same time (e.g., - # browsers and AIM and email delivery consume sockets too). - nconn = 20 - - conns = [] - for n in range(nconn): - #print 'open', n, clock() - h = HTTPConnection(LOCALHOST, self.port) - #h.debuglevel = 1 - h.request("GET", "/", headers={"Accept": "text/plain"}) - conns.append(h) - # If you uncomment the next line, you can raise the - # number of connections much higher without running - # into delays. - #sleep(0.01) - responses = [] - for h in conns: - response = h.getresponse() - self.failUnlessEqual(response.status, 200) - responses.append(response) - for response in responses: - response.read() - - def testThreading(self): - # Ensures the correct number of threads keep running. - for n in range(4): - td.addTask(SleepingTask()) - # Try to confuse the task manager. - td.setThreadCount(2) - td.setThreadCount(1) - sleep(0.5) - # There should be 1 still running. - self.failUnlessEqual(len(td.threads), 1) - - def testChunkingRequestWithoutContent(self): - h = HTTPConnection(LOCALHOST, self.port) - h.request("GET", "/", headers={"Accept": "text/plain", - "Transfer-Encoding": "chunked"}) - h.send("0\r\n\r\n") - response = h.getresponse() - self.failUnlessEqual(int(response.status), 200) - response_body = response.read() - self.failUnlessEqual(response_body, '') - - def testChunkingRequestWithContent(self): - control_line="20;\r\n" # 20 hex = 32 dec - s = 'This string has 32 characters.\r\n' - expect = s * 12 - - h = HTTPConnection(LOCALHOST, self.port) - h.request("GET", "/", headers={"Accept": "text/plain", - "Transfer-Encoding": "chunked"}) - for n in range(12): - h.send(control_line) - h.send(s) - h.send("0\r\n\r\n") - response = h.getresponse() - self.failUnlessEqual(int(response.status), 200) - response_body = response.read() - self.failUnlessEqual(response_body, expect) - - def testKeepaliveHttp10(self): - # Handling of Keep-Alive within HTTP 1.0 - data = "Default: Don't keep me alive" - s = ("GET / HTTP/1.0\n" - "Content-Length: %d\n" - "\n" - "%s") % (len(data), data) - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((LOCALHOST, self.port)) - sock.send(s) - response = ClientHTTPResponse(sock) - response.begin() - self.failUnlessEqual(int(response.status), 200) - connection = response.getheader('Connection', '') - # We sent no Connection: Keep-Alive header - # Connection: close (or no header) is default. - self.failUnless(connection != 'Keep-Alive') - - # If header Connection: Keep-Alive is explicitly sent, - # we want to keept the connection open, we also need to return - # the corresponding header - data = "Keep me alive" - s = ("GET / HTTP/1.0\n" - "Connection: Keep-Alive\n" - "Content-Length: %d\n" - "\n" - "%s") % (len(data), data) - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((LOCALHOST, self.port)) - sock.send(s) - response = ClientHTTPResponse(sock) - response.begin() - self.failUnlessEqual(int(response.status), 200) - connection = response.getheader('Connection', '') - self.failUnlessEqual(connection, 'Keep-Alive') - - def testKeepaliveHttp11(self): - # Handling of Keep-Alive within HTTP 1.1 - - # All connections are kept alive, unless stated otherwise - data = "Default: Keep me alive" - s = ("GET / HTTP/1.1\n" - "Content-Length: %d\n" - "\n" - "%s") % (len(data), data) - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((LOCALHOST, self.port)) - sock.send(s) - response = ClientHTTPResponse(sock) - response.begin() - self.failUnlessEqual(int(response.status), 200) - self.failUnless(response.getheader('connection') != 'close') - - # Explicitly set keep-alive - data = "Default: Keep me alive" - s = ("GET / HTTP/1.1\n" - "Connection: keep-alive\n" - "Content-Length: %d\n" - "\n" - "%s") % (len(data), data) - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((LOCALHOST, self.port)) - sock.send(s) - response = ClientHTTPResponse(sock) - response.begin() - self.failUnlessEqual(int(response.status), 200) - self.failUnless(response.getheader('connection') != 'close') - - # no idea why the test publisher handles this request incorrectly - # it would be less typing in the test :) - # h = HTTPConnection(LOCALHOST, self.port) - # h.request("GET", "/") - # response = h.getresponse() - # self.failUnlessEqual(int(response.status), 200) - # self.failUnless(response.getheader('connection') != 'close') - - # specifying Connection: close explicitly - data = "Don't keep me alive" - s = ("GET / HTTP/1.1\n" - "Connection: close\n" - "Content-Length: %d\n" - "\n" - "%s") % (len(data), data) - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((LOCALHOST, self.port)) - sock.send(s) - response = ClientHTTPResponse(sock) - response.begin() - self.failUnlessEqual(int(response.status), 200) - self.failUnlessEqual(response.getheader('connection'), 'close') - -class TestWSGIHTTPServerWithPublisher(PlacelessSetup, unittest.TestCase): - - def _getServerClass(self): - # import only now to prevent the testrunner from importing it too early - # Otherwise dualmodechannel.the_trigger is closed by the ZEO tests - from waitress.server import WSGIHTTPServer - return WSGIHTTPServer - - def setUp(self): - super(TestWSGIHTTPServerWithPublisher, self).setUp() - zope.component.provideAdapter(HTTPCharsets, [IHTTPRequest], - IUserPreferredCharsets, '') - obj = tested_object() - obj.folder = tested_object() - obj.folder.item = tested_object() - obj._protected = tested_object() - obj.wsgi = WSGIInfo() - - pub = PublicationWithConflict(obj) - - def application(environ, start_response): - request = BrowserRequest(environ['wsgi.input'], environ) - request.setPublication(pub) - request = publish(request) - response = request.response - start_response(response.getStatusString(), response.getHeaders()) - return response.consumeBodyIter() - - td.setThreadCount(4) - # Bind to any port on localhost. - ServerClass = self._getServerClass() - self.server = ServerClass(application, - LOCALHOST, 0, task_dispatcher=td) - - self.port = self.server.socket.getsockname()[1] - self.run_loop = 1 - self.thread = Thread(target=self.loop) - self.thread.start() - sleep(0.1) # Give the thread some time to start. - - def tearDown(self): - self.run_loop = 0 - self.thread.join() - td.shutdown() - self.server.close() - super(TestWSGIHTTPServerWithPublisher, self).tearDown() - - def loop(self): - while self.run_loop: - poll(0.1, socket_map) - - def invokeRequest(self, path='/', add_headers=None, request_body='', - return_response=False): - h = HTTPConnection(LOCALHOST, self.port) - h.putrequest('GET', path) - h.putheader('Accept', 'text/plain') - if add_headers: - for k, v in add_headers.items(): - h.putheader(k, v) - if request_body: - h.putheader('Content-Length', str(int(len(request_body)))) - h.endheaders() - if request_body: - h.send(request_body) - response = h.getresponse() - if return_response: - return response - length = int(response.getheader('Content-Length', '0')) - if length: - response_body = response.read(length) - else: - response_body = '' - - self.assertEqual(length, len(response_body)) - - return response.status, response_body - - - def testDeeperPath(self): - status, response_body = self.invokeRequest('/folder/item') - self.assertEqual(status, 200) - expect_response = 'URL invoked: http://%s:%d/folder/item' % ( - LOCALHOST, self.port) - self.assertEqual(response_body, expect_response) - - def testNotFound(self): - status, response_body = self.invokeRequest('/foo/bar') - self.assertEqual(status, 404) - - def testUnauthorized(self): - status, response_body = self.invokeRequest('/_protected') - self.assertEqual(status, 401) - - def testRedirectMethod(self): - status, response_body = self.invokeRequest('/redirect_method') - self.assertEqual(status, 303) - - def testRedirectException(self): - status, response_body = self.invokeRequest('/redirect_exception') - self.assertEqual(status, 303) - status, response_body = self.invokeRequest('/folder/redirect_exception') - self.assertEqual(status, 303) - - def testConflictRetry(self): - status, response_body = self.invokeRequest('/conflict?wait_tries=2') - # Expect the "Accepted" response since the retries will succeed. - self.assertEqual(status, 202) - - def testFailedConflictRetry(self): - status, response_body = self.invokeRequest('/conflict?wait_tries=10') - # Expect a "Conflict" response since there will be too many - # conflicts. - self.assertEqual(status, 409) - - def testServerAsProxy(self): - response = self.invokeRequest( - '/proxy', return_response=True) - # The headers set by the proxy are honored, - self.assertEqual( - response.getheader('Server'), 'Fake/1.0') - self.assertEqual( - response.getheader('Date'), 'Thu, 01 Apr 2010 12:00:00 GMT') - # The server adds a Via header. - self.assertEqual( - response.getheader('Via'), 'waitress') - # And the content got here too. - self.assertEqual(response.read(), 'Proxied Content') - - def testWSGIVariables(self): - # Assert that the environment contains all required WSGI variables - status, response_body = self.invokeRequest('/wsgi') - wsgi_variables = set(response_body.split()) - self.assertEqual(wsgi_variables, - set(['wsgi.version', 'wsgi.url_scheme', 'wsgi.input', - 'wsgi.errors', 'wsgi.multithread', - 'wsgi.multiprocess', 'wsgi.run_once'])) - - def testWSGIVersion(self): - status, response_body = self.invokeRequest('/wsgi/version') - self.assertEqual("(1, 0)", response_body) - - def testWSGIURLScheme(self): - status, response_body = self.invokeRequest('/wsgi/url_scheme') - self.assertEqual('http', response_body) - - def testWSGIMultithread(self): - status, response_body = self.invokeRequest('/wsgi/multithread') - self.assertEqual('True', response_body) - - def testWSGIMultiprocess(self): - status, response_body = self.invokeRequest('/wsgi/multiprocess') - self.assertEqual('True', response_body) - - def testWSGIRunOnce(self): - status, response_body = self.invokeRequest('/wsgi/run_once') - self.assertEqual('False', response_body) - - def testWSGIProxy(self): - status, response_body = self.invokeRequest( - 'https://zope.org:8080/wsgi/proxy_scheme') - self.assertEqual('https', response_body) - status, response_body = self.invokeRequest( - 'https://zope.org:8080/wsgi/proxy_host') - self.assertEqual('zope.org:8080', response_body) - - def test_ensure_multiple_task_write_calls(self): - # In order to get data out as fast as possible, the WSGI server needs - # to call task.write() multiple times. - orig_app = self.server.application - def app(eviron, start_response): - start_response('200 Ok', []) - return ['This', 'is', 'my', 'response.'] - self.server.application = app - - class FakeTask: - wrote_header = 0 - counter = 0 - getCGIEnvironment = lambda _: {} - class request_data: - getBodyStream = lambda _: StringIO.StringIO() - request_data = request_data() - setResponseStatus = appendResponseHeaders = lambda *_: None - def write(self, v): - self.counter += 1 - - task = FakeTask() - self.server.executeRequest(task) - self.assertEqual(task.counter, 4) - - self.server.application = orig_app - - def _getFakeAppAndTask(self): - - def app(environ, start_response): - try: - raise DummyException() - except DummyException: - start_response( - '500 Internal Error', - [('Content-type', 'text/plain')], - sys.exc_info()) - return ERROR_RESPONSE.split() - return RESPONSE.split() - - class FakeTask: - wrote_header = 0 - status = None - reason = None - response = [] - accumulated_headers = None - def __init__(self): - self.accumulated_headers = [] - self.response_headers = {} - getCGIEnvironment = lambda _: {} - class request_data: - getBodyStream = lambda _: StringIO.StringIO() - request_data = request_data() - def appendResponseHeaders(self, lst): - accum = self.accumulated_headers - if accum is None: - self.accumulated_headers = accum = [] - accum.extend(lst) - def setResponseStatus(self, status, reason): - self.status = status - self.reason = reason - def write(self, v): - self.response.append(v) - - return app, FakeTask() - - - def test_start_response_with_no_headers_sent(self): - # start_response exc_info if no headers have been sent - orig_app = self.server.application - self.server.application, task = self._getFakeAppAndTask() - task.accumulated_headers = ['header1', 'header2'] - task.accumulated_headers = {'key1': 'value1', 'key2': 'value2'} - - self.server.executeRequest(task) - - self.assertEqual(task.status, "500") - self.assertEqual(task.response, ERROR_RESPONSE.split()) - # any headers written before are cleared and - # only the most recent one is added. - self.assertEqual(task.accumulated_headers, ['Content-type: text/plain']) - # response headers are cleared. They'll be rebuilt from - # accumulated_headers in the prepareResponseHeaders method - self.assertEqual(task.response_headers, {}) - - self.server.application = orig_app - - - def test_multiple_start_response_calls(self): - # if start_response is called more than once with no exc_info - ignore, task = self._getFakeAppAndTask() - task.wrote_header = 1 - - self.assertRaises(AssertionError, self.server.executeRequest, task) - - - def test_start_response_with_headers_sent(self): - # If headers have been sent it raises the exception - orig_app = self.server.application - self.server.application, task = self._getFakeAppAndTask() - - # If headers have already been written an exception is raised - task.wrote_header = 1 - self.assertRaises(DummyException, self.server.executeRequest, task) - - self.server.application = orig_app - -class TestWSGIHTTPServer(PlacelessSetup, unittest.TestCase): - - def _getServerClass(self): - # import only now to prevent the testrunner from importing it too early - # Otherwise dualmodechannel.the_trigger is closed by the ZEO tests - from waitress.server import WSGIHTTPServer - return WSGIHTTPServer - - def setUp(self): - super(TestWSGIHTTPServer, self).setUp() - zope.component.provideAdapter(HTTPCharsets, [IHTTPRequest], - IUserPreferredCharsets, '') - obj = tested_object() - obj.folder = tested_object() - obj.folder.item = tested_object() - obj._protected = tested_object() - obj.wsgi = WSGIInfo() - - pub = PublicationWithConflict(obj) - - def application(environ, start_response): - request = BrowserRequest(environ['wsgi.input'], environ) - request.setPublication(pub) - request = publish(request) - response = request.response - start_response(response.getStatusString(), response.getHeaders()) - return response.consumeBodyIter() - - td.setThreadCount(4) - # Bind to any port on localhost. - ServerClass = self._getServerClass() - self.server = ServerClass(application, LOCALHOST, 0, task_dispatcher=td) - - self.port = self.server.socket.getsockname()[1] - self.run_loop = 1 - self.thread = Thread(target=self.loop) - self.thread.start() - sleep(0.1) # Give the thread some time to start. - - def tearDown(self): - self.run_loop = 0 - self.thread.join() - td.shutdown() - self.server.close() - super(TestWSGIHTTPServer, self).tearDown() - - def loop(self): - while self.run_loop: - poll(0.1, socket_map) - - def invokeRequest(self, path='/', add_headers=None, request_body='', - return_response=False): - h = HTTPConnection(LOCALHOST, self.port) - h.putrequest('GET', path) - h.putheader('Accept', 'text/plain') - if add_headers: - for k, v in add_headers.items(): - h.putheader(k, v) - if request_body: - h.putheader('Content-Length', str(int(len(request_body)))) - h.endheaders() - if request_body: - h.send(request_body) - response = h.getresponse() - if return_response: - return response - length = int(response.getheader('Content-Length', '0')) - if length: - response_body = response.read(length) - else: - response_body = '' - - self.assertEqual(length, len(response_body)) - - return response.status, response_body - - - def testDeeperPath(self): - status, response_body = self.invokeRequest('/folder/item') - self.assertEqual(status, 200) - expect_response = 'URL invoked: http://%s:%d/folder/item' % ( - LOCALHOST, self.port) - self.assertEqual(response_body, expect_response) - - def testNotFound(self): - status, response_body = self.invokeRequest('/foo/bar') - self.assertEqual(status, 404) - - def testUnauthorized(self): - status, response_body = self.invokeRequest('/_protected') - self.assertEqual(status, 401) - - def testRedirectMethod(self): - status, response_body = self.invokeRequest('/redirect_method') - self.assertEqual(status, 303) - - def testRedirectException(self): - status, response_body = self.invokeRequest('/redirect_exception') - self.assertEqual(status, 303) - status, response_body = self.invokeRequest('/folder/redirect_exception') - self.assertEqual(status, 303) - - def testConflictRetry(self): - status, response_body = self.invokeRequest('/conflict?wait_tries=2') - # Expect the "Accepted" response since the retries will succeed. - self.assertEqual(status, 202) - - def testFailedConflictRetry(self): - status, response_body = self.invokeRequest('/conflict?wait_tries=10') - # Expect a "Conflict" response since there will be too many - # conflicts. - self.assertEqual(status, 409) - - def testServerAsProxy(self): - response = self.invokeRequest( - '/proxy', return_response=True) - # The headers set by the proxy are honored, - self.assertEqual( - response.getheader('Server'), 'Fake/1.0') - self.assertEqual( - response.getheader('Date'), 'Thu, 01 Apr 2010 12:00:00 GMT') - # The server adds a Via header. - self.assertEqual( - response.getheader('Via'), 'waitress') - # And the content got here too. - self.assertEqual(response.read(), 'Proxied Content') - - def testWSGIVariables(self): - # Assert that the environment contains all required WSGI variables - status, response_body = self.invokeRequest('/wsgi') - wsgi_variables = set(response_body.split()) - self.assertEqual(wsgi_variables, - set(['wsgi.version', 'wsgi.url_scheme', 'wsgi.input', - 'wsgi.errors', 'wsgi.multithread', - 'wsgi.multiprocess', 'wsgi.run_once'])) - - def testWSGIVersion(self): - status, response_body = self.invokeRequest('/wsgi/version') - self.assertEqual("(1, 0)", response_body) - - def testWSGIURLScheme(self): - status, response_body = self.invokeRequest('/wsgi/url_scheme') - self.assertEqual('http', response_body) - - def testWSGIMultithread(self): - status, response_body = self.invokeRequest('/wsgi/multithread') - self.assertEqual('True', response_body) - - def testWSGIMultiprocess(self): - status, response_body = self.invokeRequest('/wsgi/multiprocess') - self.assertEqual('True', response_body) - - def testWSGIRunOnce(self): - status, response_body = self.invokeRequest('/wsgi/run_once') - self.assertEqual('False', response_body) - - def testWSGIProxy(self): - status, response_body = self.invokeRequest( - 'https://zope.org:8080/wsgi/proxy_scheme') - self.assertEqual('https', response_body) - status, response_body = self.invokeRequest( - 'https://zope.org:8080/wsgi/proxy_host') - self.assertEqual('zope.org:8080', response_body) - - def test_ensure_multiple_task_write_calls(self): - # In order to get data out as fast as possible, the WSGI server needs - # to call task.write() multiple times. - orig_app = self.server.application - def app(eviron, start_response): - start_response('200 Ok', []) - return ['This', 'is', 'my', 'response.'] - self.server.application = app - - class FakeTask: - wrote_header = 0 - counter = 0 - getCGIEnvironment = lambda _: {} - class request_data: - getBodyStream = lambda _: StringIO.StringIO() - request_data = request_data() - setResponseStatus = appendResponseHeaders = lambda *_: None - def write(self, v): - self.counter += 1 - - task = FakeTask() - self.server.executeRequest(task) - self.assertEqual(task.counter, 4) - - self.server.application = orig_app - - def _getFakeAppAndTask(self): - - def app(environ, start_response): - try: - raise DummyException() - except DummyException: - start_response( - '500 Internal Error', - [('Content-type', 'text/plain')], - sys.exc_info()) - return ERROR_RESPONSE.split() - return RESPONSE.split() - - class FakeTask: - wrote_header = 0 - status = None - reason = None - response = [] - accumulated_headers = None - def __init__(self): - self.accumulated_headers = [] - self.response_headers = {} - getCGIEnvironment = lambda _: {} - class request_data: - getBodyStream = lambda _: StringIO.StringIO() - request_data = request_data() - def appendResponseHeaders(self, lst): - accum = self.accumulated_headers - if accum is None: - self.accumulated_headers = accum = [] - accum.extend(lst) - def setResponseStatus(self, status, reason): - self.status = status - self.reason = reason - def write(self, v): - self.response.append(v) - - return app, FakeTask() - - - def test_start_response_with_no_headers_sent(self): - # start_response exc_info if no headers have been sent - orig_app = self.server.application - self.server.application, task = self._getFakeAppAndTask() - task.accumulated_headers = ['header1', 'header2'] - task.accumulated_headers = {'key1': 'value1', 'key2': 'value2'} - - self.server.executeRequest(task) - - self.assertEqual(task.status, "500") - self.assertEqual(task.response, ERROR_RESPONSE.split()) - # any headers written before are cleared and - # only the most recent one is added. - self.assertEqual(task.accumulated_headers, ['Content-type: text/plain']) - # response headers are cleared. They'll be rebuilt from - # accumulated_headers in the prepareResponseHeaders method - self.assertEqual(task.response_headers, {}) - - self.server.application = orig_app - - - def test_multiple_start_response_calls(self): - # if start_response is called more than once with no exc_info - ignore, task = self._getFakeAppAndTask() - task.wrote_header = 1 - - self.assertRaises(AssertionError, self.server.executeRequest, task) - - - def test_start_response_with_headers_sent(self): - # If headers have been sent it raises the exception - orig_app = self.server.application - self.server.application, task = self._getFakeAppAndTask() - - # If headers have already been written an exception is raised - task.wrote_header = 1 - self.assertRaises(DummyException, self.server.executeRequest, task) - - self.server.application = orig_app - -class SleepingTask(object): - - def service(self): - sleep(0.2) - - def cancel(self): - pass - - def defer(self): - pass - - -class Conflict(Exception): - """ - Pseudo ZODB conflict error. - """ - -ERROR_RESPONSE = "error occurred" -RESPONSE = "normal response" - -class DummyException(Exception): - value = "Dummy Exception to test start_response" - def __str__(self): - return repr(self.value) - -class PublicationWithConflict(DefaultPublication): - - def handleException(self, object, request, exc_info, retry_allowed=1): - if exc_info[0] is Conflict and retry_allowed: - # This simulates a ZODB retry. - raise Retry(exc_info) - else: - DefaultPublication.handleException(self, object, request, exc_info, - retry_allowed) - -class Accepted(Exception): - pass - -class tested_object(object): - """Docstring required by publisher.""" - tries = 0 - - def __call__(self, REQUEST): - return 'URL invoked: %s' % REQUEST.URL - - def redirect_method(self, REQUEST): - "Generates a redirect using the redirect() method." - REQUEST.response.redirect("/redirect") - - def redirect_exception(self): - "Generates a redirect using an exception." - raise Redirect("/exception") - - def conflict(self, REQUEST, wait_tries): - """ - Returns 202 status only after (wait_tries) tries. - """ - if self.tries >= int(wait_tries): - raise Accepted - else: - self.tries += 1 - raise Conflict - - def proxy(self, REQUEST): - """Behaves like a real proxy response.""" - REQUEST.response.addHeader('Server', 'Fake/1.0') - REQUEST.response.addHeader('Date', 'Thu, 01 Apr 2010 12:00:00 GMT') - return 'Proxied Content' - -class WSGIInfo(object): - """Docstring required by publisher""" - - def __call__(self, REQUEST): - """Return a list of variables beginning with 'wsgi.'""" - r = [] - for name in REQUEST.keys(): - if name.startswith('wsgi.'): - r.append(name) - return ' '.join(r) - - def version(self, REQUEST): - """Return WSGI version""" - return str(REQUEST['wsgi.version']) - - def url_scheme(self, REQUEST): - """Return WSGI URL scheme""" - return REQUEST['wsgi.url_scheme'] - - def multithread(self, REQUEST): - """Return WSGI multithreadedness""" - return str(bool(REQUEST['wsgi.multithread'])) - - def multiprocess(self, REQUEST): - """Return WSGI multiprocessedness""" - return str(bool(REQUEST['wsgi.multiprocess'])) - - def run_once(self, REQUEST): - """Return whether WSGI app is invoked only once or not""" - return str(bool(REQUEST['wsgi.run_once'])) - - def proxy_scheme(self, REQUEST): - """Return the proxy scheme.""" - return REQUEST['waitress.proxy.scheme'] - - def proxy_host(self, REQUEST): - """Return the proxy host.""" - return REQUEST['waitress.proxy.host'] - diff --git a/waitress/tests/test_server.py b/waitress/tests/test_server.py index 3177d37..7d4cf1c 100644 --- a/waitress/tests/test_server.py +++ b/waitress/tests/test_server.py @@ -51,10 +51,10 @@ class TestWSGIHTTPServer(unittest.TestCase): result = inst.computeServerName('fred.flintstone.com') self.assertEqual(result, 'fred.flintstone.com') - def test_addTask(self): + def test_add_task(self): task = DummyTask() inst = self._makeOneWithMap() - inst.addTask(task) + inst.add_task(task) self.assertEqual(inst.task_dispatcher.tasks, [task]) self.assertFalse(task.serviced) @@ -152,7 +152,7 @@ class DummySock(object): class DummyTaskDispatcher(object): def __init__(self): self.tasks = [] - def addTask(self, task): + def add_task(self, task): self.tasks.append(task) class DummyTask(object): @@ -167,7 +167,7 @@ class DummyTask(object): self.serviced = True def write(self, val): self.written += val - def getEnvironment(self): + def get_environment(self): return {} class DummyAdj: diff --git a/waitress/tests/test_task.py b/waitress/tests/test_task.py index 1338091..cf52510 100644 --- a/waitress/tests/test_task.py +++ b/waitress/tests/test_task.py @@ -5,15 +5,15 @@ class TestThreadedTaskDispatcher(unittest.TestCase): from waitress.task import ThreadedTaskDispatcher return ThreadedTaskDispatcher() - def test_handlerThread_task_is_None(self): + def test_handler_thread_task_is_None(self): inst = self._makeOne() inst.threads[0] = True inst.queue.put(None) - inst.handlerThread(0) + inst.handler_thread(0) self.assertEqual(inst.stop_count, -1) self.assertEqual(inst.threads, {}) - def test_handlerThread_task_raises(self): + def test_handler_thread_task_raises(self): from waitress.compat import NativeIO from waitress.task import JustTesting inst = self._makeOne() @@ -21,52 +21,52 @@ class TestThreadedTaskDispatcher(unittest.TestCase): inst.stderr = NativeIO() task = DummyTask(JustTesting) inst.queue.put(task) - inst.handlerThread(0) + inst.handler_thread(0) self.assertEqual(inst.stop_count, -1) self.assertEqual(inst.threads, {}) self.assertTrue(inst.stderr.getvalue()) - def test_setThread_count_increase(self): + def test_set_thread_count_increase(self): inst = self._makeOne() L = [] inst.start_new_thread = lambda *x: L.append(x) - inst.setThreadCount(1) - self.assertEqual(L, [(inst.handlerThread, (0,))]) + inst.set_thread_count(1) + self.assertEqual(L, [(inst.handler_thread, (0,))]) - def test_setThread_count_increase_with_existing(self): + def test_set_thread_count_increase_with_existing(self): inst = self._makeOne() L = [] inst.threads = {0:1} inst.start_new_thread = lambda *x: L.append(x) - inst.setThreadCount(2) - self.assertEqual(L, [(inst.handlerThread, (1,))]) + inst.set_thread_count(2) + self.assertEqual(L, [(inst.handler_thread, (1,))]) - def test_setThread_count_decrease(self): + def test_set_thread_count_decrease(self): inst = self._makeOne() inst.threads = {'a':1, 'b':2} - inst.setThreadCount(1) + inst.set_thread_count(1) self.assertEqual(inst.queue.qsize(), 1) self.assertEqual(inst.queue.get(), None) - def test_setThread_count_same(self): + def test_set_thread_count_same(self): inst = self._makeOne() L = [] inst.start_new_thread = lambda *x: L.append(x) inst.threads = {0:1} - inst.setThreadCount(1) + inst.set_thread_count(1) self.assertEqual(L, []) - def test_addTask(self): + def test_add_task(self): task = DummyTask() inst = self._makeOne() - inst.addTask(task) + inst.add_task(task) self.assertEqual(inst.queue.qsize(), 1) self.assertTrue(task.deferred) - def test_addTask_defer_raises(self): + def test_add_task_defer_raises(self): task = DummyTask(ValueError) inst = self._makeOne() - self.assertRaises(ValueError, inst.addTask, task) + self.assertRaises(ValueError, inst.add_task, task) self.assertEqual(inst.queue.qsize(), 0) self.assertTrue(task.deferred) self.assertTrue(task.cancelled) @@ -131,12 +131,12 @@ class TestHTTPTask(unittest.TestCase): inst = self._makeOne() self.assertEqual(inst.defer(), None) - def test_buildResponseHeader_v10_keepalive_no_content_length(self): + def test_build_response_header_v10_keepalive_no_content_length(self): inst = self._makeOne() inst.request_data = DummyParser() inst.request_data.headers['CONNECTION'] = 'keep-alive' inst.version = '1.0' - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 4) self.assertEqual(lines[0], b'HTTP/1.0 200 OK') @@ -146,13 +146,13 @@ class TestHTTPTask(unittest.TestCase): self.assertEqual(inst.close_on_finish, True) self.assertTrue(('Connection', 'close') in inst.response_headers) - def test_buildResponseHeader_v10_keepalive_with_content_length(self): + def test_build_response_header_v10_keepalive_with_content_length(self): inst = self._makeOne() inst.request_data = DummyParser() inst.request_data.headers['CONNECTION'] = 'keep-alive' inst.response_headers = [('Content-Length', '10')] inst.version = '1.0' - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 5) self.assertEqual(lines[0], b'HTTP/1.0 200 OK') @@ -162,12 +162,12 @@ class TestHTTPTask(unittest.TestCase): self.assertEqual(lines[4], b'Server: hithere') self.assertEqual(inst.close_on_finish, False) - def test_buildResponseHeader_v11_connection_closed_by_app(self): + def test_build_response_header_v11_connection_closed_by_app(self): inst = self._makeOne() inst.request_data = DummyParser() inst.version = '1.1' inst.response_headers = [('Connection', 'close')] - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 4) self.assertEqual(lines[0], b'HTTP/1.1 200 OK') @@ -177,12 +177,12 @@ class TestHTTPTask(unittest.TestCase): self.assertTrue(('Connection', 'close') in inst.response_headers) self.assertEqual(inst.close_on_finish, True) - def test_buildResponseHeader_v11_connection_closed_by_client(self): + def test_build_response_header_v11_connection_closed_by_client(self): inst = self._makeOne() inst.request_data = DummyParser() inst.version = '1.1' inst.request_data.headers['CONNECTION'] = 'close' - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 4) self.assertEqual(lines[0], b'HTTP/1.1 200 OK') @@ -192,12 +192,12 @@ class TestHTTPTask(unittest.TestCase): self.assertTrue(('Connection', 'close') in inst.response_headers) self.assertEqual(inst.close_on_finish, True) - def test_buildResponseHeader_v11_connection_keepalive_by_client(self): + def test_build_response_header_v11_connection_keepalive_by_client(self): inst = self._makeOne() inst.request_data = DummyParser() inst.request_data.headers['CONNECTION'] = 'keep-alive' inst.version = '1.1' - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 4) self.assertEqual(lines[0], b'HTTP/1.1 200 OK') @@ -207,12 +207,12 @@ class TestHTTPTask(unittest.TestCase): self.assertTrue(('Connection', 'close') in inst.response_headers) self.assertEqual(inst.close_on_finish, True) - def test_buildResponseHeader_v11_transfer_encoding_nonchunked(self): + def test_build_response_header_v11_transfer_encoding_nonchunked(self): inst = self._makeOne() inst.request_data = DummyParser() inst.response_headers = [('Transfer-Encoding', 'notchunked')] inst.version = '1.1' - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 5) self.assertEqual(lines[0], b'HTTP/1.1 200 OK') @@ -223,12 +223,12 @@ class TestHTTPTask(unittest.TestCase): self.assertTrue(('Connection', 'close') in inst.response_headers) self.assertEqual(inst.close_on_finish, True) - def test_buildResponseHeader_v11_transfer_encoding_chunked(self): + def test_build_response_header_v11_transfer_encoding_chunked(self): inst = self._makeOne() inst.request_data = DummyParser() inst.response_headers = [('Transfer-Encoding', 'chunked')] inst.version = '1.1' - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 4) self.assertEqual(lines[0], b'HTTP/1.1 200 OK') @@ -237,12 +237,12 @@ class TestHTTPTask(unittest.TestCase): self.assertEqual(lines[3], b'Transfer-Encoding: chunked') self.assertEqual(inst.close_on_finish, False) - def test_buildResponseHeader_v11_304_headersonly(self): + def test_build_response_header_v11_304_headersonly(self): inst = self._makeOne() inst.request_data = DummyParser() inst.status = '304 OK' inst.version = '1.1' - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 3) self.assertEqual(lines[0], b'HTTP/1.1 304 OK') @@ -250,11 +250,11 @@ class TestHTTPTask(unittest.TestCase): self.assertEqual(lines[2], b'Server: hithere') self.assertEqual(inst.close_on_finish, False) - def test_buildResponseHeader_v11_200_no_content_length(self): + def test_build_response_header_v11_200_no_content_length(self): inst = self._makeOne() inst.request_data = DummyParser() inst.version = '1.1' - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 4) self.assertEqual(lines[0], b'HTTP/1.1 200 OK') @@ -264,11 +264,11 @@ class TestHTTPTask(unittest.TestCase): self.assertEqual(inst.close_on_finish, True) self.assertTrue(('Connection', 'close') in inst.response_headers) - def test_buildResponseHeader_unrecognized_http_version(self): + def test_build_response_header_unrecognized_http_version(self): inst = self._makeOne() inst.request_data = DummyParser() inst.version = '8.1' - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 4) self.assertEqual(lines[0], b'HTTP/8.1 200 OK') @@ -278,12 +278,12 @@ class TestHTTPTask(unittest.TestCase): self.assertEqual(inst.close_on_finish, True) self.assertTrue(('Connection', 'close') in inst.response_headers) - def test_buildResponseHeader_via_added(self): + def test_build_response_header_via_added(self): inst = self._makeOne() inst.request_data = DummyParser() inst.version = '1.0' inst.response_headers = [('Server', 'abc')] - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 5) self.assertEqual(lines[0], b'HTTP/1.0 200 OK') @@ -292,12 +292,12 @@ class TestHTTPTask(unittest.TestCase): self.assertEqual(lines[3], b'Server: abc') self.assertEqual(lines[4], b'Via: hithere') - def test_buildResponseHeader_date_exists(self): + def test_build_response_header_date_exists(self): inst = self._makeOne() inst.request_data = DummyParser() inst.version = '1.0' inst.response_headers = [('Date', 'date')] - result = inst.buildResponseHeader() + result = inst.build_response_header() lines = filter_lines(result) self.assertEqual(len(lines), 4) self.assertEqual(lines[0], b'HTTP/1.0 200 OK') @@ -308,14 +308,14 @@ class TestHTTPTask(unittest.TestCase): def test_getEnviron_already_cached(self): inst = self._makeOne() inst.environ = object() - self.assertEqual(inst.getEnvironment(), inst.environ) + self.assertEqual(inst.get_environment(), inst.environ) def test_getEnviron_path_startswith_more_than_one_slash(self): inst = self._makeOne() request_data = DummyParser() request_data.path = '///abc' inst.request_data = request_data - environ = inst.getEnvironment() + environ = inst.get_environment() self.assertEqual(environ['PATH_INFO'], '/abc') def test_getEnviron_path_empty(self): @@ -323,14 +323,14 @@ class TestHTTPTask(unittest.TestCase): request_data = DummyParser() request_data.path = '' inst.request_data = request_data - environ = inst.getEnvironment() + environ = inst.get_environment() self.assertEqual(environ['PATH_INFO'], '/') def test_getEnviron_no_query(self): inst = self._makeOne() request_data = DummyParser() inst.request_data = request_data - environ = inst.getEnvironment() + environ = inst.get_environment() self.assertFalse('QUERY_STRING' in environ) def test_getEnviron_with_query(self): @@ -338,7 +338,7 @@ class TestHTTPTask(unittest.TestCase): request_data = DummyParser() request_data.query = 'abc' inst.request_data = request_data - environ = inst.getEnvironment() + environ = inst.get_environment() self.assertEqual(environ['QUERY_STRING'], 'abc') def test_getEnviron_values(self): @@ -349,7 +349,7 @@ class TestHTTPTask(unittest.TestCase): 'X_FOO':'BAR'} request_data.query = 'abc' inst.request_data = request_data - environ = inst.getEnvironment() + environ = inst.get_environment() self.assertEqual(environ['REQUEST_METHOD'], 'GET') self.assertEqual(environ['SERVER_PORT'], '80') self.assertEqual(environ['SERVER_NAME'], 'localhost') |