Skip to content

Commit

Permalink
Add fallback to @media type "all" (#533)
Browse files Browse the repository at this point in the history
* Add fallback to @media type "all" (#498)

* Add unittests for css @media rule
  • Loading branch information
timobrembeck committed Oct 31, 2020
1 parent 7828580 commit 3bf6503
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 3 deletions.
67 changes: 67 additions & 0 deletions tests/test_css_media_rule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from unittest import TestCase

from xhtml2pdf.w3c.css import CSSBuilder, CSSParser


class CssMediaRuleTest(TestCase):
"""
Test cases for the css @media rule (https://www.w3.org/TR/css3-mediaqueries/)
"""

def setUp(self):
"""
Setup css parser for all test cases
"""
self.parser = CSSParser(CSSBuilder(mediumSet=["all"]))

def test_media_all(self):
"""
Test if the rule "@media all {" works
"""

media_all = """
@media all {
p { color: yellow; }
}
"""

selector_media_all = self.parser.parse(media_all)[0]
css_media_all = self._get_first_dict_value(selector_media_all)

self.assertDictEqual(css_media_all, {"color": "yellow"})

def test_media_all_and(self):
"""
Test if the rule "@media all and (...) {" works
"""

media_all_and = """
@media all and (max-width: 500px) {
p { color: yellow; }
}
"""

selector_media_all_and = self.parser.parse(media_all_and)[0]
css_media_all_and = self._get_first_dict_value(selector_media_all_and)

self.assertDictEqual(css_media_all_and, {"color": "yellow"})

def test_media_all_default(self):
"""
Test if the rule "@media (...) {" works (no media type defaults to "all")
"""

media_all_default = """
@media (max-width: 500px) {
p { color: yellow; }
}
"""

selector_media_all_default = self.parser.parse(media_all_default)[0]
css_media_all_default = self._get_first_dict_value(selector_media_all_default)

self.assertDictEqual(css_media_all_default, {"color": "yellow"})

@staticmethod
def _get_first_dict_value(dictionary):
return dictionary[list(dictionary.keys())[0]]
7 changes: 4 additions & 3 deletions xhtml2pdf/w3c/cssParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -693,10 +693,11 @@ def _parseAtMedia(self, src):
mediums = []
while src and src[0] != '{':
medium, src = self._getIdent(src)
if medium is None:
raise self.ParseError('@media rule expected media identifier', src, ctxsrc)
# make "and ... {" work
if medium == 'and':
if medium in (None, 'and'):
# default to mediatype "all"
if medium is None:
mediums.append('all')
# strip up to curly bracket
pattern = re.compile('.*({.*)')
match = re.match(pattern, src)
Expand Down

0 comments on commit 3bf6503

Please sign in to comment.