diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml new file mode 100644 index 0000000..95f925d --- /dev/null +++ b/.github/workflows/python-package.yml @@ -0,0 +1,59 @@ +# This workflow will install Python dependencies, run tests and lint with a variety of Python versions +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python + +name: Python package + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14"] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v3 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install flake8 pytest + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + - name: Lint with flake8 + run: | + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + - name: Install exempi deps + run: | + sudo apt install -y libboost-test-dev + - name: Get number of CPU cores + uses: SimenB/github-actions-cpu-cores@v1 + id: cpu-cores + - name: Install latest exempi + run: | + git clone https://gitlab.freedesktop.org/libopenraw/exempi + cd exempi + ./autogen.sh + ./configure --prefix=/usr + make -j ${{ steps.cpu-cores.outputs.count }} + sudo make install + cd .. + ls -lA /usr/local/lib + - name: Install + run: | + python -m pip install -e . + - name: Test with pytest + run: | + pytest diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..f673aa7 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,13 @@ +# .readthedocs.yaml +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +version: 2 + +build: + os: ubuntu-22.04 + tools: + python: "3.12" + +sphinx: + configuration: docs/conf.py diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 830e5df..0000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: python -python: - - "2.6" - - "2.7" - - "3.3" - -before_install: - - sudo apt-get update -qq - - sudo apt-get install -qq libexempi3 - -# command to install dependencies -install: - - pip install coveralls - - pip install . - -# command to run tests -script: - - coverage run setup.py test - -after_success: - - coveralls - -notifications: - email: - - "john.g.evans.ne@gmail.com" - - "lars@hankat.dk" diff --git a/CHANGELOG b/CHANGELOG index 53db85b..f1a7f7f 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,15 @@ +Release 2.1.0 ( November 26, 2025 ) + * Add support for python 3.14 + * Make exempi a run-time dependency + * Add missing error codes + * Remove tox + * Use flit for build + * Remove travis + * Remove packaging dependency requirement + * Remove support for python <= 3.6 (All python2 code removed) + * fix exempi returns char-size bool, not int + * homebrew path fixup + Release 2.0.2 ( January 25, 2017 ) * Fix test following a bugfix from Exempi 2.4.0. * Fix crash when there is no schema. diff --git a/INSTALL b/INSTALL index 297a004..e5c0953 100644 --- a/INSTALL +++ b/INSTALL @@ -4,24 +4,17 @@ Installation Requirements ------------ - * Python 2.6, 2.7, 3.3, 3.4, 3.5, or 3.6 + * Python 3 (3.7+) or pypy3 * Exempi 2.2.0+ * Linux or OS X (see notes below for Windows) Python XMP Toolkit ---------------------- -The short version of installation is:: - - python setup.py install - -or if you use pip:: +The installation is:: pip install python-xmp-toolkit -Note, in case you haven't installed Exempi you will get an -:exc:`ExempiLoadError` exception once you try to load :mod:`libxmp`. - Exempi ------ Python XMP Toolkit requires Exempi 2.2.0 or higher which can be downloaded from diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index 54e0d3a..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,3 +0,0 @@ -include AUTHORS CHANGELOG INSTALL README.rst LICENSE -recursive-include test *.py *.tif *.xmp *.ai *.avi *.eps *.gif *.indd *.jpg *.mov *.mp3 *.pdf *.png *.psd *.wav *.txt -include .coveragerc run-coverage.sh diff --git a/README.rst b/README.rst index 95f7c1f..b9f7b3d 100644 --- a/README.rst +++ b/README.rst @@ -2,44 +2,49 @@ Python XMP Toolkit ================== -.. image:: https://travis-ci.org/python-xmp-toolkit/python-xmp-toolkit.png?branch=master - :target: https://travis-ci.org/python-xmp-toolkit/python-xmp-toolkit -.. image:: https://coveralls.io/repos/python-xmp-toolkit/python-xmp-toolkit/badge.png?branch=master - :target: https://coveralls.io/r/python-xmp-toolkit/python-xmp-toolkit -.. image:: https://pypip.in/v/python-xmp-toolkit/badge.png - :target: https://crate.io/packages/python-xmp-toolkit/ -.. image:: https://pypip.in/d/python-xmp-toolkit/badge.png - :target: https://crate.io/packages/python-xmp-toolkit/ +.. image:: actions/workflows/python-package.yml/badge.svg + :alt: Build status badge + :target: actions +.. image:: https://img.shields.io/coveralls/python-xmp-toolkit/python-xmp-toolkit/master.svg?maxAge=3600 + :alt: Coverage badge + :target: https://coveralls.io/r/python-xmp-toolkit/python-xmp-toolkit +.. image:: https://img.shields.io/pypi/v/python-xmp-toolkit.svg?maxAge=3600 + :alt: Version badge + :target: https://pypi.org/project/python-xmp-toolkit/ +.. image:: http://readthedocs.org/projects/python-xmp-toolkit/badge/?maxAge=3600 + :alt: Documentation badge + :target: http://python-xmp-toolkit.readthedocs.io/ + Python XMP Toolkit is a library for working with XMP metadata, as well as reading/writing XMP metadata stored in many different file formats. -Python XMP Toolkit is wrapping Exempi (using ctypes), a C/C++ XMP library -based on Adobe XMP Toolkit, ensuring that future updates to the XMP standard -are easily incorporated into the library with a minimum amount of work. +Python XMP Toolkit is wrapping `Exempi `_ +(using ctypes), a C/C++ XMP library based on Adobe XMP Toolkit, ensuring that future +updates to the XMP standard are easily incorporated into the library with a minimum +amount of work. Python XMP Toolkit has been developed by: * ESA/Hubble - European Space Agency * ESO - European Southern Observatory * CRS4 - Centre for Advanced Studies, Research and Development in Sardinia + Documentation -============ -Documentation is available at or can be build using Sphinx: :: +============= +Documentation is available at `python-xmp-toolkit.readthedocs.org +`_ or can be built using Sphinx: :: pip install Sphinx - python setup.py build_sphinx + sphinx-build docs/ docs/_build/ + Testing ======= -Running the tests are as simple as: :: - python setup.py test +Running the tests is as simple as: -or (to also show test coverage) :: +.. code:: sh - source run-coverage.sh + python -m pytest -.. image:: https://d2weczhvl823v0.cloudfront.net/python-xmp-toolkit/python-xmp-toolkit/trend.png - :alt: Bitdeli badge - :target: https://bitdeli.com/free \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py index 6f0d913..42850e9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -100,7 +100,6 @@ def read_version(): # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. -html_style = 'default.css' # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". @@ -121,7 +120,7 @@ def read_version(): # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['.static'] +html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. diff --git a/docs/developers.rst b/docs/developers.rst index d7c8711..652cbde 100644 --- a/docs/developers.rst +++ b/docs/developers.rst @@ -11,7 +11,7 @@ Overview of Source Distribution * ``docs/`` -- Source code for documentation. * ``libxmp/`` -- Source files for XMP Toolkit - * ``setup.py`` -- Distutils configuration file. + * ``pyproject.toml`` -- Packaging configuration file. * ``MANIFEST.in`` -- Template for MANIFEST file used by Distutils. * ``test`` -- Tests @@ -22,36 +22,30 @@ http://sphinx.pocoo.org/). To make the documentation run the following command in the root directory:: pip install sphinx - python setup.py build_sphinx + sphinx-build docs/ docs/_build/ -Packaging a Distribution +Publishing a release ------------------------ -To package a distribution run:: +To publish a release run:: - python setup.py sdist + flit publish -This will prepare the documentation and use distutils to package together a -distribution that will be placed in ``dist/``. +For further details see `Flit `_ Running Tests ------------- Tests are run by issuing the command:: - python setup.py test + python -m pytest For test coverage, run:: - pip install coverage - source run-coverage.sh - -To run tests in Python 2.6, 2.7, or python3, using tox, run:: - - pip install tox - tox + pip install pytest-cov + python -m pytest --cov Distribution Configuration -------------------------- -The file ``setup.py`` specify how the distribution is packed together. Most +The file ``pyproject.toml`` specifies how the distribution is packed together. Most important to note is that version in formation is read from ``libxmp.version`` file, and that the file ``MANIFEST.in`` specifies which other files to include in the distribution besides the Python source. @@ -59,5 +53,5 @@ in the distribution besides the Python source. References for Developers ------------------------- * `ctypes `_ - * `Sphinx `_ - * `Distutils `_ + * `Sphinx `_ + * `Flit `_ diff --git a/libxmp/__init__.py b/libxmp/__init__.py index bba84be..892f93a 100644 --- a/libxmp/__init__.py +++ b/libxmp/__init__.py @@ -32,6 +32,7 @@ # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE +"""XMP I/O wrapping Exempi""" import ctypes import ctypes.util @@ -56,4 +57,3 @@ class XMPError(Exception): 'core'] from . import exempi -exempi.init() diff --git a/libxmp/core.py b/libxmp/core.py index 2273470..03a48b4 100644 --- a/libxmp/core.py +++ b/libxmp/core.py @@ -52,23 +52,6 @@ __all__ = ['XMPMeta','XMPIterator'] -def _remove_bom(xstr): - """Remove BOM (byte order marker) from a string.""" - # Python 2.7 cannot encode from ascii to utf-8 (or utf-8 to ascii) when an - # XMP packet contains the XMP packet wrapper with the BOM in place. Just - # get rid of it if we find it. - regex = re.compile(r"""\s*<\?xpacket\s* - begin=\"(?P.*)\"\s* - id=\"W5M0MpCehiHzreSzNTczkc9d\"\?>""", - re.UNICODE | re.VERBOSE) - match = regex.match(xstr) - if match is not None: - # Ok we matched up to the BOM. Get rid of it. - bom_start, bom_end = match.span('bom') - xstr = xstr[0:bom_start] + xstr[bom_end:] - - return xstr - def _remove_trailing_whitespace(xstr): """Remove trailing white space. @@ -87,12 +70,6 @@ def _remove_trailing_whitespace(xstr): return xstr -def _force_rdf_to_utf8(xstr): - """Force RDF to unicode on 2.7, removing BOM in the process.""" - - xstr = _remove_bom(xstr) - return xstr.decode('utf-8') - class XMPMeta(object): """ @@ -153,12 +130,7 @@ def __str__(self): """ xstr = self.serialize_to_str() xstr = _remove_trailing_whitespace(xstr) - if sys.hexversion < 0x03000000: - # The BOM is not important, just remove it. - xstr = _remove_bom(xstr) - return xstr.encode('UTF-8', 'replace') - else: - return xstr + return xstr def __eq__(self, other): """ Checks if two XMPMeta objects are equal.""" @@ -636,8 +608,6 @@ def parse_from_str(self, xmp_packet_str, xmpmeta_wrap=False, string, it will by default be assumed to be UTF-8 encoded. :raises: IOError if operation fails. """ - if sys.hexversion < 0x03000000 and isinstance(xmp_packet_str, str): - xmp_packet_str = _force_rdf_to_utf8(xmp_packet_str) if xmpmeta_wrap: fmt = u"{0}" xmp_packet_str = fmt.format(xmp_packet_str) diff --git a/libxmp/exempi.py b/libxmp/exempi.py index 683e240..002d0fb 100644 --- a/libxmp/exempi.py +++ b/libxmp/exempi.py @@ -53,8 +53,11 @@ def _load_exempi(): if path is None: if platform.system().startswith('Darwin'): if os.path.exists('/opt/local/lib/libexempi.dylib'): - # MacPorts starndard location. + # MacPorts standard location. path = '/opt/local/lib/libexempi.dylib' + if os.path.exists('/opt/homebrew/lib/libexempi.dylib'): + # Homebrew standard location. + path = '/opt/homebrew/lib/libexempi.dylib' if path is None: raise ExempiLoadError('Exempi library not found.') @@ -66,7 +69,27 @@ def _load_exempi(): return EXEMPI -EXEMPI = _load_exempi() + +class LazyExempi: + """Wrapper for ctypes library making it loaded on actual first use. + """ + def __init__(self): + self._exempi = None + + def __getattr__(self, attr): + if self._exempi is None: + self._exempi = _load_exempi() + init() + return getattr(self._exempi, attr) + + def __setattr__(self, attr, value): + if attr == "_exempi": + self.__dict__[attr] = value + else: + return setattr(self._exempi, attr, value) + + +EXEMPI = LazyExempi() # Error codes defined by libexempi. See "xmperrors.h" ERROR_MESSAGE = { 0: "unknown error", @@ -85,6 +108,7 @@ def _load_exempi(): -13: "std exception", -14: "unknown exception", -15: "no memory", + -16: "progress abort", -101: "bad schema", -102: "bad XPath", -103: "bad options", @@ -95,6 +119,14 @@ def _load_exempi(): -108: "bad file format", -109: "no file handler", -110: "too large for JPEG", + -111: "no file", + -112: "file permission error", + -113: "disk space", + -114: "read error", + -115: "write error", + -116: "bad block format", + -117: "file path not a file", + -118: "rejected file extension", -201: "bad XML", -202: "bad RDF", -203: "bad XMP", @@ -1693,10 +1725,14 @@ def check_error(success): Return value from library function indicating success or failure. """ + success = success & 0xff # Unfortunately the success parameter does not seem to always be reliable # so we supplement it by explicitly checking the error code. ecode = EXEMPI.xmp_get_error() if not success or ecode != 0: - error_msg = ERROR_MESSAGE[ecode] + if ecode in ERROR_MESSAGE: + error_msg = ERROR_MESSAGE[ecode] + else: + error_msg = "Unexpected error code " + str(ecode) msg = 'Exempi function failure ("{0}").'.format(error_msg) raise XMPError(msg) diff --git a/libxmp/files.py b/libxmp/files.py index 6972e3d..68e99d2 100644 --- a/libxmp/files.py +++ b/libxmp/files.py @@ -85,18 +85,7 @@ def __repr__(self): return "XMPFiles()" msg = "XMPFiles(file_path='{0}')" - if sys.hexversion < 0x03000000 and isinstance(self._file_path, - unicode): - # Unicode filenames can cause trouble in python2 because __repr__ - # must return byte strings, not unicode. Get around this by - # turning the unicode filename into escaped ASCII. This means that - # in this case, the result cannot be used to recreate the object - # with the same value. - msg = msg.format(repr(self._file_path)) - else: - # Python3 does not suffer from this problem. - msg = msg.format(self._file_path) - + msg = msg.format(self._file_path) return msg def __del__(self): diff --git a/libxmp/version.py b/libxmp/version.py index bf1034f..4c31536 100644 --- a/libxmp/version.py +++ b/libxmp/version.py @@ -36,9 +36,6 @@ Version information for libxmp. """ -from distutils.version import LooseVersion - # Do not change the format of this next line! Doing so risks breaking # setup.py -VERSION = "2.0.1" -VERSION_TUPLE = LooseVersion(VERSION).version +VERSION = "2.0.3" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b97ede1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,61 @@ +[project] +name = "python-xmp-toolkit" + +dynamic = ["version", "description"] + +readme = "README.rst" + +authors = [ + { name = "Lars Holm Nielsen" }, + { name = "John Evans" }, + { name = "Federico Caboni" }, + { name = "Amit Kapadia" }, +] + +license = { file = "LICENSE" } + +keywords = ["XMP", "metadata", "multimedia", "development", "utilities"] + +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: MacOS :: MacOS X", + "Operating System :: POSIX :: Linux", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Topic :: Multimedia", + "Topic :: Software Development :: Libraries", + "Topic :: Utilities", +] + + +dependencies = [ + "pytz" +] + + +[project.urls] +Homepage = "https://github.com/python-xmp-toolkit/python-xmp-toolkit" +Download = "https://pypi.python.org/pypi/python-xmp-toolkit" + +[project.optional-dependencies] +test = [ + "pytest >=2.7.3", + "pytest-cov", +] + +[build-system] +requires = ["flit_core >=3.2,<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.module] +name = "libxmp" + + +[tool.flit.sdist] +include = [ + "test/*", ".coveragerc", + "AUTHORS", "CHANGELOG", + "INSTALL" +] diff --git a/run-coverage.sh b/run-coverage.sh deleted file mode 100644 index 60d0475..0000000 --- a/run-coverage.sh +++ /dev/null @@ -1,35 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (c) 2008-2009, European Space Agency & European Southern -# Observatory (ESA/ESO) -# Copyright (c) 2008-2009, CRS4 - Centre for Advanced Studies, Research and -# Development in Sardinia -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# * Neither the name of the European Space Agency, European Southern -# Observatory, CRS4 nor the names of its contributors may be used to -# endorse or promote products derived from this software without specific -# prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY ESA/ESO AND CRS4 ``AS IS'' AND ANY EXPRESS OR -# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -# EVENT SHALL ESA/ESO BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -# WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE -coverage run setup.py test -coverage report -m diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index baa7540..0000000 --- a/setup.cfg +++ /dev/null @@ -1,4 +0,0 @@ -[build_sphinx] -source-dir = docs/ -build-dir = docs/_build -all_files = 1 \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 684066f..0000000 --- a/setup.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (c) 2008-2009, European Space Agency & European Southern -# Observatory (ESA/ESO) -# Copyright (c) 2008-2009, CRS4 - Centre for Advanced Studies, Research and -# Development in Sardinia -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# * Neither the name of the European Space Agency, European Southern -# Observatory, CRS4 nor the names of its contributors may be used to -# endorse or promote products derived from this software without specific -# prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY ESA/ESO AND CRS4 ``AS IS'' AND ANY EXPRESS OR -# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -# EVENT SHALL ESA/ESO BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -# WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE - -""" -Install script for libxmp. -""" -import os -import re -import sys - -try: - from setuptools import setup, find_packages -except ImportError: - from distutils.core import setup, find_packages - -# Install requirements. -test_requires = [] -if sys.hexversion < 0x03030000: - test_requires.append('mock>=1.0.1') -if sys.hexversion < 0x02070000: - test_requires.append('unittest2>=0.5.1') - -KWARGS = { - 'name': 'python-xmp-toolkit', - 'description': 'Python XMP Toolkit for working with metadata.', - 'author': 'Lars Holm Nielsen, John Evans, Federico Caboni & Amit Kapadia', - 'author_email': 'lars@hankat.dk', - 'url': 'https://github.com/python-xmp-toolkit/python-xmp-toolkit', - 'long_description': open('README.rst').read(), - 'download_url': 'https://pypi.python.org/pypi/python-xmp-toolkit', - 'license': 'New BSD License', - 'install_requires': ['pytz'], - 'packages': find_packages(exclude=["*test*"]), - 'test_suite': 'test', - 'tests_require': test_requires, - 'classifiers': [ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: BSD License', - 'Operating System :: MacOS :: MacOS X', - 'Operating System :: POSIX :: Linux', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 3', - 'Topic :: Multimedia', - 'Topic :: Software Development :: Libraries', - 'Topic :: Utilities', - ], -} - -# Get the version string. Cannot do this by importing libxmp! -version_file = os.path.join('libxmp', 'version.py') -with open(version_file, 'rt') as fptr: - contents = fptr.read() - match = re.search('VERSION\s*=\s*"(?P\d*.\d*.\d*.*)"\n', contents) - KWARGS['version'] = match.group('version') - -setup(**KWARGS) diff --git a/test/common_fixtures.py b/test/common_fixtures.py index 135a795..6f6395e 100644 --- a/test/common_fixtures.py +++ b/test/common_fixtures.py @@ -33,7 +33,7 @@ # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE import os -import pkg_resources +import importlib.resources import shutil import libxmp @@ -73,7 +73,8 @@ def setup_sample_files(dirname): fmts = [] for samplefile, fmt in samplefiles.items(): relsrc = os.path.join('samples', samplefile) - full_source_file = pkg_resources.resource_filename(__name__, relsrc) + traversable = importlib.resources.files(__package__) / relsrc + full_source_file = traversable dest_file = os.path.join(dirname, samplefile) shutil.copyfile(full_source_file, dest_file) copied_samplefiles.append(dest_file) diff --git a/test/samples.py b/test/samples.py index 4a97203..393ca64 100644 --- a/test/samples.py +++ b/test/samples.py @@ -83,15 +83,13 @@ samplefiles = files def make_temp_samples(): - global sampledir if os.path.exists(sampledir): remove_temp_samples() shutil.copytree('samples', sampledir) def remove_temp_samples(): - global sampledir if os.path.exists( sampledir ): if not os.path.isdir( sampledir): - raise StandardError('Cannot remove .tempsamples - it is not a directory. Please manually remove it.') + raise RuntimeError('Cannot remove .tempsamples - it is not a directory. Please manually remove it.') shutil.rmtree( sampledir ) diff --git a/test/samples/BlueSquare.gif b/test/samples/BlueSquare.gif index 7dcc9e7..862bc24 100644 Binary files a/test/samples/BlueSquare.gif and b/test/samples/BlueSquare.gif differ diff --git a/test/test_core_unit.py b/test/test_core_unit.py index 913b946..bc15718 100644 --- a/test/test_core_unit.py +++ b/test/test_core_unit.py @@ -34,13 +34,10 @@ import datetime import sys -if sys.hexversion < 0x02070000: - import unittest2 as unittest -else: - import unittest +import unittest import os import os.path -import pkg_resources +import importlib.resources import shutil import tempfile @@ -129,11 +126,7 @@ def test_serialize_str(self): obj = xmp.serialize_to_str(use_compact_format=True, omit_packet_wrapper=True) - if sys.hexversion >= 0x03000000: - the_unicode_type = str - else: - the_unicode_type = unicode - self.assertTrue(isinstance(obj, the_unicode_type)) + self.assertTrue(isinstance(obj, str)) with self.assertRaises(XMPError): xmp.serialize_to_str(read_only_packet=True, @@ -154,14 +147,9 @@ def test_serialize_unicode(self): """ xmp = XMPMeta() xmp.parse_from_str(xmpcoverage.RDFCoverage, xmpmeta_wrap=True) - if sys.hexversion >= 0x03000000: - the_unicode_type = str - else: - the_unicode_type = unicode - obj = xmp.serialize_to_unicode(use_compact_format=True, omit_packet_wrapper=False) - self.assertTrue(isinstance(obj, the_unicode_type ), + self.assertTrue(isinstance(obj, str), "Incorrect string result type." ) with self.assertRaises(XMPError): @@ -186,11 +174,7 @@ def test_serialize_and_format(self): newlinechr='NEWLINE', tabchr = 'TAB', indent=6 ) - if sys.hexversion >= 0x03000000: - the_unicode_type = str - else: - the_unicode_type = unicode - self.assertTrue(isinstance(obj, the_unicode_type), + self.assertTrue(isinstance(obj, str), "Result is not the correct string" ) with self.assertRaises(XMPError): @@ -250,21 +234,22 @@ def test_text_property_450(self): def test_does_property_exist(self): - filename = pkg_resources.resource_filename(__name__, - "fixtures/BlueSquare450.tif") - xmp = XMPFiles(file_path=filename) - xmp_data = xmp.get_xmp() - self.assertTrue( xmp_data.does_property_exist( "http://ns.adobe.com/photoshop/1.0/", 'Headline' ) ) + traversable = importlib.resources.files(__package__) / "fixtures/BlueSquare450.tif" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + xmp = XMPFiles(file_path=filename) + xmp_data = xmp.get_xmp() + self.assertTrue( xmp_data.does_property_exist( "http://ns.adobe.com/photoshop/1.0/", 'Headline' ) ) def test_write_new_property(self): """Corresponds to test-write-new-property.cpp""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = XMPMeta() xmp.parse_from_str(strbuffer, xmpmeta_wrap=False) @@ -291,11 +276,11 @@ def test_write_new_property(self): def test_write_new_struct_in_array(self): - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = XMPMeta() xmp.parse_from_str(strbuffer) @@ -324,10 +309,11 @@ def test_write_new_struct_in_array(self): def test_exempi_core(self): """Corresponds to test_exempi.TestExempi.test_exempi_core""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = XMPMeta() xmp.parse_from_str(strbuffer) @@ -401,10 +387,11 @@ def test_exempi_core(self): def test_does_array_item_exist(self): """Tests XMPMeta method does_array_item_exist. Issue #03""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = XMPMeta() xmp.parse_from_str(strbuffer) @@ -415,13 +402,13 @@ def test_does_array_item_exist(self): self.assertTrue(xmp.does_array_item_exist(NS_DC, "creator", "foo")) self.assertFalse(xmp.does_array_item_exist(NS_DC, "creator", "blah")) - def test_count_array_items(self): """Tests XMPMeta method count_array_items.""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = XMPMeta() xmp.parse_from_str(strbuffer) @@ -434,10 +421,11 @@ def test_count_array_items(self): def test_skip(self): """Verify usage of XMPMeta skip method. """ - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = XMPMeta() xmp.parse_from_str(strbuffer) @@ -486,9 +474,10 @@ def test_file_to_dict_nofile(self): self.assertRaises( IOError, file_to_dict, "nonexistingfile.ext" ) def test_file_to_dict_noxmp(self): - filename = pkg_resources.resource_filename(__name__, - "fixtures/empty.txt") - self.assertEqual( file_to_dict(filename), {} ) + traversable = importlib.resources.files(__package__) / "fixtures/empty.txt" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + self.assertEqual( file_to_dict(filename), {} ) def test_object_to_dict_noxmp(self): self.assertEqual( object_to_dict( [] ), {} ) @@ -547,10 +536,7 @@ def test_2bytes_codepoint(self): # Replace 'Simple2 value' with 'stürm' # ü has code point 252, so takes 5+1=6 bytes to encode. expectedValue = u'stürm' - if sys.hexversion < 0x03000000: - rdf = unicode(rdf[0:272]) + expectedValue + unicode(rdf[285:]) - else: - rdf = rdf[0:272] + expectedValue + rdf[285:] + rdf = rdf[0:272] + expectedValue + rdf[285:] xmp.parse_from_str(rdf, xmpmeta_wrap=True ) @@ -571,12 +557,7 @@ def test_parse_from_str_3_bytes_per_codepoint(self): # This is 'Shiva' in Devanagari # शिव has code points [2358, 2367, 2357] expectedValue = u'शिव' - if sys.hexversion < 0x03000000: - rdf = unicode(rdf[0:272]) + expectedValue + unicode(rdf[285:]) - #rdf = rdf[0:272] + expectedValue.encode('utf-8') + rdf[285:] - #rdf = unicode(rdf) - else: - rdf = rdf[0:272] + expectedValue + rdf[285:] + rdf = rdf[0:272] + expectedValue + rdf[285:] xmp.parse_from_str(rdf, xmpmeta_wrap=True ) @@ -609,28 +590,6 @@ def test_xmpmeta_repr(self): xmp = XMPMeta() self.assertTrue(isinstance(repr(xmp), str)) - def test_xmpmeta_unicode_27(self): - """In 2.7, unicode(xmp) should return a unicode object.""" - xmp = XMPMeta() - rdf = xmpcoverage.RDFCoverage - xmp.parse_from_str(rdf) - if sys.hexversion < 0x03000000: - self.assertTrue(isinstance(unicode(xmp), unicode)) - else: - # It's a no-op in 3.x. - self.assertTrue(True) - -def suite(): - suite = unittest.TestSuite() - suite.addTest(unittest.makeSuite(XMPMetaTestCase)) - suite.addTest(unittest.makeSuite(UtilsTestCase)) - return suite - -def test( verbose=2 ): - all_tests = suite() - runner = unittest.TextTestRunner(verbosity=verbose) - result = runner.run(all_tests) - return result, runner if __name__ == "__main__": #test() diff --git a/test/test_exempi.py b/test/test_exempi.py index 690ce15..1ad261e 100644 --- a/test/test_exempi.py +++ b/test/test_exempi.py @@ -8,16 +8,13 @@ import datetime import os -import pkg_resources +import importlib.resources import platform import shutil import sys import tempfile -if sys.hexversion >= 0x02070000: - import unittest -else: - import unittest2 as unittest +import unittest import pytz @@ -48,10 +45,11 @@ class TestInit(unittest.TestCase): """ def test_init(self): """TODO: fill in the docstring""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() exempi.init() exempi.init() @@ -100,21 +98,22 @@ def tearDown(self): def test_bgo(self): """Corresponds to test-bgo.cpp """ - filename = pkg_resources.resource_filename(__name__, - "samples/fdo18635.jpg") - xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) - xmp = exempi.files_get_new_xmp(xfptr) - exempi.free(xmp) - exempi.files_free(xfptr) - self.assertTrue(True) + traversable = importlib.resources.files(__package__) / "samples/fdo18635.jpg" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) + xmp = exempi.files_get_new_xmp(xfptr) + exempi.free(xmp) + exempi.files_free(xfptr) + self.assertTrue(True) def test_write_new_property(self): """Corresponds to test-write-new-property.cpp""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = exempi.new_empty() self.assertFalse(exempi.get_error()) @@ -150,10 +149,11 @@ def test_write_new_property(self): def test_3(self): """Corresponds to test3.cpp""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = exempi.new_empty() exempi.parse(xmp, strbuffer) @@ -181,10 +181,12 @@ def test_3(self): def test_exempi_core(self): """According to test-exempi-core.cpp""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() + xmp = exempi.new_empty() exempi.parse(xmp, strbuffer) self.assertTrue(exempi.has_property(xmp, NS_TIFF, 'Make')) @@ -291,44 +293,46 @@ def test_exempi_core(self): def test_xmpfiles_write(self): """According to test-xmpfiles-write.cpp""" - filename = pkg_resources.resource_filename(__name__, - "samples/BlueSquare.jpg") + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.jpg" + with importlib.resources.as_file(traversable) as path: + filename = str(path) - fmt = exempi.files_check_file_format(filename) - self.assertEqual(fmt, libxmp.consts.XMP_FT_JPEG) + fmt = exempi.files_check_file_format(filename) + self.assertEqual(fmt, libxmp.consts.XMP_FT_JPEG) - xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) - xmp = exempi.files_get_new_xmp(xfptr) - exempi.files_free(xfptr) + xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) + xmp = exempi.files_get_new_xmp(xfptr) + exempi.files_free(xfptr) - with tempfile.NamedTemporaryFile(suffix=".jpg") as tfile: - shutil.copyfile(filename, tfile.name) + with tempfile.NamedTemporaryFile(suffix=".jpg") as tfile: + shutil.copyfile(filename, tfile.name) - xfptr = exempi.files_open_new(tfile.name, XMP_OPEN_FORUPDATE) + xfptr = exempi.files_open_new(tfile.name, XMP_OPEN_FORUPDATE) - exempi.set_property(xmp, NS_PHOTOSHOP, "ICCProfile", "foo", 0) - self.assertTrue(exempi.files_can_put_xmp(xfptr, xmp)) - exempi.files_put_xmp(xfptr, xmp) - exempi.free(xmp) - exempi.files_close(xfptr, XMP_CLOSE_SAFEUPDATE) - exempi.files_free(xfptr) + exempi.set_property(xmp, NS_PHOTOSHOP, "ICCProfile", "foo", 0) + self.assertTrue(exempi.files_can_put_xmp(xfptr, xmp)) + exempi.files_put_xmp(xfptr, xmp) + exempi.free(xmp) + exempi.files_close(xfptr, XMP_CLOSE_SAFEUPDATE) + exempi.files_free(xfptr) - xfptr = exempi.files_open_new(tfile.name, XMP_OPEN_READ) - xmp = exempi.files_get_new_xmp(xfptr) - the_prop, _ = exempi.get_property(xmp, NS_PHOTOSHOP, "ICCProfile") - self.assertEqual("foo", the_prop) + xfptr = exempi.files_open_new(tfile.name, XMP_OPEN_READ) + xmp = exempi.files_get_new_xmp(xfptr) + the_prop, _ = exempi.get_property(xmp, NS_PHOTOSHOP, "ICCProfile") + self.assertEqual("foo", the_prop) - exempi.free(xmp) - exempi.files_close(xfptr, XMP_CLOSE_NOOPTION) - exempi.files_free(xfptr) + exempi.free(xmp) + exempi.files_close(xfptr, XMP_CLOSE_NOOPTION) + exempi.files_free(xfptr) def test_serialize(self): """Corresponds to test-serialize.cpp""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() self.assertFalse(exempi.get_error()) @@ -348,21 +352,21 @@ def test_serialize(self): def test_tiff_leak(self): """Corresponds to test-tiff-leak.cpp""" - orig_file = pkg_resources.resource_filename(__name__, - "samples/BlueSquare.tif") - - with tempfile.NamedTemporaryFile(suffix='.tif') as tfile: - shutil.copyfile(orig_file, tfile.name) - - xfptr = exempi.files_open_new(tfile.name, XMP_OPEN_FORUPDATE) - - xmp = exempi.files_get_new_xmp(xfptr) - exempi.set_localized_text(xmp, NS_DC, "description", "en", "en-US", - "foo", 0) - exempi.files_put_xmp(xfptr, xmp) - exempi.files_close(xfptr, XMP_CLOSE_NOOPTION) - exempi.free(xmp) - exempi.files_free(xfptr) + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.tif" + with importlib.resources.as_file(traversable) as path: + orig_file = str(path) + with tempfile.NamedTemporaryFile(suffix='.tif') as tfile: + shutil.copyfile(orig_file, tfile.name) + + xfptr = exempi.files_open_new(tfile.name, XMP_OPEN_FORUPDATE) + + xmp = exempi.files_get_new_xmp(xfptr) + exempi.set_localized_text(xmp, NS_DC, "description", "en", "en-US", + "foo", 0) + exempi.files_put_xmp(xfptr, xmp) + exempi.files_close(xfptr, XMP_CLOSE_NOOPTION) + exempi.free(xmp) + exempi.files_free(xfptr) self.assertTrue(True) @@ -370,11 +374,11 @@ def test_write_new_date_property(self): """ TODO: fill in the doc string """ - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = exempi.new_empty() self.assertFalse(exempi.get_error()) @@ -400,23 +404,24 @@ def test_write_new_date_property(self): def test_xmp_files(self): """Corresponds to test_xmp_files.cpp""" - filename = pkg_resources.resource_filename(__name__, - "samples/BlueSquare.jpg") + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.jpg" + with importlib.resources.as_file(traversable) as path: + filename = str(path) - xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) - fmt = exempi.files_check_file_format(filename) - self.assertEqual(fmt, libxmp.consts.XMP_FT_JPEG) + xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) + fmt = exempi.files_check_file_format(filename) + self.assertEqual(fmt, libxmp.consts.XMP_FT_JPEG) - file_path, options, file_format, flags = exempi.files_get_file_info(xfptr) - self.assertEqual(options, XMP_OPEN_READ) - self.assertEqual(file_format, libxmp.consts.XMP_FT_JPEG) - self.assertEqual(flags, 0x27f) # 0x27f? - self.assertEqual(filename, file_path) + file_path, options, file_format, flags = exempi.files_get_file_info(xfptr) + self.assertEqual(options, XMP_OPEN_READ) + self.assertEqual(file_format, libxmp.consts.XMP_FT_JPEG) + self.assertEqual(flags, 0x27f) # 0x27f? + self.assertEqual(filename, file_path) - xmp = exempi.files_get_xmp(xfptr) - the_prop, _ = exempi.get_property(xmp, NS_PHOTOSHOP, "ICCProfile") - self.assertEqual(the_prop, "sRGB IEC61966-2.1") - exempi.files_free(xfptr) + xmp = exempi.files_get_xmp(xfptr) + the_prop, _ = exempi.get_property(xmp, NS_PHOTOSHOP, "ICCProfile") + self.assertEqual(the_prop, "sRGB IEC61966-2.1") + exempi.files_free(xfptr) def test_formats(self): """Verify that check_file_format function works as expected.""" @@ -434,37 +439,42 @@ def test_formats(self): } for suffix, expected_format in pairs.items(): relpath = os.path.join('samples', 'BlueSquare' + '.' + suffix) - filename = pkg_resources.resource_filename(__name__, relpath) - xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) - actual_format = exempi.files_check_file_format(filename) - self.assertEqual(actual_format, expected_format) - exempi.files_free(xfptr) + traversable = importlib.resources.files(__package__) / relpath + with importlib.resources.as_file(traversable) as path: + filename = str(path) + xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) + actual_format = exempi.files_check_file_format(filename) + self.assertEqual(actual_format, expected_format) + exempi.files_free(xfptr) @unittest.skip("Issue 26") def test_bad_formats(self): """Verify check_file_format on PDF, Adobe Illustrator, XMP.""" # Issue 26 - filename = pkg_resources.resource_filename(__name__, - "samples/BlueSquare.pdf") - xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) - fmt = exempi.files_check_file_format(filename) - self.assertEqual(fmt, libxmp.consts.XMP_FT_PDF) - exempi.files_free(xfptr) - - filename = pkg_resources.resource_filename(__name__, - "samples/BlueSquare.ai") - xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) - fmt = exempi.files_check_file_format(filename) - self.assertEqual(fmt, libxmp.consts.XMP_FT_ILLUSTRATOR) - exempi.files_free(xfptr) - - filename = pkg_resources.resource_filename(__name__, - "samples/BlueSquare.xmp") - xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) - fmt = exempi.files_check_file_format(filename) - self.assertEqual(fmt, libxmp.consts.XMP_FT_XML) - exempi.files_free(xfptr) + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.pdf" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) + fmt = exempi.files_check_file_format(filename) + self.assertEqual(fmt, libxmp.consts.XMP_FT_PDF) + exempi.files_free(xfptr) + + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.ai" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) + fmt = exempi.files_check_file_format(filename) + self.assertEqual(fmt, libxmp.consts.XMP_FT_ILLUSTRATOR) + exempi.files_free(xfptr) + + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + xfptr = exempi.files_open_new(filename, XMP_OPEN_READ) + fmt = exempi.files_check_file_format(filename) + self.assertEqual(fmt, libxmp.consts.XMP_FT_XML) + exempi.files_free(xfptr) class TestIteration(unittest.TestCase): @@ -476,10 +486,11 @@ def setUp(self): def collect_iteration(self, schema, prop, options): """Run thru an iteration for a given configuration.""" - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = exempi.new_empty() exempi.parse(xmp, strbuffer) @@ -658,10 +669,11 @@ def test_iter_skip_subtree(self): """Alter the iteration midstream.""" options = XMP_ITERATOR_OPTIONS['iter_properties'] - filename = pkg_resources.resource_filename(__name__, - "samples/test1.xmp") - with open(filename, 'r') as fptr: - strbuffer = fptr.read() + traversable = importlib.resources.files(__package__) / "samples/test1.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with open(filename, 'r') as fptr: + strbuffer = fptr.read() xmp = exempi.new_empty() exempi.parse(xmp, strbuffer) diff --git a/test/test_files.py b/test/test_files.py index 1885a31..51b2ac8 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -34,26 +34,16 @@ import os import os.path -import pkg_resources as pkg +import importlib.resources import platform import re import shutil import sys import tempfile -if sys.hexversion < 0x02070000: - import unittest2 as unittest -else: - import unittest +import unittest +from unittest.mock import patch -if sys.hexversion <= 0x03030000: - from mock import patch -else: - from unittest.mock import patch - -if sys.hexversion < 0x03000000: - from StringIO import StringIO -else: - from io import StringIO +from io import StringIO from libxmp import XMPFiles, XMPMeta, XMPError from libxmp.consts import XMP_NS_Photoshop as NS_PHOTOSHOP @@ -82,8 +72,10 @@ def test_repr(self): # If the XMPFiles object has a file associated with it, then use a # regular expression to match the output. - filename = pkg.resource_filename(__name__, "samples/BlueSquare.jpg") - xmpf.open_file(file_path=filename) + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.jpg" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + xmpf.open_file(file_path=filename) actual_value = str(xmpf) regex = re.compile(r"""XMPFiles\(file_path=""", re.VERBOSE) @@ -95,10 +87,12 @@ def test_print_bom(self): # The BOM cannot be decoded from utf-8 into ascii, so a 2.7 XMPMeta # object's __repr__ function would error out on it. - filename = pkg.resource_filename(__name__, "samples/BlueSquare.jpg") - xmpf = XMPFiles() - xmpf.open_file(file_path=filename) - xmp = xmpf.get_xmp() + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.jpg" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + xmpf = XMPFiles() + xmpf.open_file(file_path=filename) + xmp = xmpf.get_xmp() with patch('sys.stdout', new=StringIO()) as fake_out: print(xmp) repr(xmp) @@ -160,24 +154,30 @@ def test_open_file_with_options(self): def test_open_use_smarthandler(self): """Verify this library failure.""" # Issue 5 - filenames = [pkg.resource_filename(__name__, "samples/BlueSquare.pdf"), - pkg.resource_filename(__name__, "samples/BlueSquare.ai"), - pkg.resource_filename(__name__, "samples/BlueSquare.xmp")] + filenames = ["samples/BlueSquare.pdf", + "samples/BlueSquare.ai", + "samples/BlueSquare.xmp"] xmpfile = XMPFiles() - for filename in filenames: - with self.assertRaises(XMPError): - xmpfile.open_file(filename, open_usesmarthandler=True) + for filename_ in filenames: + traversable = importlib.resources.files(__package__) / filename_ + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with self.assertRaises(XMPError): + xmpfile.open_file(filename, open_usesmarthandler=True) def test_open_open_limitscanning(self): """Verify this library failure.""" # Issue 5 - filenames = [pkg.resource_filename(__name__, "samples/BlueSquare.pdf"), - pkg.resource_filename(__name__, "samples/BlueSquare.xmp")] + filenames = ["samples/BlueSquare.pdf", + "samples/BlueSquare.xmp"] xmpfile = XMPFiles() - for filename in filenames: - with self.assertRaises(XMPError): - xmpfile.open_file(filename, open_limitscanning=True) + for filename_ in filenames: + traversable = importlib.resources.files(__package__) / filename_ + with importlib.resources.as_file(traversable) as path: + filename = str(path) + with self.assertRaises(XMPError): + xmpfile.open_file(filename, open_limitscanning=True) def test_close_file(self): @@ -265,11 +265,13 @@ def exempi_error(self): So loading a sidecar file and call can_put_xmp will kill python interpreter since a C++ exception is thrown. """ - filename = pkg.resource_filename(__name__, "samples/sig05-002a.xmp") - xmpfile = XMPFiles() - xmpfile.open_file(filename, open_forupdate = True ) - xmp = xmpfile.get_xmp() - xmpfile.can_put_xmp( xmp ) + traversable = importlib.resources.files(__package__) / "samples/sig05-002a.xmp" + with importlib.resources.as_file(traversable) as path: + filename = str(path) + xmpfile = XMPFiles() + xmpfile.open_file(filename, open_forupdate = True ) + xmp = xmpfile.get_xmp() + xmpfile.can_put_xmp( xmp ) def test_write_in_readonly(self): """If not "open_forupdate = True", should raise exception""" @@ -286,25 +288,27 @@ def test_write_in_readonly(self): def test_tiff_smarthandler(self): """Verify action of TIFF smarthandler when tag length > 255""" # See issue 12 - srcfile = pkg.resource_filename(__name__, "fixtures/zeros.tif") - with tempfile.NamedTemporaryFile(suffix='.tif') as tfile: - shutil.copyfile(srcfile, tfile.name) - - # Create a tag with 280 chars. - xmpf = XMPFiles() - xmpf.open_file(tfile.name, open_forupdate=True) - xmp = xmpf.get_xmp() - blurb = "Some really long text blurb " - xmp.set_property(NS_PHOTOSHOP, 'Headline', blurb * 10) - xmpf.put_xmp(xmp) - xmpf.close_file() + traversable = importlib.resources.files(__package__) / "fixtures/zeros.tif" + with importlib.resources.as_file(traversable) as path: + srcfile = str(path) + with tempfile.NamedTemporaryFile(suffix='.tif') as tfile: + shutil.copyfile(srcfile, tfile.name) + + # Create a tag with 280 chars. + xmpf = XMPFiles() + xmpf.open_file(tfile.name, open_forupdate=True) + xmp = xmpf.get_xmp() + blurb = "Some really long text blurb " + xmp.set_property(NS_PHOTOSHOP, 'Headline', blurb * 10) + xmpf.put_xmp(xmp) + xmpf.close_file() - xmpf.open_file(tfile.name, usesmarthandler=True) - xmp = xmpf.get_xmp() - prop = xmp.get_property(NS_PHOTOSHOP, "Headline") - xmpf.close_file() + xmpf.open_file(tfile.name, usesmarthandler=True) + xmp = xmpf.get_xmp() + prop = xmp.get_property(NS_PHOTOSHOP, "Headline") + xmpf.close_file() - self.assertEqual(prop, blurb * 10) + self.assertEqual(prop, blurb * 10) def test_non_ascii_filename(self): """ @@ -313,87 +317,70 @@ def test_non_ascii_filename(self): See issue 36 """ # Rename one of the test files to use non-ascii characters. - relpath = os.path.join('samples', 'BlueSquare.tif') - srcfile = pkg.resource_filename(__name__, relpath) - tdir = tempfile.mkdtemp() - destdir = os.path.join(tdir, u"éà*çc! teeest!!") - os.makedirs(destdir) - - with tempfile.NamedTemporaryFile(dir=destdir, - prefix="image", - suffix=".tif") as tfile: - with open(srcfile, 'rb') as srcfile: - tfile.write(srcfile.read()) - tfile.seek(0) - xf = XMPFiles() - xf.open_file(file_path=tfile.name) - - # This was the point of failure in python2 - actual = repr(xf) - - self.assertTrue(actual.startswith("XMPFiles(file_path=")) - - if sys.hexversion < 0x03000000: - # The directory path (up to the non-ascii portion) should be - # in the output. - self.assertIn(tdir, actual) - else: - # The complete directory path should be present in the repr-ed - # string under python3. + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.tif" + with importlib.resources.as_file(traversable) as path: + srcfile = str(path) + tdir = tempfile.mkdtemp() + destdir = os.path.join(tdir, u"éà*çc! teeest!!") + os.makedirs(destdir) + + with tempfile.NamedTemporaryFile(dir=destdir, + prefix="image", + suffix=".tif") as tfile: + with open(srcfile, 'rb') as srcfile: + tfile.write(srcfile.read()) + tfile.seek(0) + xf = XMPFiles() + xf.open_file(file_path=tfile.name) + + # This was the point of failure in python2 + actual = repr(xf) + + self.assertTrue(actual.startswith("XMPFiles(file_path=")) self.assertIn(destdir, actual) - shutil.rmtree(tdir) + shutil.rmtree(tdir) def test_cannot_inject_xmp_info_pdf(self): """Verify behavior of not being able to inject XMP into barren PDF""" # See issue 40 - srcfile = pkg.resource_filename(__name__, os.path.join("fixtures", - "zeros.pdf")) - - with tempfile.NamedTemporaryFile() as tfile: - shutil.copyfile(srcfile, tfile.name) - - xmpf = XMPFiles() - xmpf.open_file(tfile.name, open_forupdate=True) - xmp = XMPMeta() - xmp.set_property(NS_PHOTOSHOP, "ICCProfile", "foo") - with self.assertRaises(XMPError): - xmpf.put_xmp(xmp) - xmpf.close_file() + traversable = importlib.resources.files(__package__) / "fixtures/zeros.pdf" + with importlib.resources.as_file(traversable) as path: + srcfile = str(path) + with tempfile.NamedTemporaryFile() as tfile: + shutil.copyfile(srcfile, tfile.name) + + xmpf = XMPFiles() + xmpf.open_file(tfile.name, open_forupdate=True) + xmp = XMPMeta() + xmp.set_property(NS_PHOTOSHOP, "ICCProfile", "foo") + with self.assertRaises(XMPError): + xmpf.put_xmp(xmp) + xmpf.close_file() def test_can_inject_xmp_info_png(self): """Verify behavior of being able to inject XMP into barren PNG""" # See issue 40 - srcfile = pkg.resource_filename(__name__, os.path.join("fixtures", - "zeros.png")) - - with tempfile.NamedTemporaryFile() as tfile: - shutil.copyfile(srcfile, tfile.name) - - xmpf = XMPFiles() - xmpf.open_file(tfile.name, open_forupdate=True) - xmp = XMPMeta() - xmp.set_property(NS_PHOTOSHOP, "ICCProfile", "foo") - xmpf.put_xmp(xmp) - xmpf.close_file() - - xmpf.open_file(tfile.name, usesmarthandler=True) - xmp = xmpf.get_xmp() - prop = xmp.get_property(NS_PHOTOSHOP, "ICCProfile") - xmpf.close_file() + traversable = importlib.resources.files(__package__) / "fixtures/zeros.png" + with importlib.resources.as_file(traversable) as path: + srcfile = str(path) + with tempfile.NamedTemporaryFile() as tfile: + shutil.copyfile(srcfile, tfile.name) + + xmpf = XMPFiles() + xmpf.open_file(tfile.name, open_forupdate=True) + xmp = XMPMeta() + xmp.set_property(NS_PHOTOSHOP, "ICCProfile", "foo") + xmpf.put_xmp(xmp) + xmpf.close_file() - self.assertEqual(prop, "foo") + xmpf.open_file(tfile.name, usesmarthandler=True) + xmp = xmpf.get_xmp() + prop = xmp.get_property(NS_PHOTOSHOP, "ICCProfile") + xmpf.close_file() -def suite(): - the_suite = unittest.TestSuite() - the_suite.addTest(unittest.makeSuite(XMPFilesTestCase)) - return the_suite + self.assertEqual(prop, "foo") -def test( verbose=2 ): - all_tests = suite() - runner = unittest.TextTestRunner(verbosity=verbose) - result = runner.run(all_tests) - return result, runner if __name__ == "__main__": unittest.main() diff --git a/test/test_roundtrip.py b/test/test_roundtrip.py index 62b27b9..8891c1e 100644 --- a/test/test_roundtrip.py +++ b/test/test_roundtrip.py @@ -5,7 +5,7 @@ import datetime import os -import pkg_resources +import importlib.resources import platform import shutil import sys @@ -13,10 +13,7 @@ import pytz -if sys.hexversion >= 0x02070000: - import unittest -else: - import unittest2 as unittest +import unittest from libxmp import XMPFiles, XMPMeta from libxmp.consts import XMP_NS_CC as NS_CC @@ -30,111 +27,113 @@ class TestRoundTrip(unittest.TestCase): def test_tiff(self): """Write to a TIFF that does not already have the XMP tag.""" - srcfile = pkg_resources.resource_filename(__name__, - "fixtures/zeros.tif") - with tempfile.NamedTemporaryFile(suffix='.tif') as tfile: - shutil.copyfile(srcfile, tfile.name) + traversable = importlib.resources.files(__package__) / "fixtures/zeros.tif" + with importlib.resources.as_file(traversable) as path: + srcfile = str(path) + with tempfile.NamedTemporaryFile(suffix='.tif') as tfile: + shutil.copyfile(srcfile, tfile.name) - xmpf = XMPFiles() - xmpf.open_file(file_path=tfile.name, open_forupdate=True) + xmpf = XMPFiles() + xmpf.open_file(file_path=tfile.name, open_forupdate=True) - # Since it's a TIFF, it already has everything possible from the - # TIFF IFD filled in into the TIFF namespace. - xmp = xmpf.get_xmp() - xmp.set_property(NS_DC, "rights", "no one in particular") - xmpf.put_xmp(xmp) - xmpf.close_file() + # Since it's a TIFF, it already has everything possible from the + # TIFF IFD filled in into the TIFF namespace. + xmp = xmpf.get_xmp() + xmp.set_property(NS_DC, "rights", "no one in particular") + xmpf.put_xmp(xmp) + xmpf.close_file() - xmpf.open_file(file_path=tfile.name) - xmp = xmpf.get_xmp() - xmpf.close_file() + xmpf.open_file(file_path=tfile.name) + xmp = xmpf.get_xmp() + xmpf.close_file() - # TODO: explain why this happened. - prop = xmp.get_property(NS_DC, "rights") - prop2 = xmp.get_localized_text(NS_DC, "rights", None, "x-default") - self.assertEqual(prop2, "no one in particular") + # TODO: explain why this happened. + prop = xmp.get_property(NS_DC, "rights") + prop2 = xmp.get_localized_text(NS_DC, "rights", None, "x-default") + self.assertEqual(prop2, "no one in particular") def test_sturm_und_drang(self): """Should be able to write a property which includes umlauts.""" - srcfile = pkg_resources.resource_filename(__name__, - "fixtures/zeros.tif") - with tempfile.NamedTemporaryFile(suffix='.tif') as tfile: - shutil.copyfile(srcfile, tfile.name) - - expected_value = u'Stürm und Drang' - - xmpf = XMPFiles() - xmpf.open_file(file_path=tfile.name, open_forupdate=True) - xmp = xmpf.get_xmp() - xmp.set_property(NS_DC, "Title", expected_value) - xmpf.put_xmp(xmp) - xmpf.close_file() - - xmpf = XMPFiles() - xmpf.open_file(file_path=tfile.name) - xmp = xmpf.get_xmp() - actual_value = xmp.get_property(NS_DC, "Title") - xmpf.close_file() - - self.assertEqual(actual_value, expected_value) + traversable = importlib.resources.files(__package__) / "fixtures/zeros.tif" + with importlib.resources.as_file(traversable) as path: + srcfile = str(path) + with tempfile.NamedTemporaryFile(suffix='.tif') as tfile: + shutil.copyfile(srcfile, tfile.name) + + expected_value = u'Stürm und Drang' + + xmpf = XMPFiles() + xmpf.open_file(file_path=tfile.name, open_forupdate=True) + xmp = xmpf.get_xmp() + xmp.set_property(NS_DC, "Title", expected_value) + xmpf.put_xmp(xmp) + xmpf.close_file() + + xmpf = XMPFiles() + xmpf.open_file(file_path=tfile.name) + xmp = xmpf.get_xmp() + actual_value = xmp.get_property(NS_DC, "Title") + xmpf.close_file() + + self.assertEqual(actual_value, expected_value) def test_jpeg(self): """Create XMP from scratch to store in a jpeg.""" + traversable = importlib.resources.files(__package__) / "samples/BlueSquare.jpg" + with importlib.resources.as_file(traversable) as path: + srcfile = str(path) + with tempfile.NamedTemporaryFile(suffix='.tif', mode='wb') as tfile: - srcfile = pkg_resources.resource_filename(__name__, - "samples/BlueSquare.jpg") - with tempfile.NamedTemporaryFile(suffix='.tif', mode='wb') as tfile: - - # Do some surgery on the file, remove existing xmp. - # The APP1 marker segment in question starts at byte 2156, has - # length of 4813 - with open(srcfile, 'rb') as infptr: + # Do some surgery on the file, remove existing xmp. + # The APP1 marker segment in question starts at byte 2156, has + # length of 4813 + with open(srcfile, 'rb') as infptr: - # Write the SOI marker - tfile.write(infptr.read(2)) + # Write the SOI marker + tfile.write(infptr.read(2)) - # Skip over ALL the APP0, APP1 segments. - infptr.seek(21619) - tfile.write(infptr.read()) - tfile.flush() + # Skip over ALL the APP0, APP1 segments. + infptr.seek(21619) + tfile.write(infptr.read()) + tfile.flush() - xmpf = XMPFiles() - xmpf.open_file(file_path=tfile.name, open_forupdate=True) - xmp = xmpf.get_xmp() + xmpf = XMPFiles() + xmpf.open_file(file_path=tfile.name, open_forupdate=True) + xmp = xmpf.get_xmp() - xmp.set_property(NS_DC, "Title", u'Stürm und Drang') + xmp.set_property(NS_DC, "Title", u'Stürm und Drang') - # Construct the properties that would have been filled in had the - # APP0 segment been left in place. - xmp.set_property(NS_TIFF, "Orientation", "1") - xmp.set_property(NS_TIFF, "XResolution", "720000/10000") - xmp.set_property(NS_TIFF, "YResolution", "720000/10000") - xmp.set_property(NS_TIFF, "ResolutionUnit", "2") - xmpf.put_xmp(xmp) - xmpf.close_file() + # Construct the properties that would have been filled in had the + # APP0 segment been left in place. + xmp.set_property(NS_TIFF, "Orientation", "1") + xmp.set_property(NS_TIFF, "XResolution", "720000/10000") + xmp.set_property(NS_TIFF, "YResolution", "720000/10000") + xmp.set_property(NS_TIFF, "ResolutionUnit", "2") + xmpf.put_xmp(xmp) + xmpf.close_file() - xmpf = XMPFiles() - xmpf.open_file(file_path=tfile.name) - xmp = xmpf.get_xmp() + xmpf = XMPFiles() + xmpf.open_file(file_path=tfile.name) + xmp = xmpf.get_xmp() - prop = xmp.get_property(NS_DC, "Title") - self.assertEqual(prop, u'Stürm und Drang') + prop = xmp.get_property(NS_DC, "Title") + self.assertEqual(prop, u'Stürm und Drang') - prop = xmp.get_property(NS_TIFF, "Orientation") - self.assertEqual(prop, "1") + prop = xmp.get_property(NS_TIFF, "Orientation") + self.assertEqual(prop, "1") - prop = xmp.get_property(NS_TIFF, "XResolution") - self.assertEqual(prop, "720000/10000") + prop = xmp.get_property(NS_TIFF, "XResolution") + self.assertEqual(prop, "720000/10000") - prop = xmp.get_property(NS_TIFF, "YResolution") - self.assertEqual(prop, "720000/10000") + prop = xmp.get_property(NS_TIFF, "YResolution") + self.assertEqual(prop, "720000/10000") - prop = xmp.get_property(NS_TIFF, "ResolutionUnit") - self.assertEqual(prop, "2") + prop = xmp.get_property(NS_TIFF, "ResolutionUnit") + self.assertEqual(prop, "2") - xmpf.close_file() + xmpf.close_file() diff --git a/tox.ini b/tox.ini deleted file mode 100644 index 4852344..0000000 --- a/tox.ini +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (c) 2008-2009, European Space Agency & European Southern -# Observatory (ESA/ESO) -# Copyright (c) 2008-2009, CRS4 - Centre for Advanced Studies, Research and -# Development in Sardinia -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# * Neither the name of the European Space Agency, European Southern -# Observatory, CRS4 nor the names of its contributors may be used to -# endorse or promote products derived from this software without specific -# prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY ESA/ESO AND CRS4 ``AS IS'' AND ANY EXPRESS OR -# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -# EVENT SHALL ESA/ESO BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -# WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE - -[tox] -envlist = py26, py27, py33, docs - - -# Setting PYTHONPATH is needed for sphinx-build to find the test files -[testenv] -commands = - {envpython} setup.py test - {envbindir}/sphinx-build -E -a -b doctest -d {envtmpdir}/cache/ docs {envtmpdir}/doctest/ -setenv = - PYTHONPATH = {toxinidir} -deps = - sphinx - -[testenv:docs] -basepython=python -deps=sphinx -commands= - {envpython} setup.py build_sphinx -E -a - {envpython} setup.py build_sphinx -E -a -b doctest - {envpython} setup.py build_sphinx -E -a -b coverage - /bin/cat docs/_build/doctest/output.txt - /bin/cat docs/_build/coverage/python.txt