Skip to content

Commit

Permalink
unittest2pytest
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Jun 9, 2022
1 parent 591039d commit 2cdeecf
Show file tree
Hide file tree
Showing 39 changed files with 2,011 additions and 2,046 deletions.
108 changes: 17 additions & 91 deletions cssutils/tests/basetest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging
import re
import sys
import unittest
import pytest

if sys.version_info >= (3, 9):
from importlib import resources
Expand All @@ -18,100 +18,23 @@ def get_sheet_filename(sheet_name):
return resources.files('cssutils') / 'tests' / 'sheets' / sheet_name


class BaseTestCase(unittest.TestCase):
def setUp(self):
class BaseTestCase:
def setup(self):
# a raising parser!!!
cssutils.log.raiseExceptions = True
cssutils.log.setLevel(logging.FATAL)
self.p = cssutils.CSSParser(raiseExceptions=True)

def assertRaisesEx(self, exception, callable, *args, **kwargs):
"""
from
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307970
"""
if "exc_args" in kwargs:
exc_args = kwargs["exc_args"]
del kwargs["exc_args"]
else:
exc_args = None
if "exc_pattern" in kwargs:
exc_pattern = kwargs["exc_pattern"]
del kwargs["exc_pattern"]
else:
exc_pattern = None

argv = [repr(a) for a in args] + [
"%s=%r" % (k, v) for k, v in list(kwargs.items())
]
callsig = "%s(%s)" % (callable.__name__, ", ".join(argv))

try:
def assertRaisesEx(
self, exception, callable, *args, exc_args=None, exc_pattern=None, **kwargs
):
assert exc_args is None
with pytest.raises(exception, match=exc_pattern):
callable(*args, **kwargs)
except exception as exc:
if exc_args is not None:
self.assertFalse(
exc.args != exc_args,
"%s raised %s with unexpected args: "
"expected=%r, actual=%r"
% (callsig, exc.__class__, exc_args, exc.args),
)
if exc_pattern is not None:
self.assertTrue(
exc_pattern.search(str(exc)),
"%s raised %s, but the exception "
"does not match '%s': %r"
% (callsig, exc.__class__, exc_pattern.pattern, str(exc)),
)
except Exception:
exc_info = sys.exc_info()
print(exc_info)
self.fail(
"%s raised an unexpected exception type: "
"expected=%s, actual=%s" % (callsig, exception, exc_info[0])
)
else:
self.fail("%s did not raise %s" % (callsig, exception))

def assertRaisesMsg(self, excClass, msg, callableObj, *args, **kwargs):
"""
Just like unittest.TestCase.assertRaises,
but checks that the message is right too.
Usage::
self.assertRaisesMsg(
MyException, "Exception message",
my_function, (arg1, arg2)
)
from
http://www.nedbatchelder.com/blog/200609.html#e20060905T064418
"""
try:
with pytest.raises(excClass, match=re.escape(msg)):
callableObj(*args, **kwargs)
except excClass as exc:
excMsg = str(exc)
if not msg:
# No message provided: any message is fine.
return
elif msg in excMsg:
# Message provided, and we got the right message: passes.
return
else:
# Message provided, and it didn't match: fail!
raise self.failureException(
"Right exception, wrong message: got '%s' instead of '%s'"
% (excMsg, msg)
)
else:
if hasattr(excClass, '__name__'):
excName = excClass.__name__
else:
excName = str(excClass)
raise self.failureException(
"Expected to raise %s, didn't get an exception at all" % excName
)

