From 894ee62c7a1ed4f2661405ac9ef542f96916f236 Mon Sep 17 00:00:00 2001 From: "Jens W. Klein" Date: Thu, 25 Aug 2022 19:05:44 +0200 Subject: [PATCH] black --- bootstrap.py | 144 +++++++------- plone/__init__.py | 2 +- .../outputfilters/browser/captioned_image.py | 3 +- plone/outputfilters/browser/resolveuid.py | 28 +-- plone/outputfilters/filters/example.py | 4 +- .../outputfilters/filters/picture_variants.py | 8 +- .../filters/resolveuid_and_caption.py | 159 +++++++++------- plone/outputfilters/interfaces.py | 2 +- plone/outputfilters/mimetype.py | 2 +- plone/outputfilters/setuphandlers.py | 21 ++- plone/outputfilters/testing.py | 20 +- .../outputfilters/tests/test_apply_filters.py | 13 +- plone/outputfilters/tests/test_docs.py | 33 ++-- .../tests/test_picture_variants.py | 72 +++---- .../tests/test_resolveuid_and_caption.py | 176 ++++++++++-------- plone/outputfilters/tests/test_transforms.py | 24 ++- .../html_to_plone_outputfilters_html.py | 12 +- .../plone_outputfilters_html_to_html.py | 8 +- setup.py | 53 +++--- 19 files changed, 429 insertions(+), 355 deletions(-) diff --git a/bootstrap.py b/bootstrap.py index b62354a..85111f9 100644 --- a/bootstrap.py +++ b/bootstrap.py @@ -26,12 +26,12 @@ import tempfile -__version__ = '2015-07-01' +__version__ = "2015-07-01" # See zc.buildout's changelog if this version is up to date. -tmpeggs = tempfile.mkdtemp(prefix='bootstrap-') +tmpeggs = tempfile.mkdtemp(prefix="bootstrap-") -usage = '''\ +usage = """\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. @@ -41,36 +41,50 @@ Note that by using --find-links to point to local resources, you can keep this script from going over the network. -''' +""" parser = OptionParser(usage=usage) -parser.add_option("--version", - action="store_true", default=False, - help=("Return bootstrap.py version.")) -parser.add_option("-t", "--accept-buildout-test-releases", - dest='accept_buildout_test_releases', - action="store_true", default=False, - help=("Normally, if you do not specify a --buildout-version, " - "the bootstrap script and buildout gets the newest " - "*final* versions of zc.buildout and its recipes and " - "extensions for you. If you use this flag, " - "bootstrap and buildout will get the newest releases " - "even if they are alphas or betas.")) -parser.add_option("-c", "--config-file", - help=("Specify the path to the buildout configuration " - "file to be used.")) -parser.add_option("-f", "--find-links", - help=("Specify a URL to search for buildout releases")) -parser.add_option("--allow-site-packages", - action="store_true", default=False, - help=("Let bootstrap.py use existing site packages")) -parser.add_option("--buildout-version", - help="Use a specific zc.buildout version") -parser.add_option("--setuptools-version", - help="Use a specific setuptools version") -parser.add_option("--setuptools-to-dir", - help=("Allow for re-use of existing directory of " - "setuptools versions")) +parser.add_option( + "--version", + action="store_true", + default=False, + help=("Return bootstrap.py version."), +) +parser.add_option( + "-t", + "--accept-buildout-test-releases", + dest="accept_buildout_test_releases", + action="store_true", + default=False, + help=( + "Normally, if you do not specify a --buildout-version, " + "the bootstrap script and buildout gets the newest " + "*final* versions of zc.buildout and its recipes and " + "extensions for you. If you use this flag, " + "bootstrap and buildout will get the newest releases " + "even if they are alphas or betas." + ), +) +parser.add_option( + "-c", + "--config-file", + help=("Specify the path to the buildout configuration " "file to be used."), +) +parser.add_option( + "-f", "--find-links", help=("Specify a URL to search for buildout releases") +) +parser.add_option( + "--allow-site-packages", + action="store_true", + default=False, + help=("Let bootstrap.py use existing site packages"), +) +parser.add_option("--buildout-version", help="Use a specific zc.buildout version") +parser.add_option("--setuptools-version", help="Use a specific setuptools version") +parser.add_option( + "--setuptools-to-dir", + help=("Allow for re-use of existing directory of " "setuptools versions"), +) options, args = parser.parse_args() if options.version: @@ -87,10 +101,10 @@ from urllib2 import urlopen ez = {} -if os.path.exists('ez_setup.py'): - exec(open('ez_setup.py').read(), ez) +if os.path.exists("ez_setup.py"): + exec(open("ez_setup.py").read(), ez) else: - exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) + exec(urlopen("https://bootstrap.pypa.io/ez_setup.py").read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages @@ -100,23 +114,22 @@ # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably - if hasattr(site, 'getsitepackages'): + if hasattr(site, "getsitepackages"): for sitepackage_path in site.getsitepackages(): # Strip all site-packages directories from sys.path that # are not sys.prefix; this is because on Windows # sys.prefix is a site-package directory. if sitepackage_path != sys.prefix: - sys.path[:] = [x for x in sys.path - if sitepackage_path not in x] + sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: - setup_args['version'] = options.setuptools_version + setup_args["version"] = options.setuptools_version if options.setuptools_to_dir is not None: - setup_args['to_dir'] = options.setuptools_to_dir + setup_args["to_dir"] = options.setuptools_to_dir -ez['use_setuptools'](**setup_args) +ez["use_setuptools"](**setup_args) import pkg_resources import setuptools @@ -132,30 +145,37 @@ ws = pkg_resources.working_set -setuptools_path = ws.find( - pkg_resources.Requirement.parse('setuptools')).location +setuptools_path = ws.find(pkg_resources.Requirement.parse("setuptools")).location # Fix sys.path here as easy_install.pth added before PYTHONPATH -cmd = [sys.executable, '-c', - 'import sys; sys.path[0:0] = [%r]; ' % setuptools_path + - 'from setuptools.command.easy_install import main; main()', - '-mZqNxd', tmpeggs] +cmd = [ + sys.executable, + "-c", + "import sys; sys.path[0:0] = [%r]; " % setuptools_path + + "from setuptools.command.easy_install import main; main()", + "-mZqNxd", + tmpeggs, +] find_links = os.environ.get( - 'bootstrap-testing-find-links', - options.find_links or - ('http://downloads.buildout.org/' - if options.accept_buildout_test_releases else None) - ) + "bootstrap-testing-find-links", + options.find_links + or ( + "http://downloads.buildout.org/" + if options.accept_buildout_test_releases + else None + ), +) if find_links: - cmd.extend(['-f', find_links]) + cmd.extend(["-f", find_links]) -requirement = 'zc.buildout' +requirement = "zc.buildout" version = options.buildout_version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index - _final_parts = '*final-', '*final' + + _final_parts = "*final-", "*final" def _final_version(parsed_version): try: @@ -163,12 +183,11 @@ def _final_version(parsed_version): except AttributeError: # Older setuptools for part in parsed_version: - if (part[:1] == '*') and (part not in _final_parts): + if (part[:1] == "*") and (part not in _final_parts): return False return True - index = setuptools.package_index.PackageIndex( - search_path=[setuptools_path]) + index = setuptools.package_index.PackageIndex(search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) @@ -187,15 +206,14 @@ def _final_version(parsed_version): best.sort() version = best[-1].version if version: - requirement = '=='.join((requirement, version)) + requirement = "==".join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd) != 0: - raise Exception( - "Failed to execute command:\n%s" % repr(cmd)[1:-1]) + raise Exception("Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout @@ -205,12 +223,12 @@ def _final_version(parsed_version): import zc.buildout.buildout -if not [a for a in args if '=' not in a]: - args.append('bootstrap') +if not [a for a in args if "=" not in a]: + args.append("bootstrap") # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: - args[0:0] = ['-c', options.config_file] + args[0:0] = ["-c", options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs) diff --git a/plone/__init__.py b/plone/__init__.py index 68c04af..03d08ff 100644 --- a/plone/__init__.py +++ b/plone/__init__.py @@ -1,2 +1,2 @@ # -*- coding: utf-8 -*- -__import__('pkg_resources').declare_namespace(__name__) +__import__("pkg_resources").declare_namespace(__name__) diff --git a/plone/outputfilters/browser/captioned_image.py b/plone/outputfilters/browser/captioned_image.py index 2e08478..8f286f2 100644 --- a/plone/outputfilters/browser/captioned_image.py +++ b/plone/outputfilters/browser/captioned_image.py @@ -4,8 +4,7 @@ class CaptionedImageView(BrowserView): - """Captioned image template. - """ + """Captioned image template.""" @lazy_property def template(self): diff --git a/plone/outputfilters/browser/resolveuid.py b/plone/outputfilters/browser/resolveuid.py index 7883fd1..8ef9eb8 100644 --- a/plone/outputfilters/browser/resolveuid.py +++ b/plone/outputfilters/browser/resolveuid.py @@ -16,9 +16,8 @@ @deprecate("Please use plone.app.uuid.utils.uuidToURL instead.") def uuidToURL(uuid): - """Resolves a UUID to a URL via the UID index of portal_catalog. - """ - catalog = getToolByName(getSite(), 'portal_catalog') + """Resolves a UUID to a URL via the UID index of portal_catalog.""" + catalog = getToolByName(getSite(), "portal_catalog") res = catalog.unrestrictedSearchResults(UID=uuid) if res: return res[0].getURL() @@ -29,9 +28,8 @@ def uuidToURL(uuid): "But be aware that this does an extra security check." ) def uuidToObject(uuid): - """Resolves a UUID to an object via the UID index of portal_catalog. - """ - catalog = getToolByName(getSite(), 'portal_catalog') + """Resolves a UUID to an object via the UID index of portal_catalog.""" + catalog = getToolByName(getSite(), "portal_catalog") res = catalog.unrestrictedSearchResults(UID=uuid) if res: return res[0]._unrestrictedGetObject() @@ -40,31 +38,33 @@ def uuidToObject(uuid): try: from plone.uuid.interfaces import IUUID except ImportError: + def uuidFor(obj): return obj.UID() + else: + def uuidFor(obj): uuid = IUUID(obj, None) - if uuid is None and hasattr(aq_base(obj), 'UID'): + if uuid is None and hasattr(aq_base(obj), "UID"): uuid = obj.UID() return uuid @implementer(IPublishTraverse) class ResolveUIDView(BrowserView): - """Resolve a URL like /resolveuid/ to a normalized URL. - """ + """Resolve a URL like /resolveuid/ to a normalized URL.""" subpath = None def publishTraverse(self, request, name): self.uuid = name - traverse_subpath = self.request['TraversalRequestNameStack'] + traverse_subpath = self.request["TraversalRequestNameStack"] if traverse_subpath: traverse_subpath = list(traverse_subpath) traverse_subpath.reverse() self.subpath = traverse_subpath - self.request['TraversalRequestNameStack'] = [] + self.request["TraversalRequestNameStack"] = [] return self def __call__(self): @@ -74,11 +74,11 @@ def __call__(self): raise NotFound("The link you followed is broken") if self.subpath: - url = '/'.join([url] + self.subpath) + url = "/".join([url] + self.subpath) if self.request.QUERY_STRING: - url += '?' + self.request.QUERY_STRING + url += "?" + self.request.QUERY_STRING self.request.response.redirect(url, status=301) - return '' + return "" diff --git a/plone/outputfilters/filters/example.py b/plone/outputfilters/filters/example.py index 9a79ff0..9dcb1a1 100644 --- a/plone/outputfilters/filters/example.py +++ b/plone/outputfilters/filters/example.py @@ -15,7 +15,7 @@ def __init__(self, context, request): def is_enabled(self): return True - pattern = re.compile(r'--') + pattern = re.compile(r"--") def __call__(self, data): - return self.pattern.sub(u'—', data) + return self.pattern.sub("—", data) diff --git a/plone/outputfilters/filters/picture_variants.py b/plone/outputfilters/filters/picture_variants.py index 738f780..45566a1 100644 --- a/plone/outputfilters/filters/picture_variants.py +++ b/plone/outputfilters/filters/picture_variants.py @@ -13,8 +13,7 @@ @implementer(IFilter) class PictureVariantsFilter(object): - """Converts img tags with a data-picturevariant attribute into picture/source tag's with srcset definitions. - """ + """Converts img tags with a data-picturevariant attribute into picture/source tag's with srcset definitions.""" order = 700 @@ -30,7 +29,6 @@ def __init__(self, context=None, request=None): self.request = request self.img2picturetag = Img2PictureTag() - def __call__(self, data): soup = BeautifulSoup(safe_nativestring(data), "html.parser") @@ -49,5 +47,7 @@ def __call__(self, data): sourceset = picture_variants_config.get("sourceset") if not sourceset: continue - elem.replace_with(self.img2picturetag.create_picture_tag(sourceset, elem.attrs)) + elem.replace_with( + self.img2picturetag.create_picture_tag(sourceset, elem.attrs) + ) return soup.prettify() diff --git a/plone/outputfilters/filters/resolveuid_and_caption.py b/plone/outputfilters/filters/resolveuid_and_caption.py index 55c1ec1..857a8d4 100644 --- a/plone/outputfilters/filters/resolveuid_and_caption.py +++ b/plone/outputfilters/filters/resolveuid_and_caption.py @@ -30,26 +30,25 @@ import six -appendix_re = re.compile('^(.*)([?#].*)$') -resolveuid_re = re.compile('^[./]*resolve[Uu]id/([^/]*)/?(.*)$') +appendix_re = re.compile("^(.*)([?#].*)$") +resolveuid_re = re.compile("^[./]*resolve[Uu]id/([^/]*)/?(.*)$") class IImageCaptioningEnabler(Interface): available = Attribute( - "Boolean indicating whether image captioning should be performed.") + "Boolean indicating whether image captioning should be performed." + ) class IResolveUidsEnabler(Interface): - available = Attribute( - "Boolean indicating whether UID links should be resolved.") + available = Attribute("Boolean indicating whether UID links should be resolved.") @implementer(IImageCaptioningEnabler) class ImageCaptioningEnabler(object): - @property def available(self): - name = 'plone.image_captioning' + name = "plone.image_captioning" registry = getUtility(IRegistry) if name in registry: return registry[name] @@ -62,18 +61,37 @@ class ResolveUidsAlwaysEnabled(object): def tag(img, **attributes): - if hasattr(aq_base(img), 'tag'): + if hasattr(aq_base(img), "tag"): return img.tag(**attributes) @implementer(IFilter) class ResolveUIDAndCaptionFilter(object): - """ Parser to convert UUID links and captioned images """ - - singleton_tags = set([ - 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', - 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param', - 'source', 'track', 'wbr']) + """Parser to convert UUID links and captioned images""" + + singleton_tags = set( + [ + "area", + "base", + "basefont", + "br", + "col", + "command", + "embed", + "frame", + "hr", + "img", + "input", + "isindex", + "keygen", + "link", + "meta", + "param", + "source", + "track", + "wbr", + ] + ) def __init__(self, context=None, request=None): self.current_status = None @@ -85,8 +103,7 @@ def __init__(self, context=None, request=None): @lazy_property def captioned_image_template(self): - return self.context.restrictedTraverse( - 'plone.outputfilters_captioned_image') + return self.context.restrictedTraverse("plone.outputfilters_captioned_image") @lazy_property def captioned_images(self): @@ -111,79 +128,85 @@ def is_enabled(self): def _shorttag_replace(self, match): tag = match.group(1) if tag in self.singleton_tags: - return '<' + tag + ' />' + return "<" + tag + " />" else: - return '<' + tag + '>' + return "<" + tag + ">" def _render_resolveuid(self, href): url_parts = urlsplit(href) scheme = url_parts[0] - path_parts = urlunsplit(['', ''] + list(url_parts[2:])) + path_parts = urlunsplit(["", ""] + list(url_parts[2:])) obj, subpath, appendix = self.resolve_link(path_parts) if obj is not None: href = obj.absolute_url() if subpath: - href += '/' + subpath + href += "/" + subpath href += appendix - elif resolveuid_re.match(href) is None \ - and not scheme \ - and not href.startswith('/'): + elif ( + resolveuid_re.match(href) is None + and not scheme + and not href.startswith("/") + ): # absolutize relative URIs; this text isn't necessarily # being rendered in the context where it was stored relative_root = self.context - if not getattr(self.context, 'isPrincipiaFolderish', False): + if not getattr(self.context, "isPrincipiaFolderish", False): relative_root = aq_parent(self.context) actual_url = relative_root.absolute_url() - href = urljoin(actual_url + '/', subpath) + appendix + href = urljoin(actual_url + "/", subpath) + appendix return href def __call__(self, data): - data = re.sub(r'<([^<>\s]+?)\s*/>', self._shorttag_replace, data) - soup = BeautifulSoup(safe_unicode(data), 'html.parser') - for elem in soup.find_all(['a', 'area']): + data = re.sub(r"<([^<>\s]+?)\s*/>", self._shorttag_replace, data) + soup = BeautifulSoup(safe_unicode(data), "html.parser") + for elem in soup.find_all(["a", "area"]): attributes = elem.attrs - href = attributes.get('href') + href = attributes.get("href") # an 'a' anchor element has no href if not href: continue - if not href.startswith('mailto<') \ - and not href.startswith('mailto:') \ - and not href.startswith('tel:') \ - and not href.startswith('#'): - attributes['href'] = self._render_resolveuid(href) - for elem in soup.find_all(['source', 'img']): + if ( + not href.startswith("mailto<") + and not href.startswith("mailto:") + and not href.startswith("tel:") + and not href.startswith("#") + ): + attributes["href"] = self._render_resolveuid(href) + for elem in soup.find_all(["source", "img"]): # handles srcset attributes, not src # parent of SOURCE is picture here. # SRCSET on source/img specifies one or more images (see below). attributes = elem.attrs - srcset = attributes.get('srcset') + srcset = attributes.get("srcset") if not srcset: continue # https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images # [(src1, 480w), (src2, 360w)] - srcs = [src.strip().split() for src in srcset.strip().split(',') if src.strip()] + srcs = [ + src.strip().split() for src in srcset.strip().split(",") if src.strip() + ] for idx, elm in enumerate(srcs): image_url = elm[0] image, fullimage, src, description = self.resolve_image(image_url) srcs[idx][0] = src - attributes['srcset'] = ','.join(' '.join(src) for src in srcs) - for elem in soup.find_all(['source', 'iframe', 'audio', 'video']): + attributes["srcset"] = ",".join(" ".join(src) for src in srcs) + for elem in soup.find_all(["source", "iframe", "audio", "video"]): # parent of SOURCE is video or audio here. # AUDIO/VIDEO can also have src attribute. # IFRAME is used to embed PDFs. attributes = elem.attrs - src = attributes.get('src') + src = attributes.get("src") if not src: continue - attributes['src'] = self._render_resolveuid(src) - for elem in soup.find_all(['img', 'picture']): + attributes["src"] = self._render_resolveuid(src) + for elem in soup.find_all(["img", "picture"]): if elem.name == "picture": img_elem = elem.find("img") else: img_elem = elem # handle src attribute attributes = img_elem.attrs - src = attributes.get('src', '') + src = attributes.get("src", "") image, fullimage, src, description = self.resolve_image(src) attributes["src"] = src if image and hasattr(image, "width"): @@ -193,36 +216,37 @@ def __call__(self, data): attributes["height"] = image.height if fullimage is not None: # Check to see if the alt / title tags need setting - title = safe_unicode(aq_acquire(fullimage, 'Title')()) - if not attributes.get('alt'): + title = safe_unicode(aq_acquire(fullimage, "Title")()) + if not attributes.get("alt"): # bettr an emty alt tag than none. This avoid's screen readers # to read the file name instead. A better fallback would be # a fallback alt text comming from the img object. - attributes['alt'] = "" - if 'title' not in attributes: - attributes['title'] = title + attributes["alt"] = "" + if "title" not in attributes: + attributes["title"] = title # handle captions - if 'captioned' in elem.attrs.get('class', []): + if "captioned" in elem.attrs.get("class", []): caption = description caption_manual_override = attributes.get("data-captiontext", "") if caption_manual_override: caption = caption_manual_override # Check if the image needs to be captioned - if (self.captioned_images and caption): + if self.captioned_images and caption: options = {} options["tag"] = elem.prettify() options["caption"] = newline_to_br(html_quote(caption)) - options["class"] = ' '.join(attributes['class']) - del attributes['class'] + options["class"] = " ".join(attributes["class"]) + del attributes["class"] if elem.name == "picture": elem.append(img_elem) captioned = BeautifulSoup( - self.captioned_image_template(**options), 'html.parser') + self.captioned_image_template(**options), "html.parser" + ) # if we are a captioned image within a link, remove and occurrences # of a tags inside caption template to preserve the outer link - if bool(elem.find_parent('a')) and bool(captioned.find('a')): + if bool(elem.find_parent("a")) and bool(captioned.find("a")): captioned.a.unwrap() if elem.name == "picture": del captioned.picture.img["class"] @@ -232,19 +256,18 @@ def __call__(self, data): return six.text_type(soup) def resolve_scale_data(self, url): - """ return scale url, width and height - """ + """return scale url, width and height""" url_parts = url.split("/") field_name = url_parts[-2] scale_name = url_parts[-1] obj, subpath, appendix = self.resolve_link(url) - scale_view = obj.unrestrictedTraverse('@@images', None) + scale_view = obj.unrestrictedTraverse("@@images", None) return scale_view.scale(field_name, scale_name, pre=True) def resolve_link(self, href): obj = None subpath = href - appendix = '' + appendix = "" # preserve querystring and/or appendix match = appendix_re.match(href) @@ -262,26 +285,26 @@ def resolve_link(self, href): return obj, subpath, appendix def resolve_image(self, src): - description = '' + description = "" if urlsplit(src)[0]: # We have a scheme return None, None, src, description base = self.context subpath = src - appendix = '' + appendix = "" def traversal_stack(base, path): - if path.startswith('/'): + if path.startswith("/"): base = getSite() path = path[1:] obj = base stack = [obj] - components = path.split('/') + components = path.split("/") # print("components: {}".format(components)) while components: child_id = unquote(components.pop(0)) try: - if hasattr(aq_base(obj), 'scale'): + if hasattr(aq_base(obj), "scale"): if components: child = obj.scale(child_id, components.pop(), pre=True) else: @@ -318,13 +341,13 @@ def traverse_path(base, path): image = traverse_path(fullimage, "@@images/image") if image is None: image = traverse_path(fullimage, subpath) - elif '/@@' in subpath: + elif "/@@" in subpath: # split on view - pos = subpath.find('/@@') + pos = subpath.find("/@@") fullimage = traverse_path(base, subpath[:pos]) if fullimage is None: return None, None, src, description - image = traverse_path(fullimage, subpath[pos + 1:]) + image = traverse_path(fullimage, subpath[pos + 1 :]) else: stack = traversal_stack(base, subpath) if stack is None: @@ -335,7 +358,7 @@ def traverse_path(base, path): if not IContentish.providedBy(fullimage): stack.reverse() for parent in stack: - if hasattr(aq_base(parent), 'tag'): + if hasattr(aq_base(parent), "tag"): fullimage = parent break if not hasattr(image, "width"): @@ -350,5 +373,5 @@ def traverse_path(base, path): except AttributeError: return None, None, src, description src = url + appendix - description = safe_unicode(aq_acquire(fullimage, 'Description')()) + description = safe_unicode(aq_acquire(fullimage, "Description")()) return image, fullimage, src, description diff --git a/plone/outputfilters/interfaces.py b/plone/outputfilters/interfaces.py index 2b109bc..6fbda54 100644 --- a/plone/outputfilters/interfaces.py +++ b/plone/outputfilters/interfaces.py @@ -12,7 +12,7 @@ class IFilter(Interface): To control the order of filters, use the 'order' attribute. It may be positive or negative.""" - order = schema.Int(title=u"Order") + order = schema.Int(title="Order") def is_enabled(): """Returns a boolean indicating whether the filter should be diff --git a/plone/outputfilters/mimetype.py b/plone/outputfilters/mimetype.py index 8298444..3f715d5 100644 --- a/plone/outputfilters/mimetype.py +++ b/plone/outputfilters/mimetype.py @@ -5,5 +5,5 @@ class text_plone_outputfilters_html(MimeTypeItem): __name__ = "Plone Output Filters HTML" - mimetypes = ('text/x-plone-outputfilters-html',) + mimetypes = ("text/x-plone-outputfilters-html",) binary = 0 diff --git a/plone/outputfilters/setuphandlers.py b/plone/outputfilters/setuphandlers.py index eaa6756..c8e8b16 100644 --- a/plone/outputfilters/setuphandlers.py +++ b/plone/outputfilters/setuphandlers.py @@ -43,33 +43,36 @@ def register_transform_policy(context, output_mimetype, required_transform): def unregister_transform_policy(context, output_mimetype): transform_tool = getUtility(IPortalTransformsTool) - policies = [mimetype for (mimetype, required) - in transform_tool.listPolicies() - if mimetype == output_mimetype] + policies = [ + mimetype + for (mimetype, required) in transform_tool.listPolicies() + if mimetype == output_mimetype + ] if policies: # There is a policy, remove it! transform_tool.manage_delPolicies([output_mimetype]) def install_mimetype_and_transforms(context): - """ register mimetype and transformations for captioned images """ + """register mimetype and transformations for captioned images""" register_mimetype(context, text_plone_outputfilters_html) register_transform(context, plone_outputfilters_html_to_html) register_transform(context, html_to_plone_outputfilters_html) - register_transform_policy(context, "text/x-html-safe", - "html_to_plone_outputfilters_html") + register_transform_policy( + context, "text/x-html-safe", "html_to_plone_outputfilters_html" + ) def uninstall_mimetype_and_transforms(context): - """ unregister mimetype and transformations for captioned images """ + """unregister mimetype and transformations for captioned images""" unregister_transform(context, "plone_outputfilters_html_to_html") unregister_transform(context, "html_to_plone_outputfilters_html") - unregister_mimetype(context, 'text/x-plone-outputfilters-html') + unregister_mimetype(context, "text/x-plone-outputfilters-html") unregister_transform_policy(context, "text/x-html-safe") def importVarious(context): - if context.readDataFile('plone.outputfilters.txt') is None: + if context.readDataFile("plone.outputfilters.txt") is None: return site = context.getSite() install_mimetype_and_transforms(site) diff --git a/plone/outputfilters/testing.py b/plone/outputfilters/testing.py index 4444664..ef44fbb 100644 --- a/plone/outputfilters/testing.py +++ b/plone/outputfilters/testing.py @@ -24,30 +24,28 @@ class PloneOutputfilters(PloneSandboxLayer): def setUpZope(self, app, configurationContext): import plone.outputfilters + self.loadZCML(package=plone.outputfilters) gsm = zope.component.getGlobalSiteManager() gsm.registerUtility( DummyImageCaptioningEnabler(), IImageCaptioningEnabler, - 'outputfiltertest', - event=False + "outputfiltertest", + event=False, ) def tearDownZope(self, app): gsm = zope.component.getGlobalSiteManager() - gsm.unregisterUtility( - provided=IImageCaptioningEnabler, - name='outputfiltertest' - ) + gsm.unregisterUtility(provided=IImageCaptioningEnabler, name="outputfiltertest") def setUpPloneSite(self, portal): - applyProfile(portal, 'plone.outputfilters:default') + applyProfile(portal, "plone.outputfilters:default") PLONE_OUTPUTFILTERS_FIXTURE = PloneOutputfilters() PLONE_OUTPUTFILTERS_INTEGRATION_TESTING = IntegrationTesting( - bases=(PLONE_OUTPUTFILTERS_FIXTURE,), - name="PloneOutputfilters:Integration") + bases=(PLONE_OUTPUTFILTERS_FIXTURE,), name="PloneOutputfilters:Integration" +) PLONE_OUTPUTFILTERS_FUNCTIONAL_TESTING = FunctionalTesting( - bases=(PLONE_OUTPUTFILTERS_FIXTURE,), - name="PloneOutputfilters:Functional") + bases=(PLONE_OUTPUTFILTERS_FIXTURE,), name="PloneOutputfilters:Functional" +) diff --git a/plone/outputfilters/tests/test_apply_filters.py b/plone/outputfilters/tests/test_apply_filters.py index f6800a7..150f84c 100644 --- a/plone/outputfilters/tests/test_apply_filters.py +++ b/plone/outputfilters/tests/test_apply_filters.py @@ -18,14 +18,13 @@ def __call__(self, data): class FilterTestCase(unittest.TestCase): - def setUp(self): DummyFilter.called = [] def test_apply_filters(self): filters = [DummyFilter()] - apply_filters(filters, '') + apply_filters(filters, "") self.assertEqual([filters[0]], DummyFilter.called) def test_apply_filters_ordering(self): @@ -34,7 +33,7 @@ def test_apply_filters_ordering(self): filter2.order = 100 filters = [filter1, filter2] - apply_filters(filters, '') + apply_filters(filters, "") self.assertEqual([filters[1], filters[0]], DummyFilter.called) def test_apply_filters_checks_is_enabled(self): @@ -42,18 +41,18 @@ def test_apply_filters_checks_is_enabled(self): filter.is_enabled = lambda: False filters = [filter] - apply_filters(filters, '') + apply_filters(filters, "") self.assertEqual([], DummyFilter.called) def test_apply_filters_handles_return_none(self): class DummyFilterReturningNone(DummyFilter): - def __call__(self, data): return None + filter = DummyFilterReturningNone() - res = apply_filters([filter], '') - self.assertEqual('', res) + res = apply_filters([filter], "") + self.assertEqual("", res) def test_suite(): diff --git a/plone/outputfilters/tests/test_docs.py b/plone/outputfilters/tests/test_docs.py index cba5c9e..71dc87c 100644 --- a/plone/outputfilters/tests/test_docs.py +++ b/plone/outputfilters/tests/test_docs.py @@ -9,29 +9,32 @@ optionflags = ( - doctest.ELLIPSIS | - doctest.NORMALIZE_WHITESPACE | - doctest.REPORT_ONLY_FIRST_FAILURE + doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_ONLY_FIRST_FAILURE ) if six.PY3: - normal_testfiles = [ - '../README.rst' - ] + normal_testfiles = ["../README.rst"] else: normal_testfiles = [ - './README_py2.rst', + "./README_py2.rst", ] def test_suite(): suite = unittest.TestSuite() - suite.addTests([ - layered(doctest.DocFileSuite(test, - optionflags=optionflags, - globs={'pprint': pprint.pprint, - }, - ), - layer=PLONE_OUTPUTFILTERS_FUNCTIONAL_TESTING) - for test in normal_testfiles]) + suite.addTests( + [ + layered( + doctest.DocFileSuite( + test, + optionflags=optionflags, + globs={ + "pprint": pprint.pprint, + }, + ), + layer=PLONE_OUTPUTFILTERS_FUNCTIONAL_TESTING, + ) + for test in normal_testfiles + ] + ) return suite diff --git a/plone/outputfilters/tests/test_picture_variants.py b/plone/outputfilters/tests/test_picture_variants.py index 2307eef..f4e5035 100644 --- a/plone/outputfilters/tests/test_picture_variants.py +++ b/plone/outputfilters/tests/test_picture_variants.py @@ -20,9 +20,9 @@ def dummy_image(): - filename = join(PREFIX, u'image.jpg') + filename = join(PREFIX, "image.jpg") data = None - with open(filename, 'rb') as fd: + with open(filename, "rb") as fd: data = fd.read() fd.close() return NamedBlobImage(data=data, filename=filename) @@ -32,7 +32,7 @@ class PictureVariantsFilterIntegrationTestCase(PloneTestCase): layer = PLONE_OUTPUTFILTERS_FUNCTIONAL_TESTING - image_id = 'image.jpg' + image_id = "image.jpg" def _makeParser(self, **kw): parser = PictureVariantsFilter(context=self.portal) @@ -44,32 +44,31 @@ def _makeDummyContent(self): from OFS.SimpleItem import SimpleItem class DummyContent(SimpleItem): - def __init__(self, id): self.id = id def UID(self): - return 'foo' + return "foo" - allowedRolesAndUsers = ('Anonymous',) + allowedRolesAndUsers = ("Anonymous",) class DummyContent2(NFDummyContent): - id = __name__ = 'foo2' - title = u'Schönes Bild' + id = __name__ = "foo2" + title = "Schönes Bild" def UID(self): - return 'foo2' + return "foo2" - dummy = DummyContent('foo') - self.portal._setObject('foo', dummy) + dummy = DummyContent("foo") + self.portal._setObject("foo", dummy) self.portal.portal_catalog.catalog_object(self.portal.foo) - dummy2 = DummyContent2('foo2') - with open(join(PREFIX, self.image_id), 'rb') as fd: + dummy2 = DummyContent2("foo2") + with open(join(PREFIX, self.image_id), "rb") as fd: data = fd.read() fd.close() - dummy2.image = NamedImage(data, 'image/jpeg', u'image.jpeg') - self.portal._setObject('foo2', dummy2) + dummy2.image = NamedImage(data, "image/jpeg", "image.jpeg") + self.portal._setObject("foo2", dummy2) self.portal.portal_catalog.catalog_object(self.portal.foo2) def _assertTransformsTo(self, input, expected): @@ -81,35 +80,35 @@ def _assertTransformsTo(self, input, expected): # print("\n e: {}".format(expected)) # print("\n o: {}".format(out)) try: - self.assertTrue(_ellipsis_match(normalized_expected, - normalized_out)) + self.assertTrue(_ellipsis_match(normalized_expected, normalized_out)) except AssertionError: + class wrapper(object): want = expected - raise AssertionError(self.outputchecker.output_difference( - wrapper, out, REPORT_NDIFF)) + + raise AssertionError( + self.outputchecker.output_difference(wrapper, out, REPORT_NDIFF) + ) def afterSetUp(self): # create an image and record its UID - setRoles(self.portal, TEST_USER_ID, ['Manager']) + setRoles(self.portal, TEST_USER_ID, ["Manager"]) if self.image_id not in self.portal: - self.portal.invokeFactory( - 'Image', id=self.image_id, title='Image') + self.portal.invokeFactory("Image", id=self.image_id, title="Image") image = self.portal[self.image_id] - image.setDescription('My caption') + image.setDescription("My caption") image.image = dummy_image() image.reindexObject() self.UID = image.UID() - self.parser = self._makeParser(captioned_images=True, - resolve_uids=True) + self.parser = self._makeParser(captioned_images=True, resolve_uids=True) assert self.parser.is_enabled() self.outputchecker = OutputChecker() def beforeTearDown(self): self.login() - setRoles(self.portal, TEST_USER_ID, ['Manager']) + setRoles(self.portal, TEST_USER_ID, ["Manager"]) del self.portal[self.image_id] def test_parsing_minimal(self): @@ -159,11 +158,14 @@ def test_parsing_long_doc(self):

