diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5e06a538..9c2f5caa 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -190,8 +190,6 @@ jobs: strategy: matrix: binary: - - name: vuforia-cloud-reco-linux - spec: bin/vuforia-cloud-reco.py - name: vws-linux spec: bin/vuforia-web-services.py - name: vumark-linux @@ -343,17 +341,6 @@ jobs: shell: bash run: echo "vws-cli==$NEW_TAG" > requirements.txt - - name: Create Windows binary for Vuforia Cloud Reco - uses: sayyid5416/pyinstaller@v1 - with: - python_ver: '3.14' - pyinstaller_ver: ==6.22.1 - spec: bin/vuforia-cloud-reco.py - requirements: requirements.txt - options: --onefile, --name "vuforia-cloud-reco-windows" - upload_exe_with_name: vuforia-cloud-reco-windows - clean_checkout: false - - name: Create Windows binary for Vuforia Web Services uses: sayyid5416/pyinstaller@v1 with: @@ -383,7 +370,6 @@ jobs: shell: bash run: |- gh release upload "$NEW_TAG" dist/vws-windows.exe --clobber - gh release upload "$NEW_TAG" dist/vuforia-cloud-reco-windows.exe --clobber gh release upload "$NEW_TAG" dist/vumark-windows.exe --clobber build-macos: @@ -423,17 +409,6 @@ jobs: NEW_TAG: ${{ needs.build.outputs.new_tag }} run: echo "vws-cli==$NEW_TAG" > requirements.txt - - name: Create macOS binary for Vuforia Cloud Reco - uses: sayyid5416/pyinstaller@v1 - with: - python_ver: '3.14' - pyinstaller_ver: ==6.22.1 - spec: bin/vuforia-cloud-reco.py - requirements: requirements.txt - options: --onefile, --name "vuforia-cloud-reco-macos" - upload_exe_with_name: vuforia-cloud-reco-macos - clean_checkout: false - - name: Create macOS binary for Vuforia Web Services uses: sayyid5416/pyinstaller@v1 with: @@ -487,7 +462,7 @@ jobs: # prerequisites for notarization. The hardened runtime needs the # entitlements file to leave a ``--onefile`` binary runnable; see # the comments in that file. - for binary in vws-macos vuforia-cloud-reco-macos vumark-macos; do + for binary in vws-macos vumark-macos; do codesign \ --force \ --timestamp \ @@ -507,7 +482,6 @@ jobs: - name: Check the signed binaries still run run: | dist/vws-macos --version - dist/vuforia-cloud-reco-macos --version dist/vumark-macos --version # A notarization ticket cannot be stapled to a bare Mach-O @@ -558,7 +532,7 @@ jobs: max_attempts: 10 retry_wait_seconds: 30 command: | - for binary in vws-macos vuforia-cloud-reco-macos vumark-macos; do + for binary in vws-macos vumark-macos; do codesign -vvvv -R="notarized" --check-notarization "dist/${binary}" done @@ -568,7 +542,6 @@ jobs: NEW_TAG: ${{ needs.build.outputs.new_tag }} run: |- gh release upload "$NEW_TAG" dist/vws-macos --clobber - gh release upload "$NEW_TAG" dist/vuforia-cloud-reco-macos --clobber gh release upload "$NEW_TAG" dist/vumark-macos --clobber publish-to-winget: @@ -588,14 +561,6 @@ jobs: installers-regex: ^vws-windows\.exe$ token: ${{ secrets.WINGET_TOKEN }} - - uses: vedantmgoyal9/winget-releaser@v2 - with: - identifier: VWSPython.vuforia-cloud-reco - version: ${{ needs.build.outputs.new_tag }} - release-tag: ${{ needs.build.outputs.new_tag }} - installers-regex: ^vuforia-cloud-reco-windows\.exe$ - token: ${{ secrets.WINGET_TOKEN }} - - uses: vedantmgoyal9/winget-releaser@v2 with: identifier: VWSPython.vumark diff --git a/Dockerfile b/Dockerfile index f8ddc445..70242a87 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,5 +12,5 @@ COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/ # Install the package from PyPI with pinned version RUN uv pip install --system --no-cache "vws-cli==${VWS_CLI_VERSION}" -# Set up entrypoint - users can override with vuforia-cloud-reco +# Set up entrypoint - users can override with vumark ENTRYPOINT ["vws"] diff --git a/README.rst b/README.rst index 2e531d51..94aa8472 100644 --- a/README.rst +++ b/README.rst @@ -63,12 +63,6 @@ With Docker $ docker run --rm "ghcr.io/vws-python/vws-cli" --help -To use ``vuforia-cloud-reco``: - -.. code-block:: console - - $ docker run --rm --entrypoint vuforia-cloud-reco "ghcr.io/vws-python/vws-cli" --help - To use ``vumark``: .. code-block:: console @@ -83,7 +77,6 @@ Requires `winget`_. .. code-block:: console $ winget install --id VWSPython.vws-cli --source winget --exact - $ winget install --id VWSPython.vuforia-cloud-reco --source winget --exact .. _winget: https://docs.microsoft.com/windows/package-manager/winget/ @@ -101,7 +94,6 @@ Download the Windows executables from the `latest release`_ and place them in a The filenames are: * ``vws-windows.exe`` -* ``vuforia-cloud-reco-windows.exe`` * ``vumark-windows.exe`` .. _latest release: https://github.com/VWS-Python/vws-cli/releases/latest @@ -114,27 +106,10 @@ See the `full documentation`_ for details on how to install pre-built macOS bina Usage example ------------- -.. skip doccmd[shellcheck]: next - .. code-block:: console - $ vws add-target \ - --server-access-key "$SERVER_ACCESS_KEY" \ - --server-secret-key "$SERVER_SECRET_KEY" \ - --name my_image_name \ - --width 2 \ - --image ~/Documents/my_image.png \ - --application-metadata "$(echo 'my_metadata' | base64)" \ - --active-flag true - 03b99df0-78cf-4b01-b929-f1860d4f8ed1 $ vws --help - ... - $ vuforia-cloud-reco my_image.jpg \ - --max-num-results 5 \ - --include-target-data none - - target_id: b60f60121d37418eb1de123c381b2af9 - - target_id: e3a6e1a216ad4df3aaae1f6dd309c800 - $ + $ vumark --help Full documentation ------------------ diff --git a/bin/vuforia-cloud-reco.py b/bin/vuforia-cloud-reco.py deleted file mode 100755 index 22d5bce7..00000000 --- a/bin/vuforia-cloud-reco.py +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env python3 - -"""Run VWS Cloud Reco CLI.""" - -from vws_cli.query import vuforia_cloud_reco - -vuforia_cloud_reco() diff --git a/docs/source/commands.rst b/docs/source/commands.rst index 541407ee..1d3fdf5a 100644 --- a/docs/source/commands.rst +++ b/docs/source/commands.rst @@ -5,9 +5,5 @@ Commands :prog: vws :show-nested: -.. click:: vws_cli.query:vuforia_cloud_reco - :prog: vuforia-cloud-reco - :show-nested: - .. click:: vws_cli.vumark:generate_vumark :prog: vumark diff --git a/docs/source/install.rst b/docs/source/install.rst index 5669fc67..aadacadd 100644 --- a/docs/source/install.rst +++ b/docs/source/install.rst @@ -54,13 +54,6 @@ With Docker $ docker run --rm "|docker-image|" --help -To use ``vuforia-cloud-reco``: - -.. code-block:: console - :substitutions: - - $ docker run --rm --entrypoint vuforia-cloud-reco "|docker-image|" --help - To use ``vumark``: .. code-block:: console @@ -76,7 +69,6 @@ Requires winget_. .. code-block:: console $ winget install --id VWSPython.vws-cli --source winget --exact - $ winget install --id VWSPython.vuforia-cloud-reco --source winget --exact .. _winget: https://docs.microsoft.com/windows/package-manager/winget/ @@ -88,8 +80,6 @@ Pre-built Linux (x86) binaries $ curl --fail -L "https://github.com/|github-owner|/|github-repository|/releases/download/|release|/vws-linux" -o /usr/local/bin/vws && chmod +x /usr/local/bin/vws - $ curl --fail -L "https://github.com/|github-owner|/|github-repository|/releases/download/|release|/vuforia-cloud-reco-linux" -o /usr/local/bin/vuforia-cloud-reco && - chmod +x /usr/local/bin/vuforia-cloud-reco $ curl --fail -L "https://github.com/|github-owner|/|github-repository|/releases/download/|release|/vumark-linux" -o /usr/local/bin/vumark && chmod +x /usr/local/bin/vumark @@ -100,7 +90,6 @@ Download the Windows executables from the `latest release`_ and place them in a The filenames are: * ``vws-windows.exe`` -* ``vuforia-cloud-reco-windows.exe`` * ``vumark-windows.exe`` .. _latest release: https://github.com/VWS-Python/vws-cli/releases/latest @@ -113,8 +102,6 @@ Pre-built macOS (ARM) binaries $ curl --fail -L "https://github.com/|github-owner|/|github-repository|/releases/download/|release|/vws-macos" -o /usr/local/bin/vws && chmod +x /usr/local/bin/vws - $ curl --fail -L "https://github.com/|github-owner|/|github-repository|/releases/download/|release|/vuforia-cloud-reco-macos" -o /usr/local/bin/vuforia-cloud-reco && - chmod +x /usr/local/bin/vuforia-cloud-reco $ curl --fail -L "https://github.com/|github-owner|/|github-repository|/releases/download/|release|/vumark-macos" -o /usr/local/bin/vumark && chmod +x /usr/local/bin/vumark diff --git a/docs/source/release-process.rst b/docs/source/release-process.rst index c12556a7..ab695de8 100644 --- a/docs/source/release-process.rst +++ b/docs/source/release-process.rst @@ -9,7 +9,7 @@ Outcomes * A new Homebrew recipe available to install. * A new Docker image on GitHub Container Registry. * New binary assets attached to the GitHub release. -* New Winget packages available to install for ``vws``, ``vuforia-cloud-reco``, and ``vumark``. +* New Winget packages available to install for ``vws`` and ``vumark``. Repository secrets ~~~~~~~~~~~~~~~~~~ diff --git a/docs/source/usage-example.rst b/docs/source/usage-example.rst index 2f3dd790..c593cb63 100644 --- a/docs/source/usage-example.rst +++ b/docs/source/usage-example.rst @@ -1,30 +1,6 @@ Usage example ------------- -.. skip doccmd[shellcheck]: start - -.. code-block:: console - - $ vws add-target \ - --server-access-key "$SERVER_ACCESS_KEY" \ - --server-secret-key "$SERVER_SECRET_KEY" \ - --name my_image_name \ - --width 2 \ - --image ~/Documents/my_image.png \ - --application-metadata "$(echo 'my_metadata' | base64)" \ - --active-flag true - 03b99df0-78cf-4b01-b929-f1860d4f8ed1 - $ vws --help - ... - $ vuforia-cloud-reco my_image.jpg \ - --max-num-results 5 \ - --include-target-data none - - target_id: b60f60121d37418eb1de123c381b2af9 - - target_id: e3a6e1a216ad4df3aaae1f6dd309c800 - $ - -.. skip doccmd[shellcheck]: end - Model Target datasets ~~~~~~~~~~~~~~~~~~~~~ diff --git a/flake.nix b/flake.nix index fbc6c377..d1ba4074 100644 --- a/flake.nix +++ b/flake.nix @@ -102,10 +102,6 @@ type = "app"; program = "${self.packages.${system}.default}/bin/vws"; }; - vuforia-cloud-reco = { - type = "app"; - program = "${self.packages.${system}.default}/bin/vuforia-cloud-reco"; - }; }); devShells = forAllSystems ( diff --git a/newsfragments/2713.change.md b/newsfragments/2713.change.md new file mode 100644 index 00000000..a311470a --- /dev/null +++ b/newsfragments/2713.change.md @@ -0,0 +1,3 @@ +Remove cloud image target commands, the `vuforia-cloud-reco` entry point, and its standalone binaries, installers, and release automation. +The `vws` group now manages Model Target datasets. +`vumark` remains available for VuMark generation. diff --git a/pyproject.toml b/pyproject.toml index 22e03769..75b92f87 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,7 @@ requires = [ [project] name = "vws-cli" -description = "A CLI for the Vuforia Web Services (VWS) API." +description = "A CLI for Vuforia Model Targets and VuMark generation." readme = { file = "README.rst", content-type = "text/x-rst" } keywords = [ "cli", @@ -39,7 +39,6 @@ dependencies = [ ] urls.Documentation = "https://vws-python.github.io/vws-cli/" urls.Source = "https://github.com/VWS-Python/vws-cli" -scripts.vuforia-cloud-reco = "vws_cli.query:vuforia_cloud_reco" scripts.vumark = "vws_cli.vumark:generate_vumark" scripts.vws = "vws_cli:vws_group" @@ -97,7 +96,6 @@ dev = [ "vale==3.25.1.0", "vulture==2.16", "vws-python-mock==2026.10.13.1", - "vws-test-fixtures==2026.10.8", "yamlfix==1.19.1", "zizmor==1.31.1", ] diff --git a/src/vws_cli/__init__.py b/src/vws_cli/__init__.py index 8395e7b0..9bde30e4 100644 --- a/src/vws_cli/__init__.py +++ b/src/vws_cli/__init__.py @@ -5,18 +5,6 @@ import click from beartype import beartype -from vws_cli.commands import ( - add_target, - delete_target, - get_database_reco_counts_report, - get_database_summary_report, - get_duplicate_targets, - get_target_record, - get_target_summary_report, - list_targets, - update_target, - wait_for_target_processed, -) from vws_cli.model_target import ( create_model_target_dataset, delete_model_target_dataset, @@ -46,21 +34,11 @@ @click.version_option(version=__version__) @beartype def vws_group() -> None: - """Manage a Vuforia Web Services cloud database.""" + """Manage Vuforia Model Target datasets.""" -vws_group.add_command(cmd=add_target) vws_group.add_command(cmd=create_model_target_dataset) vws_group.add_command(cmd=delete_model_target_dataset) -vws_group.add_command(cmd=delete_target) vws_group.add_command(cmd=download_model_target_dataset) -vws_group.add_command(cmd=get_database_reco_counts_report) -vws_group.add_command(cmd=get_database_summary_report) -vws_group.add_command(cmd=get_duplicate_targets) vws_group.add_command(cmd=get_model_target_dataset_status) -vws_group.add_command(cmd=get_target_record) -vws_group.add_command(cmd=get_target_summary_report) -vws_group.add_command(cmd=list_targets) -vws_group.add_command(cmd=update_target) vws_group.add_command(cmd=wait_for_model_target_dataset_generated) -vws_group.add_command(cmd=wait_for_target_processed) diff --git a/src/vws_cli/_error_handling.py b/src/vws_cli/_error_handling.py index 40adca3b..c32631bb 100644 --- a/src/vws_cli/_error_handling.py +++ b/src/vws_cli/_error_handling.py @@ -2,10 +2,7 @@ from beartype import beartype from vws.exceptions.custom_exceptions import ( - RecoCountsReportDownloadError, - RecoCountsReportTimeoutError, ServerError, - TargetProcessingTimeoutError, ) from vws.exceptions.model_target_exceptions import ( ModelTargetAuthenticationError, @@ -18,25 +15,16 @@ from vws.exceptions.vws_exceptions import ( AuthenticationFailureError, AuthorizationFailedError, - BadImageError, - DateRangeError, FailError, - ImageTooLargeError, InvalidTargetTypeError, LicenseCheckFailedError, - MetadataTooLargeError, ProjectHasNoAPIAccessError, ProjectInactiveError, ProjectSuspendedError, QuotaExceededError, RequestQuotaReachedError, RequestTimeTooSkewedError, - TargetNameExistError, - TargetQuotaReachedError, - TargetStatusNotSuccessError, - TargetStatusProcessingError, TooManyRequestsError, - UnknownTargetError, ) @@ -46,49 +34,23 @@ def get_error_message(exc: Exception) -> str: exc_type_to_message: dict[type[Exception], str] = { AuthenticationFailureError: "The given secret key was incorrect.", AuthorizationFailedError: "Error: The request was not authorized.", - BadImageError: "Error: The given image is corrupted or the format is not supported.", - DateRangeError: "Error: There was a problem with the date details given in the request.", FailError: "Error: The request made to Vuforia was invalid and could not be processed. Check the given parameters.", - ImageTooLargeError: "Error: The given image is too large.", InvalidTargetTypeError: "Error: The target type is invalid.", LicenseCheckFailedError: "Error: The Vuforia license check failed.", - MetadataTooLargeError: "Error: The given metadata is too large.", - RecoCountsReportDownloadError: "Error: The recognition counts report could not be downloaded. This may be because the report's URL has expired.", - RecoCountsReportTimeoutError: "Error: The recognition counts report was not generated within the allowed limit.", ServerError: "Error: There was an unknown error from Vuforia. This may be because there is a problem with the given name.", ProjectInactiveError: "Error: The project associated with the given keys is inactive.", QuotaExceededError: "Error: The request quota has been exceeded.", RequestQuotaReachedError: "Error: The maximum number of API calls for this database has been reached.", RequestTimeTooSkewedError: "Error: Vuforia reported that the time given with this request was outside the expected range. This may be because the system clock is out of sync.", - TargetProcessingTimeoutError: "Error: The target processing time has exceeded the allowed limit.", - TargetQuotaReachedError: "Error: The maximum number of targets for this database has been reached.", TooManyRequestsError: "Error: Too many requests were made to Vuforia. Try again later.", ProjectSuspendedError: "Error: The request could not be completed because this database has been suspended.", ProjectHasNoAPIAccessError: "Error: The request could not be completed because this database is not allowed to make API requests.", } - match exc: - case UnknownTargetError(): - return f'Error: Target "{exc.target_id}" does not exist.' - case TargetNameExistError(): - return ( - f'Error: There is already a target named "{exc.target_name}".' - ) - case TargetStatusNotSuccessError(): - return ( - f'Error: The target "{exc.target_id}" cannot be updated as it is ' - "not in the success state." - ) - case TargetStatusProcessingError(): - return ( - f'Error: The target "{exc.target_id}" cannot be deleted as it is ' - "in the processing state." - ) - case _: - return exc_type_to_message.get( - type(exc), - "Error: Vuforia returned an unrecognized error.", - ) + return exc_type_to_message.get( + type(exc), + "Error: Vuforia returned an unrecognized error.", + ) @beartype diff --git a/src/vws_cli/commands.py b/src/vws_cli/commands.py deleted file mode 100644 index 42f8af5b..00000000 --- a/src/vws_cli/commands.py +++ /dev/null @@ -1,650 +0,0 @@ -"""``click`` commands the VWS CLI.""" - -import calendar -import contextlib -import dataclasses -import datetime as dt -import io -import sys -from collections.abc import Generator -from pathlib import Path -from zoneinfo import ZoneInfo - -import click -import yaml -from beartype import beartype -from vws import VWS -from vws.exceptions.base_exceptions import VWSError -from vws.exceptions.custom_exceptions import ( - RecoCountsReportDownloadError, - RecoCountsReportTimeoutError, - ServerError, - TargetProcessingTimeoutError, -) - -from vws_cli._error_handling import get_error_message -from vws_cli.options.credentials import ( - server_access_key_option, - server_secret_key_option, -) -from vws_cli.options.targets import ( - ActiveFlagChoice, - active_flag_option, - application_metadata_option, - target_id_option, - target_image_option, - target_name_option, - target_width_option, -) -from vws_cli.options.timeout import ( - connection_timeout_seconds_option, - read_timeout_seconds_option, -) -from vws_cli.options.vws import base_vws_url_option, database_id_option - - -@beartype -@contextlib.contextmanager -def _handle_vws_exceptions() -> Generator[None]: - """Show error messages and catch exceptions from ``VWS-Python``.""" - error_message = "" - error_stream = sys.stderr - - try: - yield - except ( - VWSError, - RecoCountsReportDownloadError, - RecoCountsReportTimeoutError, - ServerError, - TargetProcessingTimeoutError, - ) as exc: - error_message = get_error_message(exc=exc) - else: - return - - click.echo(message=error_message, file=error_stream) - sys.exit(1) - - -@click.command(name="get-target-record") -@server_access_key_option -@server_secret_key_option -@target_id_option -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@_handle_vws_exceptions() -@beartype -def get_target_record( - *, - server_access_key: str, - server_secret_key: str, - target_id: str, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, -) -> None: - """Get a target record. - - \b - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#target-record. - """ - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - record = vws_client.get_target_record(target_id=target_id).target_record - - yaml_record = yaml.dump(data=dataclasses.asdict(obj=record)) - click.echo(message=yaml_record) - - -@click.command(name="list-targets") -@server_access_key_option -@server_secret_key_option -@_handle_vws_exceptions() -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@beartype -def list_targets( - *, - server_access_key: str, - server_secret_key: str, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, -) -> None: - """List targets. - - \b - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#details-list. - """ - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - targets = vws_client.list_targets() - yaml_list = yaml.dump(data=targets) - click.echo(message=yaml_list) - - -@click.command(name="get-duplicate-targets") -@server_access_key_option -@server_secret_key_option -@target_id_option -@_handle_vws_exceptions() -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@beartype -def get_duplicate_targets( - *, - server_access_key: str, - server_secret_key: str, - target_id: str, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, -) -> None: - """Get a list of potential duplicate targets. - - \b - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#check. - """ - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - record = vws_client.get_duplicate_targets(target_id=target_id) - - yaml_record = yaml.dump(data=record) - click.echo(message=yaml_record) - - -@click.command(name="get-database-summary-report") -@server_access_key_option -@server_secret_key_option -@_handle_vws_exceptions() -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@beartype -def get_database_summary_report( - *, - server_access_key: str, - server_secret_key: str, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, -) -> None: - """Get a database summary report. - - \b - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#summary-report. - """ - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - report = vws_client.get_database_summary_report() - yaml_report = yaml.dump(data=dataclasses.asdict(obj=report)) - click.echo(message=yaml_report) - - -@click.command(name="get-target-summary-report") -@server_access_key_option -@server_secret_key_option -@target_id_option -@_handle_vws_exceptions() -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@beartype -def get_target_summary_report( - *, - server_access_key: str, - server_secret_key: str, - target_id: str, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, -) -> None: - """Get a target summary report. - - \b - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#retrieve-report. - """ - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - report = vws_client.get_target_summary_report(target_id=target_id) - report_dict = dataclasses.asdict(obj=report) - report_dict["status"] = report.status.value - report_dict["upload_date"] = str(object=report.upload_date) - yaml_summary_report = yaml.dump(data=report_dict) - click.echo(message=yaml_summary_report) - - -@click.command(name="delete-target") -@server_access_key_option -@server_secret_key_option -@target_id_option -@_handle_vws_exceptions() -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@beartype -def delete_target( - *, - server_access_key: str, - server_secret_key: str, - target_id: str, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, -) -> None: - """Delete a target. - - \b - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#delete. - """ - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - - vws_client.delete_target(target_id=target_id) - - -@click.command(name="add-target") -@target_width_option(required=True) -@application_metadata_option -@server_access_key_option -@server_secret_key_option -@target_name_option(required=True) -@target_image_option(required=True) -@active_flag_option(allow_none=False) -@_handle_vws_exceptions() -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@beartype -def add_target( - *, - server_access_key: str, - server_secret_key: str, - name: str, - width: float, - image_file_path: Path, - active_flag_choice: ActiveFlagChoice, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, - application_metadata: str | None = None, -) -> None: - """Add a target. - - \b - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#add - """ - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - - image_bytes = image_file_path.read_bytes() - image = io.BytesIO(initial_bytes=image_bytes) - - active_flag = { - ActiveFlagChoice.TRUE: True, - ActiveFlagChoice.FALSE: False, - }[active_flag_choice] - - target_id = vws_client.add_target( - name=name, - width=width, - image=image, - active_flag=active_flag, - application_metadata=application_metadata, - ) - - click.echo(message=target_id) - - -@click.command(name="update-target") -@target_width_option(required=False) -@application_metadata_option -@server_access_key_option -@server_secret_key_option -@target_name_option(required=False) -@target_image_option(required=False) -@active_flag_option(allow_none=True) -@target_id_option -@_handle_vws_exceptions() -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@beartype -def update_target( - *, - server_access_key: str, - server_secret_key: str, - target_id: str, - image_file_path: Path | None, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, - name: str | None = None, - application_metadata: str | None = None, - active_flag_choice: ActiveFlagChoice | None = None, - width: float | None = None, -) -> None: - """Update a target. - - \b - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#update - """ - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - - if image_file_path is None: - image = None - else: - image_bytes = image_file_path.read_bytes() - image = io.BytesIO(initial_bytes=image_bytes) - - active_flag = { - ActiveFlagChoice.TRUE: True, - ActiveFlagChoice.FALSE: False, - None: None, - }[active_flag_choice] - - vws_client.update_target( - name=name, - target_id=target_id, - image=image, - application_metadata=application_metadata, - active_flag=active_flag, - width=width, - ) - - -_SECONDS_BETWEEN_REQUESTS_DEFAULT = 0.2 - -_SECONDS_BETWEEN_REQUESTS_HELP = ( - "The number of seconds to wait between requests made while polling the " - "target status. " - f"We wait {_SECONDS_BETWEEN_REQUESTS_DEFAULT} seconds by default, rather " - "than less, than that to decrease the number of calls made to the API, to " - "decrease the likelihood of hitting the request quota." -) - -_TIMEOUT_SECONDS_HELP = ( - "The maximum number of seconds to wait for the target to be processed." -) - - -@click.command(name="wait-for-target-processed") -@click.option( - "--seconds-between-requests", - type=click.FloatRange(min=0.05), - default=_SECONDS_BETWEEN_REQUESTS_DEFAULT, - help=_SECONDS_BETWEEN_REQUESTS_HELP, - show_default=True, -) -@click.option( - "--timeout-seconds", - type=click.FloatRange(min=0.05), - default=300, - help=_TIMEOUT_SECONDS_HELP, - show_default=True, -) -@server_access_key_option -@server_secret_key_option -@target_id_option -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@_handle_vws_exceptions() -@beartype -def wait_for_target_processed( - *, - server_access_key: str, - server_secret_key: str, - target_id: str, - seconds_between_requests: float, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, - timeout_seconds: float, -) -> None: - """Wait for a target to be "processed". This is done by polling the VWS - API. - """ - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - - vws_client.wait_for_target_processed( - target_id=target_id, - seconds_between_requests=seconds_between_requests, - timeout_seconds=timeout_seconds, - ) - - -_MONTH_FORMAT = "%Y-%m" - -_REPORT_SECONDS_BETWEEN_REQUESTS_HELP = ( - "The number of seconds to wait between requests made while polling for " - "the report. " - f"We wait {_SECONDS_BETWEEN_REQUESTS_DEFAULT} seconds by default, rather " - "than less, than that to decrease the number of calls made to the API, to " - "decrease the likelihood of hitting the request quota." -) - -_REPORT_TIMEOUT_SECONDS_HELP = ( - "The maximum number of seconds to wait for the report to be generated." -) - - -@beartype -def _default_month() -> str: - """Return the current month, in the form which ``--month`` takes.""" - now = dt.datetime.now(tz=ZoneInfo(key="UTC")) - return now.strftime(format=_MONTH_FORMAT) - - -@beartype -def _validate_month( - ctx: click.Context, - param: click.Parameter, - value: str, -) -> dt.date: - """Turn a ``YYYY-mm`` string into the first day of that month.""" - # These are given by ``click``, and we do not use them. - del ctx - del param - try: - parsed = dt.date.fromisoformat(f"{value}-01") - except ValueError as exc: - message = f'"{value}" is not a month in the YYYY-mm form.' - raise click.BadParameter(message=message) from exc - return parsed - - -@click.command(name="get-database-reco-counts-report") -@click.option( - "--month", - type=str, - default=_default_month, - callback=_validate_month, - help=( - "The month to get recognition counts for, in the YYYY-mm form. " - "Vuforia accepts only the current month and the previous month." - ), - show_default="the current month", -) -@click.option( - "--output", - "output_file_path", - type=click.Path( - dir_okay=False, - writable=True, - path_type=Path, - ), - required=False, - help=( - "The path to write the CSV report to. By default, the report is " - "written to stdout." - ), -) -@click.option( - "--no-wait", - "no_wait", - is_flag=True, - default=False, - help=( - "Do not wait for the report to be generated. Instead, show the URL " - "to download the report from once it has been generated." - ), -) -@click.option( - "--seconds-between-requests", - type=click.FloatRange(min=0.05), - default=_SECONDS_BETWEEN_REQUESTS_DEFAULT, - help=_REPORT_SECONDS_BETWEEN_REQUESTS_HELP, - show_default=True, -) -@click.option( - "--timeout-seconds", - type=click.FloatRange(min=0.05), - default=300, - help=_REPORT_TIMEOUT_SECONDS_HELP, - show_default=True, -) -@server_access_key_option -@server_secret_key_option -@database_id_option -@base_vws_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@_handle_vws_exceptions() -@beartype -def get_database_reco_counts_report( - *, - server_access_key: str, - server_secret_key: str, - database_id: str, - month: dt.date, - output_file_path: Path | None, - no_wait: bool, - seconds_between_requests: float, - timeout_seconds: float, - base_vws_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, -) -> None: - """Get a per-target recognition counts report for a database. - - The report is a CSV with a ``target_id,reco_count`` header. Vuforia - generates the report in the background, so by default we wait for the - report to be generated before downloading it. - - \b - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api. - """ - if no_wait and output_file_path is not None: - message = "--output cannot be used with --no-wait." - raise click.UsageError(message=message) - - vws_client = VWS( - server_access_key=server_access_key, - server_secret_key=server_secret_key, - base_vws_url=base_vws_url, - database_id=database_id, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - - report_request = vws_client.request_database_reco_counts_report( - year=month.year, - month=calendar.Month(value=month.month), - ) - - if no_wait: - click.echo(message=report_request.presigned_url) - return - - report = vws_client.wait_for_reco_counts_report( - presigned_url=report_request.presigned_url, - seconds_between_requests=seconds_between_requests, - timeout_seconds=timeout_seconds, - ) - - if output_file_path is None: - click.echo(message=report.raw_csv, nl=False) - return - - _ = output_file_path.write_bytes(data=report.raw_csv) diff --git a/src/vws_cli/options/credentials.py b/src/vws_cli/options/credentials.py index 1424750d..eefe5446 100644 --- a/src/vws_cli/options/credentials.py +++ b/src/vws_cli/options/credentials.py @@ -40,39 +40,3 @@ def server_secret_key_option[**P, R]( envvar="VUFORIA_SERVER_SECRET_KEY", show_envvar=True, )(command) - - -@beartype -def client_access_key_option[**P, R]( - command: Callable[P, R], -) -> Callable[P, R]: - """An option decorator for the Vuforia client access key.""" - return click.option( - "--client-access-key", - type=str, - help=( - "A Vuforia client access key to use to access the Vuforia " - "Cloud Recognition API." - ), - required=True, - envvar="VUFORIA_CLIENT_ACCESS_KEY", - show_envvar=True, - )(command) - - -@beartype -def client_secret_key_option[**P, R]( - command: Callable[P, R], -) -> Callable[P, R]: - """An option decorator for the Vuforia client secret key.""" - return click.option( - "--client-secret-key", - type=str, - help=( - "A Vuforia client secret key to use to access the Vuforia " - "Cloud Recognition API." - ), - required=True, - envvar="VUFORIA_CLIENT_SECRET_KEY", - show_envvar=True, - )(command) diff --git a/src/vws_cli/options/targets.py b/src/vws_cli/options/targets.py index 39fdcf67..fc912cd8 100644 --- a/src/vws_cli/options/targets.py +++ b/src/vws_cli/options/targets.py @@ -1,10 +1,6 @@ """``click`` options regarding targets.""" -from enum import Enum, unique -from pathlib import Path - import click -from beartype import beartype from vws_cli.options._types import ClickOptionDecorator @@ -14,82 +10,3 @@ help="The ID of a target in the Vuforia database.", required=True, ) - - -@beartype -def target_name_option(*, required: bool) -> ClickOptionDecorator: - """An option decorator for choosing a target name.""" - return click.option( - "--name", - type=str, - help="The name of the target in the Vuforia database.", - required=required, - ) - - -@beartype -def target_width_option(*, required: bool) -> ClickOptionDecorator: - """An option decorator for choosing a target width.""" - option: ClickOptionDecorator = click.option( - "--width", - type=float, - help="The width of the target in the Vuforia database.", - required=required, - ) - return option - - -@beartype -def target_image_option(*, required: bool) -> ClickOptionDecorator: - """An option decorator for choosing a target image.""" - return click.option( - "--image", - "image_file_path", - type=click.Path( - exists=True, - file_okay=True, - dir_okay=False, - path_type=Path, - ), - help="The path to an image to upload and set as the target image.", - required=required, - ) - - -@unique -class ActiveFlagChoice(Enum): - """Choices for active flag.""" - - TRUE = "true" - FALSE = "false" - - -@beartype -def active_flag_option( - *, - allow_none: bool, -) -> ClickOptionDecorator: - """An option decorator for setting a target's active flag.""" - if allow_none: - default = None - show_default = False - else: - default = ActiveFlagChoice.TRUE.value - show_default = True - - return click.option( - "--active-flag", - "active_flag_choice", - help="Whether or not the target is active for query.", - type=click.Choice(choices=ActiveFlagChoice, case_sensitive=False), - default=default, - show_default=show_default, - ) - - -application_metadata_option: ClickOptionDecorator = click.option( - "--application-metadata", - type=str, - required=False, - help="The base64 encoded application metadata associated with the target.", -) diff --git a/src/vws_cli/options/vws.py b/src/vws_cli/options/vws.py index fcabc932..84b87223 100644 --- a/src/vws_cli/options/vws.py +++ b/src/vws_cli/options/vws.py @@ -6,24 +6,6 @@ from beartype import beartype -@beartype -def database_id_option[**P, R]( - command: Callable[P, R], -) -> Callable[P, R]: - """An option decorator for the Vuforia database ID.""" - return click.option( - "--database-id", - type=str, - help=( - "The ID of the Vuforia database which the given server keys " - "belong to. This is shown in the Vuforia target manager." - ), - required=True, - envvar="VUFORIA_DATABASE_ID", - show_envvar=True, - )(command) - - @beartype def base_vws_url_option[**P, R]( command: Callable[P, R], diff --git a/src/vws_cli/query.py b/src/vws_cli/query.py deleted file mode 100644 index 7e24c09f..00000000 --- a/src/vws_cli/query.py +++ /dev/null @@ -1,177 +0,0 @@ -"""A CLI for the Vuforia Cloud Recognition Service API.""" - -import contextlib -import dataclasses -import io -import sys -from collections.abc import Generator -from pathlib import Path - -import click -import yaml -from beartype import beartype -from vws import CloudRecoService -from vws.exceptions.base_exceptions import CloudRecoError -from vws.exceptions.cloud_reco_exceptions import ( - AuthenticationFailureError, - BadImageError, - InactiveProjectError, - RequestTimeTooSkewedError, -) -from vws.exceptions.custom_exceptions import ( - RequestEntityTooLargeError, - ServerError, -) -from vws.include_target_data import CloudRecoIncludeTargetData - -from vws_cli import __version__ -from vws_cli.options.credentials import ( - client_access_key_option, - client_secret_key_option, -) -from vws_cli.options.timeout import ( - connection_timeout_seconds_option, - read_timeout_seconds_option, -) - - -@beartype -def _get_cloud_reco_error_message(exc: Exception) -> str: - """Get an error message from a Cloud Reco exception.""" - match exc: - case BadImageError(): - message = ( - "Error: The given image is corrupted or the format is not " - "supported." - ) - case InactiveProjectError(): - message = "Error: The project associated with the given keys is inactive." - case AuthenticationFailureError(): - message = "The given secret key was incorrect." - case RequestTimeTooSkewedError(): - message = ( - "Error: Vuforia reported that the time given with this request " - "was outside the expected range. " - "This may be because the system clock is out of sync." - ) - case RequestEntityTooLargeError(): - message = "Error: The given image is too large." - case ServerError(): - message = "Error: There was an unknown error from Vuforia." - case _: - message = "Error: Vuforia rejected the request." - - return message - - -@beartype -@contextlib.contextmanager -def _handle_vwq_exceptions() -> Generator[None]: - """Show error messages and catch exceptions from ``VWS-Python``.""" - error_stream = sys.stderr - try: - yield - except (CloudRecoError, RequestEntityTooLargeError, ServerError) as exc: - error_message = _get_cloud_reco_error_message(exc=exc) - else: - return - - click.echo(message=error_message, file=error_stream) - sys.exit(1) - - -_image_argument = click.argument( - "image", - type=click.Path( - exists=True, - file_okay=True, - dir_okay=False, - path_type=Path, - ), -) - -_MAX_NUM_RESULTS_DEFAULT = 50 -_max_num_results_option = click.option( - "--max-num-results", - type=click.IntRange(min=1, max=_MAX_NUM_RESULTS_DEFAULT), - default=1, - help=( - "The maximum number of matching targets to be returned. " - f"Must be <= {_MAX_NUM_RESULTS_DEFAULT}." - ), - show_default=True, -) - - -_include_target_data_option = click.option( - "--include-target-data", - type=click.Choice( - choices=CloudRecoIncludeTargetData, - case_sensitive=False, - ), - default=CloudRecoIncludeTargetData.TOP.lower(), - help=( - "Whether target_data records shall be returned for the matched " - "targets. Accepted values are top (default value, only return " - "target_data for top ranked match), none (return no target_data), " - "all (for all matched targets)." - ), - show_default=True, -) - -_base_vwq_url_option = click.option( - "--base-vwq-url", - type=click.STRING, - default="https://cloudreco.vuforia.com", - help="The base URL for the VWQ API.", - show_default=True, -) - - -@click.command(name="vuforia-cloud-reco") -@_image_argument -@client_access_key_option -@client_secret_key_option -@_include_target_data_option -@_max_num_results_option -@_base_vwq_url_option -@connection_timeout_seconds_option -@read_timeout_seconds_option -@_handle_vwq_exceptions() -# We set the ``version`` parameter because in PyInstaller binaries, -# ``pkg_resources`` is not available. -# -# Click uses ``pkg_resources`` to determine the version if it is not given. -@click.version_option(version=__version__) -@beartype -def vuforia_cloud_reco( - *, - image: Path, - client_access_key: str, - client_secret_key: str, - max_num_results: int, - include_target_data: CloudRecoIncludeTargetData, - base_vwq_url: str, - connection_timeout_seconds: float, - read_timeout_seconds: float, -) -> None: - """Make a request to the Vuforia Cloud Recognition Service API.""" - client = CloudRecoService( - client_access_key=client_access_key, - client_secret_key=client_secret_key, - base_vwq_url=base_vwq_url, - request_timeout_seconds=( - connection_timeout_seconds, - read_timeout_seconds, - ), - ) - query_result = client.query( - image=io.BytesIO(initial_bytes=image.read_bytes()), - max_num_results=max_num_results, - include_target_data=include_target_data, - ) - query_result_dict_list = [ - dataclasses.asdict(obj=res) for res in query_result - ] - yaml_list = yaml.dump(data=query_result_dict_list) - click.echo(message=yaml_list) diff --git a/tests/conftest.py b/tests/conftest.py index 836a94d6..88bab602 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,27 +4,8 @@ import pytest from mock_vws import MockVWS -from mock_vws.database import CloudDatabase, VuMarkDatabase +from mock_vws.database import VuMarkDatabase from mock_vws.target import VuMarkTarget -from vws import VWS, CloudRecoService - - -@pytest.fixture(name="mock_database") -def fixture_mock_database() -> Iterator[CloudDatabase]: - """Yield a mock ``CloudDatabase``.""" - with MockVWS() as mock: - database = CloudDatabase() - mock.add_cloud_database(cloud_database=database) - yield database - - -@pytest.fixture -def vws_client(*, mock_database: CloudDatabase) -> VWS: - """Return a VWS client which connects to a mock database.""" - return VWS( - server_access_key=mock_database.server_access_key, - server_secret_key=mock_database.server_secret_key, - ) @pytest.fixture(name="vumark_database") @@ -41,18 +22,3 @@ def fixture_vumark_database() -> Iterator[VuMarkDatabase]: def fixture_vumark_target(*, vumark_database: VuMarkDatabase) -> VuMarkTarget: """Return the pre-created ``VuMarkTarget`` in the database.""" return next(iter(vumark_database.not_deleted_targets)) - - -@pytest.fixture -def cloud_reco_client( - *, - mock_database: CloudDatabase, -) -> CloudRecoService: - """ - Return a ``CloudRecoService`` client which connects to a mock - database. - """ - return CloudRecoService( - client_access_key=mock_database.client_access_key, - client_secret_key=mock_database.client_secret_key, - ) diff --git a/tests/query/__init__.py b/tests/query/__init__.py deleted file mode 100644 index 75a879ba..00000000 --- a/tests/query/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Query tests.""" diff --git a/tests/query/test_options.py b/tests/query/test_options.py deleted file mode 100644 index bbec427e..00000000 --- a/tests/query/test_options.py +++ /dev/null @@ -1,405 +0,0 @@ -"""Tests for `query` options commands.""" - -import io -import uuid -from pathlib import Path - -import yaml -from click.testing import CliRunner -from mock_vws.database import CloudDatabase -from vws import VWS - -from vws_cli.query import vuforia_cloud_reco - - -def test_max_num_results_default( - *, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """By default the maximum number of results is 1.""" - runner = CliRunner() - target_id = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - target_id_2 = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - vws_client.wait_for_target_processed(target_id=target_id_2) - - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - assert len(result_data) == 1 - - -def test_custom( - *, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """It is possible to set a custom ``--max-num-results``.""" - runner = CliRunner() - target_id = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - target_id_2 = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - target_id_3 = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - vws_client.wait_for_target_processed(target_id=target_id_2) - vws_client.wait_for_target_processed(target_id=target_id_3) - - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - max_num_results = 2 - commands = [ - str(object=new_file), - "--max-num-results", - str(object=max_num_results), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - assert len(result_data) == max_num_results - - -def test_out_of_range( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """``--max-num-results`` must be between 1 and 50.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--max-num-results", - str(object=0), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_result_code = 2 - assert result.exit_code == expected_result_code - expected_stderr_substring = ( - "Error: Invalid value for '--max-num-results': 0 is not in the " - "range 1<=x<=50." - ) - assert expected_stderr_substring in result.stderr - - -def test_include_target_data_default( - *, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """By default, target data is only returned in the top match.""" - runner = CliRunner() - target_id = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - target_id_2 = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - vws_client.wait_for_target_processed(target_id=target_id_2) - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--max-num-results", - str(object=2), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - matches = yaml.safe_load(stream=result.stdout) - top_match, second_match = matches - assert top_match["target_data"] is not None - assert second_match["target_data"] is None - - -def test_top( - *, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """ - When 'top' is given, target data is only returned in the top - match. - """ - runner = CliRunner() - target_id = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - target_id_2 = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - vws_client.wait_for_target_processed(target_id=target_id_2) - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--max-num-results", - str(object=2), - "--include-target-data", - "top", - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - matches = yaml.safe_load(stream=result.stdout) - top_match, second_match = matches - assert top_match["target_data"] is not None - assert second_match["target_data"] is None - - -def test_none( - *, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """ - When 'none' is given, target data is not returned in any - match. - """ - runner = CliRunner() - target_id = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - target_id_2 = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - vws_client.wait_for_target_processed(target_id=target_id_2) - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--max-num-results", - str(object=2), - "--include-target-data", - "none", - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - matches = yaml.safe_load(stream=result.stdout) - top_match, second_match = matches - assert top_match["target_data"] is None - assert second_match["target_data"] is None - - -def test_all( - *, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """When 'all' is given, target data is returned in all matches.""" - runner = CliRunner() - target_id = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - target_id_2 = vws_client.add_target( - name=uuid.uuid4().hex, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - vws_client.wait_for_target_processed(target_id=target_id_2) - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - - commands = [ - str(object=new_file), - "--max-num-results", - str(object=2), - "--include-target-data", - "all", - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - matches = yaml.safe_load(stream=result.stdout) - top_match, second_match = matches - assert top_match["target_data"] is not None - assert second_match["target_data"] is not None - - -def test_other( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """ - When a string other than 'top', 'all', or 'none' is given, an - error is - shown. - """ - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--max-num-results", - str(object=2), - "--include-target-data", - "other", - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_result_code = 2 - assert result.exit_code == expected_result_code - expected_stderr = ( - "'--include-target-data': 'other' is not one of 'top', 'none', 'all'." - ) - assert expected_stderr in result.stderr diff --git a/tests/query/test_requests.py b/tests/query/test_requests.py deleted file mode 100644 index 0b7198f3..00000000 --- a/tests/query/test_requests.py +++ /dev/null @@ -1,298 +0,0 @@ -"""Tests for `query` requests commands.""" - -import io -import uuid -from pathlib import Path -from textwrap import dedent - -import yaml -from click.testing import CliRunner -from mock_vws import MockVWS -from mock_vws.database import CloudDatabase -from vws import VWS - -from vws_cli.query import vuforia_cloud_reco - - -def test_no_matches( - *, - mock_database: CloudDatabase, - tmp_path: Path, - high_quality_image: io.BytesIO, -) -> None: - """An empty list is returned if there are no matches.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - assert result_data == [] - - -def test_matches( - *, - tmp_path: Path, - high_quality_image: io.BytesIO, - vws_client: VWS, - mock_database: CloudDatabase, -) -> None: - """Details of matching targets are shown.""" - name = uuid.uuid4().hex - target_id = vws_client.add_target( - name=name, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - [matching_target] = result_data - target_timestamp: object = matching_target["target_data"][ - "target_timestamp" - ] - expected_result_data = { - "target_data": { - "application_metadata": None, - "name": name, - "target_timestamp": target_timestamp, - }, - "target_id": target_id, - } - assert matching_target == expected_result_data - - -def test_image_file_is_dir( - *, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """ - An appropriate error is given if the given image file path - points to a - directory. - """ - runner = CliRunner() - commands = [ - str(object=tmp_path), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_result_code = 2 - assert result.exit_code == expected_result_code - assert not bool(result.stdout) - expected_stderr = dedent( - text=f"""\ - Usage: vuforia-cloud-reco [OPTIONS] IMAGE - Try 'vuforia-cloud-reco --help' for help. - - Error: Invalid value for 'IMAGE': File '{tmp_path}' is a directory. - """, - ).replace("\\", "\\\\") - assert result.stderr == expected_stderr - - -def test_relative_path( - *, - tmp_path: Path, - mock_database: CloudDatabase, - high_quality_image: io.BytesIO, -) -> None: - """Image file paths are resolved.""" - runner = CliRunner() - new_filename = uuid.uuid4().hex - original_image_file = tmp_path / "foo" - image_data = high_quality_image.getvalue() - _ = original_image_file.write_bytes(data=image_data) - commands = [ - str(object=new_filename), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - with runner.isolated_filesystem(): - new_file = Path(new_filename) - new_file.symlink_to(target=original_image_file) - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - assert result_data == [] - - -def test_image_file_does_not_exist( - *, - mock_database: CloudDatabase, - tmp_path: Path, -) -> None: - """ - An appropriate error is given if the given image file does not - exist. - """ - runner = CliRunner() - does_not_exist_file = tmp_path / uuid.uuid4().hex - commands = [ - str(object=does_not_exist_file), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_result_code = 2 - assert result.exit_code == expected_result_code - assert not bool(result.stdout) - expected_stderr = dedent( - text=f"""\ - Usage: vuforia-cloud-reco [OPTIONS] IMAGE - Try 'vuforia-cloud-reco --help' for help. - - Error: Invalid value for 'IMAGE': File '{does_not_exist_file}' does not exist. - """, - ).replace("\\", "\\\\") - assert result.stderr == expected_stderr - - -def test_version() -> None: - """``vuforia-cloud-reco --version`` shows the version.""" - runner = CliRunner() - commands = ["--version"] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - assert result.stdout.startswith("vuforia-cloud-reco, version ") - - -def test_base_vwq_url( - *, high_quality_image: io.BytesIO, tmp_path: Path -) -> None: - """ - It is possible to use query a target to a database under a custom - VWQ URL. - """ - runner = CliRunner() - base_vwq_url = "http://example.com" - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - with MockVWS(base_vwq_url=base_vwq_url) as mock: - mock_database = CloudDatabase() - mock.add_cloud_database(cloud_database=mock_database) - vws_client = VWS( - server_access_key=mock_database.server_access_key, - server_secret_key=mock_database.server_secret_key, - ) - - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - vws_client.wait_for_target_processed(target_id=target_id) - - commands = [ - str(object=new_file), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - "--base-vwq-url", - base_vwq_url, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - - [match] = yaml.safe_load(stream=result.stdout) - assert match["target_id"] == target_id - - -def test_env_var_credentials( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, - mock_database: CloudDatabase, -) -> None: - """ - It is possible to use environment variables to set the - credentials. - """ - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [str(object=new_file)] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - env={ - "VUFORIA_CLIENT_ACCESS_KEY": mock_database.client_access_key, - "VUFORIA_CLIENT_SECRET_KEY": mock_database.client_secret_key, - }, - ) - assert result.exit_code == 0 diff --git a/tests/query/test_timeouts.py b/tests/query/test_timeouts.py deleted file mode 100644 index d55dfa7a..00000000 --- a/tests/query/test_timeouts.py +++ /dev/null @@ -1,163 +0,0 @@ -"""Tests for `query` timeouts commands.""" - -import datetime as dt -import io -import uuid -from pathlib import Path - -import pytest -import requests -from click.testing import CliRunner -from freezegun import freeze_time -from mock_vws import MockVWS -from mock_vws.database import CloudDatabase - -from vws_cli.query import vuforia_cloud_reco - - -@pytest.mark.parametrize( - argnames=("response_delay_seconds", "expect_timeout"), - argvalues=[(29, False), (31, True)], -) -def test_default_timeout( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, - response_delay_seconds: int, - expect_timeout: bool, -) -> None: - """At 29 seconds there is no error; at 31 seconds there is a - timeout. - """ - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - with ( - freeze_time() as frozen_datetime, - MockVWS( - response_delay_seconds=response_delay_seconds, - sleep_fn=lambda seconds: ( - frozen_datetime.tick( - delta=dt.timedelta(seconds=seconds), - ), - None, - )[1], - ) as mock, - ): - database = CloudDatabase() - mock.add_cloud_database(cloud_database=database) - commands = [ - str(object=new_file), - "--client-access-key", - database.client_access_key, - "--client-secret-key", - database.client_secret_key, - ] - - if expect_timeout: - with pytest.raises( - expected_exception=requests.exceptions.Timeout, - ): - _ = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - else: - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - - -def test_custom_timeout( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """Custom connection and read timeouts are respected.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - with ( - freeze_time() as frozen_datetime, - MockVWS( - response_delay_seconds=5, - sleep_fn=lambda seconds: ( - frozen_datetime.tick( - delta=dt.timedelta(seconds=seconds), - ), - None, - )[1], - ) as mock, - ): - database = CloudDatabase() - mock.add_cloud_database(cloud_database=database) - commands = [ - str(object=new_file), - "--client-access-key", - database.client_access_key, - "--client-secret-key", - database.client_secret_key, - "--read-timeout-seconds", - "1", - ] - - with pytest.raises( - expected_exception=requests.exceptions.Timeout, - ): - _ = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - - -def test_custom_timeout_no_error( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """A sufficiently large timeout does not cause an error.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - with ( - freeze_time() as frozen_datetime, - MockVWS( - response_delay_seconds=5, - sleep_fn=lambda seconds: ( - frozen_datetime.tick( - delta=dt.timedelta(seconds=seconds), - ), - None, - )[1], - ) as mock, - ): - database = CloudDatabase() - mock.add_cloud_database(cloud_database=database) - commands = [ - str(object=new_file), - "--client-access-key", - database.client_access_key, - "--client-secret-key", - database.client_secret_key, - "--read-timeout-seconds", - "60", - ] - - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 diff --git a/tests/test_error_handling.py b/tests/test_error_handling.py index 1fd22fc0..30061a74 100644 --- a/tests/test_error_handling.py +++ b/tests/test_error_handling.py @@ -1,17 +1,14 @@ """Tests for shared error handling through public CLI commands.""" -import io from pathlib import Path import pytest from click.testing import CliRunner from mock_vws import MockVWS, VuMarkGenerationFailure -from mock_vws.database import CloudDatabase -from vws import VWS +from mock_vws.database import VuMarkDatabase from vws.exceptions.model_target_exceptions import ModelTargetValidationError from vws.response import Response -from vws_cli import vws_group from vws_cli._error_handling import get_model_target_error_message from vws_cli.vumark import generate_vumark @@ -57,9 +54,9 @@ def test_vumark_service_error( *, failure: VuMarkGenerationFailure, expected_message: str, tmp_path: Path ) -> None: """Configured VuMark failures have user-facing messages.""" - database = CloudDatabase() + database = VuMarkDatabase() with MockVWS(vumark_generation_failure=failure) as mock: - mock.add_cloud_database(cloud_database=database) + mock.add_vumark_database(vumark_database=database) result = CliRunner().invoke( cli=generate_vumark, args=[ @@ -80,69 +77,3 @@ def test_vumark_service_error( assert result.exit_code == 1 assert result.stderr == f"{expected_message}\n" assert not bool(result.stdout) - - -def test_invalid_target_type( - *, high_quality_image: io.BytesIO, tmp_path: Path -) -> None: - """Generating a VuMark for an image target reports its invalid - type. - """ - database = CloudDatabase() - with MockVWS() as mock: - mock.add_cloud_database(cloud_database=database) - target_id = VWS( - server_access_key=database.server_access_key, - server_secret_key=database.server_secret_key, - ).add_target( - name="image-target", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - result = CliRunner().invoke( - cli=generate_vumark, - args=[ - "--target-id", - target_id, - "--instance-id", - "instance-id", - "--output", - str(object=tmp_path / "vumark.png"), - "--server-access-key", - database.server_access_key, - "--server-secret-key", - database.server_secret_key, - ], - catch_exceptions=False, - ) - - assert result.exit_code == 1 - assert result.stderr == "Error: The target type is invalid.\n" - assert not bool(result.stdout) - - -def test_too_many_requests() -> None: - """A rate-limited public request has a user-facing message.""" - database = CloudDatabase(requests_per_second_limit=0) - with MockVWS() as mock: - mock.add_cloud_database(cloud_database=database) - result = CliRunner().invoke( - cli=vws_group, - args=[ - "list-targets", - "--server-access-key", - database.server_access_key, - "--server-secret-key", - database.server_secret_key, - ], - catch_exceptions=False, - ) - - assert result.exit_code == 1 - assert ( - result.stderr - == "Error: Too many requests were made to Vuforia. Try again later.\n" - ) - assert not bool(result.stdout) diff --git a/tests/test_help.py b/tests/test_help.py index c6fc02cd..fe3e9409 100644 --- a/tests/test_help.py +++ b/tests/test_help.py @@ -5,7 +5,6 @@ from pytest_regressions.file_regression import FileRegressionFixture from vws_cli import vws_group -from vws_cli.query import vuforia_cloud_reco from vws_cli.vumark import generate_vumark @@ -52,21 +51,3 @@ def test_vumark_help(file_regression: FileRegressionFixture) -> None: ) assert result.exit_code == 0 file_regression.check(contents=result.output) - - -def test_query_help(file_regression: FileRegressionFixture) -> None: - """Expected help text is shown for the ``vuforia-cloud-reco`` command. - - This help text is defined in files. - To update these files, run ``pytest`` with the ``--regen-all`` flag. - """ - runner = CliRunner() - arguments = ["--help"] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=arguments, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - file_regression.check(contents=result.output) diff --git a/tests/test_help/test_query_help.txt b/tests/test_help/test_query_help.txt deleted file mode 100644 index 713550da..00000000 --- a/tests/test_help/test_query_help.txt +++ /dev/null @@ -1,32 +0,0 @@ -Usage: vuforia-cloud-reco [OPTIONS] IMAGE - - Make a request to the Vuforia Cloud Recognition Service API. - -Options: - --client-access-key TEXT A Vuforia client access key to use to access - the Vuforia Cloud Recognition API. [env var: - VUFORIA_CLIENT_ACCESS_KEY; required] - --client-secret-key TEXT A Vuforia client secret key to use to access - the Vuforia Cloud Recognition API. [env var: - VUFORIA_CLIENT_SECRET_KEY; required] - --include-target-data [top|none|all] - Whether target_data records shall be returned - for the matched targets. Accepted values are - top (default value, only return target_data - for top ranked match), none (return no - target_data), all (for all matched targets). - [default: top] - --max-num-results INTEGER RANGE - The maximum number of matching targets to be - returned. Must be <= 50. [default: 1; - 1<=x<=50] - --base-vwq-url TEXT The base URL for the VWQ API. [default: - https://cloudreco.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --version Show the version and exit. - --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help____.txt b/tests/test_help/test_vws_command_help____.txt index c757a12b..f6ce3a47 100644 --- a/tests/test_help/test_vws_command_help____.txt +++ b/tests/test_help/test_vws_command_help____.txt @@ -1,27 +1,16 @@ Usage: vws [OPTIONS] COMMAND [ARGS]... - Manage a Vuforia Web Services cloud database. + Manage Vuforia Model Target datasets. Options: --version Show the version and exit. -h, --help Show this message and exit. Commands: - add-target Add a target. create-model-target-dataset Create a Model Target dataset. delete-model-target-dataset Delete a Model Target dataset. - delete-target Delete a target. download-model-target-dataset Download a generated Model... - get-database-reco-counts-report - Get a per-target recognition... - get-database-summary-report Get a database summary report. - get-duplicate-targets Get a list of potential... get-model-target-dataset-status Get the status of a Model Target... - get-target-record Get a target record. - get-target-summary-report Get a target summary report. - list-targets List targets. - update-target Update a target. wait-for-model-target-dataset-generated Wait for Vuforia to finish... - wait-for-target-processed Wait for a target to be... diff --git a/tests/test_help/test_vws_command_help___add_target___.txt b/tests/test_help/test_vws_command_help___add_target___.txt deleted file mode 100644 index d7b4c9ad..00000000 --- a/tests/test_help/test_vws_command_help___add_target___.txt +++ /dev/null @@ -1,33 +0,0 @@ -Usage: vws add-target [OPTIONS] - - Add a target. - - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#add - -Options: - --width FLOAT The width of the target in the Vuforia - database. [required] - --application-metadata TEXT The base64 encoded application metadata - associated with the target. - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --name TEXT The name of the target in the Vuforia - database. [required] - --image FILE The path to an image to upload and set as the - target image. [required] - --active-flag [true|false] Whether or not the target is active for query. - [default: true] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help___delete_target___.txt b/tests/test_help/test_vws_command_help___delete_target___.txt deleted file mode 100644 index 8862a48a..00000000 --- a/tests/test_help/test_vws_command_help___delete_target___.txt +++ /dev/null @@ -1,25 +0,0 @@ -Usage: vws delete-target [OPTIONS] - - Delete a target. - - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#delete. - -Options: - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --target-id TEXT The ID of a target in the Vuforia database. - [required] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help___get_database_reco_counts_report___.txt b/tests/test_help/test_vws_command_help___get_database_reco_counts_report___.txt deleted file mode 100644 index 2cd38898..00000000 --- a/tests/test_help/test_vws_command_help___get_database_reco_counts_report___.txt +++ /dev/null @@ -1,50 +0,0 @@ -Usage: vws get-database-reco-counts-report [OPTIONS] - - Get a per-target recognition counts report for a database. - - The report is a CSV with a ``target_id,reco_count`` header. Vuforia generates - the report in the background, so by default we wait for the report to be - generated before downloading it. - - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api. - -Options: - --month TEXT The month to get recognition counts for, in - the YYYY-mm form. Vuforia accepts only the - current month and the previous month. - [default: (the current month)] - --output FILE The path to write the CSV report to. By - default, the report is written to stdout. - --no-wait Do not wait for the report to be generated. - Instead, show the URL to download the report - from once it has been generated. - --seconds-between-requests FLOAT RANGE - The number of seconds to wait between requests - made while polling for the report. We wait 0.2 - seconds by default, rather than less, than - that to decrease the number of calls made to - the API, to decrease the likelihood of hitting - the request quota. [default: 0.2; x>=0.05] - --timeout-seconds FLOAT RANGE The maximum number of seconds to wait for the - report to be generated. [default: 300; - x>=0.05] - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --database-id TEXT The ID of the Vuforia database which the given - server keys belong to. This is shown in the - Vuforia target manager. [env var: - VUFORIA_DATABASE_ID; required] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help___get_database_summary_report___.txt b/tests/test_help/test_vws_command_help___get_database_summary_report___.txt deleted file mode 100644 index e6f42a6a..00000000 --- a/tests/test_help/test_vws_command_help___get_database_summary_report___.txt +++ /dev/null @@ -1,23 +0,0 @@ -Usage: vws get-database-summary-report [OPTIONS] - - Get a database summary report. - - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#summary-report. - -Options: - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help___get_duplicate_targets___.txt b/tests/test_help/test_vws_command_help___get_duplicate_targets___.txt deleted file mode 100644 index 4e406a48..00000000 --- a/tests/test_help/test_vws_command_help___get_duplicate_targets___.txt +++ /dev/null @@ -1,25 +0,0 @@ -Usage: vws get-duplicate-targets [OPTIONS] - - Get a list of potential duplicate targets. - - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#check. - -Options: - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --target-id TEXT The ID of a target in the Vuforia database. - [required] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help___get_target_record___.txt b/tests/test_help/test_vws_command_help___get_target_record___.txt deleted file mode 100644 index 1896cd69..00000000 --- a/tests/test_help/test_vws_command_help___get_target_record___.txt +++ /dev/null @@ -1,25 +0,0 @@ -Usage: vws get-target-record [OPTIONS] - - Get a target record. - - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#target-record. - -Options: - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --target-id TEXT The ID of a target in the Vuforia database. - [required] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help___get_target_summary_report___.txt b/tests/test_help/test_vws_command_help___get_target_summary_report___.txt deleted file mode 100644 index 1ec2e61c..00000000 --- a/tests/test_help/test_vws_command_help___get_target_summary_report___.txt +++ /dev/null @@ -1,25 +0,0 @@ -Usage: vws get-target-summary-report [OPTIONS] - - Get a target summary report. - - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#retrieve-report. - -Options: - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --target-id TEXT The ID of a target in the Vuforia database. - [required] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help___list_targets___.txt b/tests/test_help/test_vws_command_help___list_targets___.txt deleted file mode 100644 index 9df9f166..00000000 --- a/tests/test_help/test_vws_command_help___list_targets___.txt +++ /dev/null @@ -1,23 +0,0 @@ -Usage: vws list-targets [OPTIONS] - - List targets. - - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#details-list. - -Options: - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help___update_target___.txt b/tests/test_help/test_vws_command_help___update_target___.txt deleted file mode 100644 index 032a1567..00000000 --- a/tests/test_help/test_vws_command_help___update_target___.txt +++ /dev/null @@ -1,34 +0,0 @@ -Usage: vws update-target [OPTIONS] - - Update a target. - - See - https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#update - -Options: - --width FLOAT The width of the target in the Vuforia - database. - --application-metadata TEXT The base64 encoded application metadata - associated with the target. - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --name TEXT The name of the target in the Vuforia - database. - --image FILE The path to an image to upload and set as the - target image. - --active-flag [true|false] Whether or not the target is active for query. - --target-id TEXT The ID of a target in the Vuforia database. - [required] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_help/test_vws_command_help___wait_for_target_processed___.txt b/tests/test_help/test_vws_command_help___wait_for_target_processed___.txt deleted file mode 100644 index 9e212530..00000000 --- a/tests/test_help/test_vws_command_help___wait_for_target_processed___.txt +++ /dev/null @@ -1,32 +0,0 @@ -Usage: vws wait-for-target-processed [OPTIONS] - - Wait for a target to be "processed". This is done by polling the VWS API. - -Options: - --seconds-between-requests FLOAT RANGE - The number of seconds to wait between requests - made while polling the target status. We wait - 0.2 seconds by default, rather than less, than - that to decrease the number of calls made to - the API, to decrease the likelihood of hitting - the request quota. [default: 0.2; x>=0.05] - --timeout-seconds FLOAT RANGE The maximum number of seconds to wait for the - target to be processed. [default: 300; - x>=0.05] - --server-access-key TEXT A Vuforia server access key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_ACCESS_KEY; required] - --server-secret-key TEXT A Vuforia server secret key to use to access - the Vuforia Web Services API. [env var: - VUFORIA_SERVER_SECRET_KEY; required] - --target-id TEXT The ID of a target in the Vuforia database. - [required] - --base-vws-url TEXT The base URL for the VWS API. [default: - https://vws.vuforia.com] - --connection-timeout-seconds FLOAT RANGE - The connection timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - --read-timeout-seconds FLOAT RANGE - The read timeout for HTTP requests, in - seconds. [default: 30; x>=0.05] - -h, --help Show this message and exit. diff --git a/tests/test_query_errors.py b/tests/test_query_errors.py deleted file mode 100644 index 5361274e..00000000 --- a/tests/test_query_errors.py +++ /dev/null @@ -1,243 +0,0 @@ -"""Tests for how errors from the Cloud Reco Service are handled by the CLI.""" - -import io -import uuid -from pathlib import Path - -import pytest -from click.testing import CliRunner -from freezegun import freeze_time -from mock_vws import CloudQueryFailureResponse, MockVWS -from mock_vws.database import CloudDatabase -from mock_vws.states import States - -from vws_cli.query import vuforia_cloud_reco - - -@pytest.mark.parametrize( - argnames=("status_code", "expected_message"), - argvalues=[ - pytest.param( - 400, - "Error: Vuforia rejected the request.", - id="client-error", - ), - pytest.param( - 500, - "Error: There was an unknown error from Vuforia.", - id="server-error", - ), - ], -) -def test_fallback_error( - *, - status_code: int, - expected_message: str, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """Other Cloud Reco errors have a user-facing message.""" - image_path = tmp_path / "image.jpg" - _ = image_path.write_bytes(data=high_quality_image.getvalue()) - failure_response = CloudQueryFailureResponse( - status_code=status_code, - headers={"Content-Type": "text/plain"}, - body="error", - ) - database = CloudDatabase() - with MockVWS(cloud_query_failure_response=failure_response) as mock: - mock.add_cloud_database(cloud_database=database) - result = CliRunner().invoke( - cli=vuforia_cloud_reco, - args=[ - str(object=image_path), - "--client-access-key", - database.client_access_key, - "--client-secret-key", - database.client_secret_key, - ], - catch_exceptions=False, - ) - - assert result.exit_code == 1 - assert result.stderr == f"{expected_message}\n" - assert not bool(result.stdout) - - -def test_authentication_failure( - *, - mock_database: CloudDatabase, - tmp_path: Path, - high_quality_image: io.BytesIO, -) -> None: - """An error is given when the secret key is incorrect.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - "wrong_secret_key", - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_stderr = "The given secret key was incorrect.\n" - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_image_too_large( - *, - mock_database: CloudDatabase, - tmp_path: Path, - png_too_large: io.BytesIO, -) -> None: - """An error is given when the image is too large.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = png_too_large.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - str(object=new_file), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_stderr = "Error: The given image is too large.\n" - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_bad_image( - *, - mock_database: CloudDatabase, - tmp_path: Path, -) -> None: - """An error is given when Vuforia returns a ``BadImage`` error. - - For example, when a corrupt image is uploaded. - """ - new_file = tmp_path / uuid.uuid4().hex - _ = new_file.write_bytes(data=b"Not an image") - runner = CliRunner() - commands = [ - str(object=new_file), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 1 - expected_stderr = ( - "Error: The given image is corrupted or the format is not supported.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_inactive_project( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """ - An error is given if the project is inactive and the desired action - cannot - be taken because of this. - """ - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - database = CloudDatabase(state=States.PROJECT_INACTIVE) - with MockVWS() as mock: - mock.add_cloud_database(cloud_database=database) - runner = CliRunner() - commands = [ - str(object=new_file), - "--client-access-key", - database.client_access_key, - "--client-secret-key", - database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 1 - expected_stderr = ( - "Error: The project associated with the given keys is inactive.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_request_time_too_skewed( - *, - high_quality_image: io.BytesIO, - mock_database: CloudDatabase, - tmp_path: Path, -) -> None: - """ - An error is given when the request time is more than 65 minutes - different - from the server time. - """ - runner = CliRunner() - vwq_max_time_skew = 60 * 65 - leeway = 10 - time_difference_from_now = vwq_max_time_skew + leeway - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - - # We use a custom tick because we expect the following: - # - # * At least one time check when creating the request - # * At least one time check when processing the request - # - # >= 1 ticks are acceptable. - with freeze_time(auto_tick_seconds=time_difference_from_now): - commands = [ - str(object=new_file), - "--client-access-key", - mock_database.client_access_key, - "--client-secret-key", - mock_database.client_secret_key, - ] - result = runner.invoke( - cli=vuforia_cloud_reco, - args=commands, - catch_exceptions=False, - color=True, - ) - - expected_stderr = ( - "Error: Vuforia reported that the time given with this request was " - "outside the expected range. " - "This may be because the system clock is out of sync.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) diff --git a/tests/test_reco_counts_report.py b/tests/test_reco_counts_report.py deleted file mode 100644 index f4ed4bed..00000000 --- a/tests/test_reco_counts_report.py +++ /dev/null @@ -1,299 +0,0 @@ -"""Tests for the ``get-database-reco-counts-report`` command.""" - -import datetime as dt -import uuid -from pathlib import Path -from zoneinfo import ZoneInfo - -import pytest -from click.testing import CliRunner -from mock_vws import MockVWS -from mock_vws.database import CloudDatabase -from vws import VWS -from vws.exceptions.custom_exceptions import RecoCountsReportNotReadyError - -from vws_cli import vws_group - -_EXPECTED_CSV = b"target_id,reco_count\r\n" - -# The exit code which ``click`` uses for a usage error. -_USAGE_ERROR_EXIT_CODE = 2 - - -def _month_string(*, months_ago: int) -> str: - """Return a ``YYYY-mm`` string for a month relative to this month.""" - now = dt.datetime.now(tz=ZoneInfo(key="UTC")) - first_of_month = now.replace(day=1) - for _ in range(months_ago): - first_of_month = first_of_month.replace(day=1) - dt.timedelta( - days=1, - ) - return first_of_month.strftime(format="%Y-%m") - - -def _base_commands(*, mock_database: CloudDatabase) -> list[str]: - """Return the command and credential arguments for the report - command. - """ - return [ - "get-database-reco-counts-report", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - "--database-id", - mock_database.database_id, - ] - - -def test_get_database_reco_counts_report( - *, - mock_database: CloudDatabase, -) -> None: - """The report is written to stdout. - - The ``mock_database`` fixture does not make the report available - immediately, so this also shows that the command waits for the report. - """ - runner = CliRunner() - result = runner.invoke( - cli=vws_group, - args=_base_commands(mock_database=mock_database), - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - assert not bool(result.stderr) - assert result.stdout_bytes == _EXPECTED_CSV - - -def test_report_is_not_available_immediately() -> None: - """The command waits for a report which is not ready to download.""" - runner = CliRunner() - mock_database = CloudDatabase() - with MockVWS(processing_time_seconds=1) as mock: - mock.add_cloud_database(cloud_database=mock_database) - vws_client = VWS( - server_access_key=mock_database.server_access_key, - server_secret_key=mock_database.server_secret_key, - ) - no_wait_result = runner.invoke( - cli=vws_group, - args=[*_base_commands(mock_database=mock_database), "--no-wait"], - catch_exceptions=False, - color=True, - ) - assert no_wait_result.exit_code == 0 - presigned_url = no_wait_result.stdout.strip() - with pytest.raises(expected_exception=RecoCountsReportNotReadyError): - _ = vws_client.download_reco_counts_report( - presigned_url=presigned_url, - ) - - result = runner.invoke( - cli=vws_group, - args=_base_commands(mock_database=mock_database), - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 0 - assert result.stdout_bytes == _EXPECTED_CSV - - -def test_output_file(*, tmp_path: Path) -> None: - """The report is written to the path given by ``--output``.""" - runner = CliRunner() - mock_database = CloudDatabase() - output_file_path = tmp_path / uuid.uuid4().hex - with MockVWS(processing_time_seconds=0) as mock: - mock.add_cloud_database(cloud_database=mock_database) - result = runner.invoke( - cli=vws_group, - args=[ - *_base_commands(mock_database=mock_database), - "--output", - str(object=output_file_path), - ], - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 0 - assert not bool(result.stdout) - assert output_file_path.read_bytes() == _EXPECTED_CSV - - -def test_no_wait() -> None: - """``--no-wait`` shows the URL to download the report from.""" - runner = CliRunner() - mock_database = CloudDatabase() - with MockVWS(processing_time_seconds=0) as mock: - mock.add_cloud_database(cloud_database=mock_database) - vws_client = VWS( - server_access_key=mock_database.server_access_key, - server_secret_key=mock_database.server_secret_key, - ) - result = runner.invoke( - cli=vws_group, - args=[*_base_commands(mock_database=mock_database), "--no-wait"], - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - presigned_url = result.stdout.strip() - report = vws_client.download_reco_counts_report( - presigned_url=presigned_url, - ) - - assert report.raw_csv == _EXPECTED_CSV - - -def test_no_wait_with_output_file( - *, - mock_database: CloudDatabase, - tmp_path: Path, -) -> None: - """``--output`` cannot be used with ``--no-wait``.""" - runner = CliRunner() - output_file_path = tmp_path / uuid.uuid4().hex - result = runner.invoke( - cli=vws_group, - args=[ - *_base_commands(mock_database=mock_database), - "--no-wait", - "--output", - str(object=output_file_path), - ], - catch_exceptions=False, - color=True, - ) - assert result.exit_code == _USAGE_ERROR_EXIT_CODE - assert "--output cannot be used with --no-wait." in result.stderr - assert not output_file_path.exists() - - -def test_previous_month() -> None: - """A report can be requested for the previous month.""" - runner = CliRunner() - mock_database = CloudDatabase() - with MockVWS(processing_time_seconds=0) as mock: - mock.add_cloud_database(cloud_database=mock_database) - result = runner.invoke( - cli=vws_group, - args=[ - *_base_commands(mock_database=mock_database), - "--month", - _month_string(months_ago=1), - ], - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 0 - assert result.stdout_bytes == _EXPECTED_CSV - - -def test_month_is_not_in_the_yyyy_mm_form( - *, - mock_database: CloudDatabase, -) -> None: - """An error is shown for a month which is not in the ``YYYY-mm`` - form. - """ - runner = CliRunner() - result = runner.invoke( - cli=vws_group, - args=[ - *_base_commands(mock_database=mock_database), - "--month", - "not-a-month", - ], - catch_exceptions=False, - color=True, - ) - assert result.exit_code == _USAGE_ERROR_EXIT_CODE - expected_message = '"not-a-month" is not a month in the YYYY-mm form.' - assert expected_message in result.stderr - - -def test_month_out_of_range(*, mock_database: CloudDatabase) -> None: - """An error is shown for a month which Vuforia does not accept. - - Vuforia accepts only the current month and the previous month. - """ - runner = CliRunner() - result = runner.invoke( - cli=vws_group, - args=[ - *_base_commands(mock_database=mock_database), - "--month", - _month_string(months_ago=2), - ], - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 1 - expected_stderr = ( - "Error: The request made to Vuforia was invalid and could not be " - "processed. Check the given parameters.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_database_id_does_not_match( - *, - mock_database: CloudDatabase, -) -> None: - """An error is shown when the given database ID is not the - database's. - """ - runner = CliRunner() - commands = [ - "get-database-reco-counts-report", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - "--database-id", - uuid.uuid4().hex, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 1 - expected_stderr = "The given secret key was incorrect.\n" - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_timeout_reached() -> None: - """An error is shown when the report is not generated in time.""" - runner = CliRunner() - mock_database = CloudDatabase() - timeout_seconds = 0.1 - with MockVWS(processing_time_seconds=60) as mock: - mock.add_cloud_database(cloud_database=mock_database) - result = runner.invoke( - cli=vws_group, - args=[ - *_base_commands(mock_database=mock_database), - "--timeout-seconds", - str(object=timeout_seconds), - "--seconds-between-requests", - "0.05", - ], - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 1 - assert result.stderr == ( - "Error: The recognition counts report was not generated within the " - "allowed limit.\n" - ) - assert not bool(result.stdout) diff --git a/tests/test_vumark.py b/tests/test_vumark.py index c9f1fc87..6b1e0844 100644 --- a/tests/test_vumark.py +++ b/tests/test_vumark.py @@ -7,7 +7,7 @@ import pytest from click.testing import CliRunner from mock_vws import MockVWS -from mock_vws.database import CloudDatabase, VuMarkDatabase +from mock_vws.database import VuMarkDatabase from mock_vws.target import VuMarkTarget from vws_cli import vumark as vumark_module @@ -227,7 +227,7 @@ def test_authentication_failure( @pytest.mark.parametrize(argnames="invalid_format", argvalues=["bmp", "gif"]) def test_invalid_format( - mock_database: CloudDatabase, + vumark_database: VuMarkDatabase, tmp_path: Path, invalid_format: str, ) -> None: @@ -244,9 +244,9 @@ def test_invalid_format( "--output", str(object=output_file), "--server-access-key", - mock_database.server_access_key, + vumark_database.server_access_key, "--server-secret-key", - mock_database.server_secret_key, + vumark_database.server_secret_key, ] result = runner.invoke( cli=generate_vumark, diff --git a/tests/test_vws_errors.py b/tests/test_vws_errors.py deleted file mode 100644 index 9cb3ebf9..00000000 --- a/tests/test_vws_errors.py +++ /dev/null @@ -1,525 +0,0 @@ -"""Tests for how errors from VWS are handled by the CLI.""" - -import base64 -import io -import uuid -from pathlib import Path - -from click.testing import CliRunner -from freezegun import freeze_time -from mock_vws import MockVWS -from mock_vws.database import CloudDatabase -from mock_vws.states import States -from vws import VWS - -from vws_cli import vws_group - - -def test_target_id_does_not_exist(mock_database: CloudDatabase) -> None: - """ - Commands which take a target ID show an error if that does not map - to a - target in the database. - """ - runner = CliRunner() - for command_name, command in vws_group.commands.items(): - if "target_id" in [option.name for option in command.params]: - args = [ - command_name, - "--target-id", - "abc12345", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, args=args, catch_exceptions=False - ) - assert result.exit_code == 1 - expected_stderr = 'Error: Target "abc12345" does not exist.\n' - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_bad_image( - *, - mock_database: CloudDatabase, - tmp_path: Path, -) -> None: - """An error is given when Vuforia returns a ``BadImage`` error. - - For example, when a corrupt image is uploaded. - """ - new_file = tmp_path / uuid.uuid4().hex - _ = new_file.write_bytes(data=b"Not an image") - runner = CliRunner() - args = [ - "add-target", - "--name", - "x", - "--width", - "0.1", - "--image", - str(object=new_file), - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke(cli=vws_group, args=args, catch_exceptions=False) - assert result.exit_code == 1 - expected_stderr = ( - "Error: The given image is corrupted or the format is not supported.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_fail_bad_request( - *, - mock_database: CloudDatabase, - high_quality_image_path: Path, -) -> None: - """An error is given when Vuforia returns a ``Fail`` error with a - ``400`` - error code. For example, when the given server access key does not - exist. - - With ``vws_python`` we cannot get a (guaranteed) 500 error or 422 response - with a ``Fail`` error. - """ - runner = CliRunner() - args = [ - "add-target", - "--name", - "x", - "--width", - "0.1", - "--image", - str(object=high_quality_image_path), - "--server-access-key", - "does_not_exist_key", - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke(cli=vws_group, args=args, catch_exceptions=False) - assert result.exit_code == 1 - expected_stderr = ( - "Error: The request made to Vuforia was invalid and could not be " - "processed. " - "Check the given parameters.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_metadata_too_large( - *, - mock_database: CloudDatabase, - high_quality_image_path: Path, - application_metadata_near_size_limit: str, -) -> None: - """An error is given when the given metadata is too large.""" - decoded_metadata = base64.b64decode( - s=application_metadata_near_size_limit.encode(encoding="ascii"), - ) - over_limit_metadata = base64.b64encode( - s=decoded_metadata + b"x", - ).decode(encoding="ascii") - runner = CliRunner() - args = [ - "add-target", - "--name", - "x", - "--width", - "0.1", - "--image", - str(object=high_quality_image_path), - "--application-metadata", - over_limit_metadata, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke(cli=vws_group, args=args, catch_exceptions=False) - assert result.exit_code == 1 - expected_stderr = "Error: The given metadata is too large.\n" - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_image_too_large( - *, - mock_database: CloudDatabase, - png_too_large: io.BytesIO, - tmp_path: Path, -) -> None: - """An error is given when the given image is too large.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = png_too_large.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - "add-target", - "--name", - "foo", - "--width", - "0.1", - "--image", - str(object=new_file), - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 1 - expected_stderr = "Error: The given image is too large.\n" - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_target_name_exist( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """ - An error is given when there is already a target with the given - name. - """ - name = "foobar" - _ = vws_client.add_target( - name=name, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - "add-target", - "--name", - name, - "--width", - "0.1", - "--image", - str(object=new_file), - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 1 - expected_stderr = 'Error: There is already a target named "foobar".\n' - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_project_inactive( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """ - An error is given if the project is inactive and the desired action - cannot - be taken because of this. - """ - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - database = CloudDatabase(state=States.PROJECT_INACTIVE) - with MockVWS() as mock: - mock.add_cloud_database(cloud_database=database) - runner = CliRunner() - commands = [ - "add-target", - "--name", - "foo", - "--width", - "0.1", - "--image", - str(object=new_file), - "--server-access-key", - database.server_access_key, - "--server-secret-key", - database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 1 - expected_stderr = ( - "Error: The project associated with the given keys is inactive.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_project_has_no_api_access( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """ - An error is given if the project is not allowed to make API - requests. - """ - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - database = CloudDatabase(state=States.PROJECT_HAS_NO_API_ACCESS) - with MockVWS() as mock: - mock.add_cloud_database(cloud_database=database) - runner = CliRunner() - commands = [ - "add-target", - "--name", - "foo", - "--width", - "0.1", - "--image", - str(object=new_file), - "--server-access-key", - database.server_access_key, - "--server-secret-key", - database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 1 - expected_stderr = ( - "Error: The request could not be completed because this database is " - "not allowed to make API requests.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_unknown_vws_error( - *, - mock_database: CloudDatabase, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """ - When an unknown VWS error is given, e.g. what is given when some bad - names - are given, an error is given. - """ - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - max_char_value = 65535 - bad_name = chr(max_char_value + 1) - - commands = [ - "add-target", - "--name", - bad_name, - "--width", - "0.1", - "--image", - str(object=new_file), - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 1 - expected_stderr = ( - "Error: There was an unknown error from Vuforia. " - "This may be because there is a problem with the given name.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_target_status_processing( - *, - vws_client: VWS, - high_quality_image: io.BytesIO, - mock_database: CloudDatabase, -) -> None: - """ - An error is given when trying to delete a target which is - processing. - """ - runner = CliRunner() - - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - commands = [ - "delete-target", - "--target-id", - target_id, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 1 - expected_stderr = ( - f'Error: The target "{target_id}" cannot be deleted as it is in the ' - "processing state.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_target_status_not_success( - *, - vws_client: VWS, - high_quality_image: io.BytesIO, - mock_database: CloudDatabase, -) -> None: - """ - An error is given when updating a target which has a status which is - not - "Success". - """ - runner = CliRunner() - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - commands = [ - "update-target", - "--target-id", - target_id, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 1 - expected_stderr = ( - f'Error: The target "{target_id}" cannot be updated as it is not in ' - "the success state.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_authentication_failure(mock_database: CloudDatabase) -> None: - """An error is given when the secret key is incorrect.""" - runner = CliRunner() - commands = [ - "list-targets", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - "wrong_key", - ] - - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 1 - expected_stderr = "The given secret key was incorrect.\n" - assert result.stderr == expected_stderr - assert not bool(result.stdout) - - -def test_request_time_too_skewed(mock_database: CloudDatabase) -> None: - """ - An error is given when the request time is more than 5 minutes - different - from the server time. - """ - runner = CliRunner() - vws_max_time_skew = 60 * 5 - leeway = 10 - time_difference_from_now = vws_max_time_skew + leeway - - # We use a custom tick because we expect the following: - # - # * At least one time check when creating the request - # * At least one time check when processing the request - # - # >= 1 ticks are acceptable. - with freeze_time(auto_tick_seconds=time_difference_from_now): - commands = [ - "list-targets", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - - expected_stderr = ( - "Error: Vuforia reported that the time given with this request was " - "outside the expected range. " - "This may be because the system clock is out of sync.\n" - ) - assert result.stderr == expected_stderr - assert not bool(result.stdout) diff --git a/tests/vws/__init__.py b/tests/vws/__init__.py deleted file mode 100644 index d56bfb0c..00000000 --- a/tests/vws/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Vws tests.""" diff --git a/tests/vws/test_add_target.py b/tests/vws/test_add_target.py deleted file mode 100644 index 4b098e6a..00000000 --- a/tests/vws/test_add_target.py +++ /dev/null @@ -1,297 +0,0 @@ -"""Tests for `vws` add target commands.""" - -import base64 -import io -import secrets -import uuid -from pathlib import Path -from textwrap import dedent - -import pytest -from click.testing import CliRunner -from mock_vws.database import CloudDatabase -from vws import VWS, CloudRecoService - -from vws_cli import vws_group - - -def test_add_target( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, - cloud_reco_client: CloudRecoService, -) -> None: - """It is possible to add a target.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - name = uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - width = secrets.choice(seq=range(1, 5000)) / 100 - commands = [ - "add-target", - "--name", - name, - "--width", - str(object=width), - "--image", - str(object=new_file), - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0, result.output - - target_id = result.stdout.strip() - target_details = vws_client.get_target_record(target_id=target_id) - target_record = target_details.target_record - assert target_record.name == name - assert target_record.width == width - assert target_record.active_flag is True - vws_client.wait_for_target_processed(target_id=target_id) - - [query_result] = cloud_reco_client.query(image=high_quality_image) - assert query_result.target_id == target_id - target_data = query_result.target_data - assert target_data is not None - assert target_data.application_metadata is None - - -def test_image_file_does_not_exist( - *, - mock_database: CloudDatabase, - tmp_path: Path, -) -> None: - """ - An appropriate error is given if the given image file does not - exist. - """ - runner = CliRunner() - does_not_exist_file = tmp_path / uuid.uuid4().hex - commands = [ - "add-target", - "--name", - "foo", - "--width", - "1", - "--image", - str(object=does_not_exist_file), - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_result_code = 2 - assert result.exit_code == expected_result_code - assert not bool(result.stdout) - expected_stderr = dedent( - text=f"""\ - Usage: vws add-target [OPTIONS] - Try 'vws add-target --help' for help. - - Error: Invalid value for '--image': File '{does_not_exist_file}' does not exist. - """, - ).replace("\\", "\\\\") - assert result.stderr == expected_stderr - - -def test_image_file_is_dir( - *, - mock_database: CloudDatabase, - tmp_path: Path, -) -> None: - """ - An appropriate error is given if the given image file path - points to a - directory. - """ - runner = CliRunner() - commands = [ - "add-target", - "--name", - "foo", - "--width", - "1", - "--image", - str(object=tmp_path), - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_result_code = 2 - assert result.exit_code == expected_result_code - assert not bool(result.stdout) - expected_stderr = dedent( - text=f"""\ - Usage: vws add-target [OPTIONS] - Try 'vws add-target --help' for help. - - Error: Invalid value for '--image': File '{tmp_path}' is a directory. - """, - ).replace("\\", "\\\\") - assert result.stderr == expected_stderr - - -def test_relative_path( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """Image file paths are resolved.""" - runner = CliRunner() - new_filename = uuid.uuid4().hex - original_image_file = tmp_path / "foo" - image_data = high_quality_image.getvalue() - _ = original_image_file.write_bytes(data=image_data) - name = uuid.uuid4().hex - commands = [ - "add-target", - "--name", - name, - "--width", - "1", - "--image", - new_filename, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - with runner.isolated_filesystem(): - new_file = Path(new_filename) - new_file.symlink_to(target=original_image_file) - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - target_id = result.stdout.strip() - target_record = vws_client.get_target_record(target_id=target_id) - assert target_record.target_record.name == name - - -def test_custom_metadata( - *, - mock_database: CloudDatabase, - cloud_reco_client: CloudRecoService, - vws_client: VWS, - tmp_path: Path, - high_quality_image: io.BytesIO, -) -> None: - """Custom metadata can be given.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - name = uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - application_metadata = uuid.uuid4().hex - metadata_bytes = application_metadata.encode(encoding="ascii") - base64_encoded_metadata_bytes = base64.b64encode(s=metadata_bytes) - base64_encoded_metadata = base64_encoded_metadata_bytes.decode( - encoding="ascii", - ) - commands = [ - "add-target", - "--name", - name, - "--width", - "0.1", - "--image", - str(object=new_file), - "--application-metadata", - base64_encoded_metadata, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - target_id = result.stdout.strip() - vws_client.wait_for_target_processed(target_id=target_id) - [query_result] = cloud_reco_client.query(image=high_quality_image) - assert query_result.target_id == target_id - target_data = query_result.target_data - assert target_data is not None - assert target_data.application_metadata == base64_encoded_metadata - - -@pytest.mark.parametrize( - argnames=("active_flag_given", "active_flag_expected"), - argvalues=[ - ("true", True), - ("false", False), - ], -) -def test_custom_active_flag( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, - active_flag_given: str, - active_flag_expected: bool, -) -> None: - """The Active Flag of the new target can be chosen.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - commands = [ - "add-target", - "--name", - "foo", - "--width", - "0.1", - "--image", - str(object=new_file), - "--active-flag", - active_flag_given, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - - target_id = result.stdout.strip() - target_details = vws_client.get_target_record(target_id=target_id) - active_flag = target_details.target_record.active_flag - assert active_flag is active_flag_expected diff --git a/tests/vws/test_configuration.py b/tests/vws/test_configuration.py deleted file mode 100644 index 7d3e640f..00000000 --- a/tests/vws/test_configuration.py +++ /dev/null @@ -1,211 +0,0 @@ -"""Tests for `vws` configuration commands.""" - -import datetime as dt -import io -import uuid -from pathlib import Path - -import pytest -import requests -from click.testing import CliRunner -from freezegun import freeze_time -from mock_vws import MockVWS -from mock_vws.database import CloudDatabase - -from vws_cli import vws_group - - -@pytest.mark.parametrize( - argnames=("response_delay_seconds", "expect_timeout"), - argvalues=[(29, False), (31, True)], -) -def test_default_timeout( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, - response_delay_seconds: int, - expect_timeout: bool, -) -> None: - """At 29 seconds there is no error; at 31 seconds there is a - timeout. - """ - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - with ( - freeze_time() as frozen_datetime, - MockVWS( - response_delay_seconds=response_delay_seconds, - sleep_fn=lambda seconds: ( - frozen_datetime.tick( - delta=dt.timedelta(seconds=seconds), - ), - None, - )[1], - ) as mock, - ): - database = CloudDatabase() - mock.add_cloud_database(cloud_database=database) - commands = [ - "add-target", - "--name", - uuid.uuid4().hex, - "--width", - "1", - "--image", - str(object=new_file), - "--server-access-key", - database.server_access_key, - "--server-secret-key", - database.server_secret_key, - ] - - if expect_timeout: - with pytest.raises( - expected_exception=requests.exceptions.Timeout, - ): - _ = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - else: - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - - -def test_custom_timeout( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """Custom connection and read timeouts are respected.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - with ( - freeze_time() as frozen_datetime, - MockVWS( - response_delay_seconds=5, - sleep_fn=lambda seconds: ( - frozen_datetime.tick( - delta=dt.timedelta(seconds=seconds), - ), - None, - )[1], - ) as mock, - ): - database = CloudDatabase() - mock.add_cloud_database(cloud_database=database) - commands = [ - "add-target", - "--name", - uuid.uuid4().hex, - "--width", - "1", - "--image", - str(object=new_file), - "--server-access-key", - database.server_access_key, - "--server-secret-key", - database.server_secret_key, - "--read-timeout-seconds", - "1", - ] - - with pytest.raises( - expected_exception=requests.exceptions.Timeout, - ): - _ = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - - -def test_custom_timeout_no_error( - *, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """A sufficiently large timeout does not cause an error.""" - runner = CliRunner() - new_file = tmp_path / uuid.uuid4().hex - image_data = high_quality_image.getvalue() - _ = new_file.write_bytes(data=image_data) - with ( - freeze_time() as frozen_datetime, - MockVWS( - response_delay_seconds=5, - sleep_fn=lambda seconds: ( - frozen_datetime.tick( - delta=dt.timedelta(seconds=seconds), - ), - None, - )[1], - ) as mock, - ): - database = CloudDatabase() - mock.add_cloud_database(cloud_database=database) - commands = [ - "add-target", - "--name", - uuid.uuid4().hex, - "--width", - "1", - "--image", - str(object=new_file), - "--server-access-key", - database.server_access_key, - "--server-secret-key", - database.server_secret_key, - "--read-timeout-seconds", - "60", - ] - - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - - -def test_custom_base_url() -> None: - """ - It is possible to use the API to connect to a database under a - custom VWS - URL. - """ - runner = CliRunner() - base_vws_url = "http://example.com" - mock_database = CloudDatabase() - commands = [ - "list-targets", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - "--base-vws-url", - base_vws_url, - ] - with MockVWS(base_vws_url=base_vws_url) as mock: - mock.add_cloud_database(cloud_database=mock_database) - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 0 diff --git a/tests/vws/test_processing.py b/tests/vws/test_processing.py deleted file mode 100644 index c84ea53d..00000000 --- a/tests/vws/test_processing.py +++ /dev/null @@ -1,313 +0,0 @@ -"""Tests for `vws` processing commands.""" - -import io - -from click.testing import CliRunner -from mock_vws import MockVWS -from mock_vws.database import CloudDatabase -from vws import VWS -from vws.reports import TargetStatuses - -from vws_cli import vws_group - - -def test_wait_for_target_processed( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, -) -> None: - """ - It is possible to use a command to wait for a target to be - processed. - """ - runner = CliRunner() - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - report = vws_client.get_target_summary_report(target_id=target_id) - assert report.status == TargetStatuses.PROCESSING - commands = [ - "wait-for-target-processed", - "--target-id", - target_id, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - assert not bool(result.stdout) - report = vws_client.get_target_summary_report(target_id=target_id) - assert report.status != TargetStatuses.PROCESSING - - -def test_default_seconds_between_requests( - high_quality_image: io.BytesIO, -) -> None: - """By default, 0.2 seconds are waited between polling requests.""" - runner = CliRunner() - with MockVWS(processing_time_seconds=0.5) as mock: - mock_database = CloudDatabase() - mock.add_cloud_database(cloud_database=mock_database) - vws_client = VWS( - server_access_key=mock_database.server_access_key, - server_secret_key=mock_database.server_secret_key, - ) - - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - commands = [ - "wait-for-target-processed", - "--target-id", - target_id, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - assert not bool(result.stdout) - report = vws_client.get_database_summary_report() - expected_requests = ( - # Add target request - 1 - + - # Database summary request - 1 - + - # Initial request - 1 - + - # Request after 0.2 seconds - not processed - 1 - + - # Request after 0.4 seconds - not processed - # This assumes that there is less than 0.1 seconds taken - # between the start of the target processing and the start of - # waiting for the target to be processed. - 1 - + - # Request after 0.6 seconds - processed - 1 - ) - # At the time of writing there is a bug which prevents request - # usage from being tracked so we cannot track this. - expected_requests = 0 - assert report.request_usage == expected_requests - - -def test_custom_seconds_between_requests( - high_quality_image: io.BytesIO, -) -> None: - """ - It is possible to customize the time waited between polling - requests. - """ - runner = CliRunner() - with MockVWS(processing_time_seconds=0.5) as mock: - mock_database = CloudDatabase() - mock.add_cloud_database(cloud_database=mock_database) - vws_client = VWS( - server_access_key=mock_database.server_access_key, - server_secret_key=mock_database.server_secret_key, - ) - - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - commands = [ - "wait-for-target-processed", - "--target-id", - target_id, - "--seconds-between-requests", - "0.3", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - assert not bool(result.stdout) - report = vws_client.get_database_summary_report() - expected_requests = ( - # Add target request - 1 - + - # Database summary request - 1 - + - # Initial request - 1 - + - # Request after 0.3 seconds - not processed - # This assumes that there is less than 0.2 seconds taken - # between the start of the target processing and the start of - # waiting for the target to be processed. - 1 - + - # Request after 0.6 seconds - processed - 1 - ) - # At the time of writing there is a bug which prevents request - # usage from being tracked so we cannot track this. - expected_requests = 0 - assert report.request_usage == expected_requests - - -def test_custom_seconds_too_small(mock_database: CloudDatabase) -> None: - """ - The minimum valid value for ``--seconds-between-requests`` is - 0.05 - seconds. - """ - runner = CliRunner() - commands = [ - "wait-for-target-processed", - "--target-id", - "x", - "--seconds-between-requests", - "0.01", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code != 0 - assert not bool(result.stdout) - expected_substring = "0.01 is not in the range x>=0.05." - assert expected_substring in result.stderr - - -def test_custom_timeout(high_quality_image: io.BytesIO) -> None: - """It is possible to set a maximum timeout.""" - runner = CliRunner() - with MockVWS(processing_time_seconds=0.5) as mock: - mock_database = CloudDatabase() - mock.add_cloud_database(cloud_database=mock_database) - vws_client = VWS( - server_access_key=mock_database.server_access_key, - server_secret_key=mock_database.server_secret_key, - ) - - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - report = vws_client.get_target_summary_report(target_id=target_id) - assert report.status == TargetStatuses.PROCESSING - - commands = [ - "wait-for-target-processed", - "--target-id", - target_id, - "--timeout-seconds", - "0.1", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code != 0 - assert result.stderr == ( - "Error: The target processing time has exceeded the allowed " - "limit.\n" - ) - - commands = [ - "wait-for-target-processed", - "--target-id", - target_id, - "--timeout-seconds", - "0.5", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - report = vws_client.get_target_summary_report(target_id=target_id) - assert report.status != TargetStatuses.PROCESSING - - -def test_custom_timeout_too_small(mock_database: CloudDatabase) -> None: - """ - The minimum valid value for ``--timeout-seconds`` is 0.05 - seconds. - """ - runner = CliRunner() - commands = [ - "wait-for-target-processed", - "--target-id", - "x", - "--timeout-seconds", - "0.01", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code != 0 - expected_substring = "0.01 is not in the range x>=0.05." - assert expected_substring in result.stderr diff --git a/tests/vws/test_reports.py b/tests/vws/test_reports.py deleted file mode 100644 index b646ebcd..00000000 --- a/tests/vws/test_reports.py +++ /dev/null @@ -1,109 +0,0 @@ -"""Tests for `vws` reports commands.""" - -import io - -import yaml -from click.testing import CliRunner -from freezegun import freeze_time -from mock_vws.database import CloudDatabase -from vws import VWS - -from vws_cli import vws_group - - -def test_get_database_summary_report( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, -) -> None: - """It is possible to get a database summary report.""" - runner = CliRunner() - for name in ("a", "b"): - _ = vws_client.add_target( - name=name, - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - commands = [ - "get-database-summary-report", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - expected_result_data = { - "active_images": 0, - "current_month_recos": 0, - "failed_images": 0, - "inactive_images": 0, - "name": mock_database.database_name, - "previous_month_recos": 0, - "processing_images": 2, - "reco_threshold": 1000, - "request_quota": 100000, - "request_usage": 0, - "target_quota": 1000, - "total_recos": 0, - } - assert result_data == expected_result_data - - -def test_get_target_summary_report( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, -) -> None: - """It is possible to get a target summary report.""" - runner = CliRunner() - upload_date = "2015-04-29" - with freeze_time(time_to_freeze=upload_date): - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - commands = [ - "get-target-summary-report", - "--target-id", - target_id, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - expected_result_data = { - "active_flag": True, - "current_month_recos": 0, - "database_name": mock_database.database_name, - "previous_month_recos": 0, - "status": "success", - "target_name": "x", - "total_recos": 0, - "tracking_rating": result_data["tracking_rating"], - "upload_date": upload_date, - } - assert result_data == expected_result_data diff --git a/tests/vws/test_targets.py b/tests/vws/test_targets.py deleted file mode 100644 index 4b1e7571..00000000 --- a/tests/vws/test_targets.py +++ /dev/null @@ -1,179 +0,0 @@ -"""Tests for `vws` targets commands.""" - -import io - -import yaml -from click.testing import CliRunner -from mock_vws.database import CloudDatabase -from vws import VWS - -from vws_cli import vws_group - - -def test_list_targets( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, -) -> None: - """It is possible to get a list of targets in the database.""" - runner = CliRunner() - target_id_1 = vws_client.add_target( - name="x1", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - target_id_2 = vws_client.add_target( - name="x2", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - commands = [ - "list-targets", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - expected_result_data = [target_id_1, target_id_2] - # We do not expect a particular order. - assert sorted(result_data) == sorted(expected_result_data) - - -def test_get_target_record( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, -) -> None: - """It is possible to get a target record.""" - runner = CliRunner() - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - commands = [ - "get-target-record", - "--target-id", - target_id, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - expected_result_data = { - "active_flag": True, - "name": "x", - "reco_rating": "", - "target_id": target_id, - "tracking_rating": -1, - "width": 1, - } - assert result_data == expected_result_data - - -def test_delete_target( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, -) -> None: - """It is possible to delete a target.""" - runner = CliRunner() - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - assert vws_client.list_targets() == [target_id] - commands = [ - "delete-target", - "--target-id", - target_id, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - vws_client.wait_for_target_processed(target_id=target_id) - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - assert not bool(result.stdout) - assert vws_client.list_targets() == [] - - -def test_get_duplicate_targets( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, -) -> None: - """It is possible to get a list of duplicate targets.""" - runner = CliRunner() - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - target_id_2 = vws_client.add_target( - name="x2", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - - vws_client.wait_for_target_processed(target_id=target_id) - vws_client.wait_for_target_processed(target_id=target_id_2) - - commands = [ - "get-duplicate-targets", - "--target-id", - target_id, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - result_data = yaml.safe_load(stream=result.stdout) - expected_result_data = [target_id_2] - assert result_data == expected_result_data diff --git a/tests/vws/test_update_target.py b/tests/vws/test_update_target.py deleted file mode 100644 index 307d6736..00000000 --- a/tests/vws/test_update_target.py +++ /dev/null @@ -1,297 +0,0 @@ -"""Tests for `vws` update target commands.""" - -import base64 -import io -import secrets -import uuid -from pathlib import Path -from textwrap import dedent - -from click.testing import CliRunner -from mock_vws.database import CloudDatabase -from vws import VWS, CloudRecoService - -from vws_cli import vws_group - - -def test_update_target( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, - cloud_reco_client: CloudRecoService, - different_high_quality_image: io.BytesIO, -) -> None: - """It is possible to update a target.""" - runner = CliRunner() - old_name = uuid.uuid4().hex - old_width = secrets.choice(seq=range(1, 5000)) / 100 - target_id = vws_client.add_target( - name=old_name, - width=old_width, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - new_application_metadata = base64.b64encode(s=b"a").decode( - encoding="ascii", - ) - new_name = uuid.uuid4().hex - new_width = secrets.choice(seq=range(1, 5000)) / 100 - new_image_file = tmp_path / uuid.uuid4().hex - new_image_data = different_high_quality_image.getvalue() - _ = new_image_file.write_bytes(data=new_image_data) - - commands = [ - "update-target", - "--target-id", - target_id, - "--name", - new_name, - "--width", - str(object=new_width), - "--image", - str(object=new_image_file), - "--active-flag", - "true", - "--application-metadata", - new_application_metadata, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - assert not bool(result.stdout) - - vws_client.wait_for_target_processed(target_id=target_id) - [ - matching_target, - ] = cloud_reco_client.query(image=different_high_quality_image) - assert matching_target.target_id == target_id - query_target_data = matching_target.target_data - assert query_target_data is not None - query_metadata = query_target_data.application_metadata - assert query_metadata == new_application_metadata - - commands = [ - "update-target", - "--target-id", - target_id, - "--active-flag", - "false", - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - assert not bool(result.stdout) - target_details = vws_client.get_target_record(target_id=target_id) - target_record = target_details.target_record - assert not target_record.active_flag - assert target_record.name == new_name - assert target_record.width == new_width - assert not target_record.active_flag - - -def test_no_fields_given( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, -) -> None: - """It is possible to give no update fields.""" - runner = CliRunner() - old_name = uuid.uuid4().hex - old_width = secrets.choice(seq=range(1, 5000)) / 100 - target_id = vws_client.add_target( - name=old_name, - width=old_width, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - - commands = [ - "update-target", - "--target-id", - target_id, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - assert result.exit_code == 0 - assert not bool(result.stdout) - - -def test_image_file_does_not_exist( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """ - An appropriate error is given if the given image file does not - exist. - """ - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - runner = CliRunner() - does_not_exist_file = tmp_path / uuid.uuid4().hex - commands = [ - "update-target", - "--target-id", - target_id, - "--image", - str(object=does_not_exist_file), - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_result_code = 2 - assert result.exit_code == expected_result_code - assert not bool(result.stdout) - expected_stderr = dedent( - text=f"""\ - Usage: vws update-target [OPTIONS] - Try 'vws update-target --help' for help. - - Error: Invalid value for '--image': File '{does_not_exist_file}' does not exist. - """, - ).replace("\\", "\\\\") - assert result.stderr == expected_stderr - - -def test_image_file_is_dir( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """ - An appropriate error is given if the given image file path - points to a - directory. - """ - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - runner = CliRunner() - commands = [ - "update-target", - "--target-id", - target_id, - "--image", - str(object=tmp_path), - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - expected_result_code = 2 - assert result.exit_code == expected_result_code - assert not bool(result.stdout) - expected_stderr = dedent( - text=f"""\ - Usage: vws update-target [OPTIONS] - Try 'vws update-target --help' for help. - - Error: Invalid value for '--image': File '{tmp_path}' is a directory. - """, - ).replace("\\", "\\\\") - assert result.stderr == expected_stderr - - -def test_relative_path( - *, - mock_database: CloudDatabase, - vws_client: VWS, - high_quality_image: io.BytesIO, - tmp_path: Path, -) -> None: - """Image file paths are resolved.""" - runner = CliRunner() - target_id = vws_client.add_target( - name="x", - width=1, - image=high_quality_image, - active_flag=True, - application_metadata=None, - ) - vws_client.wait_for_target_processed(target_id=target_id) - new_filename = uuid.uuid4().hex - original_image_file = tmp_path / "foo" - image_data = high_quality_image.getvalue() - _ = original_image_file.write_bytes(data=image_data) - commands = [ - "update-target", - "--target-id", - target_id, - "--image", - new_filename, - "--server-access-key", - mock_database.server_access_key, - "--server-secret-key", - mock_database.server_secret_key, - ] - - with runner.isolated_filesystem(): - new_file = Path(new_filename) - new_file.symlink_to(target=original_image_file) - result = runner.invoke( - cli=vws_group, - args=commands, - catch_exceptions=False, - color=True, - ) - - assert result.exit_code == 0 diff --git a/uv.lock b/uv.lock index 7d18c39a..0f67d66e 100644 --- a/uv.lock +++ b/uv.lock @@ -2603,7 +2603,6 @@ dev = [ { name = "vale" }, { name = "vulture" }, { name = "vws-python-mock" }, - { name = "vws-test-fixtures" }, { name = "yamlfix" }, { name = "zizmor" }, ] @@ -2670,7 +2669,6 @@ dev = [ { name = "vale", specifier = "==3.25.1.0" }, { name = "vulture", specifier = "==2.16" }, { name = "vws-python-mock", specifier = "==2026.10.13.1" }, - { name = "vws-test-fixtures", specifier = "==2026.10.8" }, { name = "yamlfix", specifier = "==1.19.1" }, { name = "zizmor", specifier = "==1.31.1" }, ] @@ -2725,19 +2723,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9d/4e/8c322762652741546567859ea70d4bf3260eaf97b5a3be42fc0f580f5708/vws_python_mock-2026.10.13.1-py3-none-any.whl", hash = "sha256:93acbb2076be181714cd1cc983da2997369446f811bd06bb8db9a17bd176a4fe", size = 123160, upload-time = "2026-10-13T08:12:52.641Z" }, ] -[[package]] -name = "vws-test-fixtures" -version = "2026.10.8" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pillow" }, - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8b/a9/da97ec4112b059fbfe495c0a7711dedf6fd4ee3afd3db7ff21ce22a87706/vws_test_fixtures-2026.10.8.tar.gz", hash = "sha256:ed54a1e1e7f07a073ada72f13494c8c884196aacc5213cfbc6a7c26206dc9239", size = 74610, upload-time = "2026-10-08T03:28:28.271Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4e/85/68f98e4bdf0525388b1625ce4da5c2be89601dfd3a58101947f69e9eedeb/vws_test_fixtures-2026.10.8-py3-none-any.whl", hash = "sha256:efd2e6ecd4353e9bf50ba7bce2c46e44414f7a5196ca7d70769b7e7feb7ad899", size = 51949, upload-time = "2026-10-08T03:28:26.946Z" }, -] - [[package]] name = "werkzeug" version = "3.1.9"