Skip to content

Commit

Permalink
100% coverage for everything in src/zope/server/http/tests/. Also fix…
Browse files Browse the repository at this point in the history
… usage of deprecated assertion methods.
  • Loading branch information
jamadden committed Oct 26, 2017
1 parent b147a0c commit 5bfb79e
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 140 deletions.
10 changes: 0 additions & 10 deletions src/zope/server/http/tests/test_commonaccesslogger.py
Expand Up @@ -35,13 +35,3 @@ def test_default_constructor(self):
# compute_timezone_for_log
# log_date_string
# log


def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestCommonAccessLogger))
return suite


if __name__ == '__main__':
unittest.main(defaultTest="test_suite")
10 changes: 1 addition & 9 deletions src/zope/server/http/tests/test_httpdate.py
Expand Up @@ -22,12 +22,4 @@ class Tests(unittest.TestCase):
def testDateRoundTrip(self):
from time import time
t = int(time())
self.assertEquals(t, parse_http_date(build_http_date(t)))


def test_suite():
loader = unittest.TestLoader()
return loader.loadTestsFromTestCase(Tests)

if __name__=='__main__':
unittest.TextTestRunner().run(test_suite())
self.assertEqual(t, parse_http_date(build_http_date(t)))
37 changes: 15 additions & 22 deletions src/zope/server/http/tests/test_httprequestparser.py
Expand Up @@ -29,12 +29,12 @@ def setUp(self):

def feed(self, data):
parser = self.parser
for n in range(100): # make sure we never loop forever
for _ in range(100): # make sure we never loop forever
consumed = parser.received(data)
data = data[consumed:]
if parser.completed:
return
raise ValueError('Looping')
raise AssertionError('Looping too far')