def do_equal_p(self, tests, att='cssText', debug=False, raising=True):
"""
Expand All @@ -125,15 +48,16 @@ def do_equal_p(self, tests, att='cssText', debug=False, raising=True):
s = p.parseString(test)
if expected is None:
expected = test
self.assertEqual(expected, str(s.__getattribute__(att), 'utf-8'))
assert str(s.__getattribute__(att), 'utf-8') == expected

def do_raise_p(self, tests, debug=False, raising=True):
# parses with self.p and expects raise
p = cssutils.CSSParser(raiseExceptions=raising)
for test, expected in list(tests.items()):
if debug:
print('"%s"' % test)
self.assertRaises(expected, p.parseString, test)
with pytest.raises(expected):
p.parseString(test)

def do_equal_r(self, tests, att='cssText', debug=False):
# sets attribute att of self.r and asserts Equal
Expand All @@ -143,21 +67,23 @@ def do_equal_r(self, tests, att='cssText', debug=False):
self.r.__setattr__(att, test)
if expected is None:
expected = test
self.assertEqual(expected, self.r.__getattribute__(att))
assert self.r.__getattribute__(att) == expected

def do_raise_r(self, tests, att='_setCssText', debug=False):
# sets self.r and asserts raise
for test, expected in list(tests.items()):
if debug:
print('"%s"' % test)
self.assertRaises(expected, self.r.__getattribute__(att), test)
with pytest.raises(expected):
self.r.__getattribute__(att)(test)

def do_raise_r_list(self, tests, err, att='_setCssText', debug=False):
# sets self.r and asserts raise
for test in tests:
if debug:
print('"%s"' % test)
self.assertRaises(err, self.r.__getattribute__(att), test)
with pytest.raises(err):
self.r.__getattribute__(att)(test)


class GenerateTests(type):
Expand Down
36 changes: 19 additions & 17 deletions cssutils/tests/test_csscharsetrule.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,25 @@
import xml.dom
from . import test_cssrule
import cssutils.css
import pytest


class CSSCharsetRuleTestCase(test_cssrule.CSSRuleTestCase):
def setUp(self):
super(CSSCharsetRuleTestCase, self).setUp()
class TestCSSCharsetRule(test_cssrule.TestCSSRule):
def setup(self):
super().setup()
self.r = cssutils.css.CSSCharsetRule()
self.rRO = cssutils.css.CSSCharsetRule(readonly=True)
self.r_type = cssutils.css.CSSCharsetRule.CHARSET_RULE
self.r_typeString = 'CHARSET_RULE'

def test_init(self):
"CSSCharsetRule.__init__()"
super(CSSCharsetRuleTestCase, self).test_init()
self.assertEqual(None, self.r.encoding)
self.assertEqual('', self.r.cssText)
super().test_init()
assert self.r.encoding is None
assert '' == self.r.cssText

self.assertRaises(xml.dom.InvalidModificationErr, self.r._setCssText, 'xxx')
with pytest.raises(xml.dom.InvalidModificationErr):
self.r._setCssText('xxx')

def test_InvalidModificationErr(self):
"CSSCharsetRule InvalidModificationErr"
Expand All @@ -31,11 +33,11 @@ def test_init_encoding(self):
for enc in (None, 'UTF-8', 'utf-8', 'iso-8859-1', 'ascii'):
r = cssutils.css.CSSCharsetRule(enc)
if enc is None:
self.assertEqual(None, r.encoding)
self.assertEqual('', r.cssText)
assert r.encoding is None
assert '' == r.cssText
else:
self.assertEqual(enc.lower(), r.encoding)
self.assertEqual('@charset "%s";' % enc.lower(), r.cssText)
assert enc.lower() == r.encoding
assert '@charset "%s";' % enc.lower() == r.cssText

for enc in (' ascii ', ' ascii', 'ascii '):
self.assertRaisesEx(
Expand All @@ -57,8 +59,8 @@ def test_encoding(self):
"CSSCharsetRule.encoding"
for enc in ('UTF-8', 'utf-8', 'iso-8859-1', 'ascii'):
self.r.encoding = enc
self.assertEqual(enc.lower(), self.r.encoding)
self.assertEqual('@charset "%s";' % enc.lower(), self.r.cssText)
assert enc.lower() == self.r.encoding
assert '@charset "%s";' % enc.lower() == self.r.cssText

for enc in (None, ' ascii ', ' ascii', 'ascii '):
self.assertRaisesEx(
Expand Down Expand Up @@ -115,16 +117,16 @@ def test_cssText(self):
def test_repr(self):
"CSSCharsetRule.__repr__()"
self.r.encoding = 'utf-8'
self.assertTrue('utf-8' in repr(self.r))
assert 'utf-8' in repr(self.r)

def test_reprANDstr(self):
"CSSCharsetRule.__repr__(), .__str__()"
encoding = 'utf-8'

s = cssutils.css.CSSCharsetRule(encoding=encoding)

self.assertTrue(encoding in str(s))
assert encoding in str(s)

s2 = eval(repr(s))
self.assertTrue(isinstance(s2, s.__class__))
self.assertTrue(encoding == s2.encoding)
assert isinstance(s2, s.__class__)
assert encoding == s2.encoding
12 changes: 6 additions & 6 deletions cssutils/tests/test_csscomment.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
import cssutils.css


class CSSCommentTestCase(test_cssrule.CSSRuleTestCase):
def setUp(self):
super(CSSCommentTestCase, self).setUp()
class TestCSSComment(test_cssrule.TestCSSRule):
def setup(self):
super().setup()
self.r = cssutils.css.CSSComment()
self.rRO = cssutils.css.CSSComment(readonly=True)
self.r_type = cssutils.css.CSSComment.COMMENT
self.r_typeString = 'COMMENT'

def test_init(self):
"CSSComment.type and init"
super(CSSCommentTestCase, self).test_init()
super().test_init()

def test_csstext(self):
"CSSComment.cssText"
Expand Down Expand Up @@ -64,5 +64,5 @@ def test_reprANDstr(self):
s = cssutils.css.CSSComment(cssText=text)

s2 = eval(repr(s))
self.assertTrue(isinstance(s2, s.__class__))
self.assertTrue(text == s2.cssText)
assert isinstance(s2, s.__class__)
assert text == s2.cssText

0 comments on commit 2cdeecf

Please sign in to comment.