diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..6e3d84d --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" # See docs, they say not to use '.github' + schedule: + interval: "weekly" + commit-message: + prefix: "[CI]" diff --git a/.github/workflows/build-wheels.yml b/.github/workflows/build-wheels.yml new file mode 100644 index 0000000..96eb3e5 --- /dev/null +++ b/.github/workflows/build-wheels.yml @@ -0,0 +1,39 @@ +name: Build Wheels + +on: + push: + branches: + - main + workflow_dispatch: + pull_request: + +concurrency: + # Shared with `deploy-pypi`. + group: wheel-${{ github.ref }} + # Cancel any in-progress build or publish. + cancel-in-progress: true + +jobs: + build_wheels: + name: Build wheel + runs-on: ubuntu-20.04 + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: "3.9" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install setuptools wheel + - name: Build wheels + run: pip wheel --no-deps --wheel-dir wheelhouse . + + - uses: actions/upload-artifact@v3 + with: + name: my_asset_manager_wheels + path: ./wheelhouse/*.whl diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml new file mode 100644 index 0000000..ea7896c --- /dev/null +++ b/.github/workflows/code-quality.yml @@ -0,0 +1,44 @@ +name: Code quality +on: pull_request + +jobs: + pylint: + runs-on: ubuntu-latest + name: Pylint + steps: + - uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.9 + + - name: Install dependencies + run: | + python -m pip install . + python -m pip install -r tests/requirements.txt + - name: Lint + uses: TheFoundryVisionmongers/fn-pylint-action@v1.1 + with: + pylint-rcfile: "./pyproject.toml" + pylint-paths: > + plugin + tests + + black: + runs-on: ubuntu-latest + name: Python formatting + steps: + - uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.9 + + - name: Install dependencies + run: | + python -m pip install black + + - name: Check Python formatting + run: black --check . diff --git a/.github/workflows/deploy-pypi.yml b/.github/workflows/deploy-pypi.yml new file mode 100644 index 0000000..47896f3 --- /dev/null +++ b/.github/workflows/deploy-pypi.yml @@ -0,0 +1,53 @@ +name: Deploy PyPI + +concurrency: + # Shared with `build-wheels`. + group: wheel-${{ github.ref }} + # Allow `build-wheels` to finish. + cancel-in-progress: false + +on: + release: + types: [published] + workflow_dispatch: + +jobs: + publish_testpypi: + name: Publish distribution πŸ“¦ to TestPyPI + runs-on: ubuntu-20.04 + steps: + - name: Download wheels from commit ${{ github.sha }} + uses: dawidd6/action-download-artifact@v2 + with: + workflow: build-wheels.yml + workflow_conclusion: success + commit: ${{ github.sha }} + name: my_asset_manager_wheels + path: dist + + - name: Upload to TestPyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + user: __token__ + password: ${{ secrets.TEST_PYPI_ACCESS_TOKEN }} + repository_url: https://test.pypi.org/legacy/ + + publish_pypi: + name: Publish distribution πŸ“¦ to PyPI + needs: publish_testpypi + runs-on: ubuntu-20.04 + steps: + - name: Download wheels from commit ${{ github.sha }} + uses: dawidd6/action-download-artifact@v2 + with: + workflow: build-wheels.yml + workflow_conclusion: success + commit: ${{ github.sha }} + name: my_asset_manager_wheels + path: dist + + - name: Upload to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + user: __token__ + password: ${{ secrets.PYPI_ACCESS_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..8414d64 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,45 @@ +# Runs pytest on the matrix of supported platforms any Python versions. +name: Test +on: + pull_request: + +jobs: + # You may remove this test, this merely assures that the template + # works when you find-and-replace the MyAssetManager strings. + test_project_rename: + name: Project Rename + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: "3.9" + - run: | + grep -RIl 'MyAssetManager' | xargs sed -i 's/MyAssetManager/RenamedAssetManager/g' + grep -RIl 'my_asset_manager' | xargs sed -i 's/my_asset_manager/renamed_asset_manager/g' + grep -RIl 'My Asset Manager' | xargs sed -i 's/My Asset Manager/Renamed Asset Manager/g' + grep -RIl 'myorg' | xargs sed -i 's/myorg/renamedorg/g' + mv plugin/my_asset_manager/MyAssetManagerInterface.py \ + plugin/my_asset_manager/RenamedAssetManagerInterface.py + mv plugin/my_asset_manager plugin/renamed_asset_manager + python -m pip install . + python -m pip install -r tests/requirements.txt + python -m pytest -v ./tests + + test: + name: ${{ matrix.os }} ${{ matrix.python }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: ["windows-latest", "ubuntu-latest", "macos-latest"] + python: ["3.7", "3.9", "3.10"] + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python }} + - run: | + python -m pip install . + python -m pip install -r tests/requirements.txt + python -m pytest -v ./tests diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b6e4761 --- /dev/null +++ b/.gitignore @@ -0,0 +1,129 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..57ca242 --- /dev/null +++ b/README.md @@ -0,0 +1,169 @@ +# Template-OpenAssetIO-Manager-Python + +An [OpenAssetIO](https://github.com/OpenAssetIO/OpenAssetIO) Python +manager plugin template. + +This template has been written so that it works "out of the box", +including test and lint infrastructure, integrated with github actions. + +## Using the template + +### Manager Name + +Once you have cloned the repository, you'll want to rename the template. +The template uses placeholder strings, (eg: "MyAssetManager") throughout +to facilitate easy replacement. + +Firstly, rename the directory + +```bash +plugins/my_asset_manager +``` + + and the file at + +```bash +plugins/my_asset_manager/MyAssetManagerInterface.py +``` + +substituting in the name of your asset manager in the appropriate style. + +Then, run a global find and replace across the project file contents to +replace the following strings with the name of your asset manager, in +the matching styles. + +```bash +MyAssetManager +my_asset_manager +My Asset Manager +``` + +Finally, also globally replace the string + +```bash +myorg +``` + +with the name of your organization. + +> **Note** +> +> `myorg` is the first item in a reverse-dns identifier string, See the +> `identifier()` methods in +> [`__init__.py`](plugin/my_asset_manager/__init__.py) and +> [`MyAssetManagerInterface.py`](plugin/my_asset_manager/MyAssetManagerInterface.py) + +### Install and Test + +You should then be able to install the asset manager into you Python +environment. From the project root. + +```shell +python -m pip install . +``` + +and invoke the included tests + +```shell +python -m pip install -r tests/requirements.txt +python -m pytest ./tests +``` + +### Using the manager with a host + +The manager is setup for entry point based plugin discovery. This means +that it needs only be installed into your Python environment, and then +an `OpenAssetIO` host can load it automatically, simply via configuring +to the [manager identifier](plugin/my_asset_manager/__init__.py#L35), +(usually by using a [default config +file.](https://openassetio.github.io/OpenAssetIO/glossary.html#default_config_var)) + +Alternatively, you can avoid installing the plugin by adding the +`plugin` directory to the `$OPENASSETIO_PLUGIN_PATH` environment +variable. + +## Project walkthrough + +``` +. +β”œβ”€β”€ .github +| β”œβ”€β”€ workflows +| β”œβ”€β”€ code-quality.yml +| β”œβ”€β”€ test.yml +| β”œβ”€β”€ build-wheels.yml +| └── deploy-pypi.yml +β”œβ”€β”€ plugin +β”‚Β Β  β”œβ”€β”€ my_asset_manager +β”‚Β Β  Β Β  β”œβ”€β”€ MyAssetManagerInterface.py +β”‚Β Β  Β  Β  └── __init__.py +β”œβ”€β”€ pyproject.toml +└── tests + β”œβ”€β”€ business_logic_suite.py + β”œβ”€β”€ conftest.py + β”œβ”€β”€ fixtures.py + β”œβ”€β”€ requirements.txt + └── test_apiCompliance.py +``` + +### .github + +This folder contains github actions scripts. +These are configured to run on each pull-request. + +- [`code-quality.yml`](.github/workflows/code-quality.yml): Runs pylint +and black linters. +- [`test.yml`](.github/workflows/test.yml): Installs the manager and +invokes pytest. +- [`build-wheels.yml`](.github/workflows/build-wheels.yml): When a new +commit is pushed to main, builds wheels for distribution. +- [`deploy-pypi.yml`](.github/workflows/deploy-pypi.yml): When a new +release is made, deploys wheels to PyPI. + +### plugin + +Source directory for the asset manager + +- [`MyAssetManagerInterface.py`](plugin/my_asset_manager/MyAssetManagerInterface.py): +Manager interface implementation. Implements methods such as `resolve` +from the `OpenAssetIO` manager interface. This is the place to go to +start implementing your manager logic. +- [`__init__.py`](plugin/my_asset_manager/__init__.py) The manager +module itself. Boilerplate responsible for exposing the asset manager +interface and manager identifier to `OpenAssetIO` + +### pyproject.toml + +Python project configuration. Allows the manager to be `pip install`'ed, +as well as setting linter configuration settings. + +### tests + +Test directory, assumes a `pytest` testing environment. Uses the +[OpenAssetIO test +harness](https://openassetio.github.io/OpenAssetIO/testing.html#testing_manager_plugins) +to run apiCompliance checks, as well as business logic tests. + +- [`business_logic_suite.py`](test/business_logic_suite.py): Tests for +the behaviour of the manager. Does it resolve assets correctly, etc. +Invoked from `tests.py` +- [`conftest.py`](test/conftest.py): Pytest fixtures necessary for + running the tests. +- [`fixtures.py`](test/fixtures.py): Data concerning the manager +necessary to run the test harness. See [the +documentation.](https://openassetio.github.io/OpenAssetIO/testing.html#testing_manager_plugins_fixtures) +- [`requirements.txt`](test/requirements.txt): Requirements necessary to +run the tests. Generally installed with `python -m pip install -r +tests/requirements.txt` from the root directory. +- [`tests.py`](test/tests.py): Main test entry point. Executes the + manager `business_logic_suite`, as well as [OpenAssetIOs + apiComplianceSuite.](https://github.com/OpenAssetIO/OpenAssetIO/blob/main/src/openassetio-python/package/openassetio/test/manager/apiComplianceSuite.py) + +### Releases + +The repository is setup to use the [OpenAssetIO release process](https://github.com/OpenAssetIO/OpenAssetIO/blob/main/doc/contributing/PROCESS.md#release-process.) + +Note that for the PyPI deploy to work correctly, you will have to create +a project on testPyPI and PyPI, and then add `TEST_PYPI_ACCESS_TOKEN` +and `PYPI_ACCESS_TOKEN` to the repository as secrets. As each release +is unique, the project does not come pre configured with these access +tokens. diff --git a/plugin/my_asset_manager/MyAssetManagerInterface.py b/plugin/my_asset_manager/MyAssetManagerInterface.py new file mode 100644 index 0000000..e25efba --- /dev/null +++ b/plugin/my_asset_manager/MyAssetManagerInterface.py @@ -0,0 +1,187 @@ +# pylint: disable=invalid-name +""" +A single-class module, providing the MyAssetManagerInterface class. +This is the entry-point for the logic of your asset manager. +""" + +# Note that it should always be light-weight to construct instances of +# the this class. See the notes under the "Initialization" section of: +# https://openassetio.github.io/OpenAssetIO/classopenassetio_1_1v1_1_1manager_api_1_1_manager_interface.html#details (pylint: disable=line-too-long) +# As such, any expensive module imports should be deferred. +from openassetio import constants, BatchElementError, TraitsData +from openassetio.managerApi import ManagerInterface +from openassetio_mediacreation.traits.content import LocatableContentTrait +from openassetio_mediacreation.traits.managementPolicy import ManagedTrait + +# OpenAssetIO is building out the implementation vertically, there are +# known fails for missing abstract methods. +# pylint: disable=abstract-method +# Methods in C++ end up with "missing docstring" +# pylint: disable=missing-docstring +# pylint: disable=too-many-arguments, unused-argument + + +class MyAssetManagerInterface(ManagerInterface): + """ + Implement the OpenAssetIO ManagerInterface. + https://openassetio.github.io/OpenAssetIO/classopenassetio_1_1manager_api_1_1_manager_interface_1_1_manager_interface.html + """ + + # Entity references provided to this asset manager should be + # prefixed with this string to be considered valid. + # eg. "my_asset_manager:///my_entity_id" + __reference_prefix = "my_asset_manager:///" + + def identifier(self): + return "myorg.manager.my_asset_manager" + + def initialize(self, managerSettings, hostSession): + # Do any necessary heavy initialization here, allowing for the + # manager to be constructed quickly in situations where full + # initialization would be unnecessary and undesirable. See : + # https://openassetio.github.io/OpenAssetIO/classopenassetio_1_1v1_1_1host_api_1_1_manager.html#aa52c7436ff63ae96e33d7db8d6fd38df + print(managerSettings) + if managerSettings != {}: + raise KeyError( + "MyAssetManager should take no settings, but managerSettings is not empty" + ) + + def displayName(self): + return "My Asset Manager" + + def info(self): + # This hint allows the API middleware to short-circuit calls to + # `isEntityReferenceString` using string prefix comparisons. If + # your implementation's entity reference format supports this + # kind of matching, you should set this key. It allows for + # multi-threaded reference testing in C++ as it avoids the need + # to acquire the GIL and enter Python. + return {constants.kField_EntityReferencesMatchPrefix: self.__reference_prefix} + + def managementPolicy(self, traitSets, context, hostSession): + # The management policy defines which traits the manager is + # capable of imbuing queried traitSets with. In this case, we + # manage locations of assets only, and only in a read, not a + # write, context. Note `LocatableContentTrait` is a trait from + # the openassetio-mediacreation library, see : + # https://github.com/OpenAssetIO/OpenAssetIO-MediaCreation + policies = [] + for traitSet in traitSets: + policy = TraitsData() + # The host asks specifically if a sets of traits are + # supported In this case, if any of the input traitSets are + # for read, and contain LocatableContent, as we can supply + # data for that trait, we imbue a managed policy response, + # as well as the traits we are able to supply data for. It's + # important to get this right, for more info, see: + # https://openassetio.github.io/OpenAssetIO/classopenassetio_1_1v1_1_1host_api_1_1_manager.html#acdf7d0c3cef98cce7abaf8fb5f004354 + if context.isForRead() and LocatableContentTrait.kId in traitSet: + ManagedTrait.imbueTo(policy) + LocatableContentTrait.imbueTo(policy) + + policies.append(policy) + + return policies + + def isEntityReferenceString(self, someString, hostSession): + # This function is used by the host to determine if an entity + # reference is recognized as one handled by this manager. + # + # This should be a lightweight, textual sort of comparison, + # don't make backend calls here. + # + # If this function returns false for a string, your manager will + # not be invoked any further for that string. + # + # The recommended way to do this is to use a prefix, as that + # allows OpenAssetIO some room to perform optimizations. See + # info() + return someString.startswith(self.__reference_prefix) + + def resolve( + self, entityReferences, traitSet, context, hostSession, successCallback, errorCallback + ): + # If your resolver doesn't support write, like this one, reject + # a write context via calling the error callback. + if context.isForWrite(): + result = BatchElementError( + BatchElementError.ErrorCode.kEntityAccessError, "Entities are read-only" + ) + for idx in range(len(entityReferences)): + errorCallback(idx, result) + return + + # If the requested traitSet (which is constant for the batch), + # doesn't contain LocatableContent trait ID, there is no need to + # do any further processing, early out. + if LocatableContentTrait.kId not in traitSet: + for idx in range(len(entityReferences)): + successCallback(idx, TraitsData()) + return + + # You should attempt to retrieve your data at this point, + # especially if your backend supports batch operations. It's + # likely that there will be many entityReferences, and avoiding + # costly call-outs inside the loop below will be advantageous. + # + # For the purposes of this template, we use this fake map + # of LocatableContent paths to serve as our "database". + # Replace this with querying your backend systems. + managed_filesystem_locations = { + "my_asset_manager:///anAsset": "file:///some/filesystem/path", + "my_asset_manager:///anAsset2": "file:///some/filesystem/path2", + "my_asset_manager:///anAsset3": "file:///some/filesystem/path3", + } + + # Iterate over all the entity references, calling the correct + # error/success callbacks into the host. + # You should handle success/failure on an entity-by-entity + # basis, do not abort your entire resolve because any single + # entity is malformed/can't be processed for any reason, use + # the error callback and continue. + for idx, ref in enumerate(entityReferences): + # It may be that one of the references you are provided is + # recognized for this manager, but has some syntax error or + # is otherwise incorrect for your specific resolve context. + # For example, an asset reference that specifies a version + # for an un-versioned entity could be considered malformed. + # + # N.B. It's not required to perform an explicit check here + # if this is naturally serviced during your backend lookup, + # the key is not to error the whole batch, but use the error + # callback for relevant references. + identifier_is_malformed = is_malformed_ref(ref) + if identifier_is_malformed: + error_result = BatchElementError( + BatchElementError.ErrorCode.kMalformedEntityReference, + "Entity identifier is malformed", + ) + errorCallback(idx, error_result) + else: + # If our manager has the asset in question, we can + # let the host know about the LocatableContent for + # this specific entity. + if ref.toString() in managed_filesystem_locations: + success_result = TraitsData() + trait = LocatableContentTrait(success_result) + trait.setLocation(managed_filesystem_locations[ref.toString()]) + successCallback(idx, success_result) + else: + # Otherwise, we haven't got the entity available for + # resolution, to call the error callback with an + # entity resolution error for this specific entity. + error_result = BatchElementError( + BatchElementError.ErrorCode.kEntityResolutionError, + f"Entity '{ref.toString()}' not found", + ) + errorCallback(idx, error_result) + + +# Internal function used in Resolve, replace with logic based on what a +# malformed ref means in your backend. For the demonstrative purposes of +# this template, we pretend to support query parameters, then invent a +# completely arbitrary query parameter that we don't support. (We then +# test our implementation using the api compliance suite, see +# fixtures.py) +def is_malformed_ref(entityReference): + return "?unsupportedQueryParam" in entityReference.toString() diff --git a/plugin/my_asset_manager/__init__.py b/plugin/my_asset_manager/__init__.py new file mode 100644 index 0000000..b0b9a1e --- /dev/null +++ b/plugin/my_asset_manager/__init__.py @@ -0,0 +1,44 @@ +""" +Module Documentation for MyAssetManager here. +""" + +# pylint: disable=import-outside-toplevel +# +# It is important to minimise imports here. This module will be loaded +# when the plugin system scans for plugins. Postpone importing any +# of the actual implementation until it is needed by the +# PythonPluginSystemManagerPlugin's implementation. + +from openassetio.pluginSystem import PythonPluginSystemManagerPlugin + + +class MyAssetManagerPlugin(PythonPluginSystemManagerPlugin): + """ + The PythonPluginSystemManagerPlugin is responsible for constructing + instances of the manager's implementation of the OpenAssetIO + interfaces and returning them to the host. + """ + + @staticmethod + def identifier(): + # The identifier here _must_ be the same as the one returned by + # the interface implementation for it's `identifier` method. + return "myorg.manager.my_asset_manager" + + @classmethod + def interface(cls): + from .MyAssetManagerInterface import MyAssetManagerInterface + + # Note that it should always be light-weight to construct + # instances of the ManagerInterface class. See the notes under + # the "Initialization" section of: + # https://openassetio.github.io/OpenAssetIO/classopenassetio_1_1v1_1_1manager_api_1_1_manager_interface.html#details (pylint: disable=line-too-long) + return MyAssetManagerInterface() + + +# Set the plugin class as the public entrypoint for the plugin system. +# A plugin is only considered if it exposes a `plugin` variable at this +# level, holding a class derived from PythonPluginSystemManagerPlugin. + +# pylint: disable=invalid-name +plugin = MyAssetManagerPlugin diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..78f97b1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,44 @@ +[project] +name = "my_asset_manager" +version = "1.0.0" +requires-python = ">=3.7" +dependencies = [ + "openassetio == 1.0.0a9", + "openassetio-mediacreation == 1.0.0a3" +] + +authors = [ + { name = "MyName", email = "myemail@myserver.com" } +] + +description = """\ +An openassetio compliant asset manager implemented in python\ +""" +keywords = ["openassetio", "manager"] +readme = "README.md" + + +# Defines a Python entry point that exposes the plugin's package to +# allow entry point based discovery. +[project.entry-points."openassetio.manager_plugin"] +plugin_package_or_module = "my_asset_manager" + +[build-system] +requires = [ + "setuptools>=65.5.0" +] +build-backend = "setuptools.build_meta" + +[tool.setuptools.packages.find] +where =["plugin"] + +[tool.pylint.format] +max-line-length = 99 + +[tool.black] +line-length = 99 + +# NB: This requires the use of pyproject-flake8 +[tool.flake8] +max-line-length = 99 +extend-ignore = "E266," \ No newline at end of file diff --git a/tests/business_logic_suite.py b/tests/business_logic_suite.py new file mode 100644 index 0000000..a748efe --- /dev/null +++ b/tests/business_logic_suite.py @@ -0,0 +1,54 @@ +""" +A manager test harness test case suite that validates that +MyAssetManager behaves with the correct business logic. +""" + +# pylint: disable=invalid-name, missing-function-docstring, missing-class-docstring + +from openassetio import Context +from openassetio.test.manager.harness import FixtureAugmentedTestCase +from openassetio_mediacreation.traits.content import LocatableContentTrait + + +class Test_resolve(FixtureAugmentedTestCase): + """ + Test suite for the business logic of MyAssetManager + + The test here is illustrative only, you should extend this suite + to provide full coverage of all of the behaviour of your asset + manager. + """ + + __test_entity = ( + "my_asset_manager:///anAsset", + { + LocatableContentTrait.kId: {"location": "file:///some/filesystem/path"}, + }, + ) + + def test_when_refs_found_then_success_callback_called_with_expected_values(self): + ref_str = self.__test_entity[0] + entity_reference = self._manager.createEntityReference(ref_str) + + trait_set = {LocatableContentTrait.kId} + context = self.createTestContext(access=Context.Access.kRead) + + result = [None] + + def success_cb(idx, traits_data): + result[0] = traits_data + + def error_cb(idx, batchElementError): + self.fail( + f"Unexpected error for '{entity_reference.toString()}':" + f" {batchElementError.message}" + ) + + self._manager.resolve([entity_reference], trait_set, context, success_cb, error_cb) + + self.assertTrue(len(result) == 1) + # Check all traits are present, and their properties. + for trait in self.__test_entity[1]: + self.assertTrue(result[0].hasTrait(trait)) + for property_, value in self.__test_entity[1][trait].items(): + self.assertEqual(result[0].getTraitProperty(trait, property_), value) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..fc3a181 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,30 @@ +""" +Shared fixtures for MyAssetManager pytest coverage. +""" + +# pylint: disable=invalid-name,redefined-outer-name +# pylint: disable=missing-class-docstring,missing-function-docstring + +import os +import pytest + +from openassetio.test.manager import harness + + +@pytest.fixture +def harness_fixtures(base_dir): + """ + Provides the fixtues dict for MyAssetManager when used with + the openassetio.test.manager.apiComplianceSuite. + """ + fixtures_path = os.path.join(base_dir, "tests", "fixtures.py") + return harness.fixturesFromPyFile(fixtures_path) + + +@pytest.fixture +def base_dir(): + """ + Provides the path to the base directory for the MyAssetManager + codebase. + """ + return os.path.dirname(os.path.dirname(__file__)) diff --git a/tests/fixtures.py b/tests/fixtures.py new file mode 100644 index 0000000..7618b46 --- /dev/null +++ b/tests/fixtures.py @@ -0,0 +1,48 @@ +""" +Manager test harness test case fixtures for My Asset Manager. +""" +from openassetio.constants import kField_EntityReferencesMatchPrefix +from openassetio_mediacreation.traits.content import LocatableContentTrait + + +IDENTIFIER = "myorg.manager.my_asset_manager" + +VALID_REF = "my_asset_manager:///AssetIdentifier" +NON_REF = "not a Ε”eference" +MALFORMED_REF = "my_asset_manager:///AssetIdentifier?unsupportedQueryParam" +EXISTING_REF = "my_asset_manager:///anAsset" + +# This dictionary serves as expected outputs for the OpenAssetIO api +# compliance suite. This suite tests that your implementation functions +# as expected as far as integrating structurally into OpenAssetIO is +# concerned, (eg, are the correct callbacks being called, are errors +# being emitted when they should be, etc.) +fixtures = { + "identifier": IDENTIFIER, + "shared": { + "a_valid_reference": VALID_REF, + "an_invalid_reference": NON_REF, + "a_malformed_reference": MALFORMED_REF, + }, + "Test_identifier": {"test_matches_fixture": {"identifier": IDENTIFIER}}, + "Test_displayName": {"test_matches_fixture": {"display_name": "My Asset Manager"}}, + "Test_info": { + "test_matches_fixture": { + "info": {kField_EntityReferencesMatchPrefix: "my_asset_manager:///"} + } + }, + "Test_resolve": { + "shared": { + "a_reference_to_a_readable_entity": EXISTING_REF, + "a_set_of_valid_traits": {LocatableContentTrait.kId}, + "a_reference_to_a_readonly_entity": EXISTING_REF, + "the_error_string_for_a_reference_to_a_readonly_entity": "Entities are read-only", + "a_reference_to_a_missing_entity": "my_asset_manager:///missing_entity", + "the_error_string_for_a_reference_to_a_missing_entity": ( + "Entity 'my_asset_manager:///missing_entity' not found" + ), + "a_malformed_reference": MALFORMED_REF, + "the_error_string_for_a_malformed_reference": "Entity identifier is malformed", + } + }, +} diff --git a/tests/requirements.txt b/tests/requirements.txt new file mode 100644 index 0000000..da7e766 --- /dev/null +++ b/tests/requirements.txt @@ -0,0 +1,3 @@ +black==22.10.0 +pylint==2.15.5 +pytest==6.2.4 \ No newline at end of file diff --git a/tests/test_manager.py b/tests/test_manager.py new file mode 100644 index 0000000..81c7d9b --- /dev/null +++ b/tests/test_manager.py @@ -0,0 +1,59 @@ +""" +Test cases for MyAssetManager that make use of the OpenAssetIO +manager test harness. +Note that this file simply wraps the openassetio.test.manager harness in +a pytest test, so that it can be run as part of the project test suite. +It also serves as an example of how to programmatically execute the test +harness, by extending it with additional checks for MyAssetManagers +specific business logic. +It is not required in order to make use of the test harness. The base +API compliance tests can simply be run from a command line with +openassetio available, and the target plugin on +$OPENASSETIO_PLUGIN_PATH: + python -m openassetio.test.manager -f path/to/fixtures.py +""" + +import os +import pytest + +# pylint: disable=invalid-name,redefined-outer-name +# pylint: disable=missing-class-docstring,missing-function-docstring + +from openassetio.test.manager import harness, apiComplianceSuite +from openassetio.pluginSystem import PythonPluginSystemManagerPlugin + + +# +# Tests +# + +# MyAssetManager exposes an entry point, so can be pip installed without +# need to extend OPENASSETIO_PLUGIN_PATH. +# Tests should be invoked from an install +# +# python -m pip install . +# python -m pip install -r tests/requirements.txt +# python -m pytest tests + + +class Test_MyAssetManager: + def test_passes_apiComplianceSuite(self, harness_fixtures): + assert harness.executeSuite(apiComplianceSuite, harness_fixtures) + + def test_passes_my_asset_manager_business_logic_suite( + self, my_asset_manager_business_logic_suite, harness_fixtures + ): + assert harness.executeSuite(my_asset_manager_business_logic_suite, harness_fixtures) + + +class Test_MyAssetManager_Plugin: # pylint: disable=too-few-public-methods + def test_exposes_plugin_attribute_with_correct_type(self): + import my_asset_manager # pylint: disable=import-outside-toplevel + + assert issubclass(my_asset_manager.plugin, PythonPluginSystemManagerPlugin) + + +@pytest.fixture +def my_asset_manager_business_logic_suite(base_dir): + module_path = os.path.join(base_dir, "tests", "business_logic_suite.py") + return harness.moduleFromFile(module_path)