Thanks for using our product; we hope you like it!

—The Plone Team

- """.format(uid=self.UID) + """.format( + uid=self.UID + ) import time + startTime = time.time() res = self.parser(text) - executionTime = (time.time() - startTime) + executionTime = time.time() - startTime print("\n\nimage srcset parsing time: {}\n".format(executionTime)) self.assertTrue(res) @@ -232,17 +234,23 @@ def test_parsing_long_doc(self):

Thanks for using our product; we hope you like it!

—The Plone Team

- """.format(uid=self.UID) + """.format( + uid=self.UID + ) self._assertTransformsTo(text, text_out) def test_parsing_with_nonexisting_srcset(self): text = """

- """.format(uid=self.UID) + """.format( + uid=self.UID + ) res = self.parser(text) self.assertTrue(res) text_out = """

- """.format(uid=self.UID) + """.format( + uid=self.UID + ) # verify that tag was not converted: - self.assertTrue("data-picturevariant" in res) \ No newline at end of file + self.assertTrue("data-picturevariant" in res) diff --git a/plone/outputfilters/tests/test_resolveuid_and_caption.py b/plone/outputfilters/tests/test_resolveuid_and_caption.py index 31f41e2..70cc306 100644 --- a/plone/outputfilters/tests/test_resolveuid_and_caption.py +++ b/plone/outputfilters/tests/test_resolveuid_and_caption.py @@ -22,9 +22,9 @@ def dummy_image(): - filename = join(PREFIX, u'image.jpg') + filename = join(PREFIX, "image.jpg") data = None - with open(filename, 'rb') as fd: + with open(filename, "rb") as fd: data = fd.read() fd.close() return NamedBlobImage(data=data, filename=filename) @@ -34,7 +34,7 @@ class ResolveUIDAndCaptionFilterIntegrationTestCase(PloneTestCase): layer = PLONE_OUTPUTFILTERS_FUNCTIONAL_TESTING - image_id = 'image.jpg' + image_id = "image.jpg" def _makeParser(self, **kw): parser = ResolveUIDAndCaptionFilter(context=self.portal) @@ -46,32 +46,31 @@ def _makeDummyContent(self): from OFS.SimpleItem import SimpleItem class DummyContent(SimpleItem): - def __init__(self, id): self.id = id def UID(self): - return 'foo' + return "foo" - allowedRolesAndUsers = ('Anonymous',) + allowedRolesAndUsers = ("Anonymous",) class DummyContent2(NFDummyContent): - id = __name__ = 'foo2' - title = u'Schönes Bild' + id = __name__ = "foo2" + title = "Schönes Bild" def UID(self): - return 'foo2' + return "foo2" - dummy = DummyContent('foo') - self.portal._setObject('foo', dummy) + dummy = DummyContent("foo") + self.portal._setObject("foo", dummy) self.portal.portal_catalog.catalog_object(self.portal.foo) - dummy2 = DummyContent2('foo2') - with open(join(PREFIX, self.image_id), 'rb') as fd: + dummy2 = DummyContent2("foo2") + with open(join(PREFIX, self.image_id), "rb") as fd: data = fd.read() fd.close() - dummy2.image = NamedImage(data, 'image/jpeg', u'image.jpeg') - self.portal._setObject('foo2', dummy2) + dummy2.image = NamedImage(data, "image/jpeg", "image.jpeg") + self.portal._setObject("foo2", dummy2) self.portal.portal_catalog.catalog_object(self.portal.foo2) def _assertTransformsTo(self, input, expected, parsing=True): @@ -86,39 +85,39 @@ def _assertTransformsTo(self, input, expected, parsing=True): # print("e: {}".format(normalized_expected)) # print("o: {}".format(normalized_out)) try: - self.assertTrue(_ellipsis_match(normalized_expected, - normalized_out)) + self.assertTrue(_ellipsis_match(normalized_expected, normalized_out)) except AssertionError: + class wrapper(object): want = expected - raise AssertionError(self.outputchecker.output_difference( - wrapper, out, REPORT_NDIFF)) + + raise AssertionError( + self.outputchecker.output_difference(wrapper, out, REPORT_NDIFF) + ) def afterSetUp(self): # create an image and record its UID - setRoles(self.portal, TEST_USER_ID, ['Manager']) + setRoles(self.portal, TEST_USER_ID, ["Manager"]) if self.image_id not in self.portal: - self.portal.invokeFactory( - 'Image', id=self.image_id, title='Image') + self.portal.invokeFactory("Image", id=self.image_id, title="Image") image = self.portal[self.image_id] - image.setDescription('My caption') + image.setDescription("My caption") image.image = dummy_image() image.reindexObject() self.UID = image.UID() - self.parser = self._makeParser(captioned_images=True, - resolve_uids=True) + self.parser = self._makeParser(captioned_images=True, resolve_uids=True) assert self.parser.is_enabled() self.outputchecker = OutputChecker() def beforeTearDown(self): self.login() - setRoles(self.portal, TEST_USER_ID, ['Manager']) + setRoles(self.portal, TEST_USER_ID, ["Manager"]) del self.portal[self.image_id] def test_parsing_minimal(self): - text = '
Some simple text.
' + text = "
Some simple text.
" res = self.parser(text) self.assertEqual(text, str(res)) @@ -179,11 +178,14 @@ def test_parsing_long_doc(self):