def testSimpleGET(self):
data = b"""\
Expand All @@ -47,14 +47,14 @@ def testSimpleGET(self):
"""
parser = self.parser
self.feed(data)
self.failUnless(parser.completed)
self.assertTrue(parser.completed)
self.assertEqual(parser.version, '8.4')
self.failIf(parser.empty)
self.assertFalse(parser.empty)
self.assertEqual(parser.headers,
{'FIRSTNAME': 'mickey',
'LASTNAME': 'Mouse',
'CONTENT_LENGTH': '7',
})
})
self.assertEqual(parser.path, '/foobar')
self.assertEqual(parser.command, 'GET')
self.assertEqual(parser.query, None)
Expand All @@ -75,12 +75,12 @@ def testComplexGET(self):
self.feed(data)
self.assertEqual(parser.command, 'GET')
self.assertEqual(parser.version, '8.4')
self.failIf(parser.empty)
self.assertFalse(parser.empty)
self.assertEqual(parser.headers,
{'FIRSTNAME': 'mickey',
'LASTNAME': 'Mouse',
'CONTENT_LENGTH': '10',
})
})
# path should be utf-8 encoded
self.assertEqual(parser.path, '/foo/a++/ä=&a:int')
self.assertEqual(parser.query,
Expand All @@ -96,12 +96,12 @@ def testProxyGET(self):
"""
parser = self.parser
self.feed(data)
self.failUnless(parser.completed)
self.assertTrue(parser.completed)
self.assertEqual(parser.version, '8.4')
self.failIf(parser.empty)
self.assertFalse(parser.empty)
self.assertEqual(parser.headers,
{'CONTENT_LENGTH': '7',
})
})
self.assertEqual(parser.path, '/foobar')
self.assertEqual(parser.command, 'GET')
self.assertEqual(parser.proxy_scheme, 'https')
Expand All @@ -123,16 +123,9 @@ def testDuplicateHeaders(self):
Hello.
"""
self.feed(data)
self.failUnless(self.parser.completed)
self.assertTrue(self.parser.completed)
self.assertEqual(self.parser.headers, {
'CONTENT_LENGTH': '7',
'X_FORWARDED_FOR':
'10.11.12.13, unknown,127.0.0.1, 255.255.255.255',
})

def test_suite():
loader = unittest.TestLoader()
return loader.loadTestsFromTestCase(Tests)

if __name__=='__main__':
unittest.TextTestRunner().run(test_suite())
'CONTENT_LENGTH': '7',
'X_FORWARDED_FOR':
'10.11.12.13, unknown,127.0.0.1, 255.255.255.255',
})
88 changes: 38 additions & 50 deletions src/zope/server/http/tests/test_httpserver.py
Expand Up @@ -15,6 +15,7 @@
"""
import unittest
from asyncore import socket_map, poll
from time import sleep, time
import socket

from threading import Thread, Event
Expand All @@ -27,8 +28,6 @@
from six.moves.http_client import HTTPConnection
from six.moves.http_client import HTTPResponse as ClientHTTPResponse

from time import sleep, time

td = ThreadedTaskDispatcher()

LOCALHOST = '127.0.0.1'
Expand All @@ -49,7 +48,7 @@ def service(self):
sleep(0.2)

def cancel(self):
pass
raise AssertionError("This should never be called")

def defer(self):
pass
Expand Down Expand Up @@ -79,14 +78,14 @@ def executeRequest(self, task):
if len(socket_map) != 1:
# Let sockets die off.
# TODO tests should be more careful to clear the socket map.
poll(0.1)
poll(0.1) # pragma: no cover
self.orig_map_size = len(socket_map)
self.hook_asyncore_error()
self.server = EchoHTTPServer(LOCALHOST, SERVER_PORT,
task_dispatcher=td, adj=my_adj)
if CONNECT_TO_PORT == 0:
self.port = self.server.socket.getsockname()[1]
else:
else: # pragma: no cover
self.port = CONNECT_TO_PORT
self.run_loop = 1
self.counter = 0
Expand All @@ -95,7 +94,7 @@ def executeRequest(self, task):
self.thread.setDaemon(True)
self.thread.start()
self.thread_started.wait(10.0)
self.assert_(self.thread_started.isSet())
self.assertTrue(self.thread_started.isSet())

def tearDown(self):
self.run_loop = 0
Expand Down Expand Up @@ -132,26 +131,26 @@ def testEchoResponse(self, h=None, add_headers=None, body=b''):
# headers["Content-Length"] = str(int(len(body)))
h.request("GET", "/", body, headers)
response = h.getresponse()
self.failUnlessEqual(int(response.status), 200)
self.assertEqual(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)
self.assertEqual(length, len(response_body))
self.assertEqual(response_body, body)
# HTTP 1.1 requires the server and date header.
self.assertEqual(response.getheader('server'), 'zope.server.http')
self.assert_(response.getheader('date') is not None)
self.assertIsNotNone(response.getheader('date'))

def testMultipleRequestsWithoutBody(self):
# Tests the use of multiple requests in a single connection.
h = HTTPConnection(LOCALHOST, self.port)
for n in range(3):
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):
for _n in range(3):
self.testEchoResponse(h, body=b'Hello, world!')
self.testEchoResponse(h, {'Connection': 'close'})

Expand Down Expand Up @@ -179,11 +178,11 @@ def testPipelining(self):
expect_body = ("Response #%d\r\n" % (n + 1)).encode('ascii')
response = ClientHTTPResponse(sock)
response.begin()
self.failUnlessEqual(int(response.status), 200)
self.assertEqual(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)
self.assertEqual(length, len(response_body))
self.assertEqual(response_body, expect_body)

def testWithoutCRLF(self):
# Tests the use of just newlines rather than CR/LFs.
Expand All @@ -199,11 +198,11 @@ def testWithoutCRLF(self):
sock.send(s.encode('ascii'))
response = ClientHTTPResponse(sock)
response.begin()
self.failUnlessEqual(int(response.status), 200)
self.assertEqual(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.encode('ascii'))
self.assertEqual(length, len(data))
self.assertEqual(response_body, data.encode("ascii"))

def testLargeBody(self):
# Tests the use of multiple requests in a single connection.
Expand All @@ -224,7 +223,7 @@ def testManyClients(self):
# raise socket.error, msg
# error: (10055, 'No buffer space available')
nconn = 50
if sys.platform == 'win32':
if sys.platform == 'win32': # pragma: no cover
platform = sys.getwindowsversion()[3]
if platform < 2:
# 0 is Win32s on Windows 3.1
Expand All @@ -237,7 +236,7 @@ def testManyClients(self):
nconn = 20

conns = []
for n in range(nconn):
for _n in range(nconn):
#print('open %s %s' % (n, clock()))
h = HTTPConnection(LOCALHOST, self.port)
#h.debuglevel = 1
Expand All @@ -250,31 +249,31 @@ def testManyClients(self):
responses = []
for h in conns:
response = h.getresponse()
self.failUnlessEqual(response.status, 200)
self.assertEqual(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):
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)
self.assertEqual(len(td.threads), 1)

def testChunkingRequestWithoutContent(self):
h = HTTPConnection(LOCALHOST, self.port)
h.request("GET", "/", headers={"Accept": "text/plain",
"Transfer-Encoding": "chunked"})
h.send(b"0\r\n\r\n")
response = h.getresponse()
self.failUnlessEqual(int(response.status), 200)
self.assertEqual(int(response.status), 200)
response_body = response.read()
self.failUnlessEqual(response_body, b'')
self.assertEqual(response_body, b'')

def testChunkingRequestWithContent(self):
control_line = b"20;\r\n" # 20 hex = 32 dec
Expand All @@ -284,14 +283,14 @@ def testChunkingRequestWithContent(self):
h = HTTPConnection(LOCALHOST, self.port)
h.request("GET", "/", headers={"Accept": "text/plain",
"Transfer-Encoding": "chunked"})
for n in range(12):
for _n in range(12):
h.send(control_line)
h.send(s)
h.send(b"0\r\n\r\n")
response = h.getresponse()
self.failUnlessEqual(int(response.status), 200)
self.assertEqual(int(response.status), 200)
response_body = response.read()
self.failUnlessEqual(response_body, expect)
self.assertEqual(response_body, expect)

def testKeepaliveHttp10(self):
# Handling of Keep-Alive within HTTP 1.0
Expand All @@ -305,11 +304,11 @@ def testKeepaliveHttp10(self):
sock.send(s.encode('ascii'))
response = ClientHTTPResponse(sock)
response.begin()
self.failUnlessEqual(int(response.status), 200)
self.assertEqual(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')
self.assertNotEqual(connection, 'Keep-Alive')

# If header Connection: Keep-Alive is explicitly sent,
# we want to keept the connection open, we also need to return
Expand All @@ -325,9 +324,9 @@ def testKeepaliveHttp10(self):
sock.send(s.encode('ascii'))
response = ClientHTTPResponse(sock)
response.begin()
self.failUnlessEqual(int(response.status), 200)
self.assertEqual(int(response.status), 200)
connection = response.getheader('Connection', '')
self.failUnlessEqual(connection, 'Keep-Alive')
self.assertEqual(connection, 'Keep-Alive')

def testKeepaliveHttp11(self):
# Handling of Keep-Alive within HTTP 1.1
Expand All @@ -343,8 +342,8 @@ def testKeepaliveHttp11(self):
sock.send(s.encode('ascii'))
response = ClientHTTPResponse(sock)
response.begin()
self.failUnlessEqual(int(response.status), 200)
self.failUnless(response.getheader('connection') != 'close')
self.assertEqual(int(response.status), 200)
self.assertNotEqual(response.getheader('connection'), 'close')

# Explicitly set keep-alive
data = "Default: Keep me alive"
Expand All @@ -358,15 +357,15 @@ def testKeepaliveHttp11(self):
sock.send(s.encode('ascii'))
response = ClientHTTPResponse(sock)
response.begin()
self.failUnlessEqual(int(response.status), 200)
self.failUnless(response.getheader('connection') != 'close')
self.assertEqual(int(response.status), 200)
self.assertNotEqual(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.assertEqual(int(response.status), 200)
# self.failUnless(response.getheader('connection') != 'close')

# specifying Connection: close explicitly
Expand All @@ -381,8 +380,8 @@ def testKeepaliveHttp11(self):
sock.send(s.encode('ascii'))
response = ClientHTTPResponse(sock)
response.begin()
self.failUnlessEqual(int(response.status), 200)
self.failUnlessEqual(response.getheader('connection'), 'close')
self.assertEqual(int(response.status), 200)
self.assertEqual(response.getheader('connection'), 'close')


class TestHTTPServer(unittest.TestCase):
Expand All @@ -401,14 +400,3 @@ def __init__(self):
def test_getExtraLogMessage(self):
self.assertEqual(self.server.getExtraLogMessage(),
'\n\tURL: http://example.com:8080/')


def test_suite():
loader = unittest.TestLoader()
return unittest.TestSuite([
loader.loadTestsFromTestCase(Tests),
loader.loadTestsFromTestCase(TestHTTPServer),
])

if __name__=='__main__':
unittest.TextTestRunner().run(test_suite())

0 comments on commit 5bfb79e

Please sign in to comment.