1
1
mirror of https://github.com/Kozea/WeasyPrint.git synced 2024-10-04 16:07:57 +03:00
WeasyPrint/tests/testing_utils.py

126 lines
3.7 KiB
Python
Raw Normal View History

"""
weasyprint.tests.testing_utils
------------------------------
2011-12-16 14:19:56 +04:00
Helpers for tests.
2011-12-16 14:19:56 +04:00
"""
import contextlib
2012-02-20 16:04:35 +04:00
import functools
2017-03-25 02:33:36 +03:00
import logging
import os.path
import sys
import threading
import wsgiref.simple_server
2011-12-16 14:19:56 +04:00
2020-12-06 22:19:59 +03:00
from weasyprint import CSS, HTML
from weasyprint.logger import LOGGER
from weasyprint.urls import path2url
2011-12-16 14:19:56 +04:00
2018-03-30 01:13:36 +03:00
# Lists of fonts with many variants (including condensed)
2020-01-02 02:43:06 +03:00
if sys.platform.startswith('win'): # pragma: no cover
SANS_FONTS = 'DejaVu Sans, Arial Nova, Arial, sans'
2018-03-30 01:13:36 +03:00
MONO_FONTS = 'Courier New, Courier, monospace'
2020-01-02 02:43:06 +03:00
else: # pragma: no cover
2018-03-30 01:13:36 +03:00
SANS_FONTS = 'DejaVu Sans, sans'
MONO_FONTS = 'DejaVu Sans Mono, monospace'
TEST_UA_STYLESHEET = CSS(filename=os.path.join(
2020-12-06 22:19:59 +03:00
os.path.dirname(__file__), '..', 'weasyprint', 'css', 'tests_ua.css'
))
2011-12-16 14:19:56 +04:00
class FakeHTML(HTML):
"""Like weasyprint.HTML, but with a lighter UA stylesheet."""
def _ua_stylesheets(self):
return [TEST_UA_STYLESHEET]
2011-12-16 14:19:56 +04:00
def resource_filename(basename):
"""Return the absolute path of the resource called ``basename``."""
return os.path.join(os.path.dirname(__file__), 'resources', basename)
# Dummy filename, but in the right directory.
BASE_URL = path2url(resource_filename('<test>'))
2011-12-16 14:19:56 +04:00
class CallbackHandler(logging.Handler):
"""A logging handler that calls a function for every message."""
def __init__(self, callback):
2012-02-20 18:36:55 +04:00
logging.Handler.__init__(self)
self.emit = callback
2011-12-16 14:19:56 +04:00
@contextlib.contextmanager
def capture_logs():
2011-12-16 14:19:56 +04:00
"""Return a context manager that captures all logged messages."""
logger = LOGGER
2011-12-16 14:19:56 +04:00
messages = []
def emit(record):
if record.name == 'weasyprint.progress':
return
2020-05-30 16:48:24 +03:00
messages.append(f'{record.levelname.upper()}: {record.getMessage()}')
previous_handlers = logger.handlers
previous_level = logger.level
logger.handlers = []
logger.addHandler(CallbackHandler(emit))
logger.setLevel(logging.DEBUG)
2011-12-16 14:19:56 +04:00
try:
yield messages
finally:
logger.handlers = previous_handlers
logger.level = previous_level
2011-12-16 14:19:56 +04:00
2012-02-20 16:04:35 +04:00
def assert_no_logs(function):
"""Decorator that asserts that nothing is logged in a function."""
@functools.wraps(function)
2012-08-03 18:21:47 +04:00
def wrapper(*args, **kwargs):
2012-02-20 16:04:35 +04:00
with capture_logs() as logs:
try:
2012-08-03 18:21:47 +04:00
function(*args, **kwargs)
2012-04-02 16:45:44 +04:00
except Exception: # pragma: no cover
2012-02-21 17:13:34 +04:00
if logs:
2020-05-30 16:48:24 +03:00
print(f'{len(logs)} errors logged:', file=sys.stderr)
2012-07-23 18:07:52 +04:00
for message in logs:
print(message, file=sys.stderr)
raise
2012-02-20 16:04:35 +04:00
else:
if logs: # pragma: no cover
for message in logs:
print(message, file=sys.stderr)
2020-05-30 16:48:24 +03:00
raise AssertionError(f'{len(logs)} errors logged')
2012-02-20 16:04:35 +04:00
return wrapper
2013-04-12 17:29:21 +04:00
@contextlib.contextmanager
def http_server(handlers):
def wsgi_app(environ, start_response):
handler = handlers.get(environ['PATH_INFO'])
if handler:
status = str('200 OK')
response, headers = handler(environ)
headers = [(str(name), str(value)) for name, value in headers]
else: # pragma: no cover
status = str('404 Not Found')
response = b''
headers = []
start_response(status, headers)
return [response]
# Port 0: let the OS pick an available port number
# http://stackoverflow.com/a/1365284/1162888
server = wsgiref.simple_server.make_server('127.0.0.1', 0, wsgi_app)
_host, port = server.socket.getsockname()
thread = threading.Thread(target=server.serve_forever)
thread.start()
try:
2020-05-30 16:48:24 +03:00
yield f'http://127.0.0.1:{port}'
finally:
server.shutdown()
thread.join()