Thanks for using our product; we hope you like it!

—The Plone Team

- """.format(uid=self.UID) + """.format( + uid=self.UID + ) import time + startTime = time.time() res = self.parser(text) - executionTime = (time.time() - startTime) + executionTime = time.time() - startTime print("\n\nresolve_uid_and_caption parsing time: {}\n".format(executionTime)) self.assertTrue(res) @@ -213,7 +215,10 @@ def test_resolve_uids_in_links(self): Some link Some anchored link -""" % (self.UID, self.UID) +""" % ( + self.UID, + self.UID, + ) res = str(self.parser(text)) self.assertIn('href="http://nohost/plone/image.jpg"', res) self.assertIn('href="http://nohost/plone/image.jpg#named-anchor"', res) @@ -253,15 +258,17 @@ def test_resolve_uids_non_AT_content(self): def test_resolve_uids_fragment(self): self._makeDummyContent() - self.parser = self._makeParser(resolve_uids=True, - context=self.portal.foo) + self.parser = self._makeParser(resolve_uids=True, context=self.portal.foo) text_in = """anchor""" self._assertTransformsTo(text_in, text_in) def test_resolve_uids_in_image_maps(self): - text_in = """ + text_in = ( + """ alpha -""" % self.UID +""" + % self.UID + ) text_out = """ alpha """ @@ -284,56 +291,59 @@ def test_resolve_uids_entities(self): self._assertTransformsTo(text_in, text_in) def test_resolveuid_view(self): - res = self.publish('/plone/resolveuid/%s' % self.UID) + res = self.publish("/plone/resolveuid/%s" % self.UID) self.assertEqual(301, res.status) - self.assertEqual('http://nohost/plone/image.jpg', - res.headers['location']) + self.assertEqual("http://nohost/plone/image.jpg", res.headers["location"]) def test_resolveuid_view_bad_uuid(self): - res = self.publish('/plone/resolveuid/BOGUS') + res = self.publish("/plone/resolveuid/BOGUS") self.assertEqual(404, res.status) def test_resolveuid_view_subpath(self): - res = self.publish('/plone/resolveuid/%s/image_thumb' % self.UID) + res = self.publish("/plone/resolveuid/%s/image_thumb" % self.UID) self.assertEqual(301, res.status) - self.assertEqual('http://nohost/plone/image.jpg/image_thumb', - res.headers['location']) + self.assertEqual( + "http://nohost/plone/image.jpg/image_thumb", res.headers["location"] + ) def test_resolveuid_view_querystring(self): - res = self.publish('/plone/resolveuid/%s?qs' % self.UID) + res = self.publish("/plone/resolveuid/%s?qs" % self.UID) self.assertEqual(301, res.status) - self.assertEqual('http://nohost/plone/image.jpg?qs', - res.headers['location']) + self.assertEqual("http://nohost/plone/image.jpg?qs", res.headers["location"]) def test_uuidToURL(self): from plone.outputfilters.browser.resolveuid import uuidToURL - self.assertEqual('http://nohost/plone/image.jpg', - uuidToURL(self.UID)) + + self.assertEqual("http://nohost/plone/image.jpg", uuidToURL(self.UID)) def test_uuidToObject(self): from plone.outputfilters.browser.resolveuid import uuidToObject - self.assertTrue(self.portal['image.jpg'].aq_base - is uuidToObject(self.UID).aq_base) + + self.assertTrue( + self.portal["image.jpg"].aq_base is uuidToObject(self.UID).aq_base + ) def test_uuidToURL_permission(self): from plone.outputfilters.browser.resolveuid import uuidToObject from plone.outputfilters.browser.resolveuid import uuidToURL - self.portal.invokeFactory('Document', id='page', title='Page') - page = self.portal['page'] + + self.portal.invokeFactory("Document", id="page", title="Page") + page = self.portal["page"] self.logout() - self.assertEqual('http://nohost/plone/page', - uuidToURL(page.UID())) - self.assertTrue(page.aq_base - is uuidToObject(page.UID()).aq_base) + self.assertEqual("http://nohost/plone/page", uuidToURL(page.UID())) + self.assertTrue(page.aq_base is uuidToObject(page.UID()).aq_base) def test_image_captioning_in_news_item(self): # Create a news item with a relative unscaled image - self.portal.invokeFactory('News Item', id='a-news-item', title='Title') - news_item = self.portal['a-news-item'] + self.portal.invokeFactory("News Item", id="a-news-item", title="Title") + news_item = self.portal["a-news-item"] from plone.app.textfield.value import RichTextValue + news_item.text = RichTextValue( '', - 'text/html', 'text/html') + "text/html", + "text/html", + ) news_item.setDescription("Description.") # Test captioning output = news_item.text.output @@ -369,12 +379,10 @@ def test_image_captioning_relative_path_private_folder(self): # Images in a private folder may or may not still be renderable, but # traversal to them must not raise an error! self.loginAsPortalOwner() - self.portal.invokeFactory('Folder', id='private', - title='Private Folder') - self.portal.private.invokeFactory('Image', id='image.jpg', - title='Image') - image = getattr(self.portal.private, 'image.jpg') - image.setDescription('My private image caption') + self.portal.invokeFactory("Folder", id="private", title="Private Folder") + self.portal.private.invokeFactory("Image", id="image.jpg", title="Image") + image = getattr(self.portal.private, "image.jpg") + image.setDescription("My private image caption") image.image = dummy_image() image.reindexObject() self.logout() @@ -403,7 +411,10 @@ def test_image_captioning_resolveuid_bare(self): self._assertTransformsTo(text_in, text_out) def test_image_captioning_resolveuid_scale(self): - text_in = """""" % self.UID + text_in = ( + """""" + % self.UID + ) text_out = """
My caption
@@ -411,7 +422,10 @@ def test_image_captioning_resolveuid_scale(self): self._assertTransformsTo(text_in, text_out) def test_image_captioning_resolveuid_new_scale(self): - text_in = """""" % self.UID + text_in = ( + """""" + % self.UID + ) text_out = """
My caption
@@ -420,12 +434,16 @@ def test_image_captioning_resolveuid_new_scale(self): def test_image_captioning_resolveuid_new_scale_plone_namedfile(self): self._makeDummyContent() - text_in = """""" - text_out = u"""""" + text_in = ( + """""" + ) + text_out = """""" self._assertTransformsTo(text_in, text_out) def test_image_captioning_resolveuid_no_scale(self): - text_in = """""" % self.UID + text_in = ( + """""" % self.UID + ) text_out = """
My caption
@@ -433,7 +451,10 @@ def test_image_captioning_resolveuid_no_scale(self): self._assertTransformsTo(text_in, text_out) def test_image_captioning_resolveuid_with_srcset_and_src(self): - text_in = """""" % (self.UID, self.UID, self.UID) + text_in = ( + """""" + % (self.UID, self.UID, self.UID) + ) text_out = """
My caption
@@ -458,7 +479,7 @@ def test_audio_resolveuid(self): def test_image_captioning_resolveuid_no_scale_plone_namedfile(self): self._makeDummyContent() text_in = """""" - text_out = u"""""" + text_out = """""" self._assertTransformsTo(text_in, text_out) def test_image_captioning_bad_uid(self): @@ -486,7 +507,10 @@ def test_image_captioning_preserves_custom_attributes(self): self._assertTransformsTo(text_in, text_out) def test_image_captioning_handles_unquoted_attributes(self): - text_in = """picture alt text""" % self.UID + text_in = ( + """picture alt text""" + % self.UID + ) text_out = """
picture alt text
My caption
@@ -503,11 +527,10 @@ def test_image_captioning_preserves_existing_links(self): self._assertTransformsTo(text_in, text_out) def test_image_captioning_handles_non_ascii(self): - self.portal['image.jpg'].setTitle(u'Kupu Test Image \xe5\xe4\xf6') - self.portal['image.jpg'].setDescription( - u'Kupu Test Image \xe5\xe4\xf6') + self.portal["image.jpg"].setTitle("Kupu Test Image \xe5\xe4\xf6") + self.portal["image.jpg"].setDescription("Kupu Test Image \xe5\xe4\xf6") text_in = """""" - text_out = u"""
+ text_out = """
Kupu Test Image \xe5\xe4\xf6
""" @@ -519,8 +542,7 @@ def test_resolve_uids_with_bigU(self): self.assertTrue('href="http://nohost/plone/image.jpg"' in str(res)) def test_singleton_elements(self): - self._assertTransformsTo( - '
\r\n

foo


', '
\r\n

foo


') + self._assertTransformsTo("
\r\n

foo


", "
\r\n

foo


") def test_no_change_when_a_in_script(self): text_in = """""" diff --git a/plone/outputfilters/tests/test_transforms.py b/plone/outputfilters/tests/test_transforms.py index 696663e..80152e5 100644 --- a/plone/outputfilters/tests/test_transforms.py +++ b/plone/outputfilters/tests/test_transforms.py @@ -11,42 +11,48 @@ class TransformsTestCase(unittest.TestCase): layer = PLONE_OUTPUTFILTERS_INTEGRATION_TESTING def setUp(self): - self.portal = self.layer['portal'] - self.request = self.layer['request'] - setRoles(self.portal, TEST_USER_ID, ['Manager']) + self.portal = self.layer["portal"] + self.request = self.layer["request"] + setRoles(self.portal, TEST_USER_ID, ["Manager"]) from Products.PortalTransforms.interfaces import IPortalTransformsTool from zope.component import getUtility + self.transforms = getUtility(IPortalTransformsTool) def test_instantiate_html_to_plone_outputfilters_html_transform(self): from plone.outputfilters.transforms.html_to_plone_outputfilters_html import ( html_to_plone_outputfilters_html, ) - transform = html_to_plone_outputfilters_html(name='transform') - self.assertEqual('transform', transform.name()) + + transform = html_to_plone_outputfilters_html(name="transform") + self.assertEqual("transform", transform.name()) def test_instantiate_plone_outputfilters_html_to_html_transform(self): from plone.outputfilters.transforms.plone_outputfilters_html_to_html import ( plone_outputfilters_html_to_html, ) - transform = plone_outputfilters_html_to_html(name='transform') - self.assertEqual('transform', transform.name()) + + transform = plone_outputfilters_html_to_html(name="transform") + self.assertEqual("transform", transform.name()) def test_transform_policy_installed(self): policies = self.transforms.listPolicies() policies = [ - mimetype for (mimetype, required) in policies + mimetype + for (mimetype, required) in policies if mimetype == "text/x-html-safe" ] self.assertEqual(1, len(policies)) def test_uninstallation(self): from plone.outputfilters.setuphandlers import uninstall_mimetype_and_transforms + uninstall_mimetype_and_transforms(self.portal) policies = self.transforms.listPolicies() policies = [ - mimetype for (mimetype, required) in policies + mimetype + for (mimetype, required) in policies if mimetype == "text/x-html-safe" ] self.assertEqual(0, len(policies)) diff --git a/plone/outputfilters/transforms/html_to_plone_outputfilters_html.py b/plone/outputfilters/transforms/html_to_plone_outputfilters_html.py index 0cb3426..ba62050 100644 --- a/plone/outputfilters/transforms/html_to_plone_outputfilters_html.py +++ b/plone/outputfilters/transforms/html_to_plone_outputfilters_html.py @@ -9,15 +9,15 @@ @implementer(ITransform) class html_to_plone_outputfilters_html: - """ transform which applies output filters""" + """transform which applies output filters""" + __name__ = "html_to_plone_outputfilters_html" - inputs = ('text/html',) + inputs = ("text/html",) output = "text/x-plone-outputfilters-html" def __init__(self, name=None): self.config_metadata = { - 'inputs': ('list', 'Inputs', - 'Input(s) MIME type. Change with care.'), + "inputs": ("list", "Inputs", "Input(s) MIME type. Change with care."), } if name: self.__name__ = name @@ -26,8 +26,8 @@ def name(self): return self.__name__ def convert(self, orig, data, **kwargs): - context = kwargs.get('context') - request = getattr(getSite(), 'REQUEST', None) + context = kwargs.get("context") + request = getattr(getSite(), "REQUEST", None) filters = [f for _, f in getAdapters((context, request), IFilter)] res = apply_filters(filters, orig) diff --git a/plone/outputfilters/transforms/plone_outputfilters_html_to_html.py b/plone/outputfilters/transforms/plone_outputfilters_html_to_html.py index b1a10e9..a92c2ea 100644 --- a/plone/outputfilters/transforms/plone_outputfilters_html_to_html.py +++ b/plone/outputfilters/transforms/plone_outputfilters_html_to_html.py @@ -7,16 +7,12 @@ class plone_outputfilters_html_to_html(object): __name__ = "plone_outputfilters_html_to_html" - inputs = ('text/x-plone-outputfilters-html',) + inputs = ("text/x-plone-outputfilters-html",) output = "text/html" def __init__(self, name=None): self.config_metadata = { - 'inputs': ( - 'list', - 'Inputs', - 'Input(s) MIME type. Change with care.' - ), + "inputs": ("list", "Inputs", "Input(s) MIME type. Change with care."), } if name: self.__name__ = name diff --git a/setup.py b/setup.py index 36bdc30..1ba95f4 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ import os -version = '5.0.0b2.dev0' +version = "5.0.0b2.dev0" def read(filename): @@ -31,11 +31,10 @@ def read(filename): ) setup( - name='plone.outputfilters', + name="plone.outputfilters", version=version, description=( - "Transformations applied to HTML in " - "Plone text fields as they are rendered" + "Transformations applied to HTML in " "Plone text fields as they are rendered" ), long_description=long_description, # Get more strings from https://pypi.org/classifiers/ @@ -51,35 +50,35 @@ def read(filename): "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", ], - keywords='plone transform filter uid caption', - author='David Glick, Plone Foundation', - author_email='davidglick@groundwire.org', - url='http://github.com/plone/plone.outputfilters', - license='GPL', + keywords="plone transform filter uid caption", + author="David Glick, Plone Foundation", + author_email="davidglick@groundwire.org", + url="http://github.com/plone/plone.outputfilters", + license="GPL", packages=find_packages(), - namespace_packages=['plone'], + namespace_packages=["plone"], include_package_data=True, zip_safe=False, install_requires=[ - 'Products.CMFCore', - 'Products.GenericSetup', - 'Products.MimetypesRegistry', - 'Products.PortalTransforms>=2.0', - 'plone.namedfile', - 'plone.app.uuid', - 'setuptools', - 'six', - 'unidecode', - 'zope.deprecation', - 'beautifulsoup4', - 'lxml', + "Products.CMFCore", + "Products.GenericSetup", + "Products.MimetypesRegistry", + "Products.PortalTransforms>=2.0", + "plone.namedfile", + "plone.app.uuid", + "setuptools", + "six", + "unidecode", + "zope.deprecation", + "beautifulsoup4", + "lxml", ], extras_require={ - 'test': [ - 'plone.app.contenttypes', - 'plone.app.testing', - 'plone.app.robotframework', - 'plone.namedfile', + "test": [ + "plone.app.contenttypes", + "plone.app.testing", + "plone.app.robotframework", + "plone.namedfile", ] }, entry_points="""