Skip to content

Commit

Permalink
Display caught exceptions when debugging WeasyPrint
Browse files Browse the repository at this point in the history
  • Loading branch information
liZe committed Aug 24, 2024
1 parent b08110f commit 1711d59
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 14 deletions.
16 changes: 10 additions & 6 deletions tests/css/test_validation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Test validation of properties."""

import logging
from math import pi

import pytest
Expand All @@ -12,10 +13,10 @@
from ..testing_utils import assert_no_logs, capture_logs


def get_value(css, expected_error=None):
def get_value(css, expected_error=None, level=None):
declarations = tinycss2.parse_blocks_contents(css)

with capture_logs() as logs:
with capture_logs(level=level) as logs:
base_url = 'https://weasyprint.org/foo/'
declarations = list(preprocess_declarations(base_url, declarations))

Expand All @@ -36,13 +37,13 @@ def get_default_value(values, index, default):
return values[index] or default


def assert_invalid(css, message='invalid'):
assert get_value(css, message) is None
def assert_invalid(css, message='invalid', level=None):
assert get_value(css, message, level) is None


@assert_no_logs
def test_not_print():
assert_invalid('volume: 42', 'does not apply for the print media')
assert_invalid('volume: 42', 'does not apply for the print media', logging.DEBUG)


@assert_no_logs
Expand All @@ -60,7 +61,10 @@ def test_normal_prefix():

@assert_no_logs
def test_unknown_prefix():
assert_invalid('-unknown-display: block', 'prefixed selectors are ignored')
assert_invalid(
'-unknown-display: block',
'prefixed selectors are ignored',
logging.DEBUG)


@assert_no_logs
Expand Down
12 changes: 6 additions & 6 deletions weasyprint/css/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,9 @@ def find_stylesheets(wrapper_element, device_media_type, url_fetcher, base_url,
_check_mime_type=True, media_type=device_media_type,
font_config=font_config, counter_style=counter_style,
page_rules=page_rules)
except URLFetchingError as exc:
LOGGER.error(
'Failed to load stylesheet at %s: %s', href, exc)
except URLFetchingError as exception:
LOGGER.error('Failed to load stylesheet at %s: %s', href, exception)
LOGGER.debug('Error while loading stylesheet:', exc_info=exception)


def find_style_attributes(tree, presentational_hints=False, base_url=None):
Expand Down Expand Up @@ -998,9 +998,9 @@ def preprocess_stylesheet(device_media_type, base_url, stylesheet_rules,
media_type=device_media_type, font_config=font_config,
counter_style=counter_style, matcher=matcher,
page_rules=page_rules)
except URLFetchingError as exc:
LOGGER.error(
'Failed to load stylesheet at %s : %s', url, exc)
except URLFetchingError as exception:
LOGGER.error('Failed to load stylesheet at %s : %s', url, exception)
LOGGER.debug('Error while loading stylesheet:', exc_info=exception)

elif rule.type == 'at-rule' and rule.lower_at_keyword == 'media':
media = media_queries.parse_media_query(rule.prelude)
Expand Down
1 change: 1 addition & 0 deletions weasyprint/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ def handle_svg(element, box, get_image_from_uri, base_url):
image = SVGImage(element, base_url, url_fetcher, context)
except Exception as exception: # pragma: no cover
LOGGER.error('Failed to load inline SVG: %s', exception)
LOGGER.debug('Error while loading inline SVG:', exc_info=exception)
return []
else:
return [make_replaced_box(element, box, image)]
Expand Down
4 changes: 3 additions & 1 deletion weasyprint/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,9 @@ def draw(self, stream, concrete_width, concrete_height, image_rendering):
self._svg.draw(
stream, concrete_width, concrete_height, self._base_url,
self._url_fetcher, self._context)
except BaseException:
except BaseException as exception:
LOGGER.error('Failed to render SVG image %s', self._base_url)
LOGGER.debug('Error while rendering SVG image:', exc_info=exception)


def get_image_from_uri(cache, url_fetcher, options, url, forced_mime_type=None,
Expand Down Expand Up @@ -341,6 +342,7 @@ def get_image_from_uri(cache, url_fetcher, options, url, forced_mime_type=None,

except (URLFetchingError, ImageLoadingError) as exception:
LOGGER.error('Failed to load image at %r: %s', url, exception)
LOGGER.debug('Error while loading image:', exc_info=exception)
image = None

cache[url] = image
Expand Down
4 changes: 3 additions & 1 deletion weasyprint/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,15 @@ def __init__(self, callback):
@contextlib.contextmanager
def capture_logs(logger='weasyprint', level=None):
"""Return a context manager that captures all logged messages."""
if level is None:
level = logging.INFO
logger = logging.getLogger(logger)
messages = []

def emit(record):
if record.name == 'weasyprint.progress':
return
if level is not None and record.levelno < level:
if record.levelno < level:
return
messages.append(f'{record.levelname.upper()}: {record.getMessage()}')

Expand Down
1 change: 1 addition & 0 deletions weasyprint/pdf/anchors.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ def write_pdf_attachment(pdf, attachment, compress):
stream += data
except URLFetchingError as exception:
LOGGER.error('Failed to load attachment: %s', exception)
LOGGER.debug('Error while loading attachment:', exc_info=exception)
return
attachment.md5 = md5(stream, usedforsecurity=False).hexdigest()

Expand Down

0 comments on commit 1711d59

Please sign in to comment.