From 57179fead6a8eecb78be35a5597797ffca62e3b2 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Tue, 12 Jul 2022 11:06:20 -0400 Subject: [PATCH] Ran pyupgrade to Python 3.7+ (then fade to black). --- cssutils/_fetch.py | 2 +- cssutils/_fetchgae.py | 4 +- cssutils/css/csscharsetrule.py | 12 +- cssutils/css/csscomment.py | 12 +- cssutils/css/cssfontfacerule.py | 10 +- cssutils/css/cssimportrule.py | 14 +- cssutils/css/cssmediarule.py | 10 +- cssutils/css/cssnamespacerule.py | 20 +-- cssutils/css/csspagerule.py | 8 +- cssutils/css/cssrule.py | 19 +- cssutils/css/cssstyledeclaration.py | 10 +- cssutils/css/cssstylerule.py | 8 +- cssutils/css/cssstylesheet.py | 7 +- cssutils/css/cssunknownrule.py | 12 +- cssutils/css/cssvalue.py | 46 +++-- cssutils/css/cssvariablesdeclaration.py | 17 +- cssutils/css/cssvariablesrule.py | 8 +- cssutils/css/marginrule.py | 12 +- cssutils/css/property.py | 6 +- cssutils/css/selector.py | 4 +- cssutils/css/selectorlist.py | 4 +- cssutils/css/value.py | 35 ++-- cssutils/errorhandler.py | 2 +- cssutils/helper.py | 2 +- cssutils/prodparser.py | 22 +-- cssutils/profiles.py | 3 +- cssutils/sac.py | 28 +-- cssutils/script.py | 10 +- cssutils/serialize.py | 26 +-- cssutils/stylesheets/medialist.py | 6 +- cssutils/stylesheets/mediaquery.py | 6 +- cssutils/stylesheets/stylesheet.py | 2 +- cssutils/tests/test_codec.py | 70 ++++---- cssutils/tests/test_cssimportrule.py | 13 +- cssutils/tests/test_cssmediarule.py | 2 +- cssutils/tests/test_cssproperties.py | 6 +- cssutils/tests/test_cssstyledeclaration.py | 2 +- cssutils/tests/test_cssstylesheet.py | 88 ++++----- cssutils/tests/test_cssutils.py | 167 ++++++++---------- .../tests/test_cssvariablesdeclaration.py | 12 +- cssutils/tests/test_encutils/__init__.py | 6 +- cssutils/tests/test_errorhandler.py | 2 +- cssutils/tests/test_medialist.py | 3 +- cssutils/tests/test_mediaquery.py | 1 - cssutils/tests/test_parse.py | 75 ++++---- cssutils/tests/test_scripts_csscombine.py | 9 +- cssutils/tests/test_selector.py | 5 +- cssutils/tests/test_serialize.py | 86 ++++----- cssutils/tests/test_settings.py | 4 +- cssutils/tests/test_util.py | 86 ++++----- cssutils/tests/test_value.py | 2 +- cssutils/tests/test_x.py | 2 +- cssutils/tokenize2.py | 7 +- cssutils/util.py | 20 +-- encutils/__init__.py | 6 +- examples/testutil.py | 4 +- tools/try.py | 12 +- 57 files changed, 516 insertions(+), 561 deletions(-) diff --git a/cssutils/_fetch.py b/cssutils/_fetch.py index a5dac9fd..9426d4fc 100644 --- a/cssutils/_fetch.py +++ b/cssutils/_fetch.py @@ -29,7 +29,7 @@ def _defaultFetcher(url): res = urllib.request.urlopen(request) except urllib.error.HTTPError as e: # http error, e.g. 404, e can be raised - log.warn('HTTPError opening url=%s: %s %s' % (url, e.code, e.msg), error=e) + log.warn(f'HTTPError opening url={url}: {e.code} {e.msg}', error=e) except urllib.error.URLError as e: # URLError like mailto: or other IO errors, e can be raised log.warn('URLError, %s' % e.reason, error=e) diff --git a/cssutils/_fetchgae.py b/cssutils/_fetchgae.py index 64dd2b10..b823075b 100644 --- a/cssutils/_fetchgae.py +++ b/cssutils/_fetchgae.py @@ -45,7 +45,7 @@ def _defaultFetcher(url): try: r = urlfetch.fetch(url, method=urlfetch.GET) except urlfetch.Error as e: - log.warn('Error opening url=%r: %s' % (url, e), error=IOError) + log.warn(f'Error opening url={url!r}: {e}', error=IOError) else: if r.status_code == 200: # find mimetype and encoding @@ -65,6 +65,6 @@ def _defaultFetcher(url): else: # TODO: 301 etc log.warn( - 'Error opening url=%r: HTTP status %s' % (url, r.status_code), + f'Error opening url={url!r}: HTTP status {r.status_code}', error=IOError, ) diff --git a/cssutils/css/csscharsetrule.py b/cssutils/css/csscharsetrule.py index 0af1edee..56c1e1db 100644 --- a/cssutils/css/csscharsetrule.py +++ b/cssutils/css/csscharsetrule.py @@ -46,9 +46,7 @@ def __init__( :param readonly: defaults to False, not used yet """ - super(CSSCharsetRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._atkeyword = '@charset' if encoding: @@ -59,10 +57,12 @@ def __init__( self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(encoding=%r)" % (self.__class__.__name__, self.encoding) + return "cssutils.css.{}(encoding={!r})".format( + self.__class__.__name__, self.encoding + ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.encoding, id(self), @@ -89,7 +89,7 @@ def _setCssText(self, cssText): - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if the rule is readonly. """ - super(CSSCharsetRule, self)._setCssText(cssText) + super()._setCssText(cssText) wellformed = True tokenizer = self._tokenize2(cssText) diff --git a/cssutils/css/csscomment.py b/cssutils/css/csscomment.py index 8b09574c..01e6828d 100644 --- a/cssutils/css/csscomment.py +++ b/cssutils/css/csscomment.py @@ -22,9 +22,7 @@ class CSSComment(cssrule.CSSRule): def __init__( self, cssText=None, parentRule=None, parentStyleSheet=None, readonly=False ): - super(CSSComment, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._cssText = None if cssText: @@ -33,10 +31,12 @@ def __init__( self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(cssText=%r)" % (self.__class__.__name__, self.cssText) + return "cssutils.css.{}(cssText={!r})".format( + self.__class__.__name__, self.cssText + ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.cssText, id(self), @@ -62,7 +62,7 @@ def _setCssText(self, cssText): - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if the rule is readonly. """ - super(CSSComment, self)._setCssText(cssText) + super()._setCssText(cssText) tokenizer = self._tokenize2(cssText) commenttoken = self._nexttoken(tokenizer) diff --git a/cssutils/css/cssfontfacerule.py b/cssutils/css/cssfontfacerule.py index 2f8c65e1..3c3244bb 100644 --- a/cssutils/css/cssfontfacerule.py +++ b/cssutils/css/cssfontfacerule.py @@ -40,9 +40,7 @@ def __init__( CSSStyleDeclaration used to hold any font descriptions for this CSSFontFaceRule """ - super(CSSFontFaceRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._atkeyword = '@font-face' if style: @@ -53,13 +51,13 @@ def __init__( self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(style=%r)" % ( + return "cssutils.css.{}(style={!r})".format( self.__class__.__name__, self.style.cssText, ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.style.cssText, self.valid, @@ -85,7 +83,7 @@ def _setCssText(self, cssText): - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if the rule is readonly. """ - super(CSSFontFaceRule, self)._setCssText(cssText) + super()._setCssText(cssText) tokenizer = self._tokenize2(cssText) attoken = self._nexttoken(tokenizer, None) diff --git a/cssutils/css/cssimportrule.py b/cssutils/css/cssimportrule.py index 1ad55406..d0f5e70f 100644 --- a/cssutils/css/cssimportrule.py +++ b/cssutils/css/cssimportrule.py @@ -42,9 +42,7 @@ def __init__( :param name: Additional name of imported style sheet """ - super(CSSImportRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._atkeyword = '@import' self._styleSheet = None @@ -76,7 +74,7 @@ def __repr__(self): mediaText = self.media.mediaText else: mediaText = None - return "cssutils.css.%s(href=%r, mediaText=%r, name=%r)" % ( + return "cssutils.css.{}(href={!r}, mediaText={!r}, name={!r})".format( self.__class__.__name__, self.href, mediaText, @@ -88,7 +86,7 @@ def __str__(self): mediaText = self.media.mediaText else: mediaText = None - return "" % ( + return "".format( self.__class__.__name__, self.href, mediaText, @@ -120,7 +118,7 @@ def _setCssText(self, cssText): # noqa: C901 Raised if the specified CSS string value has a syntax error and is unparsable. """ - super(CSSImportRule, self)._setCssText(cssText) + super()._setCssText(cssText) tokenizer = self._tokenize2(cssText) attoken = self._nexttoken(tokenizer, None) if self._type(attoken) != self._prods.IMPORT_SYM: @@ -314,7 +312,7 @@ def _setHref(self, href): if cssText is None: # catched in next except below! - raise IOError('Cannot read Stylesheet.') + raise OSError('Cannot read Stylesheet.') # contentEncoding with parentStyleSheet.overrideEncoding, # HTTP or parent @@ -332,7 +330,7 @@ def _setHref(self, href): cssText, encodingOverride=encodingOverride, encoding=encoding ) - except (OSError, IOError, ValueError) as e: + except (OSError, ValueError) as e: self._log.warn( 'CSSImportRule: While processing imported ' 'style sheet href=%s: %r' % (self.href, e), diff --git a/cssutils/css/cssmediarule.py b/cssutils/css/cssmediarule.py index b2b6fa54..0a9660c2 100644 --- a/cssutils/css/cssmediarule.py +++ b/cssutils/css/cssmediarule.py @@ -33,9 +33,7 @@ def __init__( readonly=False, ): """constructor""" - super(CSSMediaRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._atkeyword = '@media' # 1. media @@ -48,13 +46,13 @@ def __init__( self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(mediaText=%r)" % ( + return "cssutils.css.{}(mediaText={!r})".format( self.__class__.__name__, self.media.mediaText, ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.media.mediaText, id(self), @@ -85,7 +83,7 @@ def _setCssText(self, cssText): # noqa: C901 Raised if the rule is readonly. """ # media "name"? { cssRules } - super(CSSMediaRule, self)._setCssText(cssText) + super()._setCssText(cssText) # might be (cssText, namespaces) cssText, namespaces = self._splitNamespacesOff(cssText) diff --git a/cssutils/css/cssnamespacerule.py b/cssutils/css/cssnamespacerule.py index 4d6a47ef..01fb4cf8 100644 --- a/cssutils/css/cssnamespacerule.py +++ b/cssutils/css/cssnamespacerule.py @@ -67,9 +67,7 @@ def __init__( : IDENT ; """ - super(CSSNamespaceRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._atkeyword = '@namespace' self._prefix = '' self._namespaceURI = None @@ -91,18 +89,20 @@ def __init__( self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(namespaceURI=%r, prefix=%r)" % ( + return "cssutils.css.{}(namespaceURI={!r}, prefix={!r})".format( self.__class__.__name__, self.namespaceURI, self.prefix, ) def __str__(self): - return "" % ( - self.__class__.__name__, - self.namespaceURI, - self.prefix, - id(self), + return ( + "".format( + self.__class__.__name__, + self.namespaceURI, + self.prefix, + id(self), + ) ) def _getCssText(self): @@ -125,7 +125,7 @@ def _setCssText(self, cssText): # noqa: C901 Raised if the specified CSS string value has a syntax error and is unparsable. """ - super(CSSNamespaceRule, self)._setCssText(cssText) + super()._setCssText(cssText) tokenizer = self._tokenize2(cssText) attoken = self._nexttoken(tokenizer, None) if self._type(attoken) != self._prods.NAMESPACE_SYM: diff --git a/cssutils/css/csspagerule.py b/cssutils/css/csspagerule.py index 0985340a..b7b71402 100644 --- a/cssutils/css/csspagerule.py +++ b/cssutils/css/csspagerule.py @@ -69,9 +69,7 @@ def __init__( :param style: CSSStyleDeclaration for this CSSStyleRule """ - super(CSSPageRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._atkeyword = '@page' self._specificity = (0, 0, 0) @@ -94,7 +92,7 @@ def __init__( self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(selectorText=%r, style=%r)" % ( + return "cssutils.css.{}(selectorText={!r}, style={!r})".format( self.__class__.__name__, self.selectorText, self.style.cssText, @@ -299,7 +297,7 @@ def _setCssText(self, cssText): - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if the rule is readonly. """ - super(CSSPageRule, self)._setCssText(cssText) + super()._setCssText(cssText) tokenizer = self._tokenize2(cssText) if self._type(self._nexttoken(tokenizer)) != self._prods.PAGE_SYM: diff --git a/cssutils/css/cssrule.py b/cssutils/css/cssrule.py index aef3f0c7..29585112 100644 --- a/cssutils/css/cssrule.py +++ b/cssutils/css/cssrule.py @@ -61,7 +61,7 @@ class CSSRule(cssutils.util.Base2): def __init__(self, parentRule=None, parentStyleSheet=None, readonly=False): """Set common attributes for all rules.""" - super(CSSRule, self).__init__() + super().__init__() self._parent = parentRule self._parentRule = parentRule self._parentStyleSheet = parentStyleSheet @@ -78,7 +78,9 @@ def _setAtkeyword(self, keyword): self._keyword = keyword else: self._log.error( - '%s: Invalid atkeyword for this rule: %r' % (self.atkeyword, keyword), + '{}: Invalid atkeyword for this rule: {!r}'.format( + self.atkeyword, keyword + ), error=xml.dom.InvalidModificationErr, ) @@ -160,16 +162,13 @@ class CSSRuleRules(CSSRule): def __init__(self, parentRule=None, parentStyleSheet=None): - super(CSSRuleRules, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self.cssRules = cssutils.css.CSSRuleList() def __iter__(self): """Generator iterating over these rule's cssRules.""" - for rule in self._cssRules: - yield rule + yield from self._cssRules def _setCssRules(self, cssRules): "Set new cssRules and update contained rules refs." @@ -257,7 +256,7 @@ def _prepareInsertRule(self, rule, index=None): and not isinstance(tempsheet.cssRules[0], cssutils.css.CSSRule) ): self._log.error( - '%s: Invalid Rule: %s' % (self.__class__.__name__, rule) + '{}: Invalid Rule: {}'.format(self.__class__.__name__, rule) ) return False, False rule = tempsheet.cssRules[0] @@ -269,7 +268,9 @@ def _prepareInsertRule(self, rule, index=None): return True, True elif not isinstance(rule, cssutils.css.CSSRule): - self._log.error('%s: Not a CSSRule: %s' % (rule, self.__class__.__name__)) + self._log.error( + '{}: Not a CSSRule: {}'.format(rule, self.__class__.__name__) + ) return False, False return rule, index diff --git a/cssutils/css/cssstyledeclaration.py b/cssutils/css/cssstyledeclaration.py index 91505ef6..5e8e3ecb 100644 --- a/cssutils/css/cssstyledeclaration.py +++ b/cssutils/css/cssstyledeclaration.py @@ -106,7 +106,7 @@ def __init__(self, cssText='', parentRule=None, readonly=False, validating=None) a flag defining if this sheet should be validated on change. Defaults to None, which means defer to the parent stylesheet. """ - super(CSSStyleDeclaration, self).__init__() + super().__init__() self._parentRule = parentRule self.validating = validating self.cssText = cssText @@ -192,7 +192,7 @@ def __setattr__(self, n, v): ] known.extend(CSS2Properties._properties) if n in known: - super(CSSStyleDeclaration, self).__setattr__(n, v) + super().__setattr__(n, v) else: raise AttributeError( 'Unknown CSS Property, ' @@ -201,13 +201,13 @@ def __setattr__(self, n, v): ) def __repr__(self): - return "cssutils.css.%s(cssText=%r)" % ( + return "cssutils.css.{}(cssText={!r})".format( self.__class__.__name__, self.getCssText(separator=' '), ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.length, len(self.getProperties(all=True)), @@ -666,7 +666,7 @@ def setProperty(self, name, value=None, priority='', normalize=True, replace=Tru self.seq._readonly = True else: - self._log.warn('Invalid Property: %s: %s %s' % (name, value, priority)) + self._log.warn('Invalid Property: {}: {} {}'.format(name, value, priority)) def item(self, index): """(DOM) Retrieve the properties that have been explicitly set in diff --git a/cssutils/css/cssstylerule.py b/cssutils/css/cssstylerule.py index a2f74a97..e98d0e5c 100644 --- a/cssutils/css/cssstylerule.py +++ b/cssutils/css/cssstylerule.py @@ -37,9 +37,7 @@ def __init__( readonly if True allows setting of properties in constructor only """ - super(CSSStyleRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self.selectorList = SelectorList() if selectorText: @@ -57,7 +55,7 @@ def __repr__(self): st = (self.selectorText, self._namespaces) else: st = self.selectorText - return "cssutils.css.%s(selectorText=%r, style=%r)" % ( + return "cssutils.css.{}(selectorText={!r}, style={!r})".format( self.__class__.__name__, st, self.style.cssText, @@ -100,7 +98,7 @@ def _setCssText(self, cssText): # noqa: C901 - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if the rule is readonly. """ - super(CSSStyleRule, self)._setCssText(cssText) + super()._setCssText(cssText) # might be (cssText, namespaces) cssText, namespaces = self._splitNamespacesOff(cssText) diff --git a/cssutils/css/cssstylesheet.py b/cssutils/css/cssstylesheet.py index f82537ed..fcc79db2 100644 --- a/cssutils/css/cssstylesheet.py +++ b/cssutils/css/cssstylesheet.py @@ -47,7 +47,7 @@ def __init__( """ For parameters see :class:`~cssutils.stylesheets.StyleSheet` """ - super(CSSStyleSheet, self).__init__( + super().__init__( 'text/css', href, media, @@ -70,15 +70,14 @@ def __init__( def __iter__(self): "Generator which iterates over cssRules." - for rule in self._cssRules: - yield rule + yield from self._cssRules def __repr__(self): if self.media: mediaText = self.media.mediaText else: mediaText = None - return "cssutils.css.%s(href=%r, media=%r, title=%r)" % ( + return "cssutils.css.{}(href={!r}, media={!r}, title={!r})".format( self.__class__.__name__, self.href, mediaText, diff --git a/cssutils/css/cssunknownrule.py b/cssutils/css/cssunknownrule.py index 22c62d69..23558c2b 100644 --- a/cssutils/css/cssunknownrule.py +++ b/cssutils/css/cssunknownrule.py @@ -23,9 +23,7 @@ def __init__( :param cssText: of type string """ - super(CSSUnknownRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._atkeyword = None if cssText: self.cssText = cssText @@ -33,10 +31,12 @@ def __init__( self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(cssText=%r)" % (self.__class__.__name__, self.cssText) + return "cssutils.css.{}(cssText={!r})".format( + self.__class__.__name__, self.cssText + ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.cssText, id(self), @@ -61,7 +61,7 @@ def _setCssText(self, cssText): # noqa: C901 - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if the rule is readonly. """ - super(CSSUnknownRule, self)._setCssText(cssText) + super()._setCssText(cssText) tokenizer = self._tokenize2(cssText) attoken = self._nexttoken(tokenizer, None) if not attoken or self._type(attoken) != self._prods.ATKEYWORD: diff --git a/cssutils/css/cssvalue.py b/cssutils/css/cssvalue.py index 09871b06..d3ebb719 100644 --- a/cssutils/css/cssvalue.py +++ b/cssutils/css/cssvalue.py @@ -46,7 +46,7 @@ def __init__(self, cssText=None, parent=None, readonly=False): :param readonly: defaults to False """ - super(CSSValue, self).__init__() + super().__init__() self._cssValueType = None self.wellformed = False @@ -62,7 +62,7 @@ def __init__(self, cssText=None, parent=None, readonly=False): self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(%r)" % (self.__class__.__name__, self.cssText) + return "cssutils.css.{}({!r})".format(self.__class__.__name__, self.cssText) def __str__(self): return ( @@ -555,16 +555,16 @@ class CSSPrimitiveValue(CSSValue): def __init__(self, cssText=None, parent=None, readonly=False): """See CSSPrimitiveValue.__init__()""" - super(CSSPrimitiveValue, self).__init__( - cssText=cssText, parent=parent, readonly=readonly - ) + super().__init__(cssText=cssText, parent=parent, readonly=readonly) def __str__(self): - return "" % ( - self.__class__.__name__, - self.primitiveTypeString, - self.cssText, - id(self), + return ( + "".format( + self.__class__.__name__, + self.primitiveTypeString, + self.cssText, + id(self), + ) ) _unitnames = [ @@ -800,7 +800,7 @@ def setFloatValue(self, unitType, floatValue): if val == int(val): val = int(val) - self.cssText = '%s%s' % (val, dim) + self.cssText = '{}{}'.format(val, dim) def getStringValue(self): """(DOM) This method is used to get the string value. If the @@ -922,7 +922,7 @@ def _getCssText(self): def _setCssText(self, cssText): """Use CSSValue.""" - return super(CSSPrimitiveValue, self)._setCssText(cssText) + return super()._setCssText(cssText) cssText = property( _getCssText, _setCssText, doc="A string representation of the current value." @@ -945,9 +945,7 @@ class CSSValueList(CSSValue): def __init__(self, cssText=None, parent=None, readonly=False): """Init a new CSSValueList""" - super(CSSValueList, self).__init__( - cssText=cssText, parent=parent, readonly=readonly - ) + super().__init__(cssText=cssText, parent=parent, readonly=readonly) self._items = [] def __iter__(self): @@ -1003,7 +1001,7 @@ def __init__(self, cssText=None, parent=None, readonly=False): :param readonly: defaults to False """ - super(CSSFunction, self).__init__(parent=parent) + super().__init__(parent=parent) self._funcType = None self.valid = False self.wellformed = False @@ -1134,10 +1132,10 @@ def __init__(self, cssText=None, parent=None, readonly=False): self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(%r)" % (self.__class__.__name__, self.cssText) + return "cssutils.css.{}({!r})".format(self.__class__.__name__, self.cssText) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.colorType, self.cssText, @@ -1241,7 +1239,7 @@ def _getCssText(self): return cssutils.ser.do_css_CalcValue(self) def _setCssText(self, cssText): - return super(CalcValue, self)._setCssText(cssText) + return super()._setCssText(cssText) cssText = property( _getCssText, _setCssText, doc="A string representation of the current value." @@ -1293,7 +1291,7 @@ def _getCssText(self): def _setCssText(self, cssText): # self._log.warn(u'CSSValue: Unoffial and probably invalid MS value used!') - return super(ExpressionValue, self)._setCssText(cssText) + return super()._setCssText(cssText) cssText = property( _getCssText, _setCssText, doc="A string representation of the current value." @@ -1312,15 +1310,13 @@ def __init__(self, cssText=None, parent=None, readonly=False): defaults to False """ self._name = None - super(CSSVariable, self).__init__( - cssText=cssText, parent=parent, readonly=readonly - ) + super().__init__(cssText=cssText, parent=parent, readonly=readonly) def __repr__(self): - return "cssutils.css.%s(%r)" % (self.__class__.__name__, self.cssText) + return "cssutils.css.{}({!r})".format(self.__class__.__name__, self.cssText) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.name, self.value, diff --git a/cssutils/css/cssvariablesdeclaration.py b/cssutils/css/cssvariablesdeclaration.py index 77978ebb..68b6db6c 100644 --- a/cssutils/css/cssvariablesdeclaration.py +++ b/cssutils/css/cssvariablesdeclaration.py @@ -39,7 +39,7 @@ def __init__(self, cssText='', parentRule=None, readonly=False): : IDENT S* ; """ - super(CSSVariablesDeclaration, self).__init__() + super().__init__() self._parentRule = parentRule self._vars = {} if cssText: @@ -48,10 +48,12 @@ def __init__(self, cssText='', parentRule=None, readonly=False): self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(cssText=%r)" % (self.__class__.__name__, self.cssText) + return "cssutils.css.{}(cssText={!r})".format( + self.__class__.__name__, self.cssText + ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.length, id(self), @@ -79,8 +81,7 @@ def __delitem__(self, variableName): def __iter__(self): """Iterator of names of set variables.""" - for name in list(self.keys()): - yield name + yield from list(self.keys()) def keys(self): """Analoguous to standard dict returns variable names which are set in @@ -285,7 +286,9 @@ def setVariable(self, variableName, value): normalize(variableName), 'variableName', Sequence(PreDef.ident()) ) if not wellformed: - self._log.error('Invalid variableName: %r: %r' % (variableName, value)) + self._log.error( + 'Invalid variableName: {!r}: {!r}'.format(variableName, value) + ) else: # check value if isinstance(value, PropertyValue): @@ -295,7 +298,7 @@ def setVariable(self, variableName, value): if not v.wellformed: self._log.error( - 'Invalid variable value: %r: %r' % (variableName, value) + 'Invalid variable value: {!r}: {!r}'.format(variableName, value) ) else: # update seq diff --git a/cssutils/css/cssvariablesrule.py b/cssutils/css/cssvariablesrule.py index 88421875..1242ff15 100644 --- a/cssutils/css/cssvariablesrule.py +++ b/cssutils/css/cssvariablesrule.py @@ -52,9 +52,7 @@ def __init__( """ If readonly allows setting of properties in constructor only. """ - super(CSSVariablesRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._atkeyword = '@variables' # dummy @@ -68,7 +66,7 @@ def __init__( self._readonly = readonly def __repr__(self): - return "cssutils.css.%s(mediaText=%r, variables=%r)" % ( + return "cssutils.css.{}(mediaText={!r}, variables={!r})".format( self.__class__.__name__, self._media.mediaText, self.variables.cssText, @@ -117,7 +115,7 @@ def _setCssText(self, cssText): : LBRACE S* vardeclaration [ ';' S* vardeclaration ]* '}' S* ; """ - super(CSSVariablesRule, self)._setCssText(cssText) + super()._setCssText(cssText) tokenizer = self._tokenize2(cssText) attoken = self._nexttoken(tokenizer, None) diff --git a/cssutils/css/marginrule.py b/cssutils/css/marginrule.py index 6d5e093b..7e0fe385 100644 --- a/cssutils/css/marginrule.py +++ b/cssutils/css/marginrule.py @@ -79,9 +79,7 @@ def __init__( :param style: CSSStyleDeclaration for this MarginRule """ - super(MarginRule, self).__init__( - parentRule=parentRule, parentStyleSheet=parentStyleSheet - ) + super().__init__(parentRule=parentRule, parentStyleSheet=parentStyleSheet) self._atkeyword = self._keyword = None @@ -101,7 +99,9 @@ def _setMargin(self, margin): if n not in MarginRule.margins: self._log.error( - 'Invalid margin @keyword for this %s rule: %r' % (self.margin, margin), + 'Invalid margin @keyword for this {} rule: {!r}'.format( + self.margin, margin + ), error=xml.dom.InvalidModificationErr, ) @@ -120,7 +120,7 @@ def _setMargin(self, margin): atkeyword = margin def __repr__(self): - return "cssutils.css.%s(margin=%r, style=%r)" % ( + return "cssutils.css.{}(margin={!r}, style={!r})".format( self.__class__.__name__, self.margin, self.style.cssText, @@ -153,7 +153,7 @@ def _setCssText(self, cssText): - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if the rule is readonly. """ - super(MarginRule, self)._setCssText(cssText) + super()._setCssText(cssText) # TEMP: all style tokens are saved in store to fill styledeclaration # TODO: resolve when all generators diff --git a/cssutils/css/property.py b/cssutils/css/property.py index f676980d..c21f15ea 100644 --- a/cssutils/css/property.py +++ b/cssutils/css/property.py @@ -59,7 +59,7 @@ def __init__( the parent object, normally a :class:`cssutils.css.CSSStyleDeclaration` """ - super(Property, self).__init__() + super().__init__() self.seqs = [[], None, []] self.wellformed = False self._mediaQuery = _mediaQuery @@ -79,7 +79,7 @@ def __init__( self.priority = priority def __repr__(self): - return "cssutils.css.%s(name=%r, value=%r, priority=%r)" % ( + return "cssutils.css.{}(name={!r}, value={!r}, priority={!r})".format( self.__class__.__name__, self.literalname, self.propertyValue.cssText, @@ -87,7 +87,7 @@ def __repr__(self): ) def __str__(self): - return "<%s.%s object name=%r value=%r priority=%r valid=%r at 0x%x>" % ( + return "<{}.{} object name={!r} value={!r} priority={!r} valid={!r} at 0x{:x}>".format( self.__class__.__module__, self.__class__.__name__, self.name, diff --git a/cssutils/css/selector.py b/cssutils/css/selector.py index 2985ad2f..e819fbcc 100644 --- a/cssutils/css/selector.py +++ b/cssutils/css/selector.py @@ -109,7 +109,7 @@ def __init__(self, selectorText=None, parent=None, readonly=False): readonly default to False """ - super(Selector, self).__init__() + super().__init__() self.__namespaces = _SimpleNamespaces(log=self._log) self._element = None @@ -126,7 +126,7 @@ def __repr__(self): st = (self.selectorText, self._getUsedNamespaces()) else: st = self.selectorText - return "cssutils.css.%s(selectorText=%r)" % (self.__class__.__name__, st) + return "cssutils.css.{}(selectorText={!r})".format(self.__class__.__name__, st) def __str__(self): return ( diff --git a/cssutils/css/selectorlist.py b/cssutils/css/selectorlist.py index c4f9d6d7..f86aa31c 100644 --- a/cssutils/css/selectorlist.py +++ b/cssutils/css/selectorlist.py @@ -33,7 +33,7 @@ def __init__(self, selectorText=None, parentRule=None, readonly=False): parentRule the parent CSSRule if available """ - super(SelectorList, self).__init__() + super().__init__() self._parentRule = parentRule @@ -47,7 +47,7 @@ def __repr__(self): st = (self.selectorText, self._namespaces) else: st = self.selectorText - return "cssutils.css.%s(selectorText=%r)" % (self.__class__.__name__, st) + return "cssutils.css.{}(selectorText={!r})".format(self.__class__.__name__, st) def __str__(self): return "" % ( diff --git a/cssutils/css/value.py b/cssutils/css/value.py index 08dfcd1a..4a6720a0 100644 --- a/cssutils/css/value.py +++ b/cssutils/css/value.py @@ -45,7 +45,7 @@ def __init__(self, cssText=None, parent=None, readonly=False): :param readonly: defaults to False """ - super(PropertyValue, self).__init__() + super().__init__() self.parent = parent self.wellformed = False @@ -68,11 +68,10 @@ def __getitem__(self, index): def __iter__(self): "Generator which iterates over values." - for item in self.__items(): - yield item + yield from self.__items() def __repr__(self): - return "cssutils.css.%s(%r)" % (self.__class__.__name__, self.cssText) + return "cssutils.css.{}({!r})".format(self.__class__.__name__, self.cssText) def __str__(self): return "" % ( @@ -246,7 +245,7 @@ class Value(cssutils.util._NewBase): _value = '' def __init__(self, cssText=None, parent=None, readonly=False): - super(Value, self).__init__() + super().__init__() self.parent = parent self.wellformed = False @@ -255,15 +254,17 @@ def __init__(self, cssText=None, parent=None, readonly=False): self.cssText = cssText def __repr__(self): - return "cssutils.css.%s(%r)" % (self.__class__.__name__, self.cssText) + return "cssutils.css.{}({!r})".format(self.__class__.__name__, self.cssText) def __str__(self): - return "" % ( - self.__class__.__name__, - self.type, - self.value, - self.cssText, - id(self), + return ( + "".format( + self.__class__.__name__, + self.type, + self.value, + self.cssText, + id(self), + ) ) def _setCssText(self, cssText): @@ -599,7 +600,7 @@ class URIValue(Value): _uri = Value._value def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.type, self.value, @@ -764,7 +765,7 @@ def _productions(self): return funcProds def _setCssText(self, cssText): - super(MSValue, self)._setCssText(cssText) + super()._setCssText(cssText) cssText = property( lambda self: cssutils.ser.do_css_MSValue(self), @@ -783,7 +784,9 @@ class CSSCalc(CSSFunction): _functionName = 'CSSCalc' def __str__(self): - return "" % (self.__class__.__name__, id(self)) + return "".format( + self.__class__.__name__, id(self) + ) def _setCssText(self, cssText): self._checkReadonly() @@ -864,7 +867,7 @@ class CSSVariable(CSSFunction): _fallback = None def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.name, self.value, diff --git a/cssutils/errorhandler.py b/cssutils/errorhandler.py index 8d4894a9..85b9cc40 100644 --- a/cssutils/errorhandler.py +++ b/cssutils/errorhandler.py @@ -89,7 +89,7 @@ def __handle( value, line, col = token[1], token[2], token[3] else: value, line, col = token.value, token.line, token.col - msg = '%s [%s:%s: %s]' % (msg, line, col, value) + msg = f'{msg} [{line}:{col}: {value}]' if error and self.raiseExceptions and not neverraise: if isinstance(error, urllib.error.HTTPError) or isinstance( diff --git a/cssutils/helper.py b/cssutils/helper.py index d768be07..0834af7d 100644 --- a/cssutils/helper.py +++ b/cssutils/helper.py @@ -26,7 +26,7 @@ def newFunc(*args, **kwargs): import warnings warnings.warn( - "Call to deprecated method %r. %s" % (func.__name__, self.msg), + f"Call to deprecated method {func.__name__!r}. {self.msg}", category=DeprecationWarning, stacklevel=2, ) diff --git a/cssutils/prodparser.py b/cssutils/prodparser.py index 35e61a75..d4d1e7c7 100644 --- a/cssutils/prodparser.py +++ b/cssutils/prodparser.py @@ -112,13 +112,13 @@ def nextProd(self, token): else: if not optional: # None matched but also None is optional - raise NoMatch('No match for %s in %s' % (token, self)) + raise NoMatch(f'No match for {token} in {self}') # raise ParseError(u'No match in %s for %s' % (self, token)) elif token: raise Exhausted('Extra token') def __repr__(self): - return "" % ( + return "".format( self.__class__.__name__, self.__str__(), self.optional, @@ -233,13 +233,13 @@ def nextProd(self, token): raise Done() else: - raise NoMatch('No match for %s in %s' % (token, self)) + raise NoMatch(f'No match for {token} in {self}') if token: raise Exhausted('Extra token') def __repr__(self): - return "" % ( + return "".format( self.__class__.__name__, self.__str__(), self.optional, @@ -359,7 +359,7 @@ def __str__(self): return self._name def __repr__(self): - return "" % ( + return "".format( self.__class__.__name__, self._name, id(self), @@ -542,7 +542,7 @@ def parse( # noqa: C901 elif type_ == self.types.INVALID: # invalidate parse wellformed = False - self._log.error('Invalid token: %r' % (token,)) + self._log.error(f'Invalid token: {token!r}') break elif type_ == 'EOF': @@ -583,7 +583,7 @@ def parse( # noqa: C901 else: wellformed = False - self._log.error('%s: %s: %r' % (name, e, token)) + self._log.error(f'{name}: {e}: {token!r}') break except ParseError as e: @@ -595,7 +595,7 @@ def parse( # noqa: C901 else: wellformed = False - self._log.error('%s: %s: %r' % (name, e, token)) + self._log.error(f'{name}: {e}: {token!r}') break else: @@ -660,12 +660,12 @@ def parse( # noqa: C901 # last was a S operator which may End a Sequence, then ok if hasattr(lastprod, 'mayEnd') and not lastprod.mayEnd: wellformed = False - self._log.error('%s: %s' % (name, e)) + self._log.error(f'{name}: {e}') except ParseError as e: prod = None wellformed = False - self._log.error('%s: %s' % (name, e)) + self._log.error(f'{name}: {e}') else: if prods[-1].optional: @@ -677,7 +677,7 @@ def parse( # noqa: C901 if prod and not prod.optional: wellformed = False self._log.error( - '%s: Missing token for production %r' % (name, str(prod)) + f'{name}: Missing token for production {str(prod)!r}' ) break elif len(prods) > 1: diff --git a/cssutils/profiles.py b/cssutils/profiles.py index 7cea09b2..b4b2c839 100644 --- a/cssutils/profiles.py +++ b/cssutils/profiles.py @@ -361,8 +361,7 @@ def propertiesByProfile(self, profiles=None): profiles = (profiles,) try: for profile in sorted(profiles): - for name in sorted(self._profilesProperties[profile].keys()): - yield name + yield from sorted(self._profilesProperties[profile].keys()) except KeyError as e: raise NoSuchProfileException(e) diff --git a/cssutils/sac.py b/cssutils/sac.py index 7657d6bc..07ec7b5d 100644 --- a/cssutils/sac.py +++ b/cssutils/sac.py @@ -67,7 +67,7 @@ def log(msg): def comment(self, text, line=None, col=None): "Receive notification of a comment." - self._log("comment %r at [%s, %s]" % (text, line, col)) + self._log(f"comment {text!r} at [{line}, {col}]") def startDocument(self, encoding): "Receive notification of the beginning of a style sheet." @@ -81,43 +81,43 @@ def endDocument(self, source=None, line=None, col=None): def importStyle(self, uri, media, name, line=None, col=None): "Receive notification of a import statement in the style sheet." # defaultNamespaceURI??? - self._log("importStyle at [%s, %s]" % (line, col)) + self._log(f"importStyle at [{line}, {col}]") def namespaceDeclaration(self, prefix, uri, line=None, col=None): "Receive notification of an unknown rule t-rule not supported by this parser." # prefix might be None! - self._log("namespaceDeclaration at [%s, %s]" % (line, col)) + self._log(f"namespaceDeclaration at [{line}, {col}]") def startSelector(self, selectors=None, line=None, col=None): "Receive notification of the beginning of a rule statement." # TODO selectorList! - self._log("startSelector at [%s, %s]" % (line, col)) + self._log(f"startSelector at [{line}, {col}]") def endSelector(self, selectors=None, line=None, col=None): "Receive notification of the end of a rule statement." - self._log("endSelector at [%s, %s]" % (line, col)) + self._log(f"endSelector at [{line}, {col}]") def property(self, name, value='TODO', important=False, line=None, col=None): "Receive notification of a declaration." # TODO: value is LexicalValue? - self._log("property %r at [%s, %s]" % (name, line, col)) + self._log(f"property {name!r} at [{line}, {col}]") def ignorableAtRule(self, atRule, line=None, col=None): "Receive notification of an unknown rule t-rule not supported by this parser." - self._log("ignorableAtRule %r at [%s, %s]" % (atRule, line, col)) + self._log(f"ignorableAtRule {atRule!r} at [{line}, {col}]") class EchoHandler(DocumentHandler): "Echos all input to property `out`" def __init__(self): - super(EchoHandler, self).__init__() + super().__init__() self._out = [] out = property(lambda self: ''.join(self._out)) def startDocument(self, encoding): - super(EchoHandler, self).startDocument(encoding) + super().startDocument(encoding) if 'utf-8' != encoding: self._out.append('@charset "%s";\n' % encoding) @@ -127,7 +127,7 @@ def startDocument(self, encoding): def importStyle(self, uri, media, name, line=None, col=None): "Receive notification of a import statement in the style sheet." # defaultNamespaceURI??? - super(EchoHandler, self).importStyle(uri, media, name, line, col) + super().importStyle(uri, media, name, line, col) self._out.append( '@import %s%s%s;\n' % ( @@ -138,14 +138,14 @@ def importStyle(self, uri, media, name, line=None, col=None): ) def namespaceDeclaration(self, prefix, uri, line=None, col=None): - super(EchoHandler, self).namespaceDeclaration(prefix, uri, line, col) + super().namespaceDeclaration(prefix, uri, line, col) self._out.append( '@namespace %s%s;\n' % ('%s ' % prefix if prefix else '', helper.string(uri)) ) def startSelector(self, selectors=None, line=None, col=None): - super(EchoHandler, self).startSelector(selectors, line, col) + super().startSelector(selectors, line, col) if selectors: self._out.append(', '.join(selectors)) self._out.append(' {\n') @@ -154,9 +154,9 @@ def endSelector(self, selectors=None, line=None, col=None): self._out.append(' }') def property(self, name, value, important=False, line=None, col=None): - super(EchoHandler, self).property(name, value, line, col) + super().property(name, value, line, col) self._out.append( - ' %s: %s%s;\n' % (name, value, ' !important' if important else '') + ' {}: {}{};\n'.format(name, value, ' !important' if important else '') ) diff --git a/cssutils/script.py b/cssutils/script.py index 02fe0307..30f8d6ae 100644 --- a/cssutils/script.py +++ b/cssutils/script.py @@ -30,7 +30,7 @@ class CSSCaptureHTMLParser(html.parser.HTMLParser): sheets = [] # (type, [atts, cssText]) def _loweratts(self, atts): - return dict([(a.lower(), v.lower()) for a, v in atts]) + return {a.lower(): v.lower() for a, v in atts} def handle_starttag(self, tag, atts): if tag == 'link': @@ -114,9 +114,7 @@ def _doRequest(self, url): try: res = urllib.request.urlopen(req) except urllib.error.HTTPError as e: - self._log.critical( - ' %s\n%s %s\n%s' % (e.geturl(), e.code, e.msg, e.headers) - ) + self._log.critical(f' {e.geturl()}\n{e.code} {e.msg}\n{e.headers}') return None, None # get real url @@ -286,7 +284,7 @@ def saveto(self, dir, saveraw=False, minified=False): url = sheet.href if not url: inlines += 1 - url = '%s_INLINE_%s.css' % (self._filename, inlines) + url = f'{self._filename}_INLINE_{inlines}.css' # build savepath scheme, loc, path, query, fragment = urllib.parse.urlsplit(url) @@ -304,7 +302,7 @@ def saveto(self, dir, saveraw=False, minified=False): raise e self._log.debug('Path "%s" already exists.', savepath) - self._log.info('SAVING %s, %s %r' % (i + 1, msg, savefn)) + self._log.info(f'SAVING {i + 1}, {msg} {savefn!r}') sf = open(savefn, 'wb') if saveraw: diff --git a/cssutils/serialize.py b/cssutils/serialize.py index e954d47e..afb4ca66 100644 --- a/cssutils/serialize.py +++ b/cssutils/serialize.py @@ -115,17 +115,17 @@ def __init__(self, **initials): self.__setattr__(key, value) def __repr__(self): - return "cssutils.css.%s(%s)" % ( + return "cssutils.css.{}({})".format( self.__class__.__name__, ', '.join( - ['\n %s=%r' % (p, self.__getattribute__(p)) for p in self.__dict__] + [f'\n {p}={self.__getattribute__(p)!r}' for p in self.__dict__] ), ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.mediaText, id(self), diff --git a/cssutils/stylesheets/mediaquery.py b/cssutils/stylesheets/mediaquery.py index c4ba0f0a..938afe48 100644 --- a/cssutils/stylesheets/mediaquery.py +++ b/cssutils/stylesheets/mediaquery.py @@ -54,7 +54,7 @@ def __init__(self, mediaText=None, readonly=False, _partof=False): # _standalone: True if new from ML parser """ - super(MediaQuery, self).__init__() + super().__init__() self._wellformed = False self._mediaType = '' @@ -66,13 +66,13 @@ def __init__(self, mediaText=None, readonly=False, _partof=False): self._readonly = readonly def __repr__(self): - return "cssutils.stylesheets.%s(mediaText=%r)" % ( + return "cssutils.stylesheets.{}(mediaText={!r})".format( self.__class__.__name__, self.mediaText, ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.mediaText, id(self), diff --git a/cssutils/stylesheets/stylesheet.py b/cssutils/stylesheets/stylesheet.py index 30195784..a6396de2 100644 --- a/cssutils/stylesheets/stylesheet.py +++ b/cssutils/stylesheets/stylesheet.py @@ -78,7 +78,7 @@ def __init__( a flag defining if this sheet should be validate on change. """ - super(StyleSheet, self).__init__() + super().__init__() self.validating = validating diff --git a/cssutils/tests/test_codec.py b/cssutils/tests/test_codec.py index dc9e8d68..dc6f5908 100644 --- a/cssutils/tests/test_codec.py +++ b/cssutils/tests/test_codec.py @@ -16,7 +16,7 @@ class Queue: """ def __init__(self): - self._buffer = "".encode() + self._buffer = b"" def write(self, chars): # TODO ??? @@ -30,7 +30,7 @@ def write(self, chars): def read(self, size=-1): if size < 0: s = self._buffer - self._buffer = "".encode() + self._buffer = b"" return s else: s = self._buffer[:size] @@ -41,12 +41,12 @@ def read(self, size=-1): class CodecTestCase: def test_detectencoding_str(self): "codec.detectencoding_str()" - assert codec.detectencoding_str(''.encode()) == (None, False) - assert codec.detectencoding_str('\xef'.encode('latin1')) == (None, False) - assert codec.detectencoding_str('\xef\x33'.encode("utf-8")) == ("utf-8", False) - assert codec.detectencoding_str('\xc3\xaf3'.encode("utf-8")) == ("utf-8", False) - assert codec.detectencoding_str('\xef\xbb'.encode("latin1")) == (None, False) - assert codec.detectencoding_str('\xef\xbb\x33'.encode("utf-8")) == ( + assert codec.detectencoding_str(b'') == (None, False) + assert codec.detectencoding_str(b'\xef') == (None, False) + assert codec.detectencoding_str('\xef\x33'.encode()) == ("utf-8", False) + assert codec.detectencoding_str('\xc3\xaf3'.encode()) == ("utf-8", False) + assert codec.detectencoding_str(b'\xef\xbb') == (None, False) + assert codec.detectencoding_str('\xef\xbb\x33'.encode()) == ( "utf-8", False, ) @@ -54,14 +54,14 @@ def test_detectencoding_str(self): "utf-8-sig", True, ) - assert codec.detectencoding_str('\xff'.encode("latin1")) == (None, False) - assert codec.detectencoding_str('\xff\x33'.encode("utf-8")) == ("utf-8", False) - assert codec.detectencoding_str('\xff\xfe'.encode("latin1")) == (None, False) + assert codec.detectencoding_str(b'\xff') == (None, False) + assert codec.detectencoding_str('\xff\x33'.encode()) == ("utf-8", False) + assert codec.detectencoding_str(b'\xff\xfe') == (None, False) assert codec.detectencoding_str('\xff\xfe\x33'.encode("utf-16")) == ( "utf-16", True, ) - assert codec.detectencoding_str('\xff\xfe\x00'.encode("latin1")) == ( + assert codec.detectencoding_str(b'\xff\xfe\x00') == ( None, False, ) @@ -77,7 +77,7 @@ def test_detectencoding_str(self): assert codec.detectencoding_str('\x00\x33'.encode()) == ("utf-8", False) assert codec.detectencoding_str('\x00\x00'.encode()) == (None, False) assert codec.detectencoding_str('\x00\x00\x33'.encode()) == ("utf-8", False) - assert codec.detectencoding_str('\x00\x00\xfe'.encode('latin1')) == ( + assert codec.detectencoding_str(b'\x00\x00\xfe') == ( None, False, ) @@ -90,7 +90,7 @@ def test_detectencoding_str(self): "utf-32", True, ) - assert codec.detectencoding_str('@'.encode()) == (None, False) + assert codec.detectencoding_str(b'@') == (None, False) assert codec.detectencoding_str('@\x33'.encode()) == ("utf-8", False) assert codec.detectencoding_str('@\x00'.encode()) == (None, False) assert codec.detectencoding_str('@\x00\x33'.encode()) == ("utf-8", False) @@ -100,22 +100,22 @@ def test_detectencoding_str(self): "utf-32-le", False, ) - assert codec.detectencoding_str('@c'.encode()) == (None, False) - assert codec.detectencoding_str('@ch'.encode()) == (None, False) - assert codec.detectencoding_str('@cha'.encode()) == (None, False) - assert codec.detectencoding_str('@char'.encode()) == (None, False) - assert codec.detectencoding_str('@chars'.encode()) == (None, False) - assert codec.detectencoding_str('@charse'.encode()) == (None, False) - assert codec.detectencoding_str('@charset'.encode()) == (None, False) - assert codec.detectencoding_str('@charset '.encode()) == (None, False) - assert codec.detectencoding_str('@charset "'.encode()) == (None, False) - assert codec.detectencoding_str('@charset "x'.encode()) == (None, False) - assert codec.detectencoding_str('@charset ""'.encode()) == ("", True) - assert codec.detectencoding_str('@charset "x"'.encode()) == ("x", True) - assert codec.detectencoding_str("@".encode(), False) == (None, False) - assert codec.detectencoding_str("@".encode(), True) == ("utf-8", False) - assert codec.detectencoding_str("@c".encode(), False) == (None, False) - assert codec.detectencoding_str("@c".encode(), True) == ("utf-8", False) + assert codec.detectencoding_str(b'@c') == (None, False) + assert codec.detectencoding_str(b'@ch') == (None, False) + assert codec.detectencoding_str(b'@cha') == (None, False) + assert codec.detectencoding_str(b'@char') == (None, False) + assert codec.detectencoding_str(b'@chars') == (None, False) + assert codec.detectencoding_str(b'@charse') == (None, False) + assert codec.detectencoding_str(b'@charset') == (None, False) + assert codec.detectencoding_str(b'@charset ') == (None, False) + assert codec.detectencoding_str(b'@charset "') == (None, False) + assert codec.detectencoding_str(b'@charset "x') == (None, False) + assert codec.detectencoding_str(b'@charset ""') == ("", True) + assert codec.detectencoding_str(b'@charset "x"') == ("x", True) + assert codec.detectencoding_str(b"@", False) == (None, False) + assert codec.detectencoding_str(b"@", True) == ("utf-8", False) + assert codec.detectencoding_str(b"@c", False) == (None, False) + assert codec.detectencoding_str(b"@c", True) == ("utf-8", False) def test_detectencoding_unicode(self): "codec.detectencoding_unicode()" @@ -248,7 +248,7 @@ def checkdecl(encoding, input='@charset "%s";g\xfcrk{}'): # No recursion with pytest.raises(ValueError): - '@charset "css";div{}'.encode().decode("css") + b'@charset "css";div{}'.decode("css") def test_encoder(self): "codec.encoder" @@ -345,21 +345,21 @@ def streamdecode(input, **kwargs): # output = u'@charset "utf-8"; \xff' # self.assertEqual(d(input, encoding="iso-8859-1", force=False), output) - input = '@charset "utf-8"; \xff'.encode('utf-8') + input = '@charset "utf-8"; \xff'.encode() output = '@charset "utf-8"; \xff' assert d(input) == output # input = b'@charset "utf-8"; \xc3\xbf' - input = '@charset "utf-8"; \xff'.encode('utf-8') + input = '@charset "utf-8"; \xff'.encode() output = '@charset "iso-8859-1"; \xc3\xbf' assert d(input, encoding="iso-8859-1", force=True) == output # input = b'\xc3\xbf' - input = '\xff'.encode('utf-8') + input = '\xff'.encode() output = '\xc3\xbf' assert d(input, encoding="iso-8859-1", force=True) == output # input = b'@charset "utf-8"; \xc3\xbf' - input = '@charset "utf-8"; \xff'.encode('utf-8') + input = '@charset "utf-8"; \xff'.encode() output = '@charset "utf-8"; \xff' assert d(input, encoding="iso-8859-1", force=False) == output diff --git a/cssutils/tests/test_cssimportrule.py b/cssutils/tests/test_cssimportrule.py index c214df47..5f468e68 100644 --- a/cssutils/tests/test_cssimportrule.py +++ b/cssutils/tests/test_cssimportrule.py @@ -215,12 +215,12 @@ def fetcher(url): sheet = parser.parseString('@import "http://example.com/yes" "name"') r = sheet.cssRules[0] - assert '/**/'.encode() == r.styleSheet.cssText + assert b'/**/' == r.styleSheet.cssText assert r.hrefFound assert 'name' == r.name r.cssText = '@import url(http://example.com/none) "name2";' - assert ''.encode() == r.styleSheet.cssText + assert b'' == r.styleSheet.cssText assert not r.hrefFound assert 'name2' == r.name @@ -353,7 +353,7 @@ def fetcher(url): assert ir.styleSheet.title == 'title' assert ( ir.styleSheet.cssText - == '@charset "ascii";\n@import "level2/css.css" "title2";'.encode() + == b'@charset "ascii";\n@import "level2/css.css" "title2";' ) ir2 = ir.styleSheet.cssRules[1] @@ -366,8 +366,7 @@ def fetcher(url): assert ir2.styleSheet.parentStyleSheet is None # ir.styleSheet assert ir2.styleSheet.title == 'title2' assert ( - ir2.styleSheet.cssText - == '@charset "ascii";\na {\n color: red\n }'.encode() + ir2.styleSheet.cssText == b'@charset "ascii";\na {\n color: red\n }' ) sheet = cssutils.parseString('@import "CANNOT-FIND.css";') @@ -377,9 +376,9 @@ def fetcher(url): def fetcher(url): if url.endswith('level1.css'): - return None, '@charset "ascii"; @import "level2.css";'.encode() + return None, b'@charset "ascii"; @import "level2.css";' else: - return None, 'a { color: red }'.encode() + return None, b'a { color: red }' parser = cssutils.CSSParser(fetcher=fetcher) diff --git a/cssutils/tests/test_cssmediarule.py b/cssutils/tests/test_cssmediarule.py index d889f00f..734eea8f 100644 --- a/cssutils/tests/test_cssmediarule.py +++ b/cssutils/tests/test_cssmediarule.py @@ -138,7 +138,7 @@ def test_cssText(self): for b, a in list(mls.items()): if a is None: a = b - tests['@media%s%s' % (b, style)] = '@media%s%s' % (a, style) + tests['@media{}{}'.format(b, style)] = '@media{}{}'.format(a, style) self.do_equal_p(tests) self.do_equal_r(tests) diff --git a/cssutils/tests/test_cssproperties.py b/cssutils/tests/test_cssproperties.py index 85201559..e5b31c3e 100644 --- a/cssutils/tests/test_cssproperties.py +++ b/cssutils/tests/test_cssproperties.py @@ -46,9 +46,9 @@ def test_CSS2Properties(self): "CSS2Properties" CSS2Properties = cssutils.css.cssproperties.CSS2Properties assert isinstance(property(), type(CSS2Properties.color)) - assert sum( - [len(x) for x in list(cssutils.profiles.properties.values())] - ) == len(CSS2Properties._properties) + assert sum(len(x) for x in list(cssutils.profiles.properties.values())) == len( + CSS2Properties._properties + ) c2 = CSS2Properties() # CSS2Properties has simplified implementation return always None diff --git a/cssutils/tests/test_cssstyledeclaration.py b/cssutils/tests/test_cssstyledeclaration.py index c659970d..d9961b50 100644 --- a/cssutils/tests/test_cssstyledeclaration.py +++ b/cssutils/tests/test_cssstyledeclaration.py @@ -595,5 +595,5 @@ def test_valid(self): ] for case, expected in cases: s = cssutils.css.CSSStyleDeclaration(cssText=case) - msg = '%r should be %s' % (case, 'valid' if expected else 'invalid') + msg = '{!r} should be {}'.format(case, 'valid' if expected else 'invalid') assert s.valid == expected, msg diff --git a/cssutils/tests/test_cssstylesheet.py b/cssutils/tests/test_cssstylesheet.py index f8689566..7cc49a2a 100644 --- a/cssutils/tests/test_cssstylesheet.py +++ b/cssutils/tests/test_cssstylesheet.py @@ -117,10 +117,7 @@ def test_cssRules(self): assert 2 == s.cssRules.length s.cssRules.extend(cssutils.parseString('/*3*/x {y:2}').cssRules) assert 4 == s.cssRules.length - assert ( - 'a {\n x: 1\n }\n/*2*/\n/*3*/\nx {\n y: 2\n }'.encode() - == s.cssText - ) + assert b'a {\n x: 1\n }\n/*2*/\n/*3*/\nx {\n y: 2\n }' == s.cssText for r in s.cssRules: assert r.parentStyleSheet == s @@ -128,37 +125,37 @@ def test_cssRules(self): def test_cssText(self): "CSSStyleSheet.cssText" tests = { - '': ''.encode(), + '': b'', # @charset - '@charset "ascii";\n@import "x";': '@charset "ascii";\n@import "x";'.encode(), - '@charset "ascii";\n@media all {}': '@charset "ascii";'.encode(), - '@charset "ascii";\n@x;': '@charset "ascii";\n@x;'.encode(), - '@charset "ascii";\na {\n x: 1\n }': '@charset "ascii";\na {\n x: 1\n }'.encode(), + '@charset "ascii";\n@import "x";': b'@charset "ascii";\n@import "x";', + '@charset "ascii";\n@media all {}': b'@charset "ascii";', + '@charset "ascii";\n@x;': b'@charset "ascii";\n@x;', + '@charset "ascii";\na {\n x: 1\n }': b'@charset "ascii";\na {\n x: 1\n }', # @import - '@x;\n@import "x";': '@x;\n@import "x";'.encode(), - '@import "x";\n@import "y";': '@import "x";\n@import "y";'.encode(), - '@import "x";\n@media all {}': '@import "x";'.encode(), - '@import "x";\n@x;': '@import "x";\n@x;'.encode(), - '@import "x";\na {\n x: 1\n }': '@import "x";\na {\n x: 1\n }'.encode(), + '@x;\n@import "x";': b'@x;\n@import "x";', + '@import "x";\n@import "y";': b'@import "x";\n@import "y";', + '@import "x";\n@media all {}': b'@import "x";', + '@import "x";\n@x;': b'@import "x";\n@x;', + '@import "x";\na {\n x: 1\n }': b'@import "x";\na {\n x: 1\n }', # @namespace - '@x;\n@namespace a "x";': '@x;\n@namespace a "x";'.encode(), - '@namespace a "x";\n@namespace b "y";': '@namespace a "x";\n@namespace b "y";'.encode(), - '@import "x";\n@namespace a "x";\n@media all {}': '@import "x";\n@namespace a "x";'.encode(), - '@namespace a "x";\n@x;': '@namespace a "x";\n@x;'.encode(), - '@namespace a "x";\na {\n x: 1\n }': '@namespace a "x";\na {\n x: 1\n }'.encode(), + '@x;\n@namespace a "x";': b'@x;\n@namespace a "x";', + '@namespace a "x";\n@namespace b "y";': b'@namespace a "x";\n@namespace b "y";', + '@import "x";\n@namespace a "x";\n@media all {}': b'@import "x";\n@namespace a "x";', + '@namespace a "x";\n@x;': b'@namespace a "x";\n@x;', + '@namespace a "x";\na {\n x: 1\n }': b'@namespace a "x";\na {\n x: 1\n }', """@namespace url("e1"); @namespace url("e2"); @namespace x url("x1"); @namespace x url("x2"); test{color: green} - x|test {color: green}""": """@namespace "e2"; + x|test {color: green}""": b"""@namespace "e2"; @namespace x "x2"; test { color: green } x|test { color: green - }""".encode() + }""" # ur'\1 { \2: \3 }': ur'''\x01 { # \x02: \x03 # }''', @@ -351,7 +348,7 @@ def test_namespaces1(self): with pytest.raises(IndexError): s.namespaces.prefixForNamespaceURI('UNSET') # .keys - assert set(s.namespaces.keys()) == set(['', 'ex2', 'n']) + assert set(s.namespaces.keys()) == {'', 'ex2', 'n'} # .get assert 'x' == s.namespaces.get('UNKNOWN', 'x') assert 'example' == s.namespaces.get('ex2', 'not used defa') @@ -431,7 +428,7 @@ def test_namespaces2(self): assert ( s.cssText - == '''@namespace n "new"; + == b'''@namespace n "new"; @namespace ex2 "example"; @namespace DEFAULT "default"; @media all { @@ -441,7 +438,7 @@ def test_namespaces2(self): } ex2|SEL4, a, ex2|SELSR { top: 0 - }'''.encode() + }''' ) def test_namespaces3(self): @@ -458,7 +455,7 @@ def test_namespaces3(self): r = cssutils.css.CSSStyleRule() r.cssText = (css, {'h': 'html'}) s.add(r) # uses x as set before! h is temporary only - assert s.cssText == '@namespace x "html";\nx|a {\n top: 0\n }'.encode() + assert s.cssText == b'@namespace x "html";\nx|a {\n top: 0\n }' # prefix is now "x"! with pytest.raises(xml.dom.NamespaceErr): @@ -467,23 +464,19 @@ def test_namespaces3(self): r.selectorList.append('y|b') s.namespaces['y'] = 'html' r.selectorList.append('y|b') - assert ( - s.cssText == '@namespace y "html";\ny|a, y|b {\n top: 0\n }'.encode() - ) + assert s.cssText == b'@namespace y "html";\ny|a, y|b {\n top: 0\n }' with pytest.raises(xml.dom.NoModificationAllowedErr): s.namespaces.__delitem__('y') - assert ( - s.cssText == '@namespace y "html";\ny|a, y|b {\n top: 0\n }'.encode() - ) + assert s.cssText == b'@namespace y "html";\ny|a, y|b {\n top: 0\n }' s.cssRules[0].prefix = '' - assert s.cssText == '@namespace "html";\na, b {\n top: 0\n }'.encode() + assert s.cssText == b'@namespace "html";\na, b {\n top: 0\n }' # remove need of namespace s.cssRules[0].prefix = 'x' s.cssRules[1].selectorText = 'a, b' - assert s.cssText == '@namespace x "html";\na, b {\n top: 0\n }'.encode() + assert s.cssText == b'@namespace x "html";\na, b {\n top: 0\n }' def test_namespaces4(self): "CSSStyleSheet.namespaces 4" @@ -518,7 +511,7 @@ def test_namespaces5(self): "CSSStyleSheet.namespaces 5" # unknown namespace s = cssutils.parseString('a|a { color: red }') - assert s.cssText == ''.encode() + assert s.cssText == b'' s = cssutils.css.CSSStyleSheet() with pytest.raises(xml.dom.NamespaceErr, match=r"Prefix a not found\."): @@ -541,21 +534,21 @@ def test_deleteRuleIndex(self): assert 4 == self.s.cssRules.length assert ( - '@charset "ascii";\n@import "x";\n@x;\na {\n x: 1\n }'.encode() + b'@charset "ascii";\n@import "x";\n@x;\na {\n x: 1\n }' == self.s.cssText ) # beginning self.s.deleteRule(0) assert 3 == self.s.cssRules.length - assert '@import "x";\n@x;\na {\n x: 1\n }'.encode() == self.s.cssText + assert b'@import "x";\n@x;\na {\n x: 1\n }' == self.s.cssText # middle self.s.deleteRule(1) assert 2 == self.s.cssRules.length - assert '@import "x";\na {\n x: 1\n }'.encode() == self.s.cssText + assert b'@import "x";\na {\n x: 1\n }' == self.s.cssText # end self.s.deleteRule(1) assert 1 == self.s.cssRules.length - assert '@import "x";'.encode() == self.s.cssText + assert b'@import "x";' == self.s.cssText def test_deleteRule(self): "CSSStyleSheet.deleteRule(rule)" @@ -577,16 +570,13 @@ def test_deleteRule(self): assert 3 == s.cssRules.length assert ( s.cssText - == 'a {\n color: red\n }\nb {\n color: blue\n }\nc {\n color: green\n }'.encode() + == b'a {\n color: red\n }\nb {\n color: blue\n }\nc {\n color: green\n }' ) with pytest.raises(xml.dom.IndexSizeErr): s.deleteRule(n) s.deleteRule(s2) assert 2 == s.cssRules.length - assert ( - s.cssText - == 'a {\n color: red\n }\nc {\n color: green\n }'.encode() - ) + assert s.cssText == b'a {\n color: red\n }\nc {\n color: green\n }' with pytest.raises(xml.dom.IndexSizeErr): s.deleteRule(s2) @@ -614,7 +604,7 @@ def _gets(self): s.insertRule(self.pr) # 6 s.insertRule(self.sr) # 7 assert ( - '@charset "ascii";\n@import url(x);\n@namespace p "uri";\n@media all {\n @m;\n }\na {\n x: 1\n }\n@media all {\n @m;\n }\n@page {\n margin: 0\n }\na {\n x: 1\n }'.encode() + b'@charset "ascii";\n@import url(x);\n@namespace p "uri";\n@media all {\n @m;\n }\na {\n x: 1\n }\n@media all {\n @m;\n }\n@page {\n margin: 0\n }\na {\n x: 1\n }' == s.cssText ) return s, s.cssRules.length @@ -700,7 +690,7 @@ def test_addimport(self): assert sheet == added.parentStyleSheet assert 'example.css' == added.href assert 'utf-8' == added.styleSheet.encoding - assert '/**/'.encode() == added.styleSheet.cssText + assert b'/**/' == added.styleSheet.cssText cssrulessheet = p.parseString('@import "example.css";') imports = ( @@ -717,9 +707,9 @@ def test_addimport(self): assert 'example.css' == added.href assert enc == added.styleSheet.encoding if enc == 'ascii': - assert '@charset "ascii";\n/**/'.encode() == added.styleSheet.cssText + assert b'@charset "ascii";\n/**/' == added.styleSheet.cssText else: - assert '/**/'.encode() == added.styleSheet.cssText + assert b'/**/' == added.styleSheet.cssText # if styleSheet is already there encoding is not set new impsheet = p.parseString('@import "example.css";') @@ -730,7 +720,7 @@ def test_addimport(self): assert sheet == added.parentStyleSheet assert 'example.css' == added.href assert 'utf-8' == added.styleSheet.encoding - assert '/**/'.encode() == added.styleSheet.cssText + assert b'/**/' == added.styleSheet.cssText def test_insertRule(self): "CSSStyleSheet.insertRule()" @@ -906,5 +896,5 @@ def test_valid(self): ] for case, expected in cases: sheet = cssutils.parseString(case) - msg = "%r should be %s" % (case, 'valid' if expected else 'invalid') + msg = "{!r} should be {}".format(case, 'valid' if expected else 'invalid') assert sheet.valid == expected, msg diff --git a/cssutils/tests/test_cssutils.py b/cssutils/tests/test_cssutils.py index 2de8f459..a265b807 100644 --- a/cssutils/tests/test_cssutils.py +++ b/cssutils/tests/test_cssutils.py @@ -58,17 +58,17 @@ def test_parseString(self): irs = ir.styleSheet assert isinstance(irs, cssutils.css.CSSStyleSheet) assert ( - irs.cssText == '@import "../import3.css";\n' - '@import "import-impossible.css" print;\n.import2 {\n' - ' /* sheets/import2.css */\n' - ' background: url(http://example.com/images/example.gif);\n' - ' background: url(//example.com/images/example.gif);\n' - ' background: url(/images/example.gif);\n' - ' background: url(images2/example.gif);\n' - ' background: url(./images2/example.gif);\n' - ' background: url(../images/example.gif);\n' - ' background: url(./../images/example.gif)\n' - ' }'.encode() + irs.cssText == b'@import "../import3.css";\n' + b'@import "import-impossible.css" print;\n.import2 {\n' + b' /* sheets/import2.css */\n' + b' background: url(http://example.com/images/example.gif);\n' + b' background: url(//example.com/images/example.gif);\n' + b' background: url(/images/example.gif);\n' + b' background: url(images2/example.gif);\n' + b' background: url(./images2/example.gif);\n' + b' background: url(../images/example.gif);\n' + b' background: url(./../images/example.gif)\n' + b' }' ) tests = { @@ -102,18 +102,18 @@ def test_parseFile(self): irs = ir.styleSheet assert isinstance(irs, cssutils.css.CSSStyleSheet) assert ( - irs.cssText == '@import "../import3.css";\n' - '@import "import-impossible.css" print;\n' - '.import2 {\n' - ' /* sheets/import2.css */\n' - ' background: url(http://example.com/images/example.gif);\n' - ' background: url(//example.com/images/example.gif);\n' - ' background: url(/images/example.gif);\n' - ' background: url(images2/example.gif);\n' - ' background: url(./images2/example.gif);\n' - ' background: url(../images/example.gif);\n' - ' background: url(./../images/example.gif)\n' - ' }'.encode() + irs.cssText == b'@import "../import3.css";\n' + b'@import "import-impossible.css" print;\n' + b'.import2 {\n' + b' /* sheets/import2.css */\n' + b' background: url(http://example.com/images/example.gif);\n' + b' background: url(//example.com/images/example.gif);\n' + b' background: url(/images/example.gif);\n' + b' background: url(images2/example.gif);\n' + b' background: url(./images2/example.gif);\n' + b' background: url(../images/example.gif);\n' + b' background: url(./../images/example.gif)\n' + b' }' ) # name is used for open and setting of href automatically @@ -140,18 +140,18 @@ def test_parseFile(self): irs = ir.styleSheet assert isinstance(irs, cssutils.css.CSSStyleSheet) assert ( - irs.cssText == '@import "../import3.css";\n' - '@import "import-impossible.css" print;\n' - '.import2 {\n' - ' /* sheets/import2.css */\n' - ' background: url(http://example.com/images/example.gif);\n' - ' background: url(//example.com/images/example.gif);\n' - ' background: url(/images/example.gif);\n' - ' background: url(images2/example.gif);\n' - ' background: url(./images2/example.gif);\n' - ' background: url(../images/example.gif);\n' - ' background: url(./../images/example.gif)\n' - ' }'.encode() + irs.cssText == b'@import "../import3.css";\n' + b'@import "import-impossible.css" print;\n' + b'.import2 {\n' + b' /* sheets/import2.css */\n' + b' background: url(http://example.com/images/example.gif);\n' + b' background: url(//example.com/images/example.gif);\n' + b' background: url(/images/example.gif);\n' + b' background: url(images2/example.gif);\n' + b' background: url(./images2/example.gif);\n' + b' background: url(../images/example.gif);\n' + b' background: url(./../images/example.gif)\n' + b' }' ) # next test @@ -217,33 +217,33 @@ def test_parseUrl(self): assert 'import/import2.css' == ir.href irs = ir.styleSheet assert ( - irs.cssText == '@import "../import3.css";\n' - '@import "import-impossible.css" print;\n' - '.import2 {\n' - ' /* sheets/import2.css */\n' - ' background: url(http://example.com/images/example.gif);\n' - ' background: url(//example.com/images/example.gif);\n' - ' background: url(/images/example.gif);\n' - ' background: url(images2/example.gif);\n' - ' background: url(./images2/example.gif);\n' - ' background: url(../images/example.gif);\n' - ' background: url(./../images/example.gif)\n' - ' }'.encode() + irs.cssText == b'@import "../import3.css";\n' + b'@import "import-impossible.css" print;\n' + b'.import2 {\n' + b' /* sheets/import2.css */\n' + b' background: url(http://example.com/images/example.gif);\n' + b' background: url(//example.com/images/example.gif);\n' + b' background: url(/images/example.gif);\n' + b' background: url(images2/example.gif);\n' + b' background: url(./images2/example.gif);\n' + b' background: url(../images/example.gif);\n' + b' background: url(./../images/example.gif)\n' + b' }' ) ir2 = irs.cssRules[0] assert '../import3.css' == ir2.href irs2 = ir2.styleSheet assert ( - irs2.cssText == '/* import3 */\n' - '.import3 {\n' - ' /* from ./import/../import3.css */\n' - ' background: url(images/example3.gif);\n' - ' background: url(./images/example3.gif);\n' - ' background: url(import/images2/example2.gif);\n' - ' background: url(./import/images2/example2.gif);\n' - ' background: url(import/images2/../../images/example3.gif)\n' - ' }'.encode() + irs2.cssText == b'/* import3 */\n' + b'.import3 {\n' + b' /* from ./import/../import3.css */\n' + b' background: url(images/example3.gif);\n' + b' background: url(./images/example3.gif);\n' + b' background: url(import/images2/example2.gif);\n' + b' background: url(./import/images2/example2.gif);\n' + b' background: url(import/images2/../../images/example3.gif)\n' + b' }' ) def test_setCSSSerializer(self): @@ -280,7 +280,7 @@ def test_parseStyle(self): with pytest.raises(UnicodeDecodeError): cssutils.parseStyle( - 'content: "ä"'.encode('utf-8'), + 'content: "ä"'.encode(), 'ascii', ) @@ -305,21 +305,19 @@ def test_getUrls(self): url("f.svg#f") format("svg"); }''' urls = set(cssutils.getUrls(cssutils.parseString(css))) - assert urls == set( - [ - "im1", - "im2", - "im3", - "im4", - "im5", - "a", - "b", - "c", - 'f.woff', - 'f.svg#f', - 'f.otf', - ] - ) + assert urls == { + "im1", + "im2", + "im3", + "im4", + "im5", + "a", + "b", + "c", + 'f.woff', + 'f.svg#f', + 'f.otf', + } cssutils.ser.prefs.keepAllProperties = False def test_replaceUrls(self): @@ -369,7 +367,7 @@ def test_resolveImports(self): a = '@charset "iso-8859-1";@import"b.css";\xe4{color:green}'.encode( 'iso-8859-1' ) - b = '@charset "ascii";\\E4 {color:red}'.encode('ascii') + b = b'@charset "ascii";\\E4 {color:red}' # normal m = mock.Mock() @@ -384,16 +382,10 @@ def test_resolveImports(self): c = cssutils.resolveImports(s) # py3 TODO - assert ( - '\xc3\xa4{color:red}\xc3\xa4{color:green}'.encode('iso-8859-1') - == c.cssText - ) + assert b'\xc3\xa4{color:red}\xc3\xa4{color:green}' == c.cssText c.encoding = 'ascii' - assert ( - r'@charset "ascii";\E4 {color:red}\E4 {color:green}'.encode() - == c.cssText - ) + assert br'@charset "ascii";\E4 {color:red}\E4 {color:green}' == c.cssText # b cannot be found m = mock.Mock() @@ -406,9 +398,7 @@ def test_resolveImports(self): assert isinstance(s.cssRules[1].styleSheet, cssutils.css.CSSStyleSheet) c = cssutils.resolveImports(s) # py3 TODO - assert ( - '@import"b.css";\xc3\xa4{color:green}'.encode('iso-8859-1') == c.cssText - ) + assert b'@import"b.css";\xc3\xa4{color:green}' == c.cssText # @import with media a = '@import"b.css";@import"b.css" print, tv ;@import"b.css" all;' @@ -420,10 +410,7 @@ def test_resolveImports(self): c = cssutils.resolveImports(s) - assert ( - 'a{color:red}@media print,tv{a{color:red}}a{color:red}'.encode() - == c.cssText - ) + assert b'a{color:red}@media print,tv{a{color:red}}a{color:red}' == c.cssText # cannot resolve with media => keep original a = '@import"b.css"print;' @@ -478,7 +465,7 @@ def do(): cssutils.ser.prefs.useDefaults() cssutils.ser.prefs.keepComments = False - expected = '''c { + expected = b'''c { x: url(/img/abs.gif); y: url(img/img.gif); z: url(b/subimg/subimg.gif) @@ -492,7 +479,7 @@ def do(): x: url(/img/abs.gif); y: url(img/img.gif); z: url(b/subimg/subimg.gif) - }'''.encode() + }''' assert expected == r.cssText cssutils.ser.prefs.useDefaults() diff --git a/cssutils/tests/test_cssvariablesdeclaration.py b/cssutils/tests/test_cssvariablesdeclaration.py index a0995e24..2efda0ae 100644 --- a/cssutils/tests/test_cssvariablesdeclaration.py +++ b/cssutils/tests/test_cssvariablesdeclaration.py @@ -259,7 +259,7 @@ def fetcher(url): cssutils.ser.prefs.resolveVariables = False assert ( s.cssText - == '''@import "1.css"; + == b'''@import "1.css"; @variables { over3-2-1-0: 0; over3-2-0: 0; @@ -285,14 +285,14 @@ def fetcher(url): over3-2-0: var(over3-2-0); over3-2-1: var(over3-2-1); over3-2-1-0: var(over3-2-1-0) - }'''.encode() + }''' ) # test with resolved vars cssutils.ser.prefs.resolveVariables = True assert ( s.cssText - == '''@import "1.css"; + == b'''@import "1.css"; a { local0: 0; local1: 1; @@ -308,13 +308,13 @@ def fetcher(url): over3-2-0: 0; over3-2-1: 1; over3-2-1-0: 0 - }'''.encode() + }''' ) s = cssutils.resolveImports(s) assert ( s.cssText - == '''/* START @import "1.css" */ + == b'''/* START @import "1.css" */ /* START @import "3.css" */ /* START @import "2.css" */ a { @@ -332,7 +332,7 @@ def fetcher(url): over3-2-0: 0; over3-2-1: 1; over3-2-1-0: 0 - }'''.encode() + }''' ) def test_parentRule(self): diff --git a/cssutils/tests/test_encutils/__init__.py b/cssutils/tests/test_encutils/__init__.py index 66b7ed8a..640954aa 100644 --- a/cssutils/tests/test_encutils/__init__.py +++ b/cssutils/tests/test_encutils/__init__.py @@ -211,13 +211,13 @@ def test_tryEncodings(self): "encutils.tryEncodings" try: tests = [ - ('ascii', 'abc'.encode('ascii')), + ('ascii', b'abc'), ('windows-1252', '€'.encode('windows-1252')), - ('ascii', '1'.encode('utf-8')), + ('ascii', b'1'), ] except ImportError: tests = [ - ('ascii', 'abc'.encode('ascii')), + ('ascii', b'abc'), ('windows-1252', '€'.encode('windows-1252')), ('iso-8859-1', 'äöüß'.encode('iso-8859-1')), ('iso-8859-1', 'äöüß'.encode('windows-1252')), diff --git a/cssutils/tests/test_errorhandler.py b/cssutils/tests/test_errorhandler.py index 3e938e3a..5ba9b16c 100644 --- a/cssutils/tests/test_errorhandler.py +++ b/cssutils/tests/test_errorhandler.py @@ -117,7 +117,7 @@ def test_handlers(self): try: socket.getaddrinfo('example.com', 80) - except socket.error: + except OSError: # skip the test as the name can't resolve return diff --git a/cssutils/tests/test_medialist.py b/cssutils/tests/test_medialist.py index 01c942ef..4ef3cbc8 100644 --- a/cssutils/tests/test_medialist.py +++ b/cssutils/tests/test_medialist.py @@ -1,4 +1,3 @@ -# -*- coding: iso-8859-1 -*- """Testcases for cssutils.stylesheets.MediaList""" import re @@ -113,7 +112,7 @@ def test_append2All(self): ml.appendMedium('print') sheet = cssutils.parseString('@media all, print { /**/ }') - assert '@media all {\n /**/\n }'.encode() == sheet.cssText + assert b'@media all {\n /**/\n }' == sheet.cssText def test_delete(self): "MediaList.deleteMedium()" diff --git a/cssutils/tests/test_mediaquery.py b/cssutils/tests/test_mediaquery.py index 443b898c..95496fec 100644 --- a/cssutils/tests/test_mediaquery.py +++ b/cssutils/tests/test_mediaquery.py @@ -1,4 +1,3 @@ -# -*- coding: iso-8859-1 -*- """Testcases for cssutils.stylesheets.MediaQuery""" import xml.dom diff --git a/cssutils/tests/test_parse.py b/cssutils/tests/test_parse.py index 49a9682a..77e07b7a 100644 --- a/cssutils/tests/test_parse.py +++ b/cssutils/tests/test_parse.py @@ -29,12 +29,12 @@ def test_init(self): # default non raising parser p = cssutils.CSSParser() s = p.parseString('$') - assert s.cssText == ''.encode() + assert s.cssText == b'' # explicit raiseExceptions=False p = cssutils.CSSParser(raiseExceptions=False) s = p.parseString('$') - assert s.cssText == ''.encode() + assert s.cssText == b'' # working with sheet does raise though! with pytest.raises(xml.dom.DOMException): @@ -57,19 +57,16 @@ def test_init(self): s = cssutils.css.CSSStyleSheet() # does not raise! s.__setattr__('cssText', '$') - assert s.cssText == ''.encode() + assert s.cssText == b'' def test_parseComments(self): "cssutils.CSSParser(parseComments=False)" css = '/*1*/ a { color: /*2*/ red; }' p = cssutils.CSSParser(parseComments=False) - assert p.parseString(css).cssText == 'a {\n color: red\n }'.encode() + assert p.parseString(css).cssText == b'a {\n color: red\n }' p = cssutils.CSSParser(parseComments=True) - assert ( - p.parseString(css).cssText - == '/*1*/\na {\n color: /*2*/ red\n }'.encode() - ) + assert p.parseString(css).cssText == b'/*1*/\na {\n color: /*2*/ red\n }' # def test_parseFile(self): # "CSSParser.parseFile()" @@ -153,66 +150,66 @@ def test_parseString(self): "CSSParser.parseString()" tests = { # (byte) string, encoding: encoding, cssText - ('/*a*/', None): ('utf-8', '/*a*/'.encode('utf-8')), - ('/*a*/', 'ascii'): ('ascii', '@charset "ascii";\n/*a*/'.encode('ascii')), + ('/*a*/', None): ('utf-8', b'/*a*/'), + ('/*a*/', 'ascii'): ('ascii', b'@charset "ascii";\n/*a*/'), # org # ('/*\xc3\xa4*/', None): (u'utf-8', u'/*\xc3\xa4*/'.encode('utf-8')), # ('/*\xc3\xa4*/', 'utf-8'): (u'utf-8', # u'@charset "utf-8";\n/*\xc3\xa4*/'.encode('utf-8')), # new for 2.x and 3.x - ('/*\xe4*/'.encode('utf-8'), None): ('utf-8', '/*\xe4*/'.encode('utf-8')), - ('/*\xe4*/'.encode('utf-8'), 'utf-8'): ( + ('/*\xe4*/'.encode(), None): ('utf-8', '/*\xe4*/'.encode()), + ('/*\xe4*/'.encode(), 'utf-8'): ( 'utf-8', - '@charset "utf-8";\n/*\xe4*/'.encode('utf-8'), + '@charset "utf-8";\n/*\xe4*/'.encode(), ), ('@charset "ascii";/*a*/', None): ( 'ascii', - '@charset "ascii";\n/*a*/'.encode('ascii'), + b'@charset "ascii";\n/*a*/', ), ('@charset "utf-8";/*a*/', None): ( 'utf-8', - '@charset "utf-8";\n/*a*/'.encode('utf-8'), + b'@charset "utf-8";\n/*a*/', ), ('@charset "iso-8859-1";/*a*/', None): ( 'iso-8859-1', - '@charset "iso-8859-1";\n/*a*/'.encode('iso-8859-1'), + b'@charset "iso-8859-1";\n/*a*/', ), # unicode string, no encoding: encoding, cssText - ('/*€*/', None): ('utf-8', '/*€*/'.encode('utf-8')), + ('/*€*/', None): ('utf-8', '/*€*/'.encode()), ('@charset "iso-8859-1";/*ä*/', None): ( 'iso-8859-1', '@charset "iso-8859-1";\n/*ä*/'.encode('iso-8859-1'), ), ('@charset "utf-8";/*€*/', None): ( 'utf-8', - '@charset "utf-8";\n/*€*/'.encode('utf-8'), + '@charset "utf-8";\n/*€*/'.encode(), ), ('@charset "utf-16";/**/', None): ( 'utf-16', '@charset "utf-16";\n/**/'.encode('utf-16'), ), # unicode string, encoding utf-8: encoding, cssText - ('/*€*/', 'utf-8'): ('utf-8', '@charset "utf-8";\n/*€*/'.encode('utf-8')), + ('/*€*/', 'utf-8'): ('utf-8', '@charset "utf-8";\n/*€*/'.encode()), ('@charset "iso-8859-1";/*ä*/', 'utf-8'): ( 'utf-8', - '@charset "utf-8";\n/*ä*/'.encode('utf-8'), + '@charset "utf-8";\n/*ä*/'.encode(), ), ('@charset "utf-8";/*€*/', 'utf-8'): ( 'utf-8', - '@charset "utf-8";\n/*€*/'.encode('utf-8'), + '@charset "utf-8";\n/*€*/'.encode(), ), ('@charset "utf-16";/**/', 'utf-8'): ( 'utf-8', - '@charset "utf-8";\n/**/'.encode('utf-8'), + b'@charset "utf-8";\n/**/', ), # probably not what is wanted but does not raise: ('/*€*/', 'ascii'): ( 'ascii', - '@charset "ascii";\n/*\\20AC */'.encode('utf-8'), + b'@charset "ascii";\n/*\\20AC */', ), ('/*€*/', 'iso-8859-1'): ( 'iso-8859-1', - '@charset "iso-8859-1";\n/*\\20AC */'.encode('utf-8'), + b'@charset "iso-8859-1";\n/*\\20AC */', ), } for test in tests: @@ -226,8 +223,8 @@ def test_parseString(self): # encoded css, overiding encoding ('/*€*/'.encode('utf-16'), 'utf-8'), ('/*ä*/'.encode('iso-8859-1'), 'ascii'), - ('/*€*/'.encode('utf-8'), 'ascii'), - ('a'.encode('ascii'), 'utf-16'), + ('/*€*/'.encode(), 'ascii'), + (b'a', 'utf-16'), ] for test in tests: # self.assertEqual(None, cssutils.parseString(css, encoding=encoding)) @@ -319,7 +316,7 @@ def test_fetcher(self): '@charset "utf-16"; @import "x";', 'ASCII', ('iso-8859-1', '@charset "latin1";/*t*/'), - ): ('ascii', 1, 'ascii', '@charset "ascii";\n/*t*/'.encode()), + ): ('ascii', 1, 'ascii', b'@charset "ascii";\n/*t*/'), # 1/1 not tested her but same as next # 2/1 @charset/HTTP => UTF-16/ISO-8859-1 ( @@ -330,7 +327,7 @@ def test_fetcher(self): 'utf-16', 1, 'iso-8859-1', - '@charset "iso-8859-1";\n/*t*/'.encode('iso-8859-1'), + b'@charset "iso-8859-1";\n/*t*/', ), # 2/2 @charset/@charset => UTF-16/ISO-8859-1 ( @@ -341,55 +338,55 @@ def test_fetcher(self): 'utf-16', 1, 'iso-8859-1', - '@charset "iso-8859-1";\n/*t*/'.encode('iso-8859-1'), + b'@charset "iso-8859-1";\n/*t*/', ), # 2/4 @charset/referrer => ASCII/ASCII ('@charset "ASCII"; @import "x";', None, (None, '/*t*/')): ( 'ascii', 1, 'ascii', - '@charset "ascii";\n/*t*/'.encode(), + b'@charset "ascii";\n/*t*/', ), # 5/5 default/default or referrer ('@import "x";', None, (None, '/*t*/')): ( 'utf-8', 0, 'utf-8', - '/*t*/'.encode(), + b'/*t*/', ), # 0/0 override/override+unicode ( '@charset "utf-16"; @import "x";', 'ASCII', (None, '@charset "latin1";/*\u0287*/'), - ): ('ascii', 1, 'ascii', '@charset "ascii";\n/*\\287 */'.encode()), + ): ('ascii', 1, 'ascii', b'@charset "ascii";\n/*\\287 */'), # 2/1 @charset/HTTP+unicode ('@charset "ascii"; @import "x";', None, ('iso-8859-1', '/*\u0287*/')): ( 'ascii', 1, 'iso-8859-1', - '@charset "iso-8859-1";\n/*\\287 */'.encode(), + b'@charset "iso-8859-1";\n/*\\287 */', ), # 2/4 @charset/referrer+unicode ('@charset "ascii"; @import "x";', None, (None, '/*\u0287*/')): ( 'ascii', 1, 'ascii', - '@charset "ascii";\n/*\\287 */'.encode(), + b'@charset "ascii";\n/*\\287 */', ), # 5/1 default/HTTP+unicode ('@import "x";', None, ('ascii', '/*\u0287*/')): ( 'utf-8', 0, 'ascii', - '@charset "ascii";\n/*\\287 */'.encode(), + b'@charset "ascii";\n/*\\287 */', ), # 5/5 default+unicode/default+unicode ('@import "x";', None, (None, '/*\u0287*/')): ( 'utf-8', 0, 'utf-8', - '/*\u0287*/'.encode('utf-8'), + '/*\u0287*/'.encode(), ), } parser = cssutils.CSSParser() @@ -443,10 +440,10 @@ def test_escapes(self): sheet = cssutils.parseString(css) assert ( sheet.cssText - == r'''\ x { + == br'''\ x { \ x: \ x; y: 1 - }'''.encode() + }''' ) def test_invalidstring(self): @@ -485,7 +482,7 @@ def test_invalidstring(self): ''', ) for css in csss: - assert ''.encode() == cssutils.parseString(css).cssText + assert b'' == cssutils.parseString(css).cssText def test_invalid(self): "cssutils.parseString(INVALID_CSS)" diff --git a/cssutils/tests/test_scripts_csscombine.py b/cssutils/tests/test_scripts_csscombine.py index 937a70af..f181f081 100644 --- a/cssutils/tests/test_scripts_csscombine.py +++ b/cssutils/tests/test_scripts_csscombine.py @@ -50,16 +50,15 @@ def test_combine_resolveVariables(self): # default minify assert ( csscombine(cssText=cssText, resolveVariables=False) - == '@variables{c:#0f0}a{color:var(c)}'.encode() + == b'@variables{c:#0f0}a{color:var(c)}' ) - assert csscombine(cssText=cssText) == 'a{color:#0f0}'.encode() + assert csscombine(cssText=cssText) == b'a{color:#0f0}' # no minify assert ( csscombine(cssText=cssText, minify=False, resolveVariables=False) - == '@variables {\n c: #0f0\n }\na {\n color: var(c)\n }'.encode() + == b'@variables {\n c: #0f0\n }\na {\n color: var(c)\n }' ) assert ( - csscombine(cssText=cssText, minify=False) - == 'a {\n color: #0f0\n }'.encode() + csscombine(cssText=cssText, minify=False) == b'a {\n color: #0f0\n }' ) diff --git a/cssutils/tests/test_selector.py b/cssutils/tests/test_selector.py index 5c4fb8c2..02312d7e 100644 --- a/cssutils/tests/test_selector.py +++ b/cssutils/tests/test_selector.py @@ -125,14 +125,13 @@ def test_default_namespace(self): sheet = cssutils.css.CSSStyleSheet() sheet.cssText = css assert ( - sheet.cssText - == '@namespace "default";\na[att] {\n color: green\n }'.encode() + sheet.cssText == b'@namespace "default";\na[att] {\n color: green\n }' ) # use a prefix for default namespace, does not goes for atts! sheet.namespaces['p'] = 'default' assert ( sheet.cssText - == '@namespace p "default";\np|a[att] {\n color: green\n }'.encode() + == b'@namespace p "default";\np|a[att] {\n color: green\n }' ) def test_parent(self): diff --git a/cssutils/tests/test_serialize.py b/cssutils/tests/test_serialize.py index 921969ad..63d00998 100644 --- a/cssutils/tests/test_serialize.py +++ b/cssutils/tests/test_serialize.py @@ -182,16 +182,16 @@ def test_useMinified(self): cssutils.ser.prefs.keepUnknownAtRules = True assert ( s.cssText - == '''@import"x"tv,print;@namespace prefix"uri";@media all"name"''' - '''{a{color:red}}@page :left{left:0}prefix|x,a+b>c~d,b{top:1px;''' - '''font-family:arial,"some"}@x x;'''.encode() + == b'''@import"x"tv,print;@namespace prefix"uri";@media all"name"''' + b'''{a{color:red}}@page :left{left:0}prefix|x,a+b>c~d,b{top:1px;''' + b'''font-family:arial,"some"}@x x;''' ) cssutils.ser.prefs.keepUnknownAtRules = False assert ( s.cssText - == '''@import"x"tv,print;@namespace prefix"uri";@media all"name"''' - '''{a{color:red}}@page :left{left:0}prefix|x,a+b>c~d,b{top:1px;''' - '''font-family:arial,"some"}'''.encode() + == b'''@import"x"tv,print;@namespace prefix"uri";@media all"name"''' + b'''{a{color:red}}@page :left{left:0}prefix|x,a+b>c~d,b{top:1px;''' + b'''font-family:arial,"some"}''' ) # Values valuetests = { @@ -221,11 +221,11 @@ def test_useMinified(self): def test_defaultAtKeyword(self): "Preferences.defaultAtKeyword" s = cssutils.parseString('@im\\port "x";') - assert '@import "x";'.encode() == s.cssText + assert b'@import "x";' == s.cssText cssutils.ser.prefs.defaultAtKeyword = True - assert '@import "x";'.encode() == s.cssText + assert b'@import "x";' == s.cssText cssutils.ser.prefs.defaultAtKeyword = False - assert '@im\\port "x";'.encode() == s.cssText + assert b'@im\\port "x";' == s.cssText def test_defaultPropertyName(self): "Preferences.defaultPropertyName" @@ -235,24 +235,24 @@ def test_defaultPropertyName(self): # if used with a backslash in it later... s = cssutils.parseString(r'a { c\olor: green; }') - assert 'a {\n color: green\n }'.encode() == s.cssText + assert b'a {\n color: green\n }' == s.cssText cssutils.ser.prefs.defaultPropertyName = True - assert 'a {\n color: green\n }'.encode() == s.cssText + assert b'a {\n color: green\n }' == s.cssText cssutils.ser.prefs.defaultPropertyName = False - assert 'a {\n c\\olor: green\n }'.encode() == s.cssText + assert b'a {\n c\\olor: green\n }' == s.cssText s = cssutils.parseString(r'a { color: red; c\olor: green; }') - assert 'a {\n c\\olor: green\n }'.encode() == s.cssText + assert b'a {\n c\\olor: green\n }' == s.cssText cssutils.ser.prefs.defaultPropertyName = False - assert 'a {\n c\\olor: green\n }'.encode() == s.cssText + assert b'a {\n c\\olor: green\n }' == s.cssText cssutils.ser.prefs.defaultPropertyName = True - assert 'a {\n color: green\n }'.encode() == s.cssText + assert b'a {\n color: green\n }' == s.cssText def test_defaultPropertyPriority(self): "Preferences.defaultPropertyPriority" css = 'a {\n color: green !IM\\portant\n }' s = cssutils.parseString(css) - assert s.cssText == 'a {\n color: green !important\n }'.encode() + assert s.cssText == b'a {\n color: green !important\n }' cssutils.ser.prefs.defaultPropertyPriority = False assert s.cssText == css.encode() @@ -326,21 +326,21 @@ def test_keepAllProperties(self): s = cssutils.parseString(css) # keep only last cssutils.ser.prefs.keepAllProperties = False - assert 'a {\n color: green\n }'.encode() == s.cssText + assert b'a {\n color: green\n }' == s.cssText # keep all cssutils.ser.prefs.keepAllProperties = True assert ( - 'a {\n color: pink;\n color: red;\n c\\olor: blue;\n ' - 'c\\olor: green\n }'.encode() == s.cssText + b'a {\n color: pink;\n color: red;\n c\\olor: blue;\n ' + b'c\\olor: green\n }' == s.cssText ) def test_keepComments(self): "Preferences.keepComments" s = cssutils.parseString('/*1*/ a { /*2*/ }') cssutils.ser.prefs.keepComments = False - assert ''.encode() == s.cssText + assert b'' == s.cssText cssutils.ser.prefs.keepEmptyRules = True - assert 'a {}'.encode() == s.cssText + assert b'a {}' == s.cssText def test_keepEmptyRules(self): "Preferences.keepEmptyRules" @@ -357,9 +357,9 @@ def test_keepEmptyRules(self): cssutils.ser.prefs.keepEmptyRules = True assert css.encode() == s.cssText cssutils.ser.prefs.keepEmptyRules = False - assert 'a {\n /*1*/\n }\na {\n color: red\n }'.encode() == s.cssText + assert b'a {\n /*1*/\n }\na {\n color: red\n }' == s.cssText cssutils.ser.prefs.keepComments = False - assert 'a {\n color: red\n }'.encode() == s.cssText + assert b'a {\n color: red\n }' == s.cssText # CSSMediaRule css = '''@media tv { @@ -386,7 +386,7 @@ def test_keepEmptyRules(self): # self.assertEqual(css, s.cssText) cssutils.ser.prefs.keepEmptyRules = False assert ( - '''@media all { + b'''@media all { /*1*/ } @media print { @@ -398,16 +398,16 @@ def test_keepEmptyRules(self): a { color: red } - }'''.encode() + }''' == s.cssText ) cssutils.ser.prefs.keepComments = False assert ( - '''@media all { + b'''@media all { a { color: red } - }'''.encode() + }''' == s.cssText ) @@ -508,13 +508,13 @@ def test_lineNumbers(self): def test_lineSeparator(self): "Preferences.lineSeparator" s = cssutils.parseString('a { x:1;y:2}') - assert 'a {\n x: 1;\n y: 2\n }'.encode() == s.cssText + assert b'a {\n x: 1;\n y: 2\n }' == s.cssText # cannot be indented as no split possible cssutils.ser.prefs.lineSeparator = '' - assert 'a {x: 1;y: 2 }'.encode() == s.cssText + assert b'a {x: 1;y: 2 }' == s.cssText # no valid css but should work cssutils.ser.prefs.lineSeparator = 'XXX' - assert 'a {XXX x: 1;XXX y: 2XXX }'.encode() == s.cssText + assert b'a {XXX x: 1;XXX y: 2XXX }' == s.cssText def test_listItemSpacer(self): "Preferences.listItemSpacer" @@ -524,25 +524,25 @@ def test_listItemSpacer(self): @import "x" print, tv; a, b {}''' s = cssutils.parseString(css) - assert '@import "x" print, tv;\na, b {}'.encode() == s.cssText + assert b'@import "x" print, tv;\na, b {}' == s.cssText cssutils.ser.prefs.listItemSpacer = '' - assert '@import "x" print,tv;\na,b {}'.encode() == s.cssText + assert b'@import "x" print,tv;\na,b {}' == s.cssText def test_minimizeColorHash(self): "Preferences.minimizeColorHash" css = 'a { color: #ffffff }' s = cssutils.parseString(css) - assert 'a {\n color: #fff\n }'.encode() == s.cssText + assert b'a {\n color: #fff\n }' == s.cssText cssutils.ser.prefs.minimizeColorHash = False - assert 'a {\n color: #ffffff\n }'.encode() == s.cssText + assert b'a {\n color: #ffffff\n }' == s.cssText def test_omitLastSemicolon(self): "Preferences.omitLastSemicolon" css = 'a { x: 1; y: 2 }' s = cssutils.parseString(css) - assert 'a {\n x: 1;\n y: 2\n }'.encode() == s.cssText + assert b'a {\n x: 1;\n y: 2\n }' == s.cssText cssutils.ser.prefs.omitLastSemicolon = False - assert 'a {\n x: 1;\n y: 2;\n }'.encode() == s.cssText + assert b'a {\n x: 1;\n y: 2;\n }' == s.cssText def test_normalizedVarNames(self): "Preferences.normalizedVarNames" @@ -550,9 +550,9 @@ def test_normalizedVarNames(self): css = '@variables { A: 1 }' s = cssutils.parseString(css) - assert '@variables {\n a: 1\n }'.encode() == s.cssText + assert b'@variables {\n a: 1\n }' == s.cssText cssutils.ser.prefs.normalizedVarNames = False - assert '@variables {\n A: 1\n }'.encode() == s.cssText + assert b'@variables {\n A: 1\n }' == s.cssText cssutils.ser.prefs.resolveVariables = True @@ -560,17 +560,17 @@ def test_paranthesisSpacer(self): "Preferences.paranthesisSpacer" css = 'a { x: 1; y: 2 }' s = cssutils.parseString(css) - assert 'a {\n x: 1;\n y: 2\n }'.encode() == s.cssText + assert b'a {\n x: 1;\n y: 2\n }' == s.cssText cssutils.ser.prefs.paranthesisSpacer = '' - assert 'a{\n x: 1;\n y: 2\n }'.encode() == s.cssText + assert b'a{\n x: 1;\n y: 2\n }' == s.cssText def test_propertyNameSpacer(self): "Preferences.propertyNameSpacer" css = 'a { x: 1; y: 2 }' s = cssutils.parseString(css) - assert 'a {\n x: 1;\n y: 2\n }'.encode() == s.cssText + assert b'a {\n x: 1;\n y: 2\n }' == s.cssText cssutils.ser.prefs.propertyNameSpacer = '' - assert 'a {\n x:1;\n y:2\n }'.encode() == s.cssText + assert b'a {\n x:1;\n y:2\n }' == s.cssText def test_selectorCombinatorSpacer(self): "Preferences.selectorCombinatorSpacer" @@ -692,7 +692,7 @@ def test_CSSStyleSheet(self): assert css == str(sheet.cssText, 'utf-8') sheet.cssRules[0].encoding = 'ascii' assert ( - '@charset "ascii";\n/* \\3BA \\3BF \\3C5 \\3C1 \\3BF \\3C2 */'.encode() + b'@charset "ascii";\n/* \\3BA \\3BF \\3C5 \\3C1 \\3BF \\3C2 */' == sheet.cssText ) diff --git a/cssutils/tests/test_settings.py b/cssutils/tests/test_settings.py index caab4ee2..40678456 100644 --- a/cssutils/tests/test_settings.py +++ b/cssutils/tests/test_settings.py @@ -12,12 +12,12 @@ def test_set(self): 'a {filter: progid:DXImageTransform.Microsoft.BasicImage( rotation = 90 )}' ) - assert cssutils.parseString(text).cssText == ''.encode() + assert cssutils.parseString(text).cssText == b'' cssutils.settings.set('DXImageTransform.Microsoft', True) assert ( cssutils.parseString(text).cssText - == 'a{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=90)}'.encode() + == b'a{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=90)}' ) cssutils.ser.prefs.useDefaults() diff --git a/cssutils/tests/test_util.py b/cssutils/tests/test_util.py index f70fc4be..05f1d69e 100644 --- a/cssutils/tests/test_util.py +++ b/cssutils/tests/test_util.py @@ -163,10 +163,10 @@ def fetcher(url): # defaultFetcher returns: readUrl returns None: (None, None, None), (None, ''): ('utf-8', 5, ''), - (None, '€'.encode('utf-8')): ('utf-8', 5, '€'), - ('utf-8', '€'.encode('utf-8')): ('utf-8', 1, '€'), + (None, '€'.encode()): ('utf-8', 5, '€'), + ('utf-8', '€'.encode()): ('utf-8', 1, '€'), ('ISO-8859-1', 'ä'.encode('iso-8859-1')): ('ISO-8859-1', 1, 'ä'), - ('ASCII', 'a'.encode('ascii')): ('ASCII', 1, 'a'), + ('ASCII', b'a'): ('ASCII', 1, 'a'), } for r, exp in list(tests.items()): @@ -177,16 +177,16 @@ def fetcher(url): # readUrl returns # ===== 0. OVERRIDE WINS ===== # override + parent + http - ('latin1', 'ascii', ('utf-16', ''.encode())): ('latin1', 0, ''), - ('latin1', 'ascii', ('utf-16', '123'.encode())): ('latin1', 0, '123'), + ('latin1', 'ascii', ('utf-16', b'')): ('latin1', 0, ''), + ('latin1', 'ascii', ('utf-16', b'123')): ('latin1', 0, '123'), ('latin1', 'ascii', ('utf-16', 'ä'.encode('iso-8859-1'))): ( 'latin1', 0, 'ä', ), - ('latin1', 'ascii', ('utf-16', 'a'.encode('ascii'))): ('latin1', 0, 'a'), + ('latin1', 'ascii', ('utf-16', b'a')): ('latin1', 0, 'a'), # + @charset - ('latin1', 'ascii', ('utf-16', '@charset "ascii";'.encode())): ( + ('latin1', 'ascii', ('utf-16', b'@charset "ascii";')): ( 'latin1', 0, '@charset "latin1";', @@ -196,19 +196,19 @@ def fetcher(url): 0, '@charset "latin1";ä', ), - ('latin1', 'ascii', ('utf-16', '@charset "utf-8";ä'.encode('utf-8'))): ( + ('latin1', 'ascii', ('utf-16', '@charset "utf-8";ä'.encode())): ( 'latin1', 0, '@charset "latin1";\xc3\xa4', ), # read as latin1! # override only ('latin1', None, None): (None, None, None), - ('latin1', None, (None, ''.encode())): ('latin1', 0, ''), - ('latin1', None, (None, '123'.encode())): ('latin1', 0, '123'), + ('latin1', None, (None, b'')): ('latin1', 0, ''), + ('latin1', None, (None, b'123')): ('latin1', 0, '123'), ('latin1', None, (None, 'ä'.encode('iso-8859-1'))): ('latin1', 0, 'ä'), - ('latin1', None, (None, 'a'.encode('ascii'))): ('latin1', 0, 'a'), + ('latin1', None, (None, b'a')): ('latin1', 0, 'a'), # + @charset - ('latin1', None, (None, '@charset "ascii";'.encode())): ( + ('latin1', None, (None, b'@charset "ascii";')): ( 'latin1', 0, '@charset "latin1";', @@ -218,19 +218,19 @@ def fetcher(url): 0, '@charset "latin1";ä', ), - ('latin1', None, (None, '@charset "utf-8";ä'.encode('utf-8'))): ( + ('latin1', None, (None, '@charset "utf-8";ä'.encode())): ( 'latin1', 0, '@charset "latin1";\xc3\xa4', ), # read as latin1! # override + parent ('latin1', 'ascii', None): (None, None, None), - ('latin1', 'ascii', (None, ''.encode())): ('latin1', 0, ''), - ('latin1', 'ascii', (None, '123'.encode())): ('latin1', 0, '123'), + ('latin1', 'ascii', (None, b'')): ('latin1', 0, ''), + ('latin1', 'ascii', (None, b'123')): ('latin1', 0, '123'), ('latin1', 'ascii', (None, 'ä'.encode('iso-8859-1'))): ('latin1', 0, 'ä'), - ('latin1', 'ascii', (None, 'a'.encode('ascii'))): ('latin1', 0, 'a'), + ('latin1', 'ascii', (None, b'a')): ('latin1', 0, 'a'), # + @charset - ('latin1', 'ascii', (None, '@charset "ascii";'.encode())): ( + ('latin1', 'ascii', (None, b'@charset "ascii";')): ( 'latin1', 0, '@charset "latin1";', @@ -240,18 +240,18 @@ def fetcher(url): 0, '@charset "latin1";ä', ), - ('latin1', 'ascii', (None, '@charset "utf-8";ä'.encode('utf-8'))): ( + ('latin1', 'ascii', (None, '@charset "utf-8";ä'.encode())): ( 'latin1', 0, '@charset "latin1";\xc3\xa4', ), # read as latin1! # override + http - ('latin1', None, ('utf-16', ''.encode())): ('latin1', 0, ''), - ('latin1', None, ('utf-16', '123'.encode())): ('latin1', 0, '123'), + ('latin1', None, ('utf-16', b'')): ('latin1', 0, ''), + ('latin1', None, ('utf-16', b'123')): ('latin1', 0, '123'), ('latin1', None, ('utf-16', 'ä'.encode('iso-8859-1'))): ('latin1', 0, 'ä'), - ('latin1', None, ('utf-16', 'a'.encode('ascii'))): ('latin1', 0, 'a'), + ('latin1', None, ('utf-16', b'a')): ('latin1', 0, 'a'), # + @charset - ('latin1', None, ('utf-16', '@charset "ascii";'.encode())): ( + ('latin1', None, ('utf-16', b'@charset "ascii";')): ( 'latin1', 0, '@charset "latin1";', @@ -261,13 +261,13 @@ def fetcher(url): 0, '@charset "latin1";ä', ), - ('latin1', None, ('utf-16', '@charset "utf-8";ä'.encode('utf-8'))): ( + ('latin1', None, ('utf-16', '@charset "utf-8";ä'.encode())): ( 'latin1', 0, '@charset "latin1";\xc3\xa4', ), # read as latin1! # override ü @charset - ('latin1', None, (None, '@charset "ascii";'.encode())): ( + ('latin1', None, (None, b'@charset "ascii";')): ( 'latin1', 0, '@charset "latin1";', @@ -277,18 +277,18 @@ def fetcher(url): 0, '@charset "latin1";ä', ), - ('latin1', None, (None, '@charset "utf-8";ä'.encode('utf-8'))): ( + ('latin1', None, (None, '@charset "utf-8";ä'.encode())): ( 'latin1', 0, '@charset "latin1";\xc3\xa4', ), # read as latin1! # ===== 1. HTTP WINS ===== - (None, 'ascii', ('latin1', ''.encode())): ('latin1', 1, ''), - (None, 'ascii', ('latin1', '123'.encode())): ('latin1', 1, '123'), + (None, 'ascii', ('latin1', b'')): ('latin1', 1, ''), + (None, 'ascii', ('latin1', b'123')): ('latin1', 1, '123'), (None, 'ascii', ('latin1', 'ä'.encode('iso-8859-1'))): ('latin1', 1, 'ä'), - (None, 'ascii', ('latin1', 'a'.encode('ascii'))): ('latin1', 1, 'a'), + (None, 'ascii', ('latin1', b'a')): ('latin1', 1, 'a'), # + @charset - (None, 'ascii', ('latin1', '@charset "ascii";'.encode())): ( + (None, 'ascii', ('latin1', b'@charset "ascii";')): ( 'latin1', 1, '@charset "latin1";', @@ -298,13 +298,13 @@ def fetcher(url): 1, '@charset "latin1";ä', ), - (None, 'ascii', ('latin1', '@charset "utf-8";ä'.encode('utf-8'))): ( + (None, 'ascii', ('latin1', '@charset "utf-8";ä'.encode())): ( 'latin1', 1, '@charset "latin1";\xc3\xa4', ), # read as latin1! # ===== 2. @charset WINS ===== - (None, 'ascii', (None, '@charset "latin1";'.encode())): ( + (None, 'ascii', (None, b'@charset "latin1";')): ( 'latin1', 2, '@charset "latin1";', @@ -314,7 +314,7 @@ def fetcher(url): 2, '@charset "latin1";ä', ), - (None, 'ascii', (None, '@charset "latin1";ä'.encode('utf-8'))): ( + (None, 'ascii', (None, '@charset "latin1";ä'.encode())): ( 'latin1', 2, '@charset "latin1";\xc3\xa4', @@ -336,20 +336,20 @@ def fetcher(url): '@charset "utf-8";\xe4', ), # read as latin1! # ===== 4. parentEncoding WINS ===== - (None, 'latin1', (None, ''.encode())): ('latin1', 4, ''), - (None, 'latin1', (None, '123'.encode())): ('latin1', 4, '123'), + (None, 'latin1', (None, b'')): ('latin1', 4, ''), + (None, 'latin1', (None, b'123')): ('latin1', 4, '123'), (None, 'latin1', (None, 'ä'.encode('iso-8859-1'))): ('latin1', 4, 'ä'), - (None, 'latin1', (None, 'a'.encode('ascii'))): ('latin1', 4, 'a'), - (None, 'latin1', (None, 'ä'.encode('utf-8'))): ( + (None, 'latin1', (None, b'a')): ('latin1', 4, 'a'), + (None, 'latin1', (None, 'ä'.encode())): ( 'latin1', 4, '\xc3\xa4', ), # read as latin1! # ===== 5. default WINS which in this case is None! ===== - (None, None, (None, ''.encode())): ('utf-8', 5, ''), - (None, None, (None, '123'.encode())): ('utf-8', 5, '123'), - (None, None, (None, 'a'.encode('ascii'))): ('utf-8', 5, 'a'), - (None, None, (None, 'ä'.encode('utf-8'))): ( + (None, None, (None, b'')): ('utf-8', 5, ''), + (None, None, (None, b'123')): ('utf-8', 5, '123'), + (None, None, (None, b'a')): ('utf-8', 5, 'a'), + (None, None, (None, 'ä'.encode())): ( 'utf-8', 5, 'ä', @@ -438,10 +438,10 @@ def x(*ignored): # positive tests tests = { # content-type, contentstr: encoding, contentstr - ('text/css', '€'.encode('utf-8')): (None, '€'.encode('utf-8')), - ('text/css;charset=utf-8', '€'.encode('utf-8')): ( + ('text/css', '€'.encode()): (None, '€'.encode()), + ('text/css;charset=utf-8', '€'.encode()): ( 'utf-8', - '€'.encode('utf-8'), + '€'.encode(), ), ('text/css;charset=ascii', 'a'): ('ascii', 'a'), } diff --git a/cssutils/tests/test_value.py b/cssutils/tests/test_value.py index d12591a0..6e014f04 100644 --- a/cssutils/tests/test_value.py +++ b/cssutils/tests/test_value.py @@ -779,7 +779,7 @@ def test_cssValueType(self): class CSSPrimitiveValueTestCase: def test_init(self): "CSSPrimitiveValue.__init__()" - v = cssutils.css.CSSPrimitiveValue(u'1') + v = cssutils.css.CSSPrimitiveValue('1') assert '1' == v.cssText assert v.CSS_PRIMITIVE_VALUE == v.cssValueType diff --git a/cssutils/tests/test_x.py b/cssutils/tests/test_x.py index a616c941..7a998c4d 100644 --- a/cssutils/tests/test_x.py +++ b/cssutils/tests/test_x.py @@ -18,7 +18,7 @@ def teardown(self): def test_priority(self): "Property.priority" s = cssutils.parseString('a { color: red }') - assert s.cssText == 'a {\n color: red\n }'.encode() + assert s.cssText == b'a {\n color: red\n }' assert '' == s.cssRules[0].style.getPropertyPriority('color') diff --git a/cssutils/tokenize2.py b/cssutils/tokenize2.py index 3f48bb77..90d29e07 100644 --- a/cssutils/tokenize2.py +++ b/cssutils/tokenize2.py @@ -145,8 +145,7 @@ def _normalize(value): _orig_text = text while pos < _len_text: # do pushed tokens before new ones - for pushed in self._pushed: - yield pushed + yield from self._pushed # speed test for most used CHARs, sadly . not possible :( c = text[pos] @@ -191,13 +190,13 @@ def _normalize(value): # check if found may be completed into a full token if 'INVALID' == name and suffix_eq(text, pos, found): # complete INVALID to STRING with start char " or ' - name, found = 'STRING', '%s%s' % (found, found[0]) + name, found = 'STRING', f'{found}{found[0]}' elif 'FUNCTION' == name and 'url(' == _normalize(found): # url( is a FUNCTION if incomplete sheet # FUNCTION production MUST BE after URI production for end in ("')", '")', ')'): - possibleuri = '%s%s' % (text[pos:], end) + possibleuri = f'{text[pos:]}{end}' match = self.urimatcher(possibleuri) if match: name, found = 'URI', match.group(0) diff --git a/cssutils/util.py b/cssutils/util.py index 92765994..4dab40d8 100644 --- a/cssutils/util.py +++ b/cssutils/util.py @@ -469,8 +469,7 @@ def _parse( def tokens(): "Build new tokenizer including initialtoken" yield initialtoken - for item in tokenizer: - yield item + yield from tokenizer fulltokenizer = chain([initialtoken], tokenizer) else: @@ -576,7 +575,7 @@ def __init__(self, readonly=True): def __repr__(self): "returns a repr same as a list of tuples of (value, type)" - return 'cssutils.%s.%s([\n %s], readonly=%r)' % ( + return 'cssutils.{}.{}([\n {}], readonly={!r})'.format( self.__module__, self.__class__.__name__, ',\n '.join(['%r' % item for item in self._seq]), @@ -593,7 +592,7 @@ def __str__(self): else: vals.append(repr(v)) - return "" % ( + return "".format( self.__module__, self.__class__.__name__, len(self), @@ -696,7 +695,7 @@ def __init__(self, value, type, line=None, col=None): col = property(lambda self: self.__col) def __repr__(self): - return "%s.%s(value=%r, type=%r, line=%r, col=%r)" % ( + return "{}.{}(value={!r}, type={!r}, line={!r}, col={!r})".format( self.__module__, self.__class__.__name__, self.__value, @@ -737,8 +736,7 @@ def __getitem__(self, index): def __iter__(self): def gen(): - for x in self.seq: - yield x + yield from self.seq return gen() @@ -873,7 +871,7 @@ def prefixForNamespaceURI(self, namespaceURI): raise IndexError('NamespaceURI %s not found.' % namespaceURI) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, str(self.parentStyleSheet), id(self), @@ -888,7 +886,7 @@ class _SimpleNamespaces(_Namespaces): def __init__(self, log=None, *args): """init""" - super(_SimpleNamespaces, self).__init__(parentStyleSheet=None, log=log) + super().__init__(parentStyleSheet=None, log=log) self.__namespaces = dict(*args) def __setitem__(self, prefix, namespaceURI): @@ -900,14 +898,14 @@ def __setitem__(self, prefix, namespaceURI): ) def __str__(self): - return "" % ( + return "".format( self.__class__.__name__, self.namespaces, id(self), ) def __repr__(self): - return "cssutils.util.%s(%r)" % (self.__class__.__name__, self.namespaces) + return f"cssutils.util.{self.__class__.__name__}({self.namespaces!r})" def _readUrl( # noqa: C901 diff --git a/encutils/__init__.py b/encutils/__init__.py index 51334c15..da6aa042 100644 --- a/encutils/__init__.py +++ b/encutils/__init__.py @@ -67,7 +67,7 @@ class _MetaHTMLParser(html.parser.HTMLParser): def handle_starttag(self, tag, attrs): if tag == 'meta' and not self.content_type: - atts = dict([(a.lower(), v.lower()) for a, v in attrs]) + atts = {a.lower(): v.lower() for a, v in attrs} if atts.get('http-equiv', '').strip() == 'content-type': self.content_type = atts.get('content') @@ -147,7 +147,7 @@ def __str__(self): return '' def __repr__(self): - return "<%s.%s object encoding=%r mismatch=%s at 0x%x>" % ( + return "<{}.{} object encoding={!r} mismatch={} at 0x{:x}>".format( self.__class__.__module__, self.__class__.__name__, self.encoding, @@ -569,7 +569,7 @@ def getEncodingInfo(response=None, text='', log=None, url=None): # noqa: C901 # read text from response only if not explicitly given try: text = response.read() - except IOError: + except OSError: pass if text is None: diff --git a/examples/testutil.py b/examples/testutil.py index e2e5ac64..42806a86 100644 --- a/examples/testutil.py +++ b/examples/testutil.py @@ -54,9 +54,9 @@ def end(self, expo, expe): if not ok: print() if out != expo: - print('### out:\n%r\n### != expout:\n%r\n' % (out, expo)) + print('### out:\n{!r}\n### != expout:\n{!r}\n'.format(out, expo)) else: - print('### err:\n%r\n### != experr:\n%r\n' % (err, expe)) + print('### err:\n{!r}\n### != experr:\n{!r}\n'.format(err, expe)) return ok diff --git a/tools/try.py b/tools/try.py index 6fb3e1e6..9320fb8a 100644 --- a/tools/try.py +++ b/tools/try.py @@ -740,7 +740,9 @@ def f(url): if vi.cssValueType == vi.CSS_VARIABLE: if vi.value: print( - '+ CSSValueList: Replacing %r with %r' % (p.value, vi.value) + '+ CSSValueList: Replacing {!r} with {!r}'.format( + p.value, vi.value + ) ) newvalue.append(vi.value) else: @@ -753,7 +755,7 @@ def f(url): elif v.cssValueType == v.CSS_VARIABLE: if v.value: - print('+ Replacing %r with %r' % (p.value, v.value)) + print('+ Replacing {!r} with {!r}'.format(p.value, v.value)) p.value = v.value else: print('- No value found for %r' % p.value) @@ -1040,7 +1042,7 @@ def pathname2url(p): comp = p.split(':') if len(comp) != 2 or len(comp[0]) > 1: error = 'Bad path: ' + p - raise IOError(error) + raise OSError(error) drive = urllib.parse.quote(comp[0].upper()) components = comp[1].split('\\') @@ -1217,7 +1219,7 @@ def fetchUrlGAE(self): r = urlfetch.fetch(url, method=urlfetch.GET) except urlfetch.Error as e: cssutils.log.warn( - 'Error opening url=%r: %s' % (url, e.message), error=IOError + 'Error opening url={!r}: {}'.format(url, e.message), error=IOError ) else: if r.status_code == 200: @@ -1235,7 +1237,7 @@ def fetchUrlGAE(self): else: # TODO: 301 etc cssutils.log.warn( - 'Error opening url=%r: HTTP status %s' % (url, r.status_code), + 'Error opening url={!r}: HTTP status {}'.format(url, r.status_code), error=IOError, )