summaryrefslogtreecommitdiff
path: root/cherrypy
diff options
context:
space:
mode:
authorJason R. Coombs <jaraco@jaraco.com>2019-09-03 21:37:24 -0400
committerJason R. Coombs <jaraco@jaraco.com>2019-09-03 21:38:03 -0400
commit1a6f0ecfe0cce4c628d35789fa72dc1ff14d66f4 (patch)
tree02de6c241ff962f468f4e0ad067135811f2a2298 /cherrypy
parent86d9a291eb490f601cffb6ab773cca3a853b3432 (diff)
parentb68087d0d62a8817e90a509a89afad0268052bc2 (diff)
downloadcherrypy-git-1a6f0ecfe0cce4c628d35789fa72dc1ff14d66f4.tar.gz
Merge branch 'master' into bugfix/1779
Diffstat (limited to 'cherrypy')
-rw-r--r--cherrypy/_cperror.py4
-rw-r--r--cherrypy/_cpmodpy.py2
-rw-r--r--cherrypy/_cpwsgi.py2
-rw-r--r--cherrypy/lib/caching.py3
-rw-r--r--cherrypy/lib/cpstats.py2
-rw-r--r--cherrypy/lib/sessions.py2
-rw-r--r--cherrypy/test/helper.py3
-rw-r--r--cherrypy/test/logtest.py7
-rw-r--r--cherrypy/test/test_bus.py529
-rw-r--r--cherrypy/test/test_caching.py2
-rw-r--r--cherrypy/test/test_config.py2
-rw-r--r--cherrypy/test/test_core.py7
-rw-r--r--cherrypy/test/test_httputil.py17
-rw-r--r--cherrypy/test/test_logging.py313
-rw-r--r--cherrypy/test/test_states.py78
-rw-r--r--cherrypy/test/test_tutorials.py3
16 files changed, 541 insertions, 435 deletions
diff --git a/cherrypy/_cperror.py b/cherrypy/_cperror.py
index 64ca8bb8..4e727682 100644
--- a/cherrypy/_cperror.py
+++ b/cherrypy/_cperror.py
@@ -34,6 +34,7 @@ user:
POST should not raise this error
305 Use Proxy Confirm with the user
307 Temporary Redirect Confirm with the user
+308 Permanent Redirect No confirmation
===== ================================= ===========
However, browsers have historically implemented these restrictions poorly;
@@ -254,7 +255,7 @@ class HTTPRedirect(CherryPyException):
response = cherrypy.serving.response
response.status = status = self.status
- if status in (300, 301, 302, 303, 307):
+ if status in (300, 301, 302, 303, 307, 308):
response.headers['Content-Type'] = 'text/html;charset=utf-8'
# "The ... URI SHOULD be given by the Location field
# in the response."
@@ -269,6 +270,7 @@ class HTTPRedirect(CherryPyException):
302: 'This resource resides temporarily at ',
303: 'This resource can be found at ',
307: 'This resource has moved temporarily to ',
+ 308: 'This resource has been moved to ',
}[status]
msg += '<a href=%s>%s</a>.'
msgs = [
diff --git a/cherrypy/_cpmodpy.py b/cherrypy/_cpmodpy.py
index 85db4017..0e608c48 100644
--- a/cherrypy/_cpmodpy.py
+++ b/cherrypy/_cpmodpy.py
@@ -195,7 +195,7 @@ def handler(req):
path = req.uri
qs = req.args or ''
reqproto = req.protocol
- headers = list(req.headers_in.items())
+ headers = list(req.headers_in.copy().items())
rfile = _ReadOnlyRequest(req)
prev = None
diff --git a/cherrypy/_cpwsgi.py b/cherrypy/_cpwsgi.py
index c2d36f67..b4f55fd6 100644
--- a/cherrypy/_cpwsgi.py
+++ b/cherrypy/_cpwsgi.py
@@ -23,7 +23,7 @@ def downgrade_wsgi_ux_to_1x(environ):
env1x = {}
url_encoding = environ[ntou('wsgi.url_encoding')]
- for k, v in list(environ.items()):
+ for k, v in environ.copy().items():
if k in [ntou('PATH_INFO'), ntou('SCRIPT_NAME'), ntou('QUERY_STRING')]:
v = v.encode(url_encoding)
elif isinstance(v, str):
diff --git a/cherrypy/lib/caching.py b/cherrypy/lib/caching.py
index 38bd636e..08d2d8e4 100644
--- a/cherrypy/lib/caching.py
+++ b/cherrypy/lib/caching.py
@@ -196,8 +196,7 @@ class MemoryCache(Cache):
now = time.time()
# Must make a copy of expirations so it doesn't change size
# during iteration
- items = list(self.expirations.items())
- for expiration_time, objects in items:
+ for expiration_time, objects in self.expirations.copy().items():
if expiration_time <= now:
for obj_size, uri, sel_header_values in objects:
try:
diff --git a/cherrypy/lib/cpstats.py b/cherrypy/lib/cpstats.py
index 28510887..158b01a0 100644
--- a/cherrypy/lib/cpstats.py
+++ b/cherrypy/lib/cpstats.py
@@ -205,7 +205,7 @@ if not hasattr(logging, 'statistics'):
def extrapolate_statistics(scope):
"""Return an extrapolated copy of the given scope."""
c = {}
- for k, v in list(scope.items()):
+ for k, v in scope.copy().items():
if isinstance(v, dict):
v = extrapolate_statistics(v)
elif isinstance(v, (list, tuple)):
diff --git a/cherrypy/lib/sessions.py b/cherrypy/lib/sessions.py
index a089fc94..5b3328f2 100644
--- a/cherrypy/lib/sessions.py
+++ b/cherrypy/lib/sessions.py
@@ -403,7 +403,7 @@ class RamSession(Session):
"""Clean up expired sessions."""
now = self.now()
- for _id, (data, expiration_time) in list(self.cache.items()):
+ for _id, (data, expiration_time) in self.cache.copy().items():
if expiration_time <= now:
try:
del self.cache[_id]
diff --git a/cherrypy/test/helper.py b/cherrypy/test/helper.py
index 85c8f7eb..a9109892 100644
--- a/cherrypy/test/helper.py
+++ b/cherrypy/test/helper.py
@@ -93,8 +93,7 @@ class LocalSupervisor(Supervisor):
cherrypy.engine.exit()
- servers_copy = list(getattr(cherrypy, 'servers', {}).items())
- for name, server in servers_copy:
+ for name, server in getattr(cherrypy, 'servers', {}).copy().items():
server.unsubscribe()
del cherrypy.servers[name]
diff --git a/cherrypy/test/logtest.py b/cherrypy/test/logtest.py
index c6edc5d0..344be987 100644
--- a/cherrypy/test/logtest.py
+++ b/cherrypy/test/logtest.py
@@ -4,6 +4,8 @@ import sys
import time
from uuid import UUID
+import pytest
+
from cherrypy._cpcompat import text_or_bytes
@@ -43,6 +45,7 @@ class LogCase(object):
unique enough from normal log output to use for marker identification.
"""
+ interactive = False
logfile = None
lastmarker = None
markerPrefix = b'test suite marker: '
@@ -52,7 +55,7 @@ class LogCase(object):
print(' ERROR: %s' % msg)
if not self.interactive:
- raise self.failureException(msg)
+ raise pytest.fail(msg)
p = (' Show: '
'[L]og [M]arker [P]attern; '
@@ -84,7 +87,7 @@ class LogCase(object):
# return without raising the normal exception
return
elif i == 'R':
- raise self.failureException(msg)
+ raise pytest.fail(msg)
elif i == 'X':
self.exit()
sys.stdout.write(p + ' ')
diff --git a/cherrypy/test/test_bus.py b/cherrypy/test/test_bus.py
index 12a516c9..83d89a6e 100644
--- a/cherrypy/test/test_bus.py
+++ b/cherrypy/test/test_bus.py
@@ -1,288 +1,313 @@
+"""Publish-subscribe bus tests."""
+# pylint: disable=redefined-outer-name
+
import threading
import time
import unittest.mock
+import pytest
+
from cherrypy.process import wspbus
-msg = 'Listener %d on channel %s: %s.'
+msg = 'Listener %d on channel %s: %s.' # pylint: disable=invalid-name
+
+
+@pytest.fixture
+def bus():
+ """Return a wspbus instance."""
+ return wspbus.Bus()
+
+
+@pytest.fixture
+def log_tracker(bus):
+ """Return an instance of bus log tracker."""
+ class LogTracker: # pylint: disable=too-few-public-methods
+ """Bus log tracker."""
+
+ log_entries = []
+
+ def __init__(self, bus):
+ def logit(msg, level): # pylint: disable=unused-argument
+ self.log_entries.append(msg)
+ bus.subscribe('log', logit)
+
+ return LogTracker(bus)
+
+
+@pytest.fixture
+def listener():
+ """Return an instance of bus response tracker."""
+ class Listner: # pylint: disable=too-few-public-methods
+ """Bus handler return value tracker."""
+
+ responses = []
+
+ def get_listener(self, channel, index):
+ """Return an argument tracking listener."""
+ def listener(arg=None):
+ self.responses.append(msg % (index, channel, arg))
+ return listener
+
+ return Listner()
-class PublishSubscribeTests(unittest.TestCase):
+def test_builtin_channels(bus, listener):
+ """Test that built-in channels trigger corresponding listeners."""
+ expected = []
- def get_listener(self, channel, index):
- def listener(arg=None):
- self.responses.append(msg % (index, channel, arg))
- return listener
+ for channel in bus.listeners:
+ for index, priority in enumerate([100, 50, 0, 51]):
+ bus.subscribe(
+ channel,
+ listener.get_listener(channel, index),
+ priority,
+ )
- def test_builtin_channels(self):
- b = wspbus.Bus()
+ for channel in bus.listeners:
+ bus.publish(channel)
+ expected.extend([msg % (i, channel, None) for i in (2, 1, 3, 0)])
+ bus.publish(channel, arg=79347)
+ expected.extend([msg % (i, channel, 79347) for i in (2, 1, 3, 0)])
- self.responses, expected = [], []
+ assert listener.responses == expected
- for channel in b.listeners:
- for index, priority in enumerate([100, 50, 0, 51]):
- b.subscribe(channel,
- self.get_listener(channel, index), priority)
- for channel in b.listeners:
- b.publish(channel)
- expected.extend([msg % (i, channel, None) for i in (2, 1, 3, 0)])
- b.publish(channel, arg=79347)
- expected.extend([msg % (i, channel, 79347) for i in (2, 1, 3, 0)])
+def test_custom_channels(bus, listener):
+ """Test that custom pub-sub channels work as built-in ones."""
+ expected = []
- self.assertEqual(self.responses, expected)
+ custom_listeners = ('hugh', 'louis', 'dewey')
+ for channel in custom_listeners:
+ for index, priority in enumerate([None, 10, 60, 40]):
+ bus.subscribe(
+ channel,
+ listener.get_listener(channel, index),
+ priority,
+ )
- def test_custom_channels(self):
- b = wspbus.Bus()
+ for channel in custom_listeners:
+ bus.publish(channel, 'ah so')
+ expected.extend(msg % (i, channel, 'ah so') for i in (1, 3, 0, 2))
+ bus.publish(channel)
+ expected.extend(msg % (i, channel, None) for i in (1, 3, 0, 2))
- self.responses, expected = [], []
+ assert listener.responses == expected
- custom_listeners = ('hugh', 'louis', 'dewey')
- for channel in custom_listeners:
- for index, priority in enumerate([None, 10, 60, 40]):
- b.subscribe(channel,
- self.get_listener(channel, index), priority)
- for channel in custom_listeners:
- b.publish(channel, 'ah so')
- expected.extend([msg % (i, channel, 'ah so')
- for i in (1, 3, 0, 2)])
- b.publish(channel)
- expected.extend([msg % (i, channel, None) for i in (1, 3, 0, 2)])
+def test_listener_errors(bus, listener):
+ """Test that unhandled exceptions raise channel failures."""
+ expected = []
+ channels = [c for c in bus.listeners if c != 'log']
- self.assertEqual(self.responses, expected)
+ for channel in channels:
+ bus.subscribe(channel, listener.get_listener(channel, 1))
+ # This will break since the lambda takes no args.
+ bus.subscribe(channel, lambda: None, priority=20)
- def test_listener_errors(self):
- b = wspbus.Bus()
+ for channel in channels:
+ with pytest.raises(wspbus.ChannelFailures):
+ bus.publish(channel, 123)
+ expected.append(msg % (1, channel, 123))
- self.responses, expected = [], []
- channels = [c for c in b.listeners if c != 'log']
+ assert listener.responses == expected
- for channel in channels:
- b.subscribe(channel, self.get_listener(channel, 1))
- # This will break since the lambda takes no args.
- b.subscribe(channel, lambda: None, priority=20)
- for channel in channels:
- self.assertRaises(wspbus.ChannelFailures, b.publish, channel, 123)
- expected.append(msg % (1, channel, 123))
+def test_start(bus, listener, log_tracker):
+ """Test that bus start sequence calls all listeners."""
+ num = 3
+ for index in range(num):
+ bus.subscribe('start', listener.get_listener('start', index))
- self.assertEqual(self.responses, expected)
+ bus.start()
+ try:
+ # The start method MUST call all 'start' listeners.
+ assert (
+ set(listener.responses) ==
+ set(msg % (i, 'start', None) for i in range(num)))
+ # The start method MUST move the state to STARTED
+ # (or EXITING, if errors occur)
+ assert bus.state == bus.states.STARTED
+ # The start method MUST log its states.
+ assert log_tracker.log_entries == ['Bus STARTING', 'Bus STARTED']
+ finally:
+ # Exit so the atexit handler doesn't complain.
+ bus.exit()
-class BusMethodTests(unittest.TestCase):
+def test_stop(bus, listener, log_tracker):
+ """Test that bus stop sequence calls all listeners."""
+ num = 3
- def log(self, bus):
- self._log_entries = []
+ for index in range(num):
+ bus.subscribe('stop', listener.get_listener('stop', index))
- def logit(msg, level):
- self._log_entries.append(msg)
- bus.subscribe('log', logit)
+ bus.stop()
- def assertLog(self, entries):
- self.assertEqual(self._log_entries, entries)
+ # The stop method MUST call all 'stop' listeners.
+ assert (set(listener.responses) ==
+ set(msg % (i, 'stop', None) for i in range(num)))
- def get_listener(self, channel, index):
- def listener(arg=None):
- self.responses.append(msg % (index, channel, arg))
- return listener
+ # The stop method MUST move the state to STOPPED
+ assert bus.state == bus.states.STOPPED
- def test_start(self):
- b = wspbus.Bus()
- self.log(b)
+ # The stop method MUST log its states.
+ assert log_tracker.log_entries == ['Bus STOPPING', 'Bus STOPPED']
- self.responses = []
- num = 3
- for index in range(num):
- b.subscribe('start', self.get_listener('start', index))
- b.start()
- try:
- # The start method MUST call all 'start' listeners.
- self.assertEqual(
- set(self.responses),
- set([msg % (i, 'start', None) for i in range(num)]))
- # The start method MUST move the state to STARTED
- # (or EXITING, if errors occur)
- self.assertEqual(b.state, b.states.STARTED)
- # The start method MUST log its states.
- self.assertLog(['Bus STARTING', 'Bus STARTED'])
- finally:
- # Exit so the atexit handler doesn't complain.
- b.exit()
-
- def test_stop(self):
- b = wspbus.Bus()
- self.log(b)
-
- self.responses = []
- num = 3
- for index in range(num):
- b.subscribe('stop', self.get_listener('stop', index))
-
- b.stop()
-
- # The stop method MUST call all 'stop' listeners.
- self.assertEqual(set(self.responses),
- set([msg % (i, 'stop', None) for i in range(num)]))
- # The stop method MUST move the state to STOPPED
- self.assertEqual(b.state, b.states.STOPPED)
- # The stop method MUST log its states.
- self.assertLog(['Bus STOPPING', 'Bus STOPPED'])
-
- def test_graceful(self):
- b = wspbus.Bus()
- self.log(b)
-
- self.responses = []
- num = 3
- for index in range(num):
- b.subscribe('graceful', self.get_listener('graceful', index))
-
- b.graceful()
-
- # The graceful method MUST call all 'graceful' listeners.
- self.assertEqual(
- set(self.responses),
- set([msg % (i, 'graceful', None) for i in range(num)]))
- # The graceful method MUST log its states.
- self.assertLog(['Bus graceful'])
-
- def test_exit(self):
- b = wspbus.Bus()
- self.log(b)
-
- self.responses = []
- num = 3
- for index in range(num):
- b.subscribe('stop', self.get_listener('stop', index))
- b.subscribe('exit', self.get_listener('exit', index))
-
- b.exit()
-
- # The exit method MUST call all 'stop' listeners,
- # and then all 'exit' listeners.
- self.assertEqual(set(self.responses),
- set([msg % (i, 'stop', None) for i in range(num)] +
- [msg % (i, 'exit', None) for i in range(num)]))
- # The exit method MUST move the state to EXITING
- self.assertEqual(b.state, b.states.EXITING)
- # The exit method MUST log its states.
- self.assertLog(
+def test_graceful(bus, listener, log_tracker):
+ """Test that bus graceful state triggers all listeners."""
+ num = 3
+
+ for index in range(num):
+ bus.subscribe('graceful', listener.get_listener('graceful', index))
+
+ bus.graceful()
+
+ # The graceful method MUST call all 'graceful' listeners.
+ assert (
+ set(listener.responses) ==
+ set(msg % (i, 'graceful', None) for i in range(num)))
+
+ # The graceful method MUST log its states.
+ assert log_tracker.log_entries == ['Bus graceful']
+
+
+def test_exit(bus, listener, log_tracker):
+ """Test that bus exit sequence is correct."""
+ num = 3
+
+ for index in range(num):
+ bus.subscribe('stop', listener.get_listener('stop', index))
+ bus.subscribe('exit', listener.get_listener('exit', index))
+
+ bus.exit()
+
+ # The exit method MUST call all 'stop' listeners,
+ # and then all 'exit' listeners.
+ assert (set(listener.responses) ==
+ set([msg % (i, 'stop', None) for i in range(num)] +
+ [msg % (i, 'exit', None) for i in range(num)]))
+
+ # The exit method MUST move the state to EXITING
+ assert bus.state == bus.states.EXITING
+
+ # The exit method MUST log its states.
+ assert (log_tracker.log_entries ==
['Bus STOPPING', 'Bus STOPPED', 'Bus EXITING', 'Bus EXITED'])
- def test_wait(self):
- b = wspbus.Bus()
-
- def f(method):
- time.sleep(0.2)
- getattr(b, method)()
-
- flow = [
- ('start', [b.states.STARTED]),
- ('stop', [b.states.STOPPED]),
- ('start', [b.states.STARTING, b.states.STARTED]),
- ('exit', [b.states.EXITING]),
- ]
-
- for method, states in flow:
- threading.Thread(target=f, args=(method,)).start()
- b.wait(states)
-
- # The wait method MUST wait for the given state(s).
- if b.state not in states:
- self.fail('State %r not in %r' % (b.state, states))
-
- def test_wait_publishes_periodically(self):
- bus = wspbus.Bus()
- callback = unittest.mock.MagicMock()
- bus.subscribe('main', callback)
-
- def set_start():
- time.sleep(0.05)
- bus.start()
- threading.Thread(target=set_start).start()
- bus.wait(bus.states.STARTED, interval=0.01, channel='main')
- assert callback.call_count > 3
-
- def test_block(self):
- b = wspbus.Bus()
- self.log(b)
-
- def f():
- time.sleep(0.2)
- b.exit()
-
- def g():
- time.sleep(0.4)
- threading.Thread(target=f).start()
- threading.Thread(target=g).start()
- threads = [t for t in threading.enumerate() if not t.daemon]
- self.assertEqual(len(threads), 3)
-
- b.block()
-
- # The block method MUST wait for the EXITING state.
- self.assertEqual(b.state, b.states.EXITING)
- # The block method MUST wait for ALL non-main, non-daemon threads to
- # finish.
- threads = [t for t in threading.enumerate() if not t.daemon]
- self.assertEqual(len(threads), 1)
- # The last message will mention an indeterminable thread name; ignore
- # it
- self.assertEqual(self._log_entries[:-1],
- ['Bus STOPPING', 'Bus STOPPED',
- 'Bus EXITING', 'Bus EXITED',
- 'Waiting for child threads to terminate...'])
-
- def test_start_with_callback(self):
- b = wspbus.Bus()
- self.log(b)
- try:
- events = []
-
- def f(*args, **kwargs):
- events.append(('f', args, kwargs))
-
- def g():
- events.append('g')
- b.subscribe('start', g)
- b.start_with_callback(f, (1, 3, 5), {'foo': 'bar'})
- # Give wait() time to run f()
- time.sleep(0.2)
-
- # The callback method MUST wait for the STARTED state.
- self.assertEqual(b.state, b.states.STARTED)
- # The callback method MUST run after all start methods.
- self.assertEqual(events, ['g', ('f', (1, 3, 5), {'foo': 'bar'})])
- finally:
- b.exit()
-
- def test_log(self):
- b = wspbus.Bus()
- self.log(b)
- self.assertLog([])
-
- # Try a normal message.
- expected = []
- for msg in ["O mah darlin'"] * 3 + ['Clementiiiiiiiine']:
- b.log(msg)
- expected.append(msg)
- self.assertLog(expected)
-
- # Try an error message
- try:
- foo
- except NameError:
- b.log('You are lost and gone forever', traceback=True)
- lastmsg = self._log_entries[-1]
- if 'Traceback' not in lastmsg or 'NameError' not in lastmsg:
- self.fail('Last log message %r did not contain '
- 'the expected traceback.' % lastmsg)
- else:
- self.fail('NameError was not raised as expected.')
-
-
-if __name__ == '__main__':
- unittest.main()
+
+def test_wait(bus):
+ """Test that bus wait awaits for states."""
+ def f(method): # pylint: disable=invalid-name
+ time.sleep(0.2)
+ getattr(bus, method)()
+
+ flow = [
+ ('start', [bus.states.STARTED]),
+ ('stop', [bus.states.STOPPED]),
+ ('start', [bus.states.STARTING, bus.states.STARTED]),
+ ('exit', [bus.states.EXITING]),
+ ]
+
+ for method, states in flow:
+ threading.Thread(target=f, args=(method,)).start()
+ bus.wait(states)
+
+ # The wait method MUST wait for the given state(s).
+ assert bus.state in states, 'State %r not in %r' % (bus.state, states)
+
+
+def test_wait_publishes_periodically(bus):
+ """Test that wait publishes each tick."""
+ callback = unittest.mock.MagicMock()
+ bus.subscribe('main', callback)
+
+ def set_start():
+ time.sleep(0.05)
+ bus.start()
+ threading.Thread(target=set_start).start()
+ bus.wait(bus.states.STARTED, interval=0.01, channel='main')
+ assert callback.call_count > 3
+
+
+def test_block(bus, log_tracker):
+ """Test that bus block waits for exiting."""
+ def f(): # pylint: disable=invalid-name
+ time.sleep(0.2)
+ bus.exit()
+
+ def g(): # pylint: disable=invalid-name
+ time.sleep(0.4)
+
+ threading.Thread(target=f).start()
+ threading.Thread(target=g).start()
+ threads = [t for t in threading.enumerate() if not t.daemon]
+ assert len(threads) == 3
+
+ bus.block()
+
+ # The block method MUST wait for the EXITING state.
+ assert bus.state == bus.states.EXITING
+
+ # The block method MUST wait for ALL non-main, non-daemon threads to
+ # finish.
+ threads = [t for t in threading.enumerate() if not t.daemon]
+ assert len(threads) == 1
+
+ # The last message will mention an indeterminable thread name; ignore
+ # it
+ assert (log_tracker.log_entries[:-1] ==
+ ['Bus STOPPING', 'Bus STOPPED',
+ 'Bus EXITING', 'Bus EXITED',
+ 'Waiting for child threads to terminate...'])
+
+
+def test_start_with_callback(bus):
+ """Test that callback fires on bus start."""
+ try:
+ events = []
+
+ def f(*args, **kwargs): # pylint: disable=invalid-name
+ events.append(('f', args, kwargs))
+
+ def g(): # pylint: disable=invalid-name
+ events.append('g')
+ bus.subscribe('start', g)
+ bus.start_with_callback(f, (1, 3, 5), {'foo': 'bar'})
+
+ # Give wait() time to run f()
+ time.sleep(0.2)
+
+ # The callback method MUST wait for the STARTED state.
+ assert bus.state == bus.states.STARTED
+
+ # The callback method MUST run after all start methods.
+ assert events == ['g', ('f', (1, 3, 5), {'foo': 'bar'})]
+ finally:
+ bus.exit()
+
+
+def test_log(bus, log_tracker):
+ """Test that bus messages and errors are logged."""
+ assert log_tracker.log_entries == []
+
+ # Try a normal message.
+ expected = []
+ for msg_ in ["O mah darlin'"] * 3 + ['Clementiiiiiiiine']:
+ bus.log(msg_)
+ expected.append(msg_)
+ assert log_tracker.log_entries == expected
+
+ # Try an error message
+ try:
+ foo
+ except NameError:
+ bus.log('You are lost and gone forever', traceback=True)
+ lastmsg = log_tracker.log_entries[-1]
+ assert 'Traceback' in lastmsg and 'NameError' in lastmsg, (
+ 'Last log message %r did not contain '
+ 'the expected traceback.' % lastmsg
+ )
+ else:
+ pytest.fail('NameError was not raised as expected.')
diff --git a/cherrypy/test/test_caching.py b/cherrypy/test/test_caching.py
index 19ef05bd..c0b89797 100644
--- a/cherrypy/test/test_caching.py
+++ b/cherrypy/test/test_caching.py
@@ -151,7 +151,7 @@ class CacheTest(helper.CPWebCase):
self.assertBody('visit #1')
if trial != 0:
age = int(self.assertHeader('Age'))
- self.assert_(age >= elapsed)
+ assert age >= elapsed
elapsed = age
# POST, PUT, DELETE should not be cached.
diff --git a/cherrypy/test/test_config.py b/cherrypy/test/test_config.py
index 4dfea74d..5e880d87 100644
--- a/cherrypy/test/test_config.py
+++ b/cherrypy/test/test_config.py
@@ -80,7 +80,7 @@ def setup_server():
def wrapper():
params = cherrypy.request.params
- for name, coercer in list(value.items()):
+ for name, coercer in value.copy().items():
try:
params[name] = coercer(params[name])
except KeyError:
diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py
index eae90b10..6fde3a97 100644
--- a/cherrypy/test/test_core.py
+++ b/cherrypy/test/test_core.py
@@ -385,6 +385,11 @@ class CoreRequestHandlingTest(helper.CPWebCase):
r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>")
self.assertStatus(307)
+ self.getPage('/redirect/by_code?code=308')
+ self.assertMatchesBody(
+ r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>")
+ self.assertStatus(308)
+
self.getPage('/redirect/nomodify')
self.assertBody('')
self.assertStatus(304)
@@ -549,7 +554,7 @@ class CoreRequestHandlingTest(helper.CPWebCase):
self.assertStatus(206)
ct = self.assertHeader('Content-Type')
expected_type = 'multipart/byteranges; boundary='
- self.assert_(ct.startswith(expected_type))
+ assert ct.startswith(expected_type)
boundary = ct[len(expected_type):]
expected_body = ('\r\n--%s\r\n'
'Content-type: text/html\r\n'
diff --git a/cherrypy/test/test_httputil.py b/cherrypy/test/test_httputil.py
index fe6a3f41..84661424 100644
--- a/cherrypy/test/test_httputil.py
+++ b/cherrypy/test/test_httputil.py
@@ -62,19 +62,20 @@ def test_valid_status(status, expected_status):
@pytest.mark.parametrize(
'status_code,error_msg',
[
- ('hey', "Illegal response status from server ('hey' is non-numeric)."),
+ (
+ 'hey',
+ r"Illegal response status from server \('hey' is non-numeric\)."
+ ),
(
{'hey': 'hi'},
- 'Illegal response status from server '
- "({'hey': 'hi'} is non-numeric).",
+ r'Illegal response status from server '
+ r"\(\{'hey': 'hi'\} is non-numeric\).",
),
- (1, 'Illegal response status from server (1 is out of range).'),
- (600, 'Illegal response status from server (600 is out of range).'),
+ (1, r'Illegal response status from server \(1 is out of range\).'),
+ (600, r'Illegal response status from server \(600 is out of range\).'),
]
)
def test_invalid_status(status_code, error_msg):
"""Check that invalid status cause certain errors."""
- with pytest.raises(ValueError) as excinfo:
+ with pytest.raises(ValueError, match=error_msg):
httputil.valid_status(status_code)
-
- assert error_msg in str(excinfo)
diff --git a/cherrypy/test/test_logging.py b/cherrypy/test/test_logging.py
index 5abebbf1..5308fb72 100644
--- a/cherrypy/test/test_logging.py
+++ b/cherrypy/test/test_logging.py
@@ -1,29 +1,34 @@
"""Basic tests for the CherryPy core: request handling."""
import logging
-import os
-from unittest import mock
+from cheroot.test import webtest
import pytest
import requests # FIXME: Temporary using it directly, better switch
import cherrypy
-from cherrypy._cpcompat import ntou
-from cherrypy.test import helper, logtest
+from cherrypy.test.logtest import LogCase
-localDir = os.path.dirname(__file__)
-access_log = os.path.join(localDir, 'access.log')
-error_log = os.path.join(localDir, 'error.log')
# Some unicode strings.
-tartaros = ntou('\u03a4\u1f71\u03c1\u03c4\u03b1\u03c1\u03bf\u03c2', 'escape')
-erebos = ntou('\u0388\u03c1\u03b5\u03b2\u03bf\u03c2.com', 'escape')
+tartaros = u'\u03a4\u1f71\u03c1\u03c4\u03b1\u03c1\u03bf\u03c2'
+erebos = u'\u0388\u03c1\u03b5\u03b2\u03bf\u03c2.com'
@pytest.fixture
-def server():
- setup_server()
+def access_log_file(tmp_path_factory):
+ return tmp_path_factory.mktemp('logs') / 'access.log'
+
+
+@pytest.fixture
+def error_log_file(tmp_path_factory):
+ return tmp_path_factory.mktemp('logs') / 'access.log'
+
+
+@pytest.fixture
+def server(configure_server):
cherrypy.engine.start()
+ cherrypy.engine.wait(cherrypy.engine.states.STARTED)
yield
@@ -32,14 +37,15 @@ def server():
def shutdown_server():
cherrypy.engine.exit()
+ cherrypy.engine.block()
- servers_copy = list(getattr(cherrypy, 'servers', {}).items())
- for name, server in servers_copy:
+ for name, server in getattr(cherrypy, 'servers', {}).copy().items():
server.unsubscribe()
del cherrypy.servers[name]
-def setup_server():
+@pytest.fixture
+def configure_server(access_log_file, error_log_file):
class Root:
@cherrypy.expose
@@ -79,131 +85,200 @@ def setup_server():
root = Root()
+ cherrypy.config.reset()
+ cherrypy.config.update({
+ 'server.socket_host': webtest.WebCase.HOST,
+ 'server.socket_port': webtest.WebCase.PORT,
+ 'server.protocol_version': webtest.WebCase.PROTOCOL,
+ 'environment': 'test_suite',
+ })
cherrypy.config.update({
- 'log.error_file': error_log,
- 'log.access_file': access_log,
+ 'log.error_file': str(error_log_file),
+ 'log.access_file': str(access_log_file),
})
cherrypy.tree.mount(root)
-class AccessLogTests(helper.CPWebCase, logtest.LogCase):
- setup_server = staticmethod(setup_server)
-
- logfile = access_log
-
- def testNormalReturn(self):
- self.markLog()
- self.getPage('/as_string',
- headers=[('Referer', 'http://www.cherrypy.org/'),
- ('User-Agent', 'Mozilla/5.0')])
- self.assertBody('content')
- self.assertStatus(200)
-
- intro = '%s - - [' % self.interface()
-
- self.assertLog(-1, intro)
-
- if [k for k, v in self.headers if k.lower() == 'content-length']:
- self.assertLog(-1, '] "GET %s/as_string HTTP/1.1" 200 7 '
- '"http://www.cherrypy.org/" "Mozilla/5.0"'
- % self.prefix())
- else:
- self.assertLog(-1, '] "GET %s/as_string HTTP/1.1" 200 - '
- '"http://www.cherrypy.org/" "Mozilla/5.0"'
- % self.prefix())
+@pytest.fixture
+def log_tracker(access_log_file):
+ class LogTracker(LogCase):
+ logfile = str(access_log_file)
+ return LogTracker()
+
+
+def test_normal_return(log_tracker, server):
+ log_tracker.markLog()
+ host = webtest.interface(webtest.WebCase.HOST)
+ port = webtest.WebCase.PORT
+ resp = requests.get(
+ 'http://%s:%s/as_string' % (host, port),
+ headers={
+ 'Referer': 'http://www.cherrypy.org/',
+ 'User-Agent': 'Mozilla/5.0',
+ },
+ )
+ expected_body = 'content'
+ assert resp.text == expected_body
+ assert resp.status_code == 200
+
+ intro = '%s - - [' % host
+
+ log_tracker.assertLog(-1, intro)
+
+ content_length = len(expected_body)
+ if not any(
+ k for k, v in resp.headers.items()
+ if k.lower() == 'content-length'
+ ):
+ content_length = '-'
+
+ log_tracker.assertLog(
+ -1,
+ '] "GET /as_string HTTP/1.1" 200 %s '
+ '"http://www.cherrypy.org/" "Mozilla/5.0"'
+ % content_length,
+ )
- def testNormalYield(self):
- self.markLog()
- self.getPage('/as_yield')
- self.assertBody('content')
- self.assertStatus(200)
- intro = '%s - - [' % self.interface()
+def test_normal_yield(log_tracker, server):
+ log_tracker.markLog()
+ host = webtest.interface(webtest.WebCase.HOST)
+ port = webtest.WebCase.PORT
+ resp = requests.get(
+ 'http://%s:%s/as_yield' % (host, port),
+ headers={
+ 'User-Agent': '',
+ },
+ )
+ expected_body = 'content'
+ assert resp.text == expected_body
+ assert resp.status_code == 200
+
+ intro = '%s - - [' % host
+
+ log_tracker.assertLog(-1, intro)
+ content_length = len(expected_body)
+ if not any(
+ k for k, v in resp.headers.items()
+ if k.lower() == 'content-length'
+ ):
+ content_length = '-'
+
+ log_tracker.assertLog(
+ -1,
+ '] "GET /as_yield HTTP/1.1" 200 %s "" ""'
+ % content_length,
+ )
- self.assertLog(-1, intro)
- if [k for k, v in self.headers if k.lower() == 'content-length']:
- self.assertLog(-1, '] "GET %s/as_yield HTTP/1.1" 200 7 "" ""' %
- self.prefix())
- else:
- self.assertLog(-1, '] "GET %s/as_yield HTTP/1.1" 200 - "" ""'
- % self.prefix())
- @mock.patch(
+def test_custom_log_format(log_tracker, monkeypatch, server):
+ """Test a customized access_log_format string, which is a
+ feature of _cplogging.LogManager.access()."""
+ monkeypatch.setattr(
'cherrypy._cplogging.LogManager.access_log_format',
'{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}" {o}',
)
- def testCustomLogFormat(self):
- """Test a customized access_log_format string, which is a
- feature of _cplogging.LogManager.access()."""
- self.markLog()
- self.getPage('/as_string', headers=[('Referer', 'REFERER'),
- ('User-Agent', 'USERAGENT'),
- ('Host', 'HOST')])
- self.assertLog(-1, '%s - - [' % self.interface())
- self.assertLog(-1, '] "GET /as_string HTTP/1.1" '
- '200 7 "REFERER" "USERAGENT" HOST')
-
- @mock.patch(
+ log_tracker.markLog()
+ host = webtest.interface(webtest.WebCase.HOST)
+ port = webtest.WebCase.PORT
+ requests.get(
+ 'http://%s:%s/as_string' % (host, port),
+ headers={
+ 'Referer': 'REFERER',
+ 'User-Agent': 'USERAGENT',
+ 'Host': 'HOST',
+ },
+ )
+ log_tracker.assertLog(-1, '%s - - [' % host)
+ log_tracker.assertLog(
+ -1,
+ '] "GET /as_string HTTP/1.1" '
+ '200 7 "REFERER" "USERAGENT" HOST',
+ )
+
+
+def test_timez_log_format(log_tracker, monkeypatch, server):
+ """Test a customized access_log_format string, which is a
+ feature of _cplogging.LogManager.access()."""
+ monkeypatch.setattr(
'cherrypy._cplogging.LogManager.access_log_format',
'{h} {l} {u} {z} "{r}" {s} {b} "{f}" "{a}" {o}',
)
- def testTimezLogFormat(self):
- """Test a customized access_log_format string, which is a
- feature of _cplogging.LogManager.access()."""
- self.markLog()
-
- expected_time = str(cherrypy._cplogging.LazyRfc3339UtcTime())
- with mock.patch(
- 'cherrypy._cplogging.LazyRfc3339UtcTime',
- lambda: expected_time):
- self.getPage('/as_string', headers=[('Referer', 'REFERER'),
- ('User-Agent', 'USERAGENT'),
- ('Host', 'HOST')])
-
- self.assertLog(-1, '%s - - ' % self.interface())
- self.assertLog(-1, expected_time)
- self.assertLog(-1, ' "GET /as_string HTTP/1.1" '
- '200 7 "REFERER" "USERAGENT" HOST')
-
- @mock.patch(
+ log_tracker.markLog()
+
+ expected_time = str(cherrypy._cplogging.LazyRfc3339UtcTime())
+ monkeypatch.setattr(
+ 'cherrypy._cplogging.LazyRfc3339UtcTime',
+ lambda: expected_time,
+ )
+ host = webtest.interface(webtest.WebCase.HOST)
+ port = webtest.WebCase.PORT
+ requests.get(
+ 'http://%s:%s/as_string' % (host, port),
+ headers={
+ 'Referer': 'REFERER',
+ 'User-Agent': 'USERAGENT',
+ 'Host': 'HOST',
+ },
+ )
+
+ log_tracker.assertLog(-1, '%s - - ' % host)
+ log_tracker.assertLog(-1, expected_time)
+ log_tracker.assertLog(
+ -1,
+ ' "GET /as_string HTTP/1.1" '
+ '200 7 "REFERER" "USERAGENT" HOST',
+ )
+
+
+def test_UUIDv4_parameter_log_format(log_tracker, monkeypatch, server):
+ """Test rendering of UUID4 within access log."""
+ monkeypatch.setattr(
'cherrypy._cplogging.LogManager.access_log_format',
'{i}',
)
- def testUUIDv4ParameterLogFormat(self):
- """Test rendering of UUID4 within access log."""
- self.markLog()
- self.getPage('/as_string')
- self.assertValidUUIDv4()
-
- def testEscapedOutput(self):
- # Test unicode in access log pieces.
- self.markLog()
- self.getPage('/uni_code')
- self.assertStatus(200)
- # The repr of a bytestring includes a b'' prefix
- self.assertLog(-1, repr(tartaros.encode('utf8'))[2:-1])
- # Test the erebos value. Included inline for your enlightenment.
- # Note the 'r' prefix--those backslashes are literals.
- self.assertLog(-1, r'\xce\x88\xcf\x81\xce\xb5\xce\xb2\xce\xbf\xcf\x82')
-
- # Test backslashes in output.
- self.markLog()
- self.getPage('/slashes')
- self.assertStatus(200)
- self.assertLog(-1, b'"GET /slashed\\path HTTP/1.1"')
-
- # Test whitespace in output.
- self.markLog()
- self.getPage('/whitespace')
- self.assertStatus(200)
- # Again, note the 'r' prefix.
- self.assertLog(-1, r'"Browzuh (1.0\r\n\t\t.3)"')
-
-
-@pytest.mark.xfail(reason='failing')
+ log_tracker.markLog()
+ host = webtest.interface(webtest.WebCase.HOST)
+ port = webtest.WebCase.PORT
+ requests.get('http://%s:%s/as_string' % (host, port))
+ log_tracker.assertValidUUIDv4()
+
+
+def test_escaped_output(log_tracker, server):
+ # Test unicode in access log pieces.
+ log_tracker.markLog()
+ host = webtest.interface(webtest.WebCase.HOST)
+ port = webtest.WebCase.PORT
+ resp = requests.get('http://%s:%s/uni_code' % (host, port))
+ assert resp.status_code == 200
+ # The repr of a bytestring includes a b'' prefix
+ log_tracker.assertLog(-1, repr(tartaros.encode('utf8'))[2:-1])
+ # Test the erebos value. Included inline for your enlightenment.
+ # Note the 'r' prefix--those backslashes are literals.
+ log_tracker.assertLog(
+ -1,
+ r'\xce\x88\xcf\x81\xce\xb5\xce\xb2\xce\xbf\xcf\x82',
+ )
+
+ # Test backslashes in output.
+ log_tracker.markLog()
+ resp = requests.get('http://%s:%s/slashes' % (host, port))
+ assert resp.status_code == 200
+ log_tracker.assertLog(-1, b'"GET /slashed\\path HTTP/1.1"')
+
+ # Test whitespace in output.
+ log_tracker.markLog()
+ resp = requests.get('http://%s:%s/whitespace' % (host, port))
+ assert resp.status_code == 200
+ # Again, note the 'r' prefix.
+ log_tracker.assertLog(-1, r'"Browzuh (1.0\r\n\t\t.3)"')
+
+
def test_tracebacks(server, caplog):
+ host = webtest.interface(webtest.WebCase.HOST)
+ port = webtest.WebCase.PORT
with caplog.at_level(logging.ERROR, logger='cherrypy.error'):
- resp = requests.get('http://127.0.0.1:8080/error')
+ resp = requests.get('http://%s:%s/error' % (host, port))
rec = caplog.records[0]
exc_cls, exc_msg = rec.exc_info[0], rec.message
diff --git a/cherrypy/test/test_states.py b/cherrypy/test/test_states.py
index a5addbca..c0c61827 100644
--- a/cherrypy/test/test_states.py
+++ b/cherrypy/test/test_states.py
@@ -1,8 +1,6 @@
import os
import signal
import time
-import unittest
-import warnings
from http.client import BadStatusLine
import pytest
@@ -432,41 +430,41 @@ test_case_name: "test_signal_handler_unsubscribe"
)
-class WaitTests(unittest.TestCase):
-
- def test_safe_wait_INADDR_ANY(self):
- """
- Wait on INADDR_ANY should not raise IOError
-
- In cases where the loopback interface does not exist, CherryPy cannot
- effectively determine if a port binding to INADDR_ANY was effected.
- In this situation, CherryPy should assume that it failed to detect
- the binding (not that the binding failed) and only warn that it could
- not verify it.
- """
- # At such a time that CherryPy can reliably determine one or more
- # viable IP addresses of the host, this test may be removed.
-
- # Simulate the behavior we observe when no loopback interface is
- # present by: finding a port that's not occupied, then wait on it.
-
- free_port = portend.find_available_local_port()
-
- servers = cherrypy.process.servers
-
- inaddr_any = '0.0.0.0'
-
- # Wait on the free port that's unbound
- with warnings.catch_warnings(record=True) as w:
- with servers._safe_wait(inaddr_any, free_port):
- portend.occupied(inaddr_any, free_port, timeout=1)
- self.assertEqual(len(w), 1)
- self.assertTrue(isinstance(w[0], warnings.WarningMessage))
- self.assertTrue(
- 'Unable to verify that the server is bound on ' in str(w[0]))
-
- # The wait should still raise an IO error if INADDR_ANY was
- # not supplied.
- with pytest.raises(IOError):
- with servers._safe_wait('127.0.0.1', free_port):
- portend.occupied('127.0.0.1', free_port, timeout=1)
+def test_safe_wait_INADDR_ANY(): # pylint: disable=invalid-name
+ """
+ Wait on INADDR_ANY should not raise IOError
+
+ In cases where the loopback interface does not exist, CherryPy cannot
+ effectively determine if a port binding to INADDR_ANY was effected.
+ In this situation, CherryPy should assume that it failed to detect
+ the binding (not that the binding failed) and only warn that it could
+ not verify it.
+ """
+ # At such a time that CherryPy can reliably determine one or more
+ # viable IP addresses of the host, this test may be removed.
+
+ # Simulate the behavior we observe when no loopback interface is
+ # present by: finding a port that's not occupied, then wait on it.
+
+ free_port = portend.find_available_local_port()
+
+ servers = cherrypy.process.servers
+
+ inaddr_any = '0.0.0.0'
+
+ # Wait on the free port that's unbound
+ with pytest.warns(
+ UserWarning,
+ match='Unable to verify that the server is bound on ',
+ ) as warnings:
+ # pylint: disable=protected-access
+ with servers._safe_wait(inaddr_any, free_port):
+ portend.occupied(inaddr_any, free_port, timeout=1)
+ assert len(warnings) == 1
+
+ # The wait should still raise an IO error if INADDR_ANY was
+ # not supplied.
+ with pytest.raises(IOError):
+ # pylint: disable=protected-access
+ with servers._safe_wait('127.0.0.1', free_port):
+ portend.occupied('127.0.0.1', free_port, timeout=1)
diff --git a/cherrypy/test/test_tutorials.py b/cherrypy/test/test_tutorials.py
index 002a2b45..39ca4d6f 100644
--- a/cherrypy/test/test_tutorials.py
+++ b/cherrypy/test/test_tutorials.py
@@ -1,5 +1,4 @@
import sys
-import imp
import importlib
import cherrypy
@@ -24,7 +23,7 @@ class TutorialTest(helper.CPWebCase):
"""
target = 'cherrypy.tutorial.' + name
if target in sys.modules:
- module = imp.reload(sys.modules[target])
+ module = importlib.reload(sys.modules[target])
else:
module = importlib.import_module(target)
return module