{"time": "2023-09-01T02:05:25+00:00", "type": "commit", "payload": {"sha": "098d7511816c326a423d36a73a4fd14a95756fdb", "node_id": "C_kwDOKNhT9doAKDA5OGQ3NTExODE2YzMyNmE0MjNkMzZhNzNhNGZkMTRhOTU3NTZmZGI", "commit": {"author": {"name": "Daniel Neilson", "email": "neilsd@amazon.com", "date": "2023-09-01T02:05:25Z"}, "committer": {"name": "Daniel Neilson", "email": "neilsd@amazon.com", "date": "2023-09-01T18:30:09Z"}, "message": "feat!: Import from internal repository\n\nThis is an import of the source code that had been authored on internal\nrepositories.", "tree": {"sha": "fce068f2e13f26f2a628c26f9987720ebd0089f9", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/trees/fce068f2e13f26f2a628c26f9987720ebd0089f9"}, "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/commits/098d7511816c326a423d36a73a4fd14a95756fdb", "comment_count": 0, "verification": {"verified": false, "reason": "unsigned", "signature": null, "payload": null, "verified_at": null}}, "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits/098d7511816c326a423d36a73a4fd14a95756fdb", "html_url": "https://github.com/OpenJobDescription/openjd-model-for-python/commit/098d7511816c326a423d36a73a4fd14a95756fdb", "comments_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits/098d7511816c326a423d36a73a4fd14a95756fdb/comments", "author": null, "committer": null, "parents": [{"sha": "f1d0e490683bb507a3757ab2d640ba52de0d3ee2", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits/f1d0e490683bb507a3757ab2d640ba52de0d3ee2", "html_url": "https://github.com/OpenJobDescription/openjd-model-for-python/commit/f1d0e490683bb507a3757ab2d640ba52de0d3ee2"}], "stats": {"total": 16807, "additions": 16797, "deletions": 10}, "files": [{"sha": "7472320275b48c5503c1717af7603dbb16ed5bc0", "filename": ".github/CODEOWNERS", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FCODEOWNERS", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FCODEOWNERS", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2FCODEOWNERS?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1 @@\n+* @xxyggoqtpcmcofkc/Developers\n\\ No newline at end of file"}, {"sha": "dd351d8144d2590bdf99fd426d18aa63816eb4c7", "filename": ".github/ISSUE_TEMPLATE/bug.yml", "status": "added", "additions": 33, "deletions": 0, "changes": 33, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Fbug.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Fbug.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2FISSUE_TEMPLATE%2Fbug.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,33 @@\n+name: \"\\U0001F41B Bug Report\"\n+description: Report a bug\n+title: \"Bug: TITLE\"\n+labels: [\"bug\"]\n+body:\n+ - type: textarea\n+ id: expected_behaviour\n+ attributes:\n+ label: Expected Behaviour\n+ validations:\n+ required: true\n+\n+ - type: textarea\n+ id: current_behaviour\n+ attributes:\n+ label: Current Behaviour\n+ validations:\n+ required: true\n+\n+ - type: textarea\n+ id: reproduction_steps\n+ attributes:\n+ label: Reproduction Steps\n+ validations:\n+ required: true\n+\n+ - type: textarea\n+ id: code_snippet\n+ attributes:\n+ label: Code Snippet\n+ validations:\n+ required: true\n+"}, {"sha": "ec4bb386bcf8a4946923eff961cc7cdf70c0aedf", "filename": ".github/ISSUE_TEMPLATE/config.yml", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Fconfig.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Fconfig.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2FISSUE_TEMPLATE%2Fconfig.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1 @@\n+blank_issues_enabled: false\n\\ No newline at end of file"}, {"sha": "883623bba8c47a0bbcc08928694900b1d1fe4046", "filename": ".github/ISSUE_TEMPLATE/doc.yml", "status": "added", "additions": 13, "deletions": 0, "changes": 13, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Fdoc.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Fdoc.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2FISSUE_TEMPLATE%2Fdoc.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,13 @@\n+\n+name: \"\ud83d\udcd5 Documentation Issue\"\n+description: Issue in the documentation\n+title: \"Docs: TITLE\"\n+labels: [\"documenation\"]\n+body:\n+ - type: textarea\n+ id: documentation_issue\n+ attributes:\n+ label: Documentation Issue\n+ description: Describe the issue\n+ validations:\n+ required: true\n\\ No newline at end of file"}, {"sha": "ed7f957076237eec69b71d9e672f301abf472428", "filename": ".github/ISSUE_TEMPLATE/feature_request.yml", "status": "added", "additions": 17, "deletions": 0, "changes": 17, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Ffeature_request.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Ffeature_request.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2FISSUE_TEMPLATE%2Ffeature_request.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,17 @@\n+name: \"\\U0001F680 Feature Request\"\n+description: Request a new feature\n+title: \"Feature request: TITLE\"\n+labels: [\"feature\"]\n+body:\n+ - type: textarea\n+ id: use_case\n+ attributes:\n+ label: Use Case\n+ validations:\n+ required: true\n+ - type: textarea\n+ id: proposed_solution\n+ attributes:\n+ label: Proposed Solution\n+ validations:\n+ required: true"}, {"sha": "a0f98fffb0a99dc7b82dc73b2c3326b56cd8e845", "filename": ".github/ISSUE_TEMPLATE/maintenance.yml", "status": "added", "additions": 17, "deletions": 0, "changes": 17, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Fmaintenance.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FISSUE_TEMPLATE%2Fmaintenance.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2FISSUE_TEMPLATE%2Fmaintenance.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,17 @@\n+name: \"\ud83d\udee0\ufe0f Maintenance\"\n+description: Some type of improvement\n+title: \"Maintenance: TITLE\"\n+labels: [\"feature\"]\n+body:\n+ - type: textarea\n+ id: description\n+ attributes:\n+ label: Description\n+ validations:\n+ required: true\n+ - type: textarea\n+ id: solution\n+ attributes:\n+ label: Solution\n+ validations:\n+ required: true"}, {"sha": "07e5be9e90b09293ce76ce17a764c685b2e0fce4", "filename": ".github/PULL_REQUEST_TEMPLATE.md", "status": "added", "additions": 15, "deletions": 0, "changes": 15, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FPULL_REQUEST_TEMPLATE.md", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2FPULL_REQUEST_TEMPLATE.md", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2FPULL_REQUEST_TEMPLATE.md?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,15 @@\n+### What was the problem/requirement? (What/Why)\n+\n+### What was the solution? (How)\n+\n+### What is the impact of this change?\n+\n+### How was this change tested?\n+\n+### Was this change documented?\n+\n+### Is this a breaking change?\n+\n+----\n+\n+*By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.*\n\\ No newline at end of file"}, {"sha": "ea851027c545354146c323617800efc493d1eaa8", "filename": ".github/dependabot.yml", "status": "added", "additions": 21, "deletions": 0, "changes": 21, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fdependabot.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fdependabot.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2Fdependabot.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,21 @@\n+# To get started with Dependabot version updates, you'll need to specify which\n+# package ecosystems to update and where the package manifests are located.\n+# Please see the documentation for all configuration options:\n+# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates\n+\n+version: 2\n+updates:\n+ - package-ecosystem: \"pip\"\n+ directory: \"/\" # Location of package manifests\n+ schedule:\n+ interval: \"weekly\"\n+ day: \"monday\"\n+ commit-message: \n+ prefix: \"chore(deps):\"\n+ - package-ecosystem: \"github-actions\"\n+ directory: \"/\" # Location of package manifests\n+ schedule:\n+ interval: \"weekly\"\n+ day: \"monday\"\n+ commit-message: \n+ prefix: \"chore(github):\"\n\\ No newline at end of file"}, {"sha": "5fbbef77fd06925a934b2d490187bf577ab69401", "filename": ".github/workflows/auto_approve.yml", "status": "added", "additions": 21, "deletions": 0, "changes": 21, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fworkflows%2Fauto_approve.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fworkflows%2Fauto_approve.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2Fworkflows%2Fauto_approve.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,21 @@\n+name: Dependabot auto-approve\n+on: pull_request\n+\n+permissions:\n+ pull-requests: write\n+\n+jobs:\n+ dependabot:\n+ runs-on: ubuntu-latest\n+ if: ${{ github.actor == 'dependabot[bot]' }}\n+ steps:\n+ - name: Dependabot metadata\n+ id: metadata\n+ uses: dependabot/fetch-metadata@v1\n+ with:\n+ github-token: \"${{ secrets.GITHUB_TOKEN }}\"\n+ - name: Approve a PR\n+ run: gh pr review --approve \"$PR_URL\"\n+ env:\n+ PR_URL: ${{ github.event.pull_request.html_url }}\n+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\\ No newline at end of file"}, {"sha": "c57fe58627e8dbb8b8fef624551f062f89d790e9", "filename": ".github/workflows/code_quality.yml", "status": "added", "additions": 17, "deletions": 0, "changes": 17, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fworkflows%2Fcode_quality.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fworkflows%2Fcode_quality.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2Fworkflows%2Fcode_quality.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,17 @@\n+name: Code Quality\n+\n+on:\n+ pull_request:\n+ branches: [ mainline ]\n+ workflow_call:\n+ inputs:\n+ branch:\n+ required: false\n+ type: string\n+\n+jobs:\n+ TestPython:\n+ name: Code Quality\n+ uses: ./.github/workflows/reuse_python_build.yml\n+ secrets: inherit\n+"}, {"sha": "d0a3365cd3931e29ebdb023e24123db0052e3795", "filename": ".github/workflows/release.yml", "status": "added", "additions": 51, "deletions": 0, "changes": 51, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fworkflows%2Frelease.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fworkflows%2Frelease.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2Fworkflows%2Frelease.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,51 @@\n+name: Release\n+\n+on:\n+ workflow_dispatch:\n+ inputs:\n+ version_to_publish:\n+ description: \"Version to be release\"\n+ required: false\n+\n+jobs:\n+ TestMainline:\n+ name: Test Mainline\n+ uses: ./.github/workflows/code_quality.yml\n+ with:\n+ branch: mainline\n+ secrets: inherit\n+\n+ Merge:\n+ needs: TestMainline\n+ runs-on: ubuntu-latest\n+ permissions:\n+ contents: write\n+ steps:\n+ - uses: actions/checkout@v3\n+ with:\n+ ref: release\n+ fetch-depth: 0\n+ token: ${{ secrets.CI_TOKEN }}\n+ - name: Set Git config\n+ run: |\n+ git config --local user.email \"client-software-ci@amazon.com\"\n+ git config --local user.name \"client-software-ci\"\n+ - name: Update Release\n+ run: git merge --ff-only origin/mainline -v\n+ - name: Push new release\n+ if: ${{ inputs.version_to_publish}}\n+ run: |\n+ git tag -a ${{ inputs.version_to_publish }} -m \"Release ${{ inputs.version_to_publish }}\"\n+ git push origin release ${{ inputs.version_to_publish }}\n+ - name: Push post release\n+ if: ${{ !inputs.version_to_publish}}\n+ run: git push origin release\n+\n+ TestRelease:\n+ needs: Merge\n+ name: Test Release\n+ uses: ./.github/workflows/code_quality.yml\n+ with:\n+ branch: release\n+ secrets: inherit\n+"}, {"sha": "b4f4b28d0090e07b7e3b1f4563a548b89abf1f31", "filename": ".github/workflows/reuse_python_build.yml", "status": "added", "additions": 62, "deletions": 0, "changes": 62, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fworkflows%2Freuse_python_build.yml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.github%2Fworkflows%2Freuse_python_build.yml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.github%2Fworkflows%2Freuse_python_build.yml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,62 @@\n+name: Python Build\n+\n+on:\n+ workflow_call:\n+ inputs:\n+ branch:\n+ required: false\n+ type: string\n+\n+jobs:\n+ Python:\n+ # We've seen some deadlocks in tests run on the CI. Hard-cap the job runtime\n+ # to prevent those from running too long before being terminated.\n+ timeout-minutes: 15\n+ runs-on: ${{ matrix.os }}\n+ permissions:\n+ id-token: write\n+ contents: read\n+ strategy:\n+ matrix:\n+ python-version: ['3.9', '3.10', '3.11']\n+ os: [ubuntu-latest, windows-latest, macOS-latest]\n+ env:\n+ PYTHON: ${{ matrix.python-version }}\n+ CODEARTIFACT_REGION: \"us-west-2\"\n+ CODEARTIFACT_DOMAIN: ${{ secrets.CODEARTIFACT_DOMAIN }}\n+ CODEARTIFACT_ACCOUNT_ID: ${{ secrets.CODEARTIFACT_ACCOUNT_ID }}\n+ CODEARTIFACT_REPOSITORY: ${{ secrets.CODEARTIFACT_REPOSITORY }}\n+ steps:\n+ - uses: actions/checkout@v3\n+ if: ${{ !inputs.branch }}\n+ \n+ - uses: actions/checkout@v3\n+ if: ${{ inputs.branch }}\n+ with:\n+ ref: ${{ inputs.branch }}\n+ fetch-depth: 0\n+\n+ - name: Set up Python ${{ matrix.python-version }}\n+ uses: actions/setup-python@v4\n+ with:\n+ python-version: ${{ matrix.python-version }}\n+ \n+ - name: Configure AWS credentials\n+ uses: aws-actions/configure-aws-credentials@v3\n+ with:\n+ role-to-assume: ${{ secrets.AWS_CODEARTIFACT_ROLE }}\n+ aws-region: us-west-2\n+ mask-aws-account-id: true\n+\n+ - name: Install Hatch\n+ run: |\n+ CODEARTIFACT_AUTH_TOKEN=$(aws codeartifact get-authorization-token --domain ${{ secrets.CODEARTIFACT_DOMAIN }} --domain-owner ${{ secrets.CODEARTIFACT_ACCOUNT_ID }} --query authorizationToken --output text --region us-west-2)\n+ echo \"::add-mask::$CODEARTIFACT_AUTH_TOKEN\"\n+ echo CODEARTIFACT_AUTH_TOKEN=$CODEARTIFACT_AUTH_TOKEN >> $GITHUB_ENV\n+ pip install --upgrade -r requirements-development.txt\n+\n+ - name: Run Linting\n+ run: hatch run lint\n+\n+ - name: Run Tests\n+ run: hatch run test\n\\ No newline at end of file"}, {"sha": "f30fb6f8967adf9e17f8db53ac984d18d2a9087e", "filename": ".gitignore", "status": "added", "additions": 24, "deletions": 0, "changes": 24, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/.gitignore", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/.gitignore", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/.gitignore?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,24 @@\n+*~\n+*#\n+*.swp\n+\n+*.DS_Store\n+\n+__pycache__/\n+*.py[cod]\n+*$py.class\n+*.egg-info/\n+\n+/.coverage\n+/.coverage.*\n+/.cache\n+/.pytest_cache\n+/.mypy_cache\n+/.ruff_cache\n+/.attach_pid*\n+/.venv\n+\n+/doc/_apidoc/\n+/build\n+/dist\n+_version.py"}, {"sha": "0b3cabfe7036fe9a11f5ab75528dbfe6874e1306", "filename": "CONTRIBUTING.md", "status": "modified", "additions": 7, "deletions": 2, "changes": 9, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/CONTRIBUTING.md", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/CONTRIBUTING.md", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/CONTRIBUTING.md?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -6,7 +6,6 @@ documentation, we greatly value feedback and contributions from our community.\n Please read through this document before submitting any issues or pull requests to ensure we have all the necessary\n information to effectively respond to your bug report or contribution.\n \n-\n ## Reporting Bugs/Feature Requests\n \n We welcome you to use the GitHub issue tracker to report bugs or suggest features.\n@@ -19,8 +18,12 @@ reported the issue. Please try to include as much information as you can. Detail\n * Any modifications you've made relevant to the bug\n * Anything unusual about your environment or deployment\n \n+## Development\n+\n+Please see [DEVELOPMENT.md](./DEVELOPMENT.md) for more information.\n \n ## Contributing via Pull Requests\n+\n Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:\n \n 1. You are working against the latest source on the *main* branch.\n@@ -39,18 +42,20 @@ To send us a pull request, please:\n GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and\n [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).\n \n-\n ## Finding contributions to work on\n+\n Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start.\n \n \n ## Code of Conduct\n+\n This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).\n For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact\n opensource-codeofconduct@amazon.com with any additional questions or comments.\n \n \n ## Security issue notifications\n+\n If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.\n \n "}, {"sha": "2bd07872028abe03befb3c6c85549ded1fa27f03", "filename": "DEVELOPMENT.md", "status": "added", "additions": 160, "deletions": 0, "changes": 160, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/DEVELOPMENT.md", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/DEVELOPMENT.md", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/DEVELOPMENT.md?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,160 @@\n+\n+# Development\n+\n+## Command Reference\n+\n+```\n+# Build the package\n+hatch build\n+\n+# Run tests\n+hatch run test\n+\n+# Run linting\n+hatch run lint\n+\n+# Run formatting\n+hatch run fmt\n+\n+# Run a full test\n+hatch run all:test\n+```\n+\n+## The Package's Public Interface\n+\n+This package is a library wherein we are explicit and intentional with what we expose as public.\n+\n+The standard convention in Python is to prefix things with an underscore character ('_') to\n+signify that the thing is private to the implementation, and is not intended to be used by\n+external consumers of the thing.\n+\n+We use this convention in this package in two ways:\n+\n+1. In filenames.\n+ 1. Any file whose name is not prefixed with an underscore **is** a part of the public\n+ interface of this package. The name may not change and public symbols (classes, modules,\n+ functions, etc) defined in the file may not be moved to other files or renamed without a\n+ major version number change.\n+ 2. Any file whose name is prefixed with an underscore is an internal module of the package\n+ and is not part of the public interface. These files can be renamed, refactored, have symbols\n+ renamed, etc. Any symbol defined in one of these files that is intended to be part of this\n+ package's public interface must be imported into an appropriate `__init__.py` file.\n+2. Every symbol that is defined or imported in a public module and is not intended to be part\n+ of the module's public interface is prefixed with an underscore.\n+\n+For example, a public module in this package will be defined with the following style:\n+\n+```python\n+# The os module is not part of this file's external interface\n+import os as _os\n+\n+# PublicClass is part of this file's external interface.\n+class PublicClass:\n+ def publicmethod(self):\n+ pass\n+\n+ def _privatemethod(self):\n+ pass\n+\n+# _PrivateClass is not part of this file's external interface.\n+class _PrivateClass:\n+ def publicmethod(self):\n+ pass\n+\n+ def _privatemethod(self):\n+ pass\n+```\n+\n+### On `import os as _os`\n+\n+Every module/symbol that is imported into a Python module becomes a part of that module's interface.\n+Thus, if we have a module called `foo.py` such as:\n+\n+```python\n+# foo.py\n+\n+import os\n+```\n+\n+Then, the `os` module becomes part of the public interface for `foo.py` and a consumer of that module\n+is free to do:\n+\n+```python\n+from foo import os\n+```\n+\n+We don't want all (generally, we don't want any) of our imports to become part of the public API for\n+the module, so we import modules/symbols into a public module with the following style:\n+\n+```python\n+import os as _os\n+from typing import Dict as _Dict\n+```\n+\n+## Use of Keyword-Only Arguments\n+\n+Another convention that we are adopting in this package is that all functions/methods that are a\n+part of the package's external interface should refrain from using positional-or-keyword arguments.\n+All arguments should be keyword-only unless the argument name has no true external meaning (e.g.\n+arg1, arg2, etc for `min`). Benefits of this convention are:\n+\n+1. All uses of the public APIs of this package are forced to be self-documenting; and\n+2. The benefits set forth in PEP 570 ( https://www.python.org/dev/peps/pep-0570/#problems-without-positional-only-parameters ).\n+\n+## Exceptions\n+\n+All functions/methods that raise an exception should have a section in their docstring that states\n+the exception(s) they raise. e.g.\n+\n+```py\n+def my_function(key, value):\n+\"\"\"Does something...\n+\n+ Raises:\n+ KeyError: when the key is not valid\n+ ValueError: when the value is not valid\n+\"\"\"\n+```\n+\n+All function/method calls that can raise an exception should have a comment in the line above\n+that states which exception(s) can be raised. e.g.\n+\n+```py\n+try:\n+ # Raises: KeyError, ValueError\n+ my_function(\"key\", \"value\")\n+except ValueError as e:\n+ # Error handling...\n+```\n+\n+## About the data model\n+\n+1. The data model is written using Pydantic. Pydantic provides the framework for parsing and validating\n+ input job templates.\n+1. We intentionally use `Decimal` in place of `float` in our data models as `Decimal` will preserve the\n+ precision present in the input whereas `float` will not.\n+1. Some classes in the model have \"Definition\" or \"Template\" version, as well as a \"Target model\" version.\n+ These exist for parts of the model where instantiating a JobTemplate into a Job changes the model in\n+ some way. These are not necessary for all parts of the model.\n+\n+## Super verbose test output\n+\n+If you find that you need much more information from a failing test (say you're debugging a\n+deadlocking test) then a way to get verbose output from the test is to enable Pytest\n+[Live Logging](https://docs.pytest.org/en/latest/how-to/logging.html#live-logs):\n+\n+1. Add a `pytest.ini` to the root directory of the repository that contains (Note: for some reason,\n+setting `log_cli` and `log_cli_level` in `pyproject.toml` does not work, nor does setting the options\n+on the command-line; if you figure out how to get it to work then please update this section):\n+```\n+[pytest]\n+xfail_strict = False\n+log_cli = true\n+log_cli_level = 10\n+```\n+2. Modify `pyproject.toml` to set the following additional `addopts` in the `tool.pytest.ini_options` section:\n+```\n+ \"-vvvvv\",\n+ \"--numprocesses=1\"\n+```\n+3. Add logging statements to your tests as desired and run the test(s) that you are debugging."}, {"sha": "aeda70db029e9ddddac59afe4078f35126b0d070", "filename": "README.md", "status": "modified", "additions": 3, "deletions": 8, "changes": 11, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/README.md", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/README.md", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/README.md?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -1,11 +1,7 @@\n-## My Project\n+# Open Job Description - Models\n \n-TODO: Fill this README out!\n-\n-Be sure to:\n-\n-* Change the title in this README\n-* Edit your repository description on GitHub\n+This package provides an implementation of the data model for Open Job Description. It can be used to\n+parse and validate JSON or Yaml documents against the Open Job Description Job Templates.\n \n ## Security\n \n@@ -14,4 +10,3 @@ See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more inform\n ## License\n \n This project is licensed under the Apache-2.0 License.\n-"}, {"sha": "8500348518687f0cca6f74b10dcb2e5e68e6f914", "filename": "THIRD-PARTY-LICENSES.txt", "status": "added", "additions": 52, "deletions": 0, "changes": 52, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/THIRD-PARTY-LICENSES.txt", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/THIRD-PARTY-LICENSES.txt", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/THIRD-PARTY-LICENSES.txt?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,52 @@\n+\n+\n+** PyYAML; version 6.x -- https://pyyaml.org/\n+Copyright (c) 2017-2021 Ingy d\u00f6t Net\n+Copyright (c) 2006-2016 Kirill Simonov\n+ \n+Copyright (c) 2017-2021 Ingy d\u00f6t Net\n+Copyright (c) 2006-2016 Kirill Simonov\n+\n+Permission is hereby granted, free of charge, to any person obtaining a copy of\n+this software and associated documentation files (the \"Software\"), to deal in\n+the Software without restriction, including without limitation the rights to\n+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n+of the Software, and to permit persons to whom the Software is furnished to do\n+so, subject to the following conditions:\n+\n+The above copyright notice and this permission notice shall be included in all\n+copies or substantial portions of the Software.\n+\n+THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n+SOFTWARE.\n+\n+------\n+\n+** Python-pydantic; version 1.x -- https://pydantic-docs.helpmanual.io/\n+Copyright (c) 2017, 2018, 2019, 2020, 2021 Samuel Colvin and other contributors\n+ \n+The MIT License (MIT)\n+\n+Permission is hereby granted, free of charge, to any person obtaining a copy\n+of this software and associated documentation files (the \"Software\"), to deal\n+in the Software without restriction, including without limitation the rights\n+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+copies of the Software, and to permit persons to whom the Software is\n+furnished to do so, subject to the following conditions:\n+\n+The above copyright notice and this permission notice shall be included in all\n+copies or substantial portions of the Software.\n+\n+THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n+SOFTWARE.\n+"}, {"sha": "e8d136591e2c6c8f6a76bbe563542162f20258cc", "filename": "hatch.toml", "status": "added", "additions": 33, "deletions": 0, "changes": 33, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/hatch.toml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/hatch.toml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/hatch.toml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,33 @@\n+[envs.default]\n+pre-install-commands = [\n+ \"pip install -r requirements-testing.txt\"\n+]\n+\n+[envs.default.scripts]\n+sync = \"pip install -r requirements-testing.txt\"\n+test = \"pytest --cov-config pyproject.toml {args:test}\"\n+typing = \"mypy {args:src test}\"\n+style = [\n+ \"ruff {args:.}\",\n+ \"black --check --diff {args:.}\",\n+]\n+fmt = [\n+ \"black {args:.}\",\n+ \"style\",\n+]\n+lint = [\n+ \"style\",\n+ \"typing\",\n+]\n+\n+[[envs.all.matrix]]\n+python = [\"3.9\", \"3.10\", \"3.11\"]\n+\n+[envs.default.env-vars]\n+PIP_INDEX_URL=\"https://aws:{env:CODEARTIFACT_AUTH_TOKEN}@{env:CODEARTIFACT_DOMAIN}-{env:CODEARTIFACT_ACCOUNT_ID}.d.codeartifact.{env:CODEARTIFACT_REGION}.amazonaws.com/pypi/{env:CODEARTIFACT_REPOSITORY}/simple/\"\n+\n+[envs.codebuild.scripts]\n+build = \"hatch build\"\n+\n+[envs.codebuild.env-vars]\n+PIP_INDEX_URL=\"\""}, {"sha": "d7024ea5e80c21f4bdb61a68155cb99cb8f5afe7", "filename": "hatch_version_hook.py", "status": "added", "additions": 156, "deletions": 0, "changes": 156, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/hatch_version_hook.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/hatch_version_hook.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/hatch_version_hook.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,156 @@\n+import logging\n+import os\n+import shutil\n+import sys\n+\n+from dataclasses import dataclass\n+from hatchling.builders.hooks.plugin.interface import BuildHookInterface\n+from typing import Any, Optional\n+\n+\n+_logger = logging.Logger(__name__, logging.INFO)\n+_stdout_handler = logging.StreamHandler(sys.stdout)\n+_stdout_handler.addFilter(lambda record: record.levelno <= logging.INFO)\n+_stderr_handler = logging.StreamHandler(sys.stderr)\n+_stderr_handler.addFilter(lambda record: record.levelno > logging.INFO)\n+_logger.addHandler(_stdout_handler)\n+_logger.addHandler(_stderr_handler)\n+\n+\n+@dataclass\n+class CopyConfig:\n+ sources: list[str]\n+ destinations: list[str]\n+\n+\n+class CustomBuildHookException(Exception):\n+ pass\n+\n+\n+class CustomBuildHook(BuildHookInterface):\n+ \"\"\"\n+ A Hatch build hook that is pulled in automatically by Hatch's \"custom\" hook support\n+ See: https://hatch.pypa.io/1.6/plugins/build-hook/custom/\n+ This build hook copies files from one location (sources) to another (destinations).\n+ Config options:\n+ - `log_level (str)`: The logging level. Any value accepted by logging.Logger.setLevel is allowed. Default is INFO.\n+ - `copy_map (list[dict])`: A list of mappings of files to copy and the destinations to copy them into. In TOML files,\n+ this is expressed as an array of tables. See https://toml.io/en/v1.0.0#array-of-tables\n+ Example TOML config:\n+ ```\n+ [tool.hatch.build.hooks.custom]\n+ path = \"hatch_hook.py\"\n+ log_level = \"DEBUG\"\n+ [[tool.hatch.build.hooks.custom.copy_map]]\n+ sources = [\n+ \"_version.py\",\n+ ]\n+ destinations = [\n+ \"src/openjd\",\n+ ]\n+ [[tool.hatch.build.hooks.custom.copy_map]]\n+ sources = [\n+ \"something_the_tests_need.py\",\n+ \"something_else_the_tests_need.ini\",\n+ ]\n+ destinations = [\n+ \"test/openjd\",\n+ ]\n+ ```\n+ \"\"\"\n+\n+ REQUIRED_OPTS = [\n+ \"copy_map\",\n+ ]\n+\n+ def initialize(self, version: str, build_data: dict[str, Any]) -> None:\n+ if not self._prepare():\n+ return\n+\n+ for copy_cfg in self.copy_map:\n+ _logger.info(f\"Copying {copy_cfg.sources} to {copy_cfg.destinations}\")\n+ for destination in copy_cfg.destinations:\n+ for source in copy_cfg.sources:\n+ copy_func = shutil.copy if os.path.isfile(source) else shutil.copytree\n+ copy_func(\n+ os.path.join(self.root, source),\n+ os.path.join(self.root, destination),\n+ )\n+ _logger.info(\"Copy complete\")\n+\n+ def clean(self, versions: list[str]) -> None:\n+ if not self._prepare():\n+ return\n+\n+ for copy_cfg in self.copy_map:\n+ _logger.info(f\"Cleaning {copy_cfg.sources} from {copy_cfg.destinations}\")\n+ cleaned_count = 0\n+ for destination in copy_cfg.destinations:\n+ for source in copy_cfg.sources:\n+ source_path = os.path.join(self.root, destination, source)\n+ remove_func = os.remove if os.path.isfile(source_path) else os.rmdir\n+ try:\n+ remove_func(source_path)\n+ except FileNotFoundError:\n+ _logger.debug(f\"Skipping {source_path} because it does not exist...\")\n+ else:\n+ cleaned_count += 1\n+ _logger.info(f\"Cleaned {cleaned_count} items\")\n+\n+ def _prepare(self) -> bool:\n+ missing_required_opts = [\n+ opt for opt in self.REQUIRED_OPTS if opt not in self.config or not self.config[opt]\n+ ]\n+ if missing_required_opts:\n+ _logger.warn(\n+ f\"Required options {missing_required_opts} are missing or empty. \"\n+ \"Contining without copying sources to destinations...\",\n+ file=sys.stderr,\n+ )\n+ return False\n+\n+ log_level = self.config.get(\"log_level\")\n+ if log_level:\n+ _logger.setLevel(log_level)\n+\n+ return True\n+\n+ @property\n+ def copy_map(self) -> Optional[list[CopyConfig]]:\n+ raw_copy_map: list[dict] = self.config.get(\"copy_map\")\n+ if not raw_copy_map:\n+ return None\n+\n+ if not (\n+ isinstance(raw_copy_map, list)\n+ and all(isinstance(copy_cfg, dict) for copy_cfg in raw_copy_map)\n+ ):\n+ raise CustomBuildHookException(\n+ f'\"copy_map\" config option is a nonvalid type. Expected list[dict], but got {raw_copy_map}'\n+ )\n+\n+ def verify_list_of_file_paths(file_paths: Any, config_name: str):\n+ if not (isinstance(file_paths, list) and all(isinstance(fp, str) for fp in file_paths)):\n+ raise CustomBuildHookException(\n+ f'\"{config_name}\" config option is a nonvalid type. Expected list[str], but got {file_paths}'\n+ )\n+\n+ missing_paths = [\n+ fp for fp in file_paths if not os.path.exists(os.path.join(self.root, fp))\n+ ]\n+ if len(missing_paths) > 0:\n+ raise CustomBuildHookException(\n+ f'\"{config_name}\" config option contains some file paths that do not exist: {missing_paths}'\n+ )\n+\n+ copy_map: list[CopyConfig] = []\n+ for copy_cfg in raw_copy_map:\n+ destinations: list[str] = copy_cfg.get(\"destinations\")\n+ verify_list_of_file_paths(destinations, \"destinations\")\n+\n+ sources: list[str] = copy_cfg.get(\"sources\")\n+ verify_list_of_file_paths(sources, \"source\")\n+\n+ copy_map.append(CopyConfig(sources, destinations))\n+\n+ return copy_map"}, {"sha": "e8014f30e7a1c77c531dc631c58d062760364cc2", "filename": "pipeline/build.sh", "status": "added", "additions": 10, "deletions": 0, "changes": 10, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/pipeline%2Fbuild.sh", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/pipeline%2Fbuild.sh", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/pipeline%2Fbuild.sh?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,10 @@\n+#!/bin/sh\n+# Set the -e option\n+set -e\n+\n+pip install --upgrade pip\n+pip install --upgrade hatch\n+pip install --upgrade twine\n+hatch run codebuild:lint\n+hatch run codebuild:test\n+hatch run codebuild:build\n\\ No newline at end of file"}, {"sha": "9e9c1b5b207d43aecf7dbff563522416937b936c", "filename": "pipeline/publish.sh", "status": "added", "additions": 6, "deletions": 0, "changes": 6, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/pipeline%2Fpublish.sh", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/pipeline%2Fpublish.sh", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/pipeline%2Fpublish.sh?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,6 @@\n+#!/bin/sh\n+# Set the -e option\n+set -e\n+\n+./pipeline/build.sh\n+twine upload --repository codeartifact dist/* --verbose\n\\ No newline at end of file"}, {"sha": "d8524447e19c1a5e00f7cde4bb63abab932da202", "filename": "pyproject.toml", "status": "added", "additions": 134, "deletions": 0, "changes": 134, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/pyproject.toml", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/pyproject.toml", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/pyproject.toml?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,134 @@\n+[build-system]\n+requires = [\"hatchling\", \"hatch-vcs\"]\n+build-backend = \"hatchling.build\"\n+\n+[project]\n+name = \"openjd-model\"\n+dynamic = [\"version\"]\n+readme = \"README.md\"\n+license = \"Apache-2.0\"\n+requires-python = \">=3.9\"\n+\n+dependencies = [\n+ \"pyyaml ~= 6.0\",\n+ \"pydantic ~= 1.10\",\n+]\n+\n+[tool.hatch.build]\n+artifacts = [\n+ \"*_version.py\",\n+]\n+only-packages = true\n+\n+[tool.hatch.version]\n+source = \"vcs\"\n+\n+[tool.hatch.version.raw-options]\n+version_scheme = \"post-release\"\n+\n+[tool.hatch.build.hooks.vcs]\n+version-file = \"_version.py\"\n+\n+[tool.hatch.build.hooks.custom]\n+path = \"hatch_version_hook.py\"\n+\n+[[tool.hatch.build.hooks.custom.copy_map]]\n+sources = [\n+ \"_version.py\",\n+]\n+destinations = [\n+ \"src/openjd/model\",\n+]\n+\n+[tool.hatch.build.targets.sdist]\n+packages = [\n+ \"src/openjd\",\n+]\n+only-include = [\n+ \"src/openjd\",\n+]\n+\n+[tool.hatch.build.targets.wheel]\n+packages = [\n+ \"src/openjd\",\n+]\n+only-include = [\n+ \"src/openjd\",\n+]\n+\n+[tool.mypy]\n+check_untyped_defs = false\n+show_error_codes = false\n+pretty = true\n+ignore_missing_imports = true\n+disallow_incomplete_defs = false\n+disallow_untyped_calls = false\n+show_error_context = true\n+strict_equality = false\n+python_version = 3.9\n+warn_redundant_casts = true\n+warn_unused_configs = true\n+warn_unused_ignores = false\n+# Tell mypy that there's a namespace package at src/openjd\n+namespace_packages = true\n+explicit_package_bases = true\n+mypy_path = \"src\"\n+\n+# See: https://docs.pydantic.dev/mypy_plugin/\n+# - Helps mypy understand pydantic typing.\n+plugins = \"pydantic.mypy\"\n+\n+[tool.ruff]\n+ignore = [\n+ \"E501\",\n+ # Double Check if this should be fixed\n+ \"E731\",\n+]\n+line-length = 100\n+\n+\n+[tool.ruff.pep8-naming]\n+classmethod-decorators = [\n+ \"classmethod\",\n+ # pydantic decorators are classmethod decorators\n+ # suppress N805 errors on classes decorated with them\n+ \"pydantic.validator\",\n+ \"pydantic.root_validator\",\n+]\n+\n+[tool.ruff.isort]\n+known-first-party = [\n+ \"openjd\",\n+]\n+\n+[tool.black]\n+line-length = 100\n+\n+[tool.pytest.ini_options]\n+xfail_strict = false\n+addopts = [\n+ \"-rfEx\",\n+ \"--durations=5\",\n+ \"--cov=src/openjd/model\",\n+ \"--color=yes\",\n+ \"--cov-report=html:build/coverage\",\n+ \"--cov-report=xml:build/coverage/coverage.xml\",\n+ \"--cov-report=term-missing\",\n+ \"--numprocesses=auto\",\n+ \"--timeout=30\"\n+]\n+\n+\n+[tool.coverage.run]\n+branch = true\n+parallel = true\n+\n+\n+[tool.coverage.paths]\n+source = [\n+ \"src/\"\n+]\n+\n+[tool.coverage.report]\n+show_missing = true\n+fail_under = 94"}, {"sha": "c9ba6c2cbaf6a69fafadf89f5b60c9fb6d948866", "filename": "requirements-development.txt", "status": "added", "additions": 2, "deletions": 0, "changes": 2, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/requirements-development.txt", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/requirements-development.txt", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/requirements-development.txt?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,2 @@\n+hatch >= 1.7.0, == 1.*\n+hatch-vcs ~= 0.3.0\n\\ No newline at end of file"}, {"sha": "2deeaa680e4accfb94756f6ab378a0f36f1e09ec", "filename": "requirements-testing.txt", "status": "added", "additions": 9, "deletions": 0, "changes": 9, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/requirements-testing.txt", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/requirements-testing.txt", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/requirements-testing.txt?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,9 @@\n+coverage[toml] >= 7.3, == 7.*\n+pytest >= 7.4, == 7.*\n+pytest-cov >= 4.1, == 4.*\n+pytest-timeout >= 2.1, == 2.*\n+pytest-xdist >= 3.3.1, == 3.*\n+types-PyYAML ~= 6.0\n+black >= 23.7, == 23.*\n+ruff >= 0.0.286, == 0.0.*\n+mypy >= 1.5.1, == 1.5.*"}, {"sha": "7992a6682f72c1a2f3d0c1a46fe2e36c801d4713", "filename": "scripts/add_copyright_headers.sh", "status": "added", "additions": 75, "deletions": 0, "changes": 75, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/scripts%2Fadd_copyright_headers.sh", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/scripts%2Fadd_copyright_headers.sh", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/scripts%2Fadd_copyright_headers.sh?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,75 @@\n+#!/bin/bash\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+if [ $# -eq 0 ]; then\n+ echo \"Usage: add-copyright-headers ...\" >&2\n+ exit 1\n+fi\n+\n+for file in \"$@\"; do\n+ if ! head -1 | grep 'Copyright ' \"$file\" >/dev/null; then\n+ case \"$file\" in\n+ *.java)\n+ CONTENT=$(cat \"$file\")\n+ cat > \"$file\" </dev/null; then\n+ CONTENT=$(tail -n +2 \"$file\")\n+ cat > \"$file\" <\n+$CONTENT\n+EOF\n+ else\n+ CONTENT=$(cat \"$file\")\n+ cat > \"$file\" <\n+$CONTENT\n+EOF\n+ fi\n+ ;;\n+ *.py)\n+ CONTENT=$(cat \"$file\")\n+ cat > \"$file\" < \"$file\" < \"$file\" < \"$file\" <&2\n+ exit 1\n+ ;;\n+ esac\n+ fi\n+done\n\\ No newline at end of file"}, {"sha": "9680dd92b6c351edcfc3d1ab7b5e71304b7d07d9", "filename": "src/openjd/model/__init__.py", "status": "added", "additions": 68, "deletions": 0, "changes": 68, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F__init__.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F__init__.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F__init__.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,68 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from ._capabilities import validate_attribute_capability_name, validate_amount_capability_name\n+from ._create_job import create_job, preprocess_job_parameters\n+from ._errors import (\n+ DecodeValidationError,\n+ ExpressionError,\n+ ModelValidationError,\n+ TokenError,\n+ UnsupportedSchema,\n+ ValidationError,\n+)\n+from ._parse import DocumentType, decode_template, document_string_to_object, parse_model\n+from ._step_dependency_graph import (\n+ StepDependencyGraph,\n+ StepDependencyGraphNode,\n+ StepDependencyGraphStepToStepEdge,\n+)\n+from ._step_param_space_iter import StepParameterSpaceIterator\n+from ._format_strings import FormatStringError\n+from ._symbol_table import SymbolTable\n+from ._types import (\n+ Job,\n+ JobParameterInputValues,\n+ JobParameterValues,\n+ JobTemplate,\n+ ParameterValue,\n+ ParameterValueType,\n+ SchemaVersion,\n+ Step,\n+ StepParameterSpace,\n+ TaskParameterSet,\n+)\n+from ._version import version\n+\n+__all__ = (\n+ \"create_job\",\n+ \"decode_template\",\n+ \"document_string_to_object\",\n+ \"validate_amount_capability_name\",\n+ \"validate_attribute_capability_name\",\n+ \"parse_model\",\n+ \"preprocess_job_parameters\",\n+ \"DecodeValidationError\",\n+ \"DocumentType\",\n+ \"ExpressionError\",\n+ \"FormatStringError\",\n+ \"Job\",\n+ \"JobParameterInputValues\",\n+ \"JobParameterValues\",\n+ \"JobTemplate\",\n+ \"ModelValidationError\",\n+ \"ParameterValue\",\n+ \"ParameterValueType\",\n+ \"SchemaVersion\",\n+ \"Step\",\n+ \"StepDependencyGraph\",\n+ \"StepDependencyGraphNode\",\n+ \"StepDependencyGraphStepToStepEdge\",\n+ \"StepParameterSpace\",\n+ \"StepParameterSpaceIterator\",\n+ \"SymbolTable\",\n+ \"TaskParameterSet\",\n+ \"TokenError\",\n+ \"UnsupportedSchema\",\n+ \"ValidationError\",\n+ \"version\",\n+)"}, {"sha": "cd0d51da2dc84fc2005a3ca7b7c6b350f01124bc", "filename": "src/openjd/model/_capabilities.py", "status": "added", "additions": 73, "deletions": 0, "changes": 73, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_capabilities.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_capabilities.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_capabilities.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,73 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Sequence, Union\n+import re\n+\n+from ._format_strings import FormatString\n+\n+_name_regex: re.Pattern = re.compile(\n+ r\"^(?:[a-z_][a-z0-9_]+:)?(?:amount|attr)(?:\\.[a-z_][a-z0-9_]*)+$\"\n+)\n+\n+_reserved_scopes = (\"worker\", \"job\", \"step\", \"task\")\n+\n+\n+def _split_vendor(capability_name: str) -> tuple[str, str]:\n+ if \":\" in capability_name:\n+ # Code is like this to satisfy mypy.\n+ split = capability_name.split(\":\", 1)\n+ return (split[0], split[1])\n+ return (\"\", capability_name)\n+\n+\n+def _validate_capability_name(\n+ capability_name: Union[FormatString, str],\n+ standard_capabilities: Sequence[str],\n+ required_name_prefix: str,\n+) -> None:\n+ # If it has expressions like \"{{ Param.SomeValue }}\", will\n+ # validate when those values are substituted.\n+ if isinstance(capability_name, FormatString) and len(capability_name.expressions) > 0:\n+ return\n+ capability_name = capability_name.lower()\n+ if _name_regex.fullmatch(capability_name) is None:\n+ raise ValueError(f\"Value is not a valid Capability name: {capability_name}\")\n+ vendor, capability = _split_vendor(capability_name)\n+\n+ if not vendor and capability in standard_capabilities:\n+ # Standard capability names are okay\n+ return\n+\n+ if not capability.startswith(required_name_prefix):\n+ raise ValueError(\n+ f\"Capability name after the vendor prefix must start with '{required_name_prefix}': {capability_name}\"\n+ )\n+\n+ # Make sure one of the reserved names isn't being used.\n+ scope = capability_name.split(\".\")[1]\n+ if scope in _reserved_scopes:\n+ raise ValueError(\n+ f\"Only Open Job Description defined capabilities may start with '{required_name_prefix}{scope}': {capability_name}\"\n+ )\n+\n+\n+def validate_amount_capability_name(\n+ *,\n+ capability_name: Union[FormatString, str],\n+ standard_capabilities: Sequence[str],\n+) -> None:\n+ \"\"\"Checks whether or not the given string's contents\n+\n+ Args:\n+ capability_name (Union[FormatString, str]): _description_\n+ standard_capabilities (Sequence[str]): _description_\n+ \"\"\"\n+ _validate_capability_name(capability_name, standard_capabilities, \"amount.\")\n+\n+\n+def validate_attribute_capability_name(\n+ *,\n+ capability_name: Union[FormatString, str],\n+ standard_capabilities: Sequence[str],\n+) -> None:\n+ _validate_capability_name(capability_name, standard_capabilities, \"attr.\")"}, {"sha": "955d953d754cd671b47c8e55c35d79e59c3eaa64", "filename": "src/openjd/model/_create_job.py", "status": "added", "additions": 226, "deletions": 0, "changes": 226, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_create_job.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_create_job.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_create_job.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,226 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import TYPE_CHECKING, cast\n+\n+from pydantic import ValidationError\n+\n+from ._errors import DecodeValidationError\n+from ._symbol_table import SymbolTable\n+from ._internal import instantiate_model\n+from ._types import (\n+ Job,\n+ JobParameterInputValues,\n+ JobParameterValues,\n+ JobTemplate,\n+ ParameterValue,\n+ ParameterValueType,\n+ SchemaVersion,\n+)\n+\n+if TYPE_CHECKING:\n+ # Avoiding a circular import that occurs when trying to import FormatString\n+ from .v2023_09 import JobTemplate as JobTemplate_2023_09\n+\n+\n+__all__ = (\"preprocess_job_parameters\",)\n+\n+\n+# =======================================================================\n+# ================ Preprocessing Job Parameters =========================\n+# =======================================================================\n+\n+\n+def _collect_available_parameter_names(job_template: JobTemplate) -> set[str]:\n+ # job_template.parameterDefinitions is a list[JobParameterDefinitionList]\n+ return (\n+ set(param.name for param in job_template.parameterDefinitions)\n+ if job_template.parameterDefinitions\n+ else set()\n+ )\n+\n+\n+def _collect_extra_job_parameter_names(\n+ job_template: JobTemplate, job_parameter_values: JobParameterInputValues\n+) -> set[str]:\n+ # Verify that job parameters are provided if the template requires them\n+ available_parameters: set[str] = _collect_available_parameter_names(job_template)\n+ return set(job_parameter_values).difference(available_parameters)\n+\n+\n+def _collect_missing_job_parameter_names(\n+ job_template: JobTemplate, job_parameter_values: JobParameterValues\n+) -> set[str]:\n+ available_parameters: set[str] = _collect_available_parameter_names(job_template)\n+ return available_parameters.difference(set(job_parameter_values.keys()))\n+\n+\n+def _collect_defaults_2023_09(\n+ job_template: \"JobTemplate_2023_09\", job_parameter_values: JobParameterInputValues\n+) -> JobParameterValues:\n+ # For the type checker\n+ assert job_template.parameterDefinitions is not None\n+\n+ return_value: JobParameterValues = dict[str, ParameterValue]()\n+ # Collect defaults\n+ for param in job_template.parameterDefinitions:\n+ if param.name not in job_parameter_values:\n+ if param.default is not None:\n+ return_value[param.name] = ParameterValue(\n+ type=ParameterValueType(param.type), value=str(param.default)\n+ )\n+ else:\n+ # Check the parameter against the constraints\n+ value = job_parameter_values[param.name]\n+ return_value[param.name] = ParameterValue(\n+ type=ParameterValueType(param.type), value=str(value)\n+ )\n+\n+ return return_value\n+\n+\n+def _check_2023_09(\n+ job_template: \"JobTemplate_2023_09\", job_parameter_values: JobParameterValues\n+) -> None:\n+ # For the type checker\n+ assert job_template.parameterDefinitions is not None\n+\n+ errors = list[str]()\n+ # Check values\n+ for param in job_template.parameterDefinitions:\n+ if param.name in job_parameter_values:\n+ param_value = job_parameter_values[param.name]\n+ try:\n+ param._check_constraints(param_value.value)\n+ except ValueError as err:\n+ errors.append(str(err))\n+\n+ if errors:\n+ raise ValueError(\", \".join(errors))\n+\n+\n+def preprocess_job_parameters(\n+ *, job_template: JobTemplate, job_parameter_values: JobParameterInputValues\n+) -> JobParameterValues:\n+ \"\"\"Preprocess a collection of job parameter values. Must be used prior to\n+ instantiating a Job Template into a Job.\n+ This:\n+ 1. Errors if job parameter values are defined that are not defined in the template.\n+ 2. Errors if there are job parameters defined in the job template that do not have default\n+ values, and do not have defined job parameter values.\n+ 3. Adds values to the job parameter values for any missing job parameters for which\n+ the job template defines default values.\n+ 4. Errors if any of the provided job parameter values do not meet the constraints\n+ for the parameter defined in the job template.\n+\n+ Arguments:\n+ job_template (JobTemplate) -- A Job Template to check the job parameter values against.\n+ job_parameter_values (JobParameterValues) -- Mapping of Job Parameter names to values.\n+ e.g. { \"Foo\": 12 } if you have a Job Parameter named \"Foo\"\n+\n+ Returns:\n+ A copy of job_parameter_values, but with added values for any missing job parameters\n+ that have default values defined in the Job Template.\n+\n+ Raises:\n+ ValueError - If any errors are detected with the given job parameter values.\n+ \"\"\"\n+ if job_template.version not in (SchemaVersion.v2023_09,):\n+ raise NotImplementedError(f\"Not implemented for schema version {job_template.version}\")\n+\n+ return_value: JobParameterValues = dict[str, ParameterValue]()\n+ errors = list[str]()\n+\n+ extra_defined_parameters = _collect_extra_job_parameter_names(\n+ job_template, job_parameter_values\n+ )\n+ if extra_defined_parameters:\n+ extra_list = \", \".join(extra_defined_parameters)\n+ errors.append(\n+ f\"Job parameter values provided for parameters that are not defined in the template: {extra_list}\"\n+ )\n+ if job_template.parameterDefinitions:\n+ # Set of all required, but undefined, job parameter values\n+ try:\n+ if job_template.version == SchemaVersion.v2023_09:\n+ return_value = _collect_defaults_2023_09(job_template, job_parameter_values)\n+ _check_2023_09(job_template, return_value)\n+ else:\n+ raise NotImplementedError(\n+ f\"Not implemented for schema version {job_template.version}\"\n+ )\n+ except ValueError as err:\n+ errors.append(str(err))\n+ missing = _collect_missing_job_parameter_names(job_template, return_value)\n+\n+ if missing:\n+ missing_list = \", \".join(missing)\n+ errors.append(f\"Values missing for required job parameters: {missing_list}\")\n+\n+ if errors:\n+ raise ValueError(\"\\n\".join(errors))\n+\n+ return return_value\n+\n+\n+# =======================================================================\n+# ================ Creating a Job from a Job Template ===================\n+# =======================================================================\n+\n+\n+def create_job(*, job_template: JobTemplate, job_parameter_values: JobParameterValues) -> Job:\n+ \"\"\"This function will create a job from a given Job Template and set of values for\n+ Job Parameters. Minimally, values must be provided for Job Parameters that do not have\n+ default values defined in the template.\n+\n+ This will run a check of all given job parameters via preprocess_job_parameters() before\n+ creating the job from the template.\n+\n+ Arguments:\n+ job_template (JobTemplate) -- A Job Template to check the job parameter values against.\n+ job_parameter_values (JobParameterValues) -- Mapping of Job Parameter names to values.\n+\n+ Raises:\n+ DecodeValidationError\n+\n+ Returns:\n+ Job: The job generated.\n+ \"\"\"\n+\n+ # Raises: ValueError\n+ try:\n+ # Raises: ValueError\n+ all_job_parameter_values = preprocess_job_parameters(\n+ job_template=job_template,\n+ job_parameter_values={\n+ name: param.value for name, param in job_parameter_values.items()\n+ },\n+ )\n+ except ValueError as exc:\n+ raise DecodeValidationError(str(exc))\n+\n+ # Build out the symbol table for instantiating the Job.\n+ # We just prefix all job parameter names with the appropriate prefix.\n+ symtab = SymbolTable()\n+ if job_template.specificationVersion == SchemaVersion.v2023_09:\n+ from .v2023_09 import ValueReferenceConstants as ValueReferenceConstants_2023_09\n+\n+ for name, param in all_job_parameter_values.items():\n+ if param.type != \"PATH\":\n+ symtab[\n+ f\"{ValueReferenceConstants_2023_09.JOB_PARAMETER_PREFIX.value}.{name}\"\n+ ] = all_job_parameter_values[name].value\n+ symtab[\n+ f\"{ValueReferenceConstants_2023_09.JOB_PARAMETER_RAWPREFIX.value}.{name}\"\n+ ] = all_job_parameter_values[name].value\n+ else:\n+ raise NotImplementedError(\n+ f\"Spec version {job_template.specificationVersion} not implemented.\"\n+ )\n+\n+ # Create the job\n+ try:\n+ job = instantiate_model(job_template, symtab)\n+ except ValidationError as exc:\n+ raise DecodeValidationError(str(exc))\n+\n+ return cast(Job, job)"}, {"sha": "f6ccf19c350d9983df8812e0243bde715c7815c2", "filename": "src/openjd/model/_errors.py", "status": "added", "additions": 74, "deletions": 0, "changes": 74, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_errors.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_errors.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_errors.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,74 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+__all__ = [\n+ \"DecodeValidationError\",\n+ \"ExpressionError\",\n+ \"ModelValidationError\",\n+ \"TokenError\",\n+ \"UnsupportedSchema\",\n+ \"ValidationError\",\n+]\n+\n+\n+class _BaseMessageError(Exception):\n+ \"\"\"A base class for exceptions that have an error message\"\"\"\n+\n+ msg: str\n+ \"\"\"The error message\"\"\"\n+\n+ def __init__(self, msg: str) -> None:\n+ self.msg = msg\n+ super(_BaseMessageError, self).__init__(msg)\n+\n+ def __str__(self) -> str:\n+ return self.msg\n+\n+\n+class UnsupportedSchema(_BaseMessageError):\n+ \"\"\"Error raised when an attempt is made to decode a template with\n+ an unknown or otherwise nonvalid schema identification.\n+ \"\"\"\n+\n+ _version: str\n+\n+ def __init__(self, version: str):\n+ self._version = version\n+ super().__init__(f\"Unsupported schema version: {self._version}\")\n+\n+\n+class DecodeValidationError(_BaseMessageError):\n+ \"\"\"Error raised when an decoding error is encountered while decoding\n+ a template.\n+ \"\"\"\n+\n+ pass\n+\n+\n+class ValidationError(_BaseMessageError):\n+ \"\"\"Error raised when a value, or values, in a template are nonvalid.\"\"\"\n+\n+ pass\n+\n+\n+class ModelValidationError(_BaseMessageError):\n+ \"\"\"Error raised when a validation error is encountered while validating\n+ a model.\n+ \"\"\"\n+\n+ pass\n+\n+\n+class ExpressionError(_BaseMessageError):\n+ \"\"\"Error raised when there is an error in the form of an expression that is being\n+ parsed.\n+ \"\"\"\n+\n+ pass\n+\n+\n+class TokenError(ExpressionError):\n+ \"\"\"Error raised when performing lexical analysis on an expression for parsing.\"\"\"\n+\n+ def __init__(self, expression: str, token_value: str, position: int):\n+ msg = f\"Unexpected '{token_value}' in '{expression}' after '{expression[:position]}'\"\n+ super().__init__(msg)"}, {"sha": "233533b7d2582d6ae06e52d6d3c08e65ed857b67", "filename": "src/openjd/model/_format_strings/__init__.py", "status": "added", "additions": 5, "deletions": 0, "changes": 5, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F__init__.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F__init__.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_format_strings%2F__init__.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,5 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from ._format_string import FormatString, FormatStringError\n+\n+__all__ = [\"FormatString\", \"FormatStringError\"]"}, {"sha": "610a82b2435e2c770891d69f0db9115bebec100b", "filename": "src/openjd/model/_format_strings/_dyn_constrained_str.py", "status": "added", "additions": 69, "deletions": 0, "changes": 69, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_dyn_constrained_str.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_dyn_constrained_str.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_format_strings%2F_dyn_constrained_str.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,69 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import re\n+from typing import TYPE_CHECKING, Any, Callable, Optional, Pattern, Union\n+\n+from pydantic.errors import AnyStrMaxLengthError, AnyStrMinLengthError, StrRegexError\n+from pydantic.utils import update_not_none\n+from pydantic.validators import strict_str_validator\n+\n+if TYPE_CHECKING:\n+ from pydantic.typing import CallableGenerator\n+\n+\n+class DynamicConstrainedStr(str):\n+ \"\"\"Constrained string type for interfacing with Pydantic.\n+ The maximum string length can be dynamically defined at runtime.\n+\n+ Note: Does *not* run model validation when constructed.\n+ \"\"\"\n+\n+ _min_length: Optional[int] = None\n+ _max_length: Optional[Union[int, Callable[[], int]]] = None\n+ _regex: Optional[Union[str, Pattern[str]]] = None\n+\n+ # Pydantic datamodel interfaces\n+ # ================================\n+ # Reference: https://pydantic-docs.helpmanual.io/usage/types/#custom-data-types\n+\n+ @classmethod\n+ def _get_max_length(cls) -> Optional[int]:\n+ if callable(cls._max_length):\n+ return cls._max_length()\n+ return cls._max_length\n+\n+ @classmethod\n+ def __modify_schema__(cls, field_schema: dict[str, Any]) -> None:\n+ update_not_none(\n+ field_schema,\n+ minLength=cls._min_length,\n+ maxLength=cls._get_max_length(),\n+ )\n+\n+ @classmethod\n+ def __get_validators__(cls) -> \"CallableGenerator\":\n+ yield strict_str_validator # Always strict string.\n+ yield cls._validate_min_length\n+ yield cls._validate_max_length\n+ yield cls._validate_regex\n+\n+ @classmethod\n+ def _validate_min_length(cls, value: str) -> str:\n+ if cls._min_length is not None and len(value) < cls._min_length:\n+ raise AnyStrMinLengthError(limit_value=cls._min_length)\n+ return value\n+\n+ @classmethod\n+ def _validate_max_length(cls, value: str) -> str:\n+ max_length = cls._get_max_length()\n+ if max_length is not None and len(value) > max_length:\n+ raise AnyStrMaxLengthError(limit_value=max_length)\n+ return value\n+\n+ @classmethod\n+ def _validate_regex(cls, value: str) -> str:\n+ if cls._regex is not None:\n+ if not re.match(cls._regex, value):\n+ pattern: str = cls._regex if isinstance(cls._regex, str) else cls._regex.pattern\n+ raise StrRegexError(pattern=pattern)\n+ return value"}, {"sha": "21e5b1fb5622e28c219a02db9f3c08f7c42e39d8", "filename": "src/openjd/model/_format_strings/_expression.py", "status": "added", "additions": 77, "deletions": 0, "changes": 77, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_expression.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_expression.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_format_strings%2F_expression.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,77 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import numbers\n+from typing import Union\n+\n+from .._errors import ExpressionError, ValidationError\n+from .._symbol_table import SymbolTable\n+from ._nodes import Node\n+from ._parser import Parser\n+\n+\n+class InterpolationExpression:\n+ expr: str\n+ _expression_tree: Node\n+\n+ def __init__(self, expr: str) -> None:\n+ \"\"\"Constructor.\n+\n+ Raises:\n+ ExpressionError: The provided expression cannot be parsed.\n+ TokenError: The provided expression contains nonvalid or unexpected tokens.\n+\n+ Args:\n+ expr (str): The expression\n+ \"\"\"\n+ self.expr = expr\n+ parser = Parser()\n+\n+ # Raises: ExpressionError, TokenError\n+ self._expresion_tree = parser.parse(expr)\n+\n+ def validate_symbol_refs(self, *, symbols: set[str]) -> None:\n+ \"\"\"Check whether this expression can be evaluated correctly given a set of symbol names.\n+\n+ Args:\n+ symbols (set[str]): The names of symbols visible to this expression.\n+\n+ Raises:\n+ ValueError: If the expression cannot be evaluated with the given symbol names\n+ \"\"\"\n+ self._expresion_tree.validate_symbol_refs(symbols=symbols)\n+\n+ def validate(self, *, symtab: SymbolTable) -> None:\n+ \"\"\"Check whether this expression can be evaluated correctly given a symbol table.\n+\n+ Currently, this is simply verifying that the expression references only symbols that\n+ are in the given symbol table.\n+\n+ Args:\n+ symtab (SymbolTable): A symbol table to validate against.\n+\n+ Raises:\n+ ValidationError: If the expression cannot be evaluated given the symbol table.\n+ \"\"\"\n+ self._expresion_tree.validate(symtab=symtab)\n+\n+ def evaluate(self, *, symtab: SymbolTable) -> Union[numbers.Real, str]:\n+ \"\"\"Evaluate the expression given a SymbolTable.\n+\n+ Args:\n+ symtab (SymbolTable): A symbol table containing values to use in the evaluation.\n+\n+ Raises:\n+ ExpressionError: If the expression could not be evaluated.\n+\n+ Returns:\n+ Union[numbers.Real, str]: Resulting value.\n+ \"\"\"\n+ try:\n+ result = self._expresion_tree.evaluate(symtab=symtab)\n+ except ValidationError as exc:\n+ raise ExpressionError(f\"Expression failed validation: {str(exc)}\")\n+\n+ if isinstance(result, (numbers.Real, str)):\n+ return result\n+\n+ raise ExpressionError(f\"Nonvalid result type: {result} of type {type(result)}\")"}, {"sha": "64a639841560bbb485220f8fa15935002c434a14", "filename": "src/openjd/model/_format_strings/_format_string.py", "status": "added", "additions": 265, "deletions": 0, "changes": 265, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_format_string.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_format_string.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_format_strings%2F_format_string.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,265 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from dataclasses import dataclass\n+from numbers import Real\n+from typing import TYPE_CHECKING, Optional, Union\n+\n+from .._errors import ExpressionError, TokenError, ValidationError\n+from .._symbol_table import SymbolTable\n+from ._dyn_constrained_str import DynamicConstrainedStr\n+from ._expression import InterpolationExpression\n+\n+if TYPE_CHECKING:\n+ from pydantic.typing import CallableGenerator\n+\n+\n+@dataclass\n+class ExpressionInfo:\n+ start_pos: int\n+ end_pos: int\n+ expression: Optional[InterpolationExpression] = None\n+ resolved_value: Optional[Union[Real, str]] = None\n+\n+\n+class FormatStringError(Exception):\n+ def __init__(self, *, string: str, start: int, end: int, expr: str = \"\", details: str = \"\"):\n+ expression = f\"Expression: {expr}. \" if expr else \"\"\n+ reason = f\"Reason: {details}.\" if details else \"\"\n+ msg = (\n+ f\"Failed to parse interpolation expression in {string} \"\n+ f\"at [{start}, {end}]. \"\n+ f\"{expression}\"\n+ f\"{reason}\"\n+ )\n+ super().__init__(msg)\n+\n+ def __str__(self) -> str:\n+ return self.args[0]\n+\n+\n+class FormatString(DynamicConstrainedStr):\n+ def __init__(self, value: str):\n+ \"\"\"\n+ Instantiate a FormatString from a given string.\n+\n+ Verifies that each pair of opening curly braces {{ has a corresponding pair\n+ of closing curly braces }}, and vice versa.\n+\n+ Also, verifies that each interpolation expression inside of {{ }} has a valid format.\n+\n+ Parameters\n+ ----------\n+ original_string: str\n+ A string that contains 0 or more interpolation expressions.\n+ For example, 'text', '{{expr}}', '{{ expr }}', 'text {{expr}}text{{expr}} text',\n+ are all valid inputs.\n+\n+ Raises\n+ ------\n+ FormatStringError: if the original string is nonvalid.\n+ \"\"\"\n+ # Note: str is constructed in __new__, so don't call super __init__\n+ self._processed_list: list[Union[str, ExpressionInfo]] = self._preprocess()\n+\n+ @property\n+ def original_value(self) -> str:\n+ \"\"\"\n+ Returns\n+ -------\n+ original_string: str\n+ An original string passed during the construction of this object.\n+ \"\"\"\n+ return self\n+\n+ @property\n+ def expressions(self) -> list[ExpressionInfo]:\n+ \"\"\"\n+ Returns\n+ -------\n+ expressions: list[ExpressionInfo]\n+ A list of all interpolation expressions in this interpolated string.\n+ \"\"\"\n+ return [expr for expr in self._processed_list if isinstance(expr, ExpressionInfo)]\n+\n+ def resolve(self, *, symtab: SymbolTable) -> str:\n+ \"\"\"\n+ Uses a given symbol table to resolve an interpolated string.\n+ Each interpolation expression in the original string is replaced\n+ by a value from the symbol table.\n+\n+ Parameters\n+ ----------\n+ symtab: SymbolTable\n+ A symbol table with values that are used to resolve interpolation\n+ expressions in the interpolated string.\n+ For example, to resolve '{{Some.data}}' the table should contain\n+ the value for 'Some.data'.\n+\n+ Returns\n+ -------\n+ resolved_string:\n+ A resolved string with all interpolation expressions replaced with corresponding values.\n+\n+ Raises\n+ ------\n+ FormatStringError: if it is impossible to resolve\n+ all interpolation expressions with a given symbol table.\n+ \"\"\"\n+ resolved_list: list[str] = []\n+ for element in self._processed_list:\n+ assert isinstance(element, (ExpressionInfo, str))\n+ if isinstance(element, str):\n+ resolved_list.append(element)\n+ continue\n+\n+ assert element.expression is not None\n+ try:\n+ element.resolved_value = element.expression.evaluate(symtab=symtab)\n+ except ExpressionError as exc:\n+ raise FormatStringError(\n+ string=self.original_value,\n+ start=element.start_pos,\n+ end=element.end_pos,\n+ expr=element.expression.expr,\n+ details=str(exc),\n+ )\n+\n+ resolved_list.append(str(element.resolved_value))\n+\n+ return \"\".join(resolved_list)\n+\n+ def validate(self, *, symtab: SymbolTable) -> list[FormatStringError]:\n+ \"\"\"\n+ Uses a given symbol table to validate an interpolated string.\n+ Verifies that each interpolation expression in the original string\n+ can be replaced by a value from the symbol table.\n+ Does not raise any exception if the interpolated string is valid.\n+\n+ Parameters\n+ ----------\n+ symtab: SymbolTable\n+ A symbol table with values that are used to validate interpolation\n+ expressions in the interpolated string.\n+ For example, tle format string '{{Some.data}}' is valid if the table\n+ contains the value for 'Some.data'.\n+\n+ Returns\n+ -------\n+ validation_errors: list[FormatStringError]\n+ A list of errors for every interpolation expression in the\n+ format string that can not be resolved with a given symbol table.\n+ \"\"\"\n+ validation_errors: list[FormatStringError] = []\n+\n+ for expression_info in self.expressions:\n+ assert expression_info.expression is not None\n+ try:\n+ expression_info.expression.validate(symtab=symtab)\n+ except ValidationError as exc:\n+ validation_errors.append(\n+ FormatStringError(\n+ string=self.original_value,\n+ start=expression_info.start_pos,\n+ end=expression_info.end_pos,\n+ details=str(exc),\n+ )\n+ )\n+\n+ return validation_errors\n+\n+ def _preprocess(self) -> list[Union[str, ExpressionInfo]]:\n+ \"\"\"\n+ Scans through the original string to find all interpolation expressions inside of {{ }}.\n+ Also, validates the content of each interpolation expression inside of {{ }}.\n+\n+ The output format is designed to be used later by `resolve()` function.\n+ It allows us to replace each ExpressionInfo with a resolved value\n+ and then efficiently combine simple strings and resolved values into the final string.\n+\n+ Raises\n+ ------\n+ FormatStringError\n+ - if the string contains opening pair {{ without a matching closing pair,\n+ and vice versa.\n+ - if any expression inside of {{ }} is nonvalid.\n+\n+ Returns\n+ -------\n+ preprocessed_list: list[Union[str, ExpressionInfo]]\n+ A list, where each element is either\n+ - a string that doesn't contain interpolation expression {{ }}, or\n+ - an instance of ExpressionInfo\n+ For example, for original string 'a {{ B.C }} d {{ E.f }}' the list will be\n+ ['a ', ExpressionInfo({{ B.C }}), ' d ', ExpressionInfo({{ E.f }})]\n+ \"\"\"\n+ result_list: list[Union[str, ExpressionInfo]] = []\n+\n+ opening = \"{{\"\n+ closing = \"}}\"\n+\n+ braces_end = 0\n+ while braces_end < len(self):\n+ braces_start = self.find(opening, braces_end)\n+ expression_end = self.find(closing, braces_end)\n+\n+ if braces_start == -1 and expression_end == -1:\n+ result_list.append(self[braces_end:])\n+ break\n+\n+ if expression_end < braces_start:\n+ raise FormatStringError(\n+ string=self.original_value,\n+ start=braces_end,\n+ end=len(self.original_value),\n+ details=\"Braces mismatch\",\n+ )\n+\n+ if braces_start == -1 and expression_end != -1:\n+ raise FormatStringError(\n+ string=self.original_value,\n+ start=braces_end,\n+ end=(expression_end + len(closing)),\n+ details=\"Missing opening braces\",\n+ )\n+\n+ result_list.append(self[braces_end:braces_start])\n+\n+ expression_start = braces_start + len(opening)\n+ braces_end = expression_end + len(closing)\n+\n+ expression_info = ExpressionInfo(braces_start, braces_end)\n+ try:\n+ expr = InterpolationExpression(self[expression_start:expression_end])\n+ except (ExpressionError, TokenError) as exc:\n+ raise FormatStringError(\n+ string=self.original_value,\n+ start=expression_info.start_pos,\n+ end=expression_info.end_pos,\n+ details=str(exc),\n+ )\n+\n+ expression_info.expression = expr\n+ result_list.append(expression_info)\n+\n+ return result_list\n+\n+ # Pydantic datamodel interfaces\n+ # ================================\n+ # Reference: https://pydantic-docs.helpmanual.io/usage/types/#custom-data-types\n+\n+ @classmethod\n+ def __get_validators__(cls) -> \"CallableGenerator\":\n+ for validator in super().__get_validators__():\n+ yield validator\n+ yield cls._validate\n+\n+ @classmethod\n+ def _validate(cls, value: str) -> \"FormatString\":\n+ # Reference: https://pydantic-docs.helpmanual.io/usage/validators/\n+ # Class constructor will raise validation errors on the value contents.\n+ try:\n+ return cls(value)\n+ except FormatStringError as e:\n+ # Pydantic validators must return a ValueError or AssertionError\n+ # Convert the FormatStringError into a ValueError\n+ raise ValueError(str(e))"}, {"sha": "81a9b686143dbc061073cc5f7bf62483199063ec", "filename": "src/openjd/model/_format_strings/_nodes.py", "status": "added", "additions": 102, "deletions": 0, "changes": 102, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_nodes.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_nodes.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_format_strings%2F_nodes.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,102 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from __future__ import annotations\n+\n+from abc import ABC, abstractmethod\n+from dataclasses import dataclass\n+from typing import Any\n+\n+from .._symbol_table import SymbolTable\n+from .._errors import ValidationError\n+\n+\n+class Node(ABC):\n+ \"\"\"\n+ Base expression tree node class.\n+ \"\"\"\n+\n+ @abstractmethod\n+ def validate_symbol_refs(self, *, symbols: set[str]) -> None: # pragma: no cover\n+ \"\"\"Verifies that the expression rooted at this node is valid\n+ given the definitions of symbols in a symbol table.\n+\n+ For example, an expression is not valid if it references\n+ a symbol that does not exist in the symbol table.\n+\n+ Raises:\n+ ValueError: If the expression is not valid. The given error contains\n+ context and information on the specifics of the error.\n+\n+ Args:\n+ symbols (set[str]): The names of symbols visible to this expression.\n+ \"\"\"\n+ pass\n+\n+ @abstractmethod\n+ def validate(self, *, symtab: SymbolTable) -> None: # pragma: no cover\n+ \"\"\"Verifies that the expression rooted at this node is valid\n+ given the definitions of symbols in a symbol table.\n+\n+ For example, an expression is not valid if it references\n+ a symbol that does not exist in the symbol table.\n+\n+ Raises:\n+ ValidationError: If the expression is not valid. The given error contains\n+ context and information on the specifics of the error.\n+\n+ Args:\n+ symtab (SymbolTable): Symbol definitions to validate against.\n+\n+ Note: The symtab does need to have placeholder values for each symbol\n+ that are of the appropriate type. For example, a placeholder for a\n+ number-type symbol might be the integer value 0.\n+ \"\"\"\n+ pass\n+\n+ @abstractmethod\n+ def evaluate(self, *, symtab: SymbolTable) -> Any: # pragma: no cover\n+ \"\"\"Evaluate the expression rooted at this node given definitions\n+ of symbols in a symbol table.\n+\n+ Raises:\n+ ValidationError: If the expression is not valid. The given error contains\n+ context and information on the specifics of the error.\n+\n+ Args:\n+ symtab (SymbolTable): Symbol definitions.\n+\n+ Returns:\n+ Any: Value of the expression.\n+ \"\"\"\n+ pass\n+\n+ @abstractmethod\n+ def __repr__(self) -> str: # pragma: no cover\n+ \"\"\"String representation of the node for printing.\"\"\"\n+ pass\n+\n+\n+@dataclass\n+class FullNameNode(Node):\n+ \"\"\"Expression tree node representing a fully qualified identifier name.\n+ e.g. Foo.Bar.Baz or Foo\n+ \"\"\"\n+\n+ name: str\n+\n+ def validate_symbol_refs(self, *, symbols: set[str]) -> None:\n+ if self.name not in symbols:\n+ raise ValueError(\n+ f\"{self.name} is referenced by an expression, but is out of scope or has no value\"\n+ )\n+\n+ def validate(self, *, symtab: SymbolTable) -> None:\n+ if self.name not in symtab:\n+ raise ValidationError(f\"{self.name} has no value\")\n+\n+ def evaluate(self, *, symtab: SymbolTable) -> Any:\n+ self.validate(symtab=symtab)\n+ return symtab[self.name]\n+\n+ def __repr__(self):\n+ return f\"FullName({self.name})\""}, {"sha": "70d9b9b7401210171ab9ca75b12d5c9f6d0b1844", "filename": "src/openjd/model/_format_strings/_parser.py", "status": "added", "additions": 95, "deletions": 0, "changes": 95, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_parser.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_parser.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_format_strings%2F_parser.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,95 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Type, cast\n+\n+from .._errors import ExpressionError, TokenError\n+from .._tokenstream import Token, TokenStream, TokenType\n+from ._nodes import FullNameNode, Node\n+from ._tokens import DotToken, NameToken\n+\n+_tokens: dict[TokenType, Type[Token]] = {TokenType.NAME: NameToken, TokenType.DOT: DotToken}\n+\n+\n+class Parser:\n+ \"\"\"\n+ Parser used to build an AST of the currently supported operations.\n+ \"\"\"\n+\n+ def parse(self, expr: str) -> Node:\n+ \"\"\"Generate an expression tree for the given string interpolation expression.\n+\n+ Args:\n+ expr (str): A string interpolation expression\n+\n+ Raises:\n+ ExpressionError: If the given expression does not adhere to the grammar.\n+ TokenError: If the given expression contains nonvalid or unexpected tokens.\n+\n+ Returns:\n+ Node: Root of the expression tree.\n+ \"\"\"\n+\n+ # Raises: TokenError\n+ self._tokens = TokenStream(expr, supported_tokens=_tokens)\n+\n+ result = self._expression()\n+ if not self._tokens.at_end():\n+ token = self._tokens.next()\n+ raise TokenError(self._tokens.expr, token.value, token.start)\n+\n+ return result\n+\n+ def _expression(self) -> Node:\n+ \"\"\"Matches the root of the expression grammar.\n+\n+ Grammar:\n+ ::= \n+ ::= ( )*\n+ ::= [A-Za-z_][A-Za-z0-9_]*\n+ ::= '.'\n+\n+ Raises:\n+ ExpressionError: When there is an error parsing the expression.\n+ TokenError: If the expression contains unexpected tokens.\n+\n+ Returns:\n+ Node: Root node of the expression tree.\n+ \"\"\"\n+ if self._tokens.at_end():\n+ raise ExpressionError(\"Empty expression\")\n+\n+ if isinstance(self._tokens.lookahead(0), NameToken):\n+ # Raises: ExpressionError, TokenError\n+ return self._match_name()\n+\n+ token = self._tokens.next()\n+ raise TokenError(self._tokens.expr, token.value, token.start)\n+\n+ def _match_name(self) -> FullNameNode:\n+ \"\"\"Matches:\n+ ::= ( )*\n+\n+ Raises:\n+ ExpressionError: When there is an error parsing the expression.\n+ TokenError: If the expression contains unexpected tokens.\n+ \"\"\"\n+ token: Token = cast(NameToken, self._tokens.next())\n+ names = [token.value]\n+\n+ try:\n+ while isinstance(self._tokens.lookahead(0), DotToken):\n+ _ = self._tokens.next()\n+ try:\n+ token = self._tokens.next()\n+ except IndexError:\n+ raise ExpressionError(\n+ f\"Unexpected end of name '{'.'.join(names)}.'\",\n+ )\n+ if not isinstance(token, NameToken):\n+ raise TokenError(self._tokens.expr, token.value, token.start)\n+ names.append(token.value)\n+ except IndexError:\n+ # Catches the lookahead on the while condition. Not having a dot after the name is okay.\n+ pass\n+\n+ return FullNameNode(\".\".join(names))"}, {"sha": "606a90ea18d17908d7ccd592a232c90f44c51153", "filename": "src/openjd/model/_format_strings/_tokens.py", "status": "added", "additions": 18, "deletions": 0, "changes": 18, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_tokens.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_format_strings%2F_tokens.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_format_strings%2F_tokens.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,18 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from .._tokenstream import Token\n+\n+\n+class NameToken(Token):\n+ \"\"\"An identifier matching the regex: ^[^\\\\d\\\\W][\\\\w]*$\n+ [^\\\\d\\\\W] = _ or unicode non-digit letter\n+ [\\\\w] = _ or unicode letter including digits\n+ \"\"\"\n+\n+ pass\n+\n+\n+class DotToken(Token):\n+ \"\"\"The '.' character.\"\"\"\n+\n+ pass"}, {"sha": "89927542d693ed997fc00b259f26da6695c79260", "filename": "src/openjd/model/_internal/__init__.py", "status": "added", "additions": 57, "deletions": 0, "changes": 57, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F__init__.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F__init__.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_internal%2F__init__.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,57 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any, Callable, TypeVar\n+\n+from ._combination_expr import AssociationNode as CombinationExpressionAssociationNode\n+from ._combination_expr import IdentifierNode as CombinationExpressionIdentifierNode\n+from ._combination_expr import Node as CombinationExpressionNode\n+from ._combination_expr import Parser as CombinationExpressionParser\n+from ._combination_expr import ProductNode as CombinationExpressionProductNode\n+from ._create_job import instantiate_model\n+from ._model_variable_references import validate_model_template_variable_references\n+from ._range_expr import IntRange, IntRangeExpression\n+from ._range_expr import Parser as RangeExpressionParser\n+\n+__all__ = (\n+ \"instantiate_model\",\n+ \"validate_model_template_variable_references\",\n+ \"validate_unique_elements\",\n+ \"CombinationExpressionAssociationNode\",\n+ \"CombinationExpressionIdentifierNode\",\n+ \"CombinationExpressionNode\",\n+ \"CombinationExpressionParser\",\n+ \"CombinationExpressionProductNode\",\n+ \"RangeExpressionParser\",\n+ \"IntRangeExpression\",\n+ \"IntRange\",\n+)\n+\n+T = TypeVar(\"T\")\n+\n+\n+def validate_unique_elements(\n+ lst: list[T], *, item_value: Callable[[T], Any], property: str\n+) -> list[T]:\n+ \"\"\"Pydantic validator that can be used that every item in a list has a unique\n+ value for a specific property.\n+\n+ Args:\n+ lst: The list to check\n+ item_value: A callable that extracts the value-to-compare from an element\n+ of the list.\n+ property: Name of the property for error messages\n+ \"\"\"\n+ items = tuple(item_value(i) for i in lst)\n+ item_set = set(items)\n+ if len(lst) != len(item_set):\n+ items_seen = set()\n+ duplicate_items = set()\n+ for i in items:\n+ if i in items_seen:\n+ duplicate_items.add(i)\n+ else:\n+ items_seen.add(i)\n+ raise ValueError(\n+ f\"Duplicate values for {property} are not allowed. Duplicate values: {','.join(duplicate_items)}\"\n+ )\n+ return lst"}, {"sha": "83f906bfb3f22339dd37ef227ed806cd643cff67", "filename": "src/openjd/model/_internal/_combination_expr.py", "status": "added", "additions": 266, "deletions": 0, "changes": 266, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F_combination_expr.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F_combination_expr.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_internal%2F_combination_expr.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,266 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from __future__ import annotations\n+\n+from dataclasses import dataclass\n+from typing import Union\n+\n+from .._errors import ExpressionError, TokenError\n+from .._tokenstream import Token, TokenStream, TokenType\n+\n+__all__ = [\"Node\", \"ProductNode\", \"AssociationNode\", \"IdentifierNode\", \"Parser\"]\n+\n+# ===================================\n+# -- Expression Tree Nodes\n+# ===================================\n+\n+\n+class Node:\n+ \"\"\"Base class for all expression tree nodes generated by the\n+ parser for task parameter combination expressions.\n+ \"\"\"\n+\n+ def collect_identifiers(self, destination: list[str]) -> None:\n+ if isinstance(self, (ProductNode, AssociationNode)):\n+ for node in self.children:\n+ node.collect_identifiers(destination)\n+ elif isinstance(self, IdentifierNode):\n+ destination.append(self.parameter)\n+\n+\n+@dataclass\n+class ProductNode(Node):\n+ \"\"\"Outer product operator on a list of non-product nodes.\n+\n+ e.g. A * B * C\n+ \"\"\"\n+\n+ children: tuple[Node, ...]\n+\n+ def __str__(self) -> str:\n+ return \" * \".join(str(child) for child in self.children)\n+\n+ def __repr__(self) -> str:\n+ return f\"Product({', '.join(repr(child) for child in self.children)})\"\n+\n+\n+@dataclass\n+class AssociationNode(Node):\n+ \"\"\"Association operator on a list of nodes.\n+\n+ e.g. (A, B, C)\n+ \"\"\"\n+\n+ children: tuple[Node, ...]\n+\n+ def __str__(self) -> str:\n+ return f\"({', '.join(str(child) for child in self.children)})\"\n+\n+ def __repr__(self) -> str:\n+ return f\"Assoc({', '.join(repr(child) for child in self.children)})\"\n+\n+\n+@dataclass\n+class IdentifierNode(Node):\n+ \"\"\"Leaf node representing a task parameter identifier.\"\"\"\n+\n+ parameter: str\n+\n+ def __str__(self) -> str:\n+ return self.parameter\n+\n+ def __repr__(self) -> str:\n+ return self.parameter\n+\n+\n+# =========================================\n+# -- Token types for the lexical analysis\n+# =========================================\n+\n+\n+class IdentToken(Token):\n+ \"\"\"An identifier matching the regex: ^[^\\\\d\\\\W][\\\\w]*$\n+ [^\\\\d\\\\W] = _ or unicode non-digit letter\n+ [\\\\w] = _ or unicode letter including digits\n+ \"\"\"\n+\n+ pass\n+\n+\n+class StarToken(Token):\n+ \"\"\"The '*' character.\"\"\"\n+\n+ pass\n+\n+\n+class CommaToken(Token):\n+ \"\"\"The ',' character.\"\"\"\n+\n+ pass\n+\n+\n+class LeftParenToken(Token):\n+ \"\"\"The '(' character\"\"\"\n+\n+ pass\n+\n+\n+class RightParenToken(Token):\n+ \"\"\"The ')' character\"\"\"\n+\n+ pass\n+\n+\n+# Map of TokenTypes to their corresponding Token class.\n+# Required by the TokenStream used by the parser to map\n+# lexical tokens to the correct token class.\n+_tokenmap = {\n+ TokenType.NAME: IdentToken,\n+ TokenType.STAR: StarToken,\n+ TokenType.LPAREN: LeftParenToken,\n+ TokenType.RPAREN: RightParenToken,\n+ TokenType.COMMA: CommaToken,\n+}\n+\n+\n+class Parser:\n+ \"\"\"Task parameter combination expression parser.\n+\n+ Full Grammar:\n+ ::= ( '*' )*\n+ ::= | \n+ ::= '(' ( ',' )* ')'\n+ \"\"\"\n+\n+ def parse(self, expr: str) -> Node:\n+ \"\"\"Generate an expression tree for the given string interpolation expression.\n+\n+ Raises:\n+ TokenError: If an unexpected token is encountered.\n+ ExpressionError: If the expresssion is malformed.\n+ \"\"\"\n+\n+ # Raises: TokenError\n+ self._tokens = TokenStream(expr, supported_tokens=_tokenmap)\n+\n+ if self._tokens.at_end():\n+ raise ExpressionError(\"Empty expression\")\n+\n+ result = self._expression()\n+ if not self._tokens.at_end():\n+ token = self._tokens.next()\n+ raise TokenError(self._tokens.expr, token.value, token.start)\n+\n+ return result\n+\n+ def _expression(self) -> Node:\n+ \"\"\"Matches an expression statement.\n+\n+ Grammar:\n+ ::= ( '*' )*\n+\n+ Raises:\n+ TokenError: If an unexpected token is encountered\n+ ExpressionError: If the expresssion is malformed.\n+\n+ Returns:\n+ Node: Expression tree node for the recursively matched expression.\n+ \"\"\"\n+\n+ children: list[Node] = []\n+ # Parse: \n+ # Raises: TokenError, ExpressionError\n+ children.append(self._element())\n+ try:\n+ # Parse: ( '*' )*\n+ while isinstance(self._tokens.lookahead(0), StarToken):\n+ # consume the '*'\n+ self._tokens.next()\n+ # Parse: \n+ # Raises: TokenError, ExpressionError\n+ children.append(self._element())\n+ except IndexError:\n+ # Catches the lookahead on the while condition. Not having anything after a name is okay\n+ pass\n+\n+ if len(children) == 1:\n+ return children[0]\n+ return ProductNode(tuple(children))\n+\n+ def _association_expression(self) -> AssociationNode:\n+ \"\"\"Matches an association statement in the expression.\n+\n+ Grammar:\n+ ::= '(' ( ',' )* ')'\n+\n+ Raises:\n+ TokenError: If an unexpected token is encountered\n+ ExpressionError: If the expresssion is malformed.\n+\n+ Returns:\n+ AssociationNode: Expression tree node for the recursively matched\n+ association expression.\n+ \"\"\"\n+\n+ children: list[Node] = []\n+ # We only get into this function by doing a token lookahead and\n+ # seeing a left-paren. Consume the left paren.\n+ self._tokens.next()\n+\n+ # Parse: \n+ expr = self._expression()\n+ children.append(expr)\n+ # Parse: ( ',' )+\n+ try:\n+ while isinstance(self._tokens.lookahead(0), CommaToken):\n+ # Consume the ','\n+ self._tokens.next()\n+ # Raises: TokenError, ExpressionError\n+ expr = self._expression()\n+ children.append(expr)\n+ except IndexError:\n+ # Catches the lookahead on the while condition. Not having a dot after the name is okay.\n+ pass\n+ # Parse: ')'\n+ try:\n+ token = self._tokens.next()\n+ if not isinstance(token, RightParenToken):\n+ raise TokenError(self._tokens.expr, token.value, token.start)\n+ except IndexError:\n+ raise ExpressionError(f\"Unexpected end of expression: {self._tokens.expr}\")\n+\n+ if len(children) == 1:\n+ raise ExpressionError(\n+ f\"Association expression '( {str(children[0])} )' must have more than one term.\"\n+ )\n+\n+ return AssociationNode(tuple(children))\n+\n+ def _element(self) -> Union[IdentifierNode, AssociationNode]:\n+ \"\"\"Matches an element statement from the grammar.\n+\n+ Raises:\n+ TokenError: If an unexpected token is encountered\n+ ExpressionError: If the expresssion is malformed.\n+\n+ Grammar:\n+ ::= | \n+\n+ Returns:\n+ Union[IdentifierNode, AssociationNode]: Expression tree node for the\n+ recursively matched element.\n+ \"\"\"\n+\n+ try:\n+ # Raises: IndexError\n+ lookahead = self._tokens.lookahead(0)\n+ except IndexError:\n+ raise ExpressionError(f\"Unexpected end of expression: {self._tokens.expr}\")\n+ if isinstance(lookahead, IdentToken):\n+ token = self._tokens.next()\n+ return IdentifierNode(token.value)\n+ elif isinstance(lookahead, LeftParenToken):\n+ # Raises: TokenError, ExpressionError\n+ return self._association_expression()\n+\n+ raise TokenError(self._tokens.expr, lookahead.value, lookahead.start)"}, {"sha": "45b320fb03d8708cc0f8196c69912a0e396ecdb9", "filename": "src/openjd/model/_internal/_create_job.py", "status": "added", "additions": 232, "deletions": 0, "changes": 232, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F_create_job.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F_create_job.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_internal%2F_create_job.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,232 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any, Union\n+\n+from pydantic import ValidationError\n+from pydantic.error_wrappers import ErrorWrapper\n+\n+from .._symbol_table import SymbolTable\n+from .._format_strings import FormatString, FormatStringError\n+from .._types import OpenJDModel\n+\n+__all__ = (\"instantiate_model\",)\n+\n+\n+def instantiate_model( # noqa: C901\n+ model: OpenJDModel,\n+ symtab: SymbolTable,\n+ loc: tuple[Union[str, int], ...] = tuple[str](),\n+ within_field: str = \"\",\n+) -> OpenJDModel:\n+ \"\"\"This function is for instantiating a Template model into a Job model.\n+\n+ It does a depth-first traversal through the model, mutating each stage according\n+ to the instructions given in the model's create-job metadata.\n+\n+ Args:\n+ model (OpenJDModel): The model instance to transform.\n+ symtab (SymbolTable): The symbol table containing fully qualified Job parameter values\n+ used during the instantiation.\n+ loc (tuple[Union[str,int], ...], optional): Path to the model. Used for generating contextual errors.\n+ within_field (str): The name of the field where this model was found during traversal. \"\" if this\n+ is the top-level/root model\n+\n+ Raises:\n+ ValidationError - If there are any validation errors from the target models.\n+\n+ Returns:\n+ OpenJDModel: The transformed model.\n+ \"\"\"\n+\n+ errors = list[ErrorWrapper]()\n+ instantiated_fields = dict[str, Any]()\n+\n+ for field_name in model.__fields__.keys():\n+ target_field_name = field_name\n+ if field_name in model._job_creation_metadata.rename_fields:\n+ target_field_name = model._job_creation_metadata.rename_fields[field_name]\n+ if field_name in model._job_creation_metadata.exclude_fields:\n+ # The field is marked for being excluded\n+ continue\n+ if not hasattr(model, field_name):\n+ # Field has no value. Set to None and move on.\n+ instantiated_fields[target_field_name] = None\n+ continue\n+\n+ field = getattr(model, field_name)\n+ instantiated: Any\n+ # TODO - try/except. Collect errors\n+ try:\n+ if isinstance(field, list):\n+ # Raises: ValidationError\n+ instantiated = _instantiate_list_field(model, field_name, field, symtab, loc)\n+ elif isinstance(field, dict):\n+ # Raises: ValidationError\n+ instantiated = _instantiate_dict_field(model, field_name, field, symtab, loc)\n+ else:\n+ # Raises: ValidationError, FormatStringError\n+ instantiated = _instantiate_noncollection_value(\n+ model, field_name, field, symtab, loc + (field_name,)\n+ )\n+ instantiated_fields[target_field_name] = instantiated\n+ except (ValidationError, FormatStringError) as exc:\n+ errors.append(ErrorWrapper(exc, loc))\n+\n+ if errors:\n+ raise ValidationError(errors, model.__class__)\n+\n+ if model._job_creation_metadata.adds_fields is not None:\n+ new_fields = model._job_creation_metadata.adds_fields(within_field, model, symtab)\n+ instantiated_fields.update(**new_fields)\n+\n+ try:\n+ if model._job_creation_metadata.create_as is not None:\n+ create_as_metadata = model._job_creation_metadata.create_as\n+ if create_as_metadata.model is not None:\n+ return create_as_metadata.model(**instantiated_fields)\n+ elif create_as_metadata.callable is not None:\n+ create_as_class = create_as_metadata.callable(model)\n+ return create_as_class(**instantiated_fields)\n+ return model.__class__(**instantiated_fields)\n+ except ValidationError as exc:\n+ raise ValidationError([ErrorWrapper(exc, loc)], model.__class__)\n+\n+\n+def _instantiate_noncollection_value(\n+ within_model: OpenJDModel,\n+ field_name: str,\n+ value: Any,\n+ symtab: SymbolTable,\n+ loc: tuple[Union[str, int], ...],\n+) -> Any:\n+ \"\"\"Instantiate a single value that must not be a collection type (list, dict, etc).\n+\n+ Arguments:\n+ within_model (OpenJDModel): The model within which the value is located.\n+ field_name (str): The name of the field within that model that contains the value.\n+ value (Any): Value to process.\n+ symtab (SymbolTable): Symbol table for format string value lookups.\n+ loc (tuple[Union[str,int], ...]): Path to this value.\n+ \"\"\"\n+\n+ # Note: Let the exceptions fall through to the calling context to handle.\n+ # If we wrap them into ValidationErrors here, then the locations of errors will\n+ # be incorrect.\n+\n+ if isinstance(value, OpenJDModel):\n+ # Raises: ValidationError\n+ return instantiate_model(value, symtab, loc, field_name)\n+ elif (\n+ isinstance(value, FormatString)\n+ and field_name in within_model._job_creation_metadata.resolve_fields\n+ ):\n+ # Raises: FormatStringError\n+ return value.resolve(symtab=symtab)\n+\n+ return value\n+\n+\n+def _instantiate_list_field( # noqa: C901\n+ within_model: OpenJDModel,\n+ field_name: str,\n+ value: list[Any],\n+ symtab: SymbolTable,\n+ loc: tuple[Union[str, int], ...],\n+) -> Union[list[Any], dict[str, Any]]:\n+ \"\"\"As _instantiate_noncollection_value, but where the value is a list.\n+\n+ Arguments:\n+ within_model (OpenJDModel): The model within which the value is located.\n+ field_name (str): The name of the field within that model that contains the value.\n+ value (Any): Value to process.\n+ symtab (SymbolTable): Symbol table for format string value lookups.\n+ loc (tuple[Union[str,int], ...]): Path to this value.\n+ \"\"\"\n+ errors = list[ErrorWrapper]()\n+ result: Union[list[Any], dict[str, Any]]\n+ if field_name in within_model._job_creation_metadata.reshape_field_to_dict:\n+ key_field = within_model._job_creation_metadata.reshape_field_to_dict[field_name]\n+ result = dict[str, Any]()\n+ for idx, item in enumerate(value):\n+ key = getattr(item, key_field)\n+ try:\n+ # Raises: ValidationError, FormatStringError\n+ result[key] = _instantiate_noncollection_value(\n+ within_model,\n+ field_name,\n+ item,\n+ symtab,\n+ loc\n+ + (\n+ field_name,\n+ idx,\n+ ),\n+ )\n+ except (ValidationError, FormatStringError) as exc:\n+ errors.append(ErrorWrapper(exc, loc))\n+ else:\n+ result = list[Any]()\n+ for idx, item in enumerate(value):\n+ try:\n+ # Raises: ValidationError, FormatStringError\n+ result.append(\n+ _instantiate_noncollection_value(\n+ within_model,\n+ field_name,\n+ item,\n+ symtab,\n+ loc\n+ + (\n+ field_name,\n+ idx,\n+ ),\n+ )\n+ )\n+ except (ValidationError, FormatStringError) as exc:\n+ errors.append(ErrorWrapper(exc, loc))\n+\n+ if errors:\n+ raise ValidationError(errors, within_model.__class__)\n+\n+ return result\n+\n+\n+def _instantiate_dict_field(\n+ within_model: OpenJDModel,\n+ field_name: str,\n+ value: dict[str, Any],\n+ symtab: SymbolTable,\n+ loc: tuple[Union[str, int], ...],\n+) -> dict[str, Any]:\n+ \"\"\"As _instantiate_noncollection_value, but where the value is a dict.\n+\n+ Arguments:\n+ within_model (OpenJDModel): The model within which the value is located.\n+ field_name (str): The name of the field within that model that contains the value.\n+ value (Any): Value to process.\n+ symtab (SymbolTable): Symbol table for format string value lookups.\n+ loc (tuple[Union[str,int], ...]): Path to this value.\n+ \"\"\"\n+ errors = list[ErrorWrapper]()\n+ result = dict[str, Any]()\n+ for key, item in value.items():\n+ try:\n+ # Raises: ValidationError, FormatStringError\n+ result[key] = _instantiate_noncollection_value(\n+ within_model,\n+ key, # We call the dictionary key the field name for adds_fields arguments to be correct\n+ item,\n+ symtab,\n+ loc\n+ + (\n+ field_name,\n+ key,\n+ ),\n+ )\n+ except (ValidationError, FormatStringError) as exc:\n+ errors.append(ErrorWrapper(exc, loc))\n+\n+ if errors:\n+ raise ValidationError(errors, within_model.__class__)\n+\n+ return result"}, {"sha": "ce8985f4c85cb448cc5c5abe37eaa76b41bbb35a", "filename": "src/openjd/model/_internal/_model_variable_references.py", "status": "added", "additions": 254, "deletions": 0, "changes": 254, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F_model_variable_references.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F_model_variable_references.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_internal%2F_model_variable_references.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,254 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+__all__ = [\"validate_model_template_variable_references\"]\n+\n+from collections import defaultdict\n+from typing import Any, cast\n+\n+from pydantic.error_wrappers import ErrorWrapper\n+\n+from .._format_strings import FormatString\n+from .._types import OpenJDModel, ResolutionScope\n+\n+\n+class ScopedSymtabs(defaultdict):\n+ def __init__(self, **kwargs: Any) -> None:\n+ super().__init__(set, **kwargs)\n+\n+ def union(self, other: \"ScopedSymtabs\") -> \"ScopedSymtabs\":\n+ \"\"\"Union the other's contents into self.\"\"\"\n+ for k, v in other.items():\n+ self[k] |= v\n+ return self\n+\n+\n+def validate_model_template_variable_references(\n+ cls: OpenJDModel, values: dict[str, Any]\n+) -> list[ErrorWrapper]:\n+ \"\"\"Validates the template variable references in a model object, based on the model metadata:\n+ _template_variable_scope\n+ _template_variable_definitions and\n+ _template_variable_sources\n+ \"\"\"\n+ return _validate_model_template_variable_references(\n+ cls,\n+ values,\n+ ResolutionScope.TEMPLATE, # root is template scope\n+ symbols=ScopedSymtabs(),\n+ loc=(),\n+ symbol_prefix=\"\",\n+ )\n+\n+\n+def _validate_model_template_variable_references(\n+ cls: OpenJDModel,\n+ values: dict[str, Any],\n+ current_scope: ResolutionScope,\n+ symbol_prefix: str,\n+ symbols: ScopedSymtabs,\n+ loc: tuple,\n+) -> list[ErrorWrapper]:\n+ \"\"\"Inner implementation of validate_model_template_variable_references().\n+\n+ Arguments:\n+ cls - The model class for the Open Job Description model that we're validating the references against.\n+ values - The values used to construct the model of type cls.\n+ current_scope - The variable reference scope at this level of the recursion.\n+ symbol_prefix - The variable symbol prefix (e.g. \"Task.\") for symbols defined at this level of recursion.\n+ symbols - The variable symbols that have been defined in each reference scope.\n+ loc - The path of fields taken from the root of the model to the current recursive level\n+ \"\"\"\n+ errors: list[ErrorWrapper] = []\n+\n+ # Update scope if the model defines a scope for itself and all children\n+ if cls._template_variable_scope is not None:\n+ current_scope = cls._template_variable_scope\n+\n+ value_defs = cls._template_variable_definitions\n+ if value_defs.symbol_prefix.startswith(\"|\"):\n+ # The \"|\" character resets the nesting.\n+ symbol_prefix = value_defs.symbol_prefix[1:]\n+ else:\n+ symbol_prefix += value_defs.symbol_prefix\n+\n+ # Collect all the symbols for this value, from itself or exported by its fields\n+ dict_key = \"\" # Pass in the dict key if there is one\n+ if loc and isinstance(loc[-1], str):\n+ dict_key = loc[-1]\n+ value_symbols = _collect_model_template_variables(\n+ cls, values, current_scope, symbol_prefix, dict_key=dict_key\n+ )\n+\n+ # Validate the fields\n+ for field_name, field_value in values.items():\n+ if field_value and field_name:\n+ validation_symbols = ScopedSymtabs()\n+\n+ # If field_name is in _template_variable_sources, then the value tells us which\n+ # source fields from the current model/cls we need to propagate down into the\n+ # recursion for validating field_name\n+ for source in cls._template_variable_sources.get(field_name, set()):\n+ validation_symbols.union(value_symbols.get(source, ScopedSymtabs()))\n+\n+ # Add in all of the symbols passed down from the parent.\n+ validation_symbols.union(symbols)\n+\n+ errors.extend(\n+ _validate_field_template_variable_references(\n+ field_value,\n+ current_scope,\n+ symbol_prefix,\n+ validation_symbols,\n+ (*loc, field_name),\n+ )\n+ )\n+\n+ return errors\n+\n+\n+def _collect_model_template_variables( # noqa: C901 (suppress: too complex)\n+ cls: OpenJDModel,\n+ values: dict[str, Any],\n+ current_scope: ResolutionScope,\n+ symbol_prefix: str,\n+ dict_key: str = \"\",\n+) -> dict[str, ScopedSymtabs]:\n+ \"\"\"Collects the names of variables that each field of this model object provides.\n+\n+ The return value is a dictionary with a set of symbols for each field,\n+ and \"__self__\" for the model itself.\n+ \"\"\"\n+\n+ defs = cls._template_variable_definitions\n+\n+ symbols: dict[str, ScopedSymtabs] = {\"__self__\": ScopedSymtabs()}\n+\n+ def add_symbol(into: ScopedSymtabs, scope: ResolutionScope, symbol_name: str) -> None:\n+ if scope == ResolutionScope.TEMPLATE:\n+ into[ResolutionScope.TEMPLATE].add(symbol_name)\n+ into[ResolutionScope.SESSION].add(symbol_name)\n+ into[ResolutionScope.TASK].add(symbol_name)\n+ elif scope == ResolutionScope.SESSION:\n+ into[ResolutionScope.SESSION].add(symbol_name)\n+ into[ResolutionScope.TASK].add(symbol_name)\n+ else:\n+ into[ResolutionScope.TASK].add(symbol_name)\n+\n+ if defs.field:\n+ # The cls defines template variables.\n+\n+ # Figure out the name of the variable.\n+ name: str\n+ if defs.field == \"__key__\":\n+ # The name comes from the dict key instead of a model field.\n+ name = dict_key\n+ else:\n+ name = values[defs.field]\n+\n+ # Define the symbols that are defined in the appropriate scopes.\n+ for vardef in defs.defines:\n+ if vardef.prefix.startswith(\"|\"):\n+ symbol_name = f\"{vardef.prefix[1:]}{name}\"\n+ else:\n+ symbol_name = f\"{symbol_prefix}{vardef.prefix}{name}\"\n+ add_symbol(symbols[\"__self__\"], vardef.resolves, symbol_name)\n+\n+ # If this object injects any template variables then those are injected at the\n+ # current model's scope.\n+ for symbol in defs.inject:\n+ if symbol.startswith(\"|\"):\n+ symbol_name = symbol[1:]\n+ else:\n+ symbol_name = f\"{symbol_prefix}{symbol}\"\n+ add_symbol(symbols[\"__self__\"], current_scope, symbol_name)\n+\n+ for field_name, field_value in values.items():\n+ if isinstance(field_value, OpenJDModel):\n+ # Collect all the exported variables\n+ symbols[field_name] = _collect_model_template_variables(\n+ cast(OpenJDModel, type(field_value)),\n+ dict(field_value._iter()),\n+ current_scope,\n+ f\"{symbol_prefix}\",\n+ )[\"__export__\"]\n+ elif isinstance(field_value, list):\n+ symbols[field_name] = ScopedSymtabs()\n+ for item in field_value:\n+ # Collect all the exported variables\n+ if isinstance(item, OpenJDModel):\n+ exports = _collect_model_template_variables(\n+ cast(OpenJDModel, type(item)),\n+ dict(item._iter()),\n+ current_scope,\n+ f\"{symbol_prefix}\",\n+ )[\"__export__\"]\n+ symbols[field_name].union(exports)\n+ elif isinstance(field_value, dict):\n+ # This is for when the name comes from the dict key instead of a model field.\n+ symbols[field_name] = ScopedSymtabs()\n+ for item_name, item in field_value.items():\n+ # Collect all the exported variables\n+ if isinstance(item, OpenJDModel):\n+ exports = _collect_model_template_variables(\n+ cast(OpenJDModel, type(item)),\n+ dict(item._iter()),\n+ current_scope,\n+ f\"{symbol_prefix}\",\n+ dict_key=item_name,\n+ )[\"__export__\"]\n+ symbols[field_name].union(exports)\n+\n+ # Collect the exported symbols as specified by the metadata\n+ symbols[\"__export__\"] = ScopedSymtabs()\n+ for source in cls._template_variable_sources.get(\"__export__\", set()):\n+ symbols[\"__export__\"].union(symbols.get(source, ScopedSymtabs()))\n+\n+ return symbols\n+\n+\n+def _validate_field_template_variable_references( # noqa: C901 (suppress: too complex)\n+ value: Any, current_scope: ResolutionScope, symbol_prefix: str, symbols: ScopedSymtabs, loc: Any\n+) -> list[ErrorWrapper]:\n+ \"\"\"Recursively validates all the template variable references of a model, based on its\n+ type annotation metadata. Returns the set of symbols exported by the object\n+ \"\"\"\n+\n+ errors: list[ErrorWrapper] = []\n+ if isinstance(value, list):\n+ for i, item in enumerate(value):\n+ errors.extend(\n+ _validate_field_template_variable_references(\n+ item, current_scope, symbol_prefix, symbols, (*loc, i)\n+ )\n+ )\n+ elif isinstance(value, dict):\n+ # This is for the v2022_05_01 job parameters, where the name comes\n+ # from the dict key instead of a model field.\n+ for item_name, item in value.items():\n+ # Collect all the exported variables\n+ errors.extend(\n+ _validate_field_template_variable_references(\n+ item, current_scope, symbol_prefix, symbols, (*loc, item_name)\n+ )\n+ )\n+ elif isinstance(value, FormatString):\n+ scoped_symbols = symbols[current_scope]\n+ for expr in value.expressions:\n+ if expr.expression:\n+ try:\n+ expr.expression.validate_symbol_refs(symbols=scoped_symbols)\n+ except ValueError as exc:\n+ errors.append(ErrorWrapper(exc, loc))\n+ elif isinstance(value, OpenJDModel):\n+ errors.extend(\n+ _validate_model_template_variable_references(\n+ cast(OpenJDModel, type(value)),\n+ dict(value._iter()),\n+ current_scope,\n+ symbol_prefix,\n+ symbols,\n+ loc,\n+ )\n+ )\n+\n+ return errors"}, {"sha": "77630ad19c252209f79399afb5392f882e0e535a", "filename": "src/openjd/model/_internal/_range_expr.py", "status": "added", "additions": 371, "deletions": 0, "changes": 371, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F_range_expr.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_internal%2F_range_expr.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_internal%2F_range_expr.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,371 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from __future__ import annotations\n+\n+from bisect import bisect\n+from collections.abc import Iterator, Sized\n+from functools import total_ordering\n+from itertools import chain\n+from typing import Tuple\n+\n+from .._errors import ExpressionError, TokenError\n+from .._tokenstream import Token, TokenStream, TokenType\n+\n+\n+class IntRangeExpression(Sized):\n+ \"\"\"An Int Range Expression is made up of one or more IntRanges\"\"\"\n+\n+ _start: int\n+ _end: int\n+ _ranges: list[IntRange]\n+ _length: int\n+ _range_length_indicies: list[int]\n+\n+ def __init__(self, ranges: list[IntRange]):\n+ self._ranges = sorted(ranges)\n+ self._start = self.ranges[0].start\n+ self._end = self.ranges[-1].end\n+\n+ # used to binary search ranges for __getitem__\n+ # ie. [32, 100, 132]\n+ self._range_length_indicies = []\n+ length = 0\n+ for r in self.ranges:\n+ length += len(r)\n+ self._range_length_indicies.append(length)\n+\n+ self._length = length\n+\n+ self._validate()\n+\n+ def __len__(self) -> int:\n+ return self._length\n+\n+ def __eq__(self, other: object) -> bool:\n+ if not isinstance(other, IntRangeExpression):\n+ raise NotImplementedError\n+ return self.ranges == other.ranges\n+\n+ def __repr__(self) -> str:\n+ return f\"{type(self).__name__}({self.ranges})\"\n+\n+ def __iter__(self) -> Iterator[int]:\n+ return chain(*self.ranges)\n+\n+ def __getitem__(self, index: int) -> int:\n+ \"\"\"\n+ Note: since we have to binary search the underlying ranges in the expression, this function is O(log(n))\n+ \"\"\"\n+ # support negative indicies\n+ if index < 0:\n+ index = len(self) + index\n+\n+ if not (0 <= index < self._length):\n+ raise IndexError(f\"index {index} is out of range\")\n+\n+ # gets the index for insertion position\n+ # (ie. we receive the index to the range that contains the item we're looking for)\n+ range_index = bisect(self._range_length_indicies, index)\n+ if range_index == 0:\n+ return self.ranges[0][index]\n+ else:\n+ actual_index = index - self._range_length_indicies[range_index - 1]\n+ return self.ranges[range_index][actual_index]\n+\n+ @property\n+ def start(self) -> int:\n+ \"\"\"read-only property\"\"\"\n+ return self._start\n+\n+ @property\n+ def end(self) -> int:\n+ \"\"\"read-only property\"\"\"\n+ return self._end\n+\n+ @property\n+ def ranges(self) -> list[IntRange]:\n+ \"\"\"read-only property\"\"\"\n+ return self._ranges.copy()\n+\n+ def _validate(self) -> None:\n+ \"\"\"raises: ValueError - if not valid\"\"\"\n+\n+ if len(self) <= 0:\n+ raise ValueError(\"range expression cannot be empty\")\n+\n+ # Validate that the ranges are not overlapping\n+ prev_range: IntRange | None = None\n+ for range_ in self.ranges:\n+ # With the ranges already sorted, we can just ensure that\n+ # earlier entries are completely less than later entries, regardless\n+ # of ascending vs. descending\n+ if prev_range and max(prev_range.start, prev_range.end) >= min(\n+ range_.start, range_.end\n+ ):\n+ raise ValueError(\n+ f\"Range expression is not valid due to overlapping ranges:\\n\"\n+ f\"\\t{prev_range} overlaps with {range_}\"\n+ )\n+ prev_range = range_\n+\n+\n+@total_ordering\n+class IntRange(Sized):\n+ \"\"\"Inclusive on the start and end value\"\"\"\n+\n+ _start: int\n+ _end: int\n+ _step: int\n+ _range: range\n+\n+ def __init__(self, start: int, end: int, step: int = 1):\n+ self._start = start\n+ self._end = end\n+ self._step = step\n+\n+ # makes the range inclusive on end value\n+ offset = 0\n+ if self._step > 0:\n+ offset = 1\n+ elif self._step < 0:\n+ offset = -1\n+\n+ self._range = range(self._start, self._end + offset, self._step)\n+\n+ self._validate()\n+\n+ def __repr__(self) -> str:\n+ return f\"{type(self).__name__}(start={self._start}, end={self._end}, step={self._step})\"\n+\n+ def __len__(self):\n+ return len(self._range)\n+\n+ def __eq__(self, other: object) -> bool:\n+ if not isinstance(other, IntRange):\n+ raise NotImplementedError\n+ return (self.start, self.end, self.step) == (other.start, other.end, other.step)\n+\n+ def __lt__(self, other: object) -> bool:\n+ if not isinstance(other, IntRange):\n+ raise NotImplementedError\n+ return (self.start, self.end, self.step) < (other.start, other.end, other.step)\n+\n+ def __iter__(self) -> Iterator[int]:\n+ return iter(self._range)\n+\n+ def __getitem__(self, index: int) -> int:\n+ if index >= len(self):\n+ raise IndexError(f\"index {index} is out of range\")\n+ return self._range[index]\n+\n+ @property\n+ def start(self) -> int:\n+ \"\"\"read-only property\"\"\"\n+ return self._start\n+\n+ @property\n+ def end(self) -> int:\n+ \"\"\"read-only property\"\"\"\n+ return self._end\n+\n+ @property\n+ def step(self) -> int:\n+ \"\"\"read-only property\"\"\"\n+ return self._step\n+\n+ def _validate(self) -> None:\n+ \"\"\"raises: ValueError - if not valid\"\"\"\n+\n+ if self._step == 0:\n+ raise ValueError(\"Range: step must not be zero\")\n+\n+ if self._start < self._end and self._step < 0:\n+ raise ValueError(\"Range: an ascending range must have a positive step\")\n+\n+ if self._start > self._end and self._step > 0:\n+ raise ValueError(\"Range: a descending range must have a negative step\")\n+\n+ if len(self) <= 0:\n+ raise ValueError(\"Range: cannot be empty\")\n+\n+\n+class PosIntToken(Token):\n+ \"\"\"A positive integer\"\"\"\n+\n+\n+class HyphenToken(Token):\n+ \"\"\"The '-' character.\"\"\"\n+\n+\n+class ColonToken(Token):\n+ \"\"\"The ':' character.\"\"\"\n+\n+\n+class CommaToken(Token):\n+ \"\"\"The ',' character.\"\"\"\n+\n+\n+# Map of TokenTypes to their corresponding Token class.\n+# Required by the TokenStream used by the parser to map\n+# lexical tokens to the correct token class.\n+_tokenmap = {\n+ TokenType.POSINT: PosIntToken,\n+ TokenType.HYPHEN: HyphenToken,\n+ TokenType.COLON: ColonToken,\n+ TokenType.COMMA: CommaToken,\n+}\n+\n+\n+class Parser:\n+ \"\"\"Range expression parser.\n+\n+ Full Grammar:\n+ ::= | ,\n+ ::= ** | ** | **\n+ ::= *-*\n+ ::= :\n+ ::= Any numeric base-10 value (int)\n+ ::= base-10 non-zero number\n+ ::= whitespace character: tabs or spaces\n+ \"\"\"\n+\n+ def parse(self, expr: str) -> IntRangeExpression:\n+ \"\"\"Generate an IntRangeExpression for the given string range expression.\n+\n+ Raises:\n+ TokenError: If an unexpected token is encountered.\n+ ExpressionError: If the expresssion is malformed.\n+ \"\"\"\n+\n+ # Raises: TokenError\n+ self._tokens = TokenStream(expr, supported_tokens=_tokenmap)\n+\n+ if self._tokens.at_end():\n+ raise ExpressionError(\"Empty expression\")\n+\n+ result = self._expression()\n+ if not self._tokens.at_end():\n+ token = self._tokens.next()\n+ raise TokenError(self._tokens.expr, token.value, token.start)\n+\n+ return result\n+\n+ def _integer(self) -> Tuple[str, PosIntToken]:\n+ \"\"\"Matches one number (integer) within a range expression\n+\n+ Grammar:\n+ ::= Any numeric base-10 value (int)\n+ \"\"\"\n+ num_sign = \"+\" # positive/negative 0 is still 0\n+\n+ try:\n+ # Check if there's a hyphen preceding the number, indicating a negative number\n+ if isinstance(self._tokens.lookahead(0), HyphenToken):\n+ num_sign = \"-\"\n+ self._tokens.next()\n+\n+ token = self._tokens.next()\n+ if not isinstance(token, PosIntToken):\n+ raise ExpressionError(f\"Expected {PosIntToken}, received {token}\")\n+ except IndexError as e:\n+ raise ExpressionError(\n+ \"Unexpectedly reached end of expression when parsing an integer\"\n+ ) from e\n+\n+ return num_sign, token\n+\n+ def _range(self) -> IntRange:\n+ \"\"\"Matches one element within a range expression.\n+\n+ Grammar:\n+ ::= ** | ** | **\n+ ::= :\n+ ::= *-*\n+ ::= Any numeric base-10 value (int)\n+ ::= base-10 non-zero number\n+ ::= whitespace character: tabs or spaces\n+\n+ Raises\n+ ExpressionError: If the expresssion is malformed.\n+\n+ Returns:\n+\n+ \"\"\"\n+ # get the start integer\n+ start_sign, start = self._integer()\n+\n+ # Just a start number? Technically a Range\n+ if self._tokens.at_end() or isinstance(self._tokens.lookahead(0), CommaToken):\n+ return IntRange(\n+ start=int(start_sign + start.value), end=int(start_sign + start.value), step=1\n+ )\n+\n+ token = self._tokens.next()\n+ if not isinstance(token, HyphenToken):\n+ raise ExpressionError(f\"Expected {HyphenToken}, received {token}\")\n+\n+ # get the end integer\n+ end_sign, end = self._integer()\n+\n+ # Check if we're done with this range, or if there's a step to handle\n+ if self._tokens.at_end() or isinstance(self._tokens.lookahead(0), CommaToken):\n+ return IntRange(\n+ start=int(start_sign + start.value), end=int(end_sign + end.value), step=1\n+ )\n+\n+ # Not done, now expecting a colon to indicate the step\n+ if self._tokens.at_end():\n+ raise ExpressionError(f\"Expected {ColonToken}, reached end of expression\")\n+ token = self._tokens.next()\n+ if not isinstance(token, ColonToken):\n+ raise ExpressionError(f\"Expected {ColonToken}, received {token}\")\n+\n+ # get the step integer\n+ step_sign, step = self._integer()\n+\n+ try:\n+ return IntRange(\n+ start=int(start_sign + start.value),\n+ end=int(end_sign + end.value),\n+ step=int(step_sign + step.value),\n+ )\n+ except ValueError:\n+ raise ExpressionError(\"Failed to create Range\") from ValueError\n+\n+ def _expression(self) -> IntRangeExpression:\n+ \"\"\"Matches a range expression.\n+\n+ Grammar:\n+ ::= | ,\n+ ::= ** | ** | **\n+ ::= *-*\n+ ::= :\n+ ::= Any numeric base-10 value (int)\n+ ::= base-10 non-zero number\n+ ::= whitespace character: tabs or spaces\n+\n+ Raises:\n+ TokenError: If an unexpected token is encountered\n+ ExpressionError: If the expresssion is malformed.\n+\n+ Returns:\n+ IntRangeExpression: The full range expression parsed\n+ \"\"\"\n+ range_ = self._range()\n+ ranges: list[IntRange] = [range_]\n+ try:\n+ while isinstance(self._tokens.lookahead(0), CommaToken):\n+ self._tokens.next()\n+ range_ = self._range()\n+ ranges.append(range_)\n+ else:\n+ if not self._tokens.at_end():\n+ token = self._tokens.next()\n+ raise ExpressionError(f\"Expected {CommaToken}, received {token}\")\n+ except IndexError:\n+ pass\n+\n+ try:\n+ return IntRangeExpression(ranges)\n+ except ValueError as error:\n+ raise ExpressionError(\"Failed to create IntRangeExpression\") from error"}, {"sha": "f5e80c107d5c8f4eb8bc9470d5e8b5e9fd7358d9", "filename": "src/openjd/model/_parse.py", "status": "added", "additions": 108, "deletions": 0, "changes": 108, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_parse.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_parse.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_parse.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,108 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import json\n+from dataclasses import is_dataclass\n+from enum import Enum\n+from typing import Any, ClassVar, Type, TypeVar, cast\n+\n+import yaml\n+from pydantic import BaseModel\n+from pydantic import ValidationError as PydanticValidationError\n+\n+from ._errors import DecodeValidationError\n+from ._types import JobTemplate, OpenJDModel, SchemaVersion\n+from .v2023_09 import JobTemplate as JobTemplate_2023_09\n+\n+__all__ = (\"parse_model\", \"document_string_to_object\", \"DocumentType\", \"decode_template\")\n+\n+\n+class DocumentType(str, Enum):\n+ JSON = \"JSON\"\n+ YAML = \"YAML\"\n+\n+\n+# Pydantic injects a __pydantic_model__ attribute into all dataclasses. To be able to parse\n+# dataclass models we need to be able to invoke Model.__pydantic_model__.parse_obj(), but\n+# type checkers do not realize that pydantic dataclasses have a __pydantic_model__ attribute.\n+# So, we type-cast into this class to invoke that method.\n+class PydanticDataclass:\n+ # See: https://github.com/pydantic/pydantic/blob/b0215d175ace2a3db76307c5f18819b021f48ab5/pydantic/dataclasses.py#L68\n+ __pydantic_model__: ClassVar[Type[BaseModel]]\n+\n+\n+T = TypeVar(\"T\", bound=OpenJDModel)\n+\n+\n+def _parse_model(*, model: Type[T], obj: Any) -> T:\n+ if is_dataclass(model):\n+ return cast(T, cast(PydanticDataclass, model).__pydantic_model__.parse_obj(obj))\n+ else:\n+ return cast(T, cast(BaseModel, model).parse_obj(obj))\n+\n+\n+def parse_model(*, model: Type[T], obj: Any) -> T:\n+ try:\n+ return _parse_model(model=model, obj=obj)\n+ except PydanticValidationError as exc:\n+ raise DecodeValidationError(str(exc))\n+\n+\n+def document_string_to_object(*, document: str, document_type: DocumentType) -> dict[str, Any]:\n+ \"\"\"\n+ Converts the YAML or JSON encoded document into a python dictionary.\n+\n+ Arguments:\n+ document (str): A string containing a JSON or YAML encoded document.\n+\n+ Returns:\n+ dict[str, Any]: The decoded document.\n+\n+ Raises:\n+ DecodeValidationError\n+ \"\"\"\n+ try:\n+ if document_type == DocumentType.JSON:\n+ parsed_document = json.loads(document)\n+ else: # YAML\n+ parsed_document = yaml.safe_load(document)\n+ if not isinstance(parsed_document, dict):\n+ raise ValueError()\n+ return parsed_document\n+ except (ValueError, json.decoder.JSONDecodeError, yaml.YAMLError):\n+ raise DecodeValidationError(\n+ f\"The document is not a valid {document_type.value} document consisting of key-value pairs.\"\n+ )\n+\n+\n+def decode_template(*, template: dict[str, Any]) -> JobTemplate:\n+ \"\"\"Given a dictionary containing a Job Template, this will decode the template, run validation checks on it,\n+ and then return the decoded template.\n+\n+ Args:\n+ template (dict[str, Any]): A Job Template as a dictionary object.\n+\n+ Returns:\n+ JobTemplate: The decoded job template.\n+\n+ Raises:\n+ DecodeValidationError\n+ NotImplementedError\n+ \"\"\"\n+ try:\n+ # Raises: KeyError\n+ document_version = template[\"specificationVersion\"]\n+ # Raises: ValueError\n+ schema_version = SchemaVersion(document_version)\n+ except KeyError:\n+ # Unable to get 'specificationVersion' key from the document\n+ raise DecodeValidationError(\"Template is missing Open Job Description schema version key\")\n+ except ValueError:\n+ # Value of the schema version is not one we know.\n+ raise DecodeValidationError(f\"Unknown template version: {document_version}\")\n+\n+ if schema_version == SchemaVersion.v2023_09:\n+ return parse_model(model=JobTemplate_2023_09, obj=template)\n+ else:\n+ raise NotImplementedError(\n+ f\"Template decode for schema {schema_version.value} is not yet implemented.\"\n+ )"}, {"sha": "e402004a9e0ce4f2469d569310110f1c9c67f55e", "filename": "src/openjd/model/_step_dependency_graph.py", "status": "added", "additions": 121, "deletions": 0, "changes": 121, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_step_dependency_graph.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_step_dependency_graph.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_step_dependency_graph.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,121 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+\n+from dataclasses import dataclass\n+\n+from ._types import Job, SchemaVersion, Step, dataclass_kwargs\n+\n+\n+@dataclass(frozen=True, **dataclass_kwargs)\n+class StepDependencyGraphNode:\n+ step: Step\n+ \"\"\"The Step that this node represents\n+ \"\"\"\n+\n+ in_edges: list[\"StepDependencyGraphEdgeBase\"]\n+ \"\"\"Edges wherein this step depends upon another.\n+ \"\"\"\n+\n+ out_edges: list[\"StepDependencyGraphEdgeBase\"]\n+ \"\"\"Edges wherein this step is depended-upon by another.\n+ \"\"\"\n+\n+\n+# Dev note: The edges are using a base/derived class relationship to be\n+# forward looking. We'll add addition edge types when we get different kinds\n+# of dependencies between steps (e.g. task-task dependencies)\n+@dataclass(frozen=True, **dataclass_kwargs)\n+class StepDependencyGraphEdgeBase:\n+ \"\"\"Represents that the 'dependent' step depends upon\n+ the 'origin' step in some way.\n+ \"\"\"\n+\n+ origin: StepDependencyGraphNode\n+ \"\"\"The origin Step of the dependency edge. This is the Step\n+ that is depended-upon.\n+ \"\"\"\n+\n+ dependent: StepDependencyGraphNode\n+ \"\"\"The node that depends-upon the 'step' node.\n+ \"\"\"\n+\n+\n+@dataclass(frozen=True, **dataclass_kwargs)\n+class StepDependencyGraphStepToStepEdge(StepDependencyGraphEdgeBase):\n+ \"\"\"The edge denotes a dependency whereby no Tasks of a dependent\n+ Step can be started until the successful completion of all Tasks\n+ of another Step.\n+ \"\"\"\n+\n+ pass\n+\n+\n+class StepDependencyGraph:\n+ \"\"\"The Step dependency graph of a given Job.\n+\n+ The nodes in the graph each correspond to a single Step in the Job, and\n+ edges represent a dependency relationship between Steps.\n+\n+ Each node in the graph contains the sets of its in-edges and out-edges.\n+ An in-edge for Step S is a dependency wherein S depends upon another Step.\n+ An out-edge for Step S is a dependency wherein S is depended upon by another Step.\n+ \"\"\"\n+\n+ # map from step name -> graph node\n+ _nodes: dict[str, StepDependencyGraphNode]\n+\n+ def __init__(self, *, job: Job) -> None:\n+ # The only version supported at the moment.\n+ # Assert's here as a signal to change this class when we add a new spec rev.\n+ assert job.version == SchemaVersion.v2023_09\n+\n+ # Step 1 - create all of the graph nodes (one per step)\n+ self._nodes = dict()\n+ for step in job.steps:\n+ self._nodes[step.name] = StepDependencyGraphNode(\n+ step=step, in_edges=list(), out_edges=list()\n+ )\n+\n+ # Step 2 -- create the dependency edges\n+ for step in job.steps:\n+ if step.dependencies:\n+ step_node = self._nodes[step.name]\n+ for dep in step.dependencies:\n+ origin = self._nodes[dep.dependsOn]\n+ edge = StepDependencyGraphStepToStepEdge(origin=origin, dependent=step_node)\n+ step_node.in_edges.append(edge)\n+ origin.out_edges.append(edge)\n+\n+ def __del__(self) -> None:\n+ for node in self._nodes.values():\n+ # delete the references to all edges, so they can be GC'd\n+ node.in_edges.clear()\n+ node.out_edges.clear()\n+\n+ # delete the references to all nodes, so that they can be GC'd\n+ self._nodes.clear()\n+\n+ def step_node(self, *, stepname: str) -> StepDependencyGraphNode:\n+ \"\"\"Given the name of a step in the graph, return the dependency graph\n+ node for that step; the returned node contains the sets of dependency\n+ edges in and out of the step.\n+\n+ Do not modify the returned object.\n+ \"\"\"\n+ return self._nodes[stepname]\n+\n+ @property\n+ def max_indegree(self) -> int:\n+ \"\"\"Calculate and return the maximum indegree over all steps in the graph.\n+ The indegree of a Step is the number of Steps that it depends upon; equivalently,\n+ the number of edges where the Step is the 'dependent' in the edge.\n+ \"\"\"\n+ return max(len(node.in_edges) for node in self._nodes.values())\n+\n+ @property\n+ def max_outdegree(self) -> int:\n+ \"\"\"Calculate and return the maximum outdegree over all steps in the graph.\n+ The outdegree of a Step is the number of Steps that depend upon it; equivalently,\n+ the number of edges where the Step is the 'origin' in the edge.\n+ \"\"\"\n+ return max(len(node.out_edges) for node in self._nodes.values())"}, {"sha": "f453fdba7a436d6c65d759207f1bbdd04da4ade3", "filename": "src/openjd/model/_step_param_space_iter.py", "status": "added", "additions": 454, "deletions": 0, "changes": 454, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_step_param_space_iter.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_step_param_space_iter.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_step_param_space_iter.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,454 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from __future__ import annotations\n+\n+from abc import ABC, abstractmethod\n+from collections.abc import Iterable, Iterator, Sized\n+from dataclasses import dataclass, field\n+from functools import reduce\n+from operator import mul\n+from typing import AbstractSet, Optional, Union\n+\n+from ._internal import (\n+ CombinationExpressionAssociationNode,\n+ CombinationExpressionIdentifierNode,\n+ CombinationExpressionNode,\n+ CombinationExpressionParser,\n+ CombinationExpressionProductNode,\n+ IntRangeExpression,\n+ RangeExpressionParser,\n+)\n+from ._types import ParameterValue, ParameterValueType, StepParameterSpace, TaskParameterSet\n+from .v2023_09 import (\n+ RangeExpressionTaskParameterDefinition as RangeExpressionTaskParameterDefinition_2023_09,\n+)\n+from .v2023_09 import RangeListTaskParameterDefinition as RangeListTaskParameterDefinition_2023_09\n+\n+__all__ = [\"StepParameterSpaceIterator\"]\n+\n+\n+RangeTaskParameter = Union[\n+ RangeListTaskParameterDefinition_2023_09, RangeExpressionTaskParameterDefinition_2023_09\n+]\n+TaskParameter = RangeTaskParameter\n+\n+\n+class StepParameterSpaceIterator(Iterable[TaskParameterSet], Sized):\n+ \"\"\"The multidimensional space formed by all possible task parameter values.\n+\n+ The iteration order is dictated by the order of each parameter's values, and\n+ the order of the expressions within the combination expression of the StepParameterSpace.\n+ Ordering is row-major (right-most moves fastest) for products ('*') in the expression.\n+\n+ For example, given:\n+ A = [1,2,3]\n+ B = [1,2]\n+ C = [10,11]\n+ Then:\n+ combination = \"A * (B,C)\"\n+ results in the order:\n+ (A=1,B=1,C=10), (A=1,B=2,C=11), (A=2,B=1,C=10), (A=2,B=2,C=11), (A=3,B=1,C=10), (A=3,B=2,C=11)\n+ Or\n+ combination = \"(B,C) * A\"\n+ results in the order:\n+ (A=1,B=1,C=10), (A=2,B=1,C=10), (A=3,B=1,C=10), (A=1,B=2,C=11), (A=2,B=2,C=11), (A=3,B=2,C=11)\n+\n+ For comparison:\n+ A = [3,2,1]\n+ B = [1,2]\n+ C = [10,11]\n+ combination = \"A * (B,C)\"\n+ would be the order:\n+ (A=3,B=1,C=10), (A=3,B=2,C=11), (A=2,B=1,C=10), (A=2,B=2,C=11), (A=1,B=1,C=10), (A=1,B=2,C=11)\n+\n+ Attributes:\n+ None\n+ \"\"\"\n+\n+ _parameters: dict[str, TaskParameter]\n+ _expr_tree: Node\n+ _parsedtree: CombinationExpressionNode\n+\n+ def __init__(self, *, space: StepParameterSpace):\n+ if space.combination is None:\n+ # space.taskParameterDefinitions is a dict[str,TaskParameter]\n+ combination = \"*\".join(name for name in space.taskParameterDefinitions)\n+ else:\n+ combination = space.combination\n+ self._parameters = dict(space.taskParameterDefinitions)\n+\n+ # Raises: TokenError, ExpressionError\n+ self._parsetree = CombinationExpressionParser().parse(combination)\n+ self._expr_tree = self._create_expr_tree(self._parsetree)\n+\n+ @property\n+ def names(self) -> AbstractSet[str]:\n+ \"\"\"Get the names of all parameters in the parameter space.\"\"\"\n+ return self._parameters.keys()\n+\n+ def __iter__(self) -> Iterator[TaskParameterSet]:\n+ \"\"\"Obtain an iterator that will iterate over every task parameter set\n+ in this parameter space.\n+\n+ Note: The ordering of inputs generated by this iterator is **NOT**\n+ guaranteed to be invariant across versions of this library.\n+ \"\"\"\n+\n+ class Iter:\n+ _root: NodeIterator\n+\n+ def __init__(self, root: Node):\n+ self._root = root.iter()\n+\n+ def __iter__(self): # pragma: no cover\n+ return self\n+\n+ def __next__(self) -> TaskParameterSet:\n+ result: TaskParameterSet = TaskParameterSet()\n+ self._root.next(result)\n+ return result\n+\n+ return Iter(self._expr_tree)\n+\n+ def __len__(self) -> int:\n+ \"\"\"The number of task parameter sets that are defined by this parameter space\"\"\"\n+ return len(self._expr_tree)\n+\n+ def __getitem__(self, index: int) -> TaskParameterSet:\n+ \"\"\"Get a specific task parameter set given an index.\n+\n+ Note: The ordering of inputs is **NOT** guaranteed to be\n+ invariant across versions of this library.\n+\n+ Args:\n+ index (int): Index for a task parameter set to fetch.\n+\n+ Returns:\n+ dict[str, Union[int, float, str]]: Values of every task parameter. Dictionary key\n+ is the parameter name.\n+ \"\"\"\n+ return self._expr_tree[index]\n+\n+ def _create_expr_tree(self, root: CombinationExpressionNode) -> Node:\n+ \"\"\"Recursively make a copy of the given Parser-generated expression tree using\n+ the Node types defined in this file.\n+ \"\"\"\n+ if isinstance(root, CombinationExpressionIdentifierNode):\n+ name = root.parameter\n+ parameter = self._parameters[name]\n+ if isinstance(parameter.range, list):\n+ return RangeListIdentifierNode(\n+ name,\n+ ParameterValueType(parameter.type),\n+ parameter.range,\n+ )\n+ else:\n+ return RangeExpressionIdentifierNode(\n+ name,\n+ ParameterValueType(parameter.type),\n+ parameter.range,\n+ )\n+ elif isinstance(root, CombinationExpressionAssociationNode):\n+ return AssociationNode(tuple(self._create_expr_tree(child) for child in root.children))\n+ else:\n+ assert isinstance(root, CombinationExpressionProductNode)\n+ return ProductNode(tuple(self._create_expr_tree(child) for child in root.children))\n+\n+ def __eq__(self, other: object) -> bool:\n+ # For assisting unit testing\n+ if not isinstance(other, StepParameterSpaceIterator): # pragma: no cover\n+ return NotImplemented\n+ return self._parameters == other._parameters and repr(self._parsetree) == repr(\n+ other._parsetree\n+ )\n+\n+\n+# -------\n+# Mirror classes for the parsed combination expression tree.\n+# We create these to separate out the functionality required by this class\n+# around iterating, length calculations, getitem, etc from the needs of\n+# an expression validator. To validate the expression it is sufficient to\n+# parse the expression and then collect all referenced identifiers into a list.\n+\n+\n+class NodeIterator(ABC):\n+ \"\"\"Our own special iterator base class. We don't use the standard\n+ Python iterator interface. For efficiency we need to pass a\n+ dict into the next() operator and have the method add/modify the\n+ appropriate key/values in it. With the standard iterator we would\n+ have __next__ returning a dict and end up with a tonne of intermediary\n+ dicts created as we ran __next__ on the entire tree.\n+ \"\"\"\n+\n+ @abstractmethod\n+ def next(self, result: TaskParameterSet) -> None:\n+ raise NotImplementedError(\"Base class\") # pragma: no cover\n+\n+ @abstractmethod\n+ def reset_iter(self) -> None:\n+ raise NotImplementedError(\"Base class\") # pragma: no cover\n+\n+\n+class Node(ABC, Sized):\n+ @abstractmethod\n+ def __getitem__(self, index: int) -> TaskParameterSet:\n+ raise NotImplementedError(\"Base class\") # pragma: no cover\n+\n+ @abstractmethod\n+ def iter(self) -> NodeIterator:\n+ raise NotImplementedError(\"Base class\") # pragma: no cover\n+\n+\n+class ProductNodeIter(NodeIterator):\n+ \"\"\"Iterator for a ProductNode\n+\n+ Attributes:\n+ _children: Iterators for the child nodes of this node in the expression tree.\n+ _prev_result: Cached result from the previous iteration. See next() for explanation.\n+ _first_value: True if and only if we have not yet evaluated the first value of the iterator.\n+ \"\"\"\n+\n+ _children: tuple[NodeIterator, ...]\n+ _prev_result: TaskParameterSet\n+ _first_value: bool\n+\n+ def __init__(self, children: tuple[Node, ...]):\n+ self._children = tuple(child.iter() for child in children)\n+ self._prev_result = TaskParameterSet()\n+ self._first_value = True\n+\n+ def reset_iter(self) -> None:\n+ self._first_value = True\n+ for child in self._children:\n+ child.reset_iter()\n+\n+ def next(self, result: TaskParameterSet) -> None:\n+ # We have to start from the previous result because we don't 'next' every\n+ # iterator when evaluting a ProductNode since not every value changes on each\n+ # iteration. So we start from the previous values and overwrite the values that\n+ # change\n+ if self._first_value:\n+ self._first_value = False\n+ for child in self._children:\n+ # Raises: StopIteration\n+ child.next(self._prev_result)\n+ else:\n+ # The way to think of the next() operation on a product node is\n+ # a row-major order traversal of a multidimensional space.\n+ # For example, if we have:\n+ # A = [1,2]; B = [3,4]; C = [5,6]; and\n+ # expr=\"A * B * C\"\n+ # then the parameters on the right change more rapidly\n+ # than the parmeters on the left. In this case our traversal\n+ # order is:\n+ # A | B | C\n+ # ---------------\n+ # 1 | 3 | 5\n+ # 1 | 3 | 6\n+ # 1 | 4 | 5\n+ # 1 | 4 | 6\n+ # 2 | 3 | 5\n+ # 2 | 3 | 6\n+ # 2 | 4 | 5\n+ # 2 | 4 | 6\n+ #\n+ # To acheive, algorithmically, think about grade-school addition by\n+ # 1 with a carry.\n+ # We advance the right-most parameter by one. If that overflows (i.e.\n+ # hits the end of the iterator) then we reset its iterator and advance\n+ # the next parameter to its left. Repeating as neccessary until we have\n+ # hit the end of the left-most iterator -- which indicates the end of\n+ # the product iteration.\n+\n+ pos = len(self._children) - 1\n+ while True:\n+ try:\n+ # Raises: StopIteration\n+ self._children[pos].next(self._prev_result)\n+ break\n+ except StopIteration as e:\n+ if pos > 0:\n+ self._children[pos].reset_iter()\n+ self._children[pos].next(self._prev_result)\n+ pos -= 1\n+ else:\n+ raise e from None\n+ result.update(self._prev_result)\n+\n+\n+@dataclass\n+class ProductNode(Node):\n+ children: tuple[Node, ...]\n+ _len: Optional[int] = field(default=None, init=False, repr=False, compare=False)\n+\n+ def __len__(self) -> int:\n+ if self._len is None:\n+ self._len = reduce(mul, (len(child) for child in self.children), 1)\n+ return self._len\n+\n+ def __getitem__(self, index: int) -> TaskParameterSet:\n+ if index < 0:\n+ index = len(self) + index\n+ if not (0 <= index < len(self)):\n+ raise IndexError()\n+ result = dict()\n+ # See ProductNodeIter.next() for a long comment on how we define the ordering\n+ # of a product node's values.\n+ # To go from a specific index to the value we use the fact that we're doing\n+ # a row-major-ordering. Say we have the product \"A * B * C\" and we're looking\n+ # for the index of a product-value where the components of that product-value\n+ # are at indicies (a, b, c) -- i.e. A at index 'a', B at index 'b', and C at\n+ # index 'c'.\n+ # Then, the product-value index is simply:\n+ # index = (a * len(B) + b)*len(C) + c\n+ # This generalizes... it's a big nested multiply-add.\n+ # Our algorithm here just finds (a,b,c) given index -- which we can do\n+ # because we know index, len(A), len(B), and len(C) -- and then recursively\n+ # finds the values of A @ index a, B @ index b, and C & index c to compose the\n+ # value for this product node.\n+ pos = len(self.children)\n+ while pos > 0:\n+ pos -= 1\n+ if pos > 0:\n+ child_length = len(self.children[pos])\n+ child_index = index % child_length\n+ index = index // child_length\n+ else:\n+ child_index = index\n+ result.update(self.children[pos][child_index])\n+ return result\n+\n+ def iter(self) -> ProductNodeIter:\n+ return ProductNodeIter(self.children)\n+\n+\n+class AssociationNodeIter(NodeIterator):\n+ \"\"\"Iterator for an AssociationNode\n+\n+ Attributes:\n+ _children: Iterators for the child nodes of this node in the expression tree.\n+ \"\"\"\n+\n+ _children: tuple[NodeIterator, ...]\n+\n+ def __init__(self, children: tuple[Node, ...]):\n+ self._children = tuple(child.iter() for child in children)\n+\n+ def reset_iter(self) -> None:\n+ for child in self._children:\n+ child.reset_iter()\n+\n+ def next(self, result: TaskParameterSet) -> None:\n+ for child in self._children:\n+ # Raises: StopIteration\n+ child.next(result)\n+\n+\n+@dataclass\n+class AssociationNode(Node):\n+ children: tuple[Node, ...]\n+ _len: Optional[int] = field(default=None, init=False, repr=False, compare=False)\n+\n+ def __len__(self) -> int:\n+ if self._len is None:\n+ self._len = len(self.children[0])\n+ return self._len\n+\n+ def __getitem__(self, index: int) -> TaskParameterSet:\n+ result = TaskParameterSet()\n+ for child in self.children:\n+ result.update(child[index])\n+ return result\n+\n+ def iter(self) -> AssociationNodeIter:\n+ return AssociationNodeIter(self.children)\n+\n+\n+class RangeListIdentifierNodeIterator(NodeIterator):\n+ \"\"\"Iterator for a RangeListIdentifierNode\n+\n+ Attributes:\n+ _it: Iterator for the corresponding task parameter\n+ _parameter: The RangeListIdentifierNode this is iterating over.\n+ \"\"\"\n+\n+ _it: Iterator[str]\n+ _node: RangeListIdentifierNode\n+\n+ def __init__(self, node: RangeListIdentifierNode):\n+ self._node = node\n+ self.reset_iter()\n+\n+ def reset_iter(self) -> None:\n+ self._it = iter(self._node.range)\n+\n+ def next(self, result: TaskParameterSet) -> None:\n+ # Raises: StopIteration\n+ v = next(self._it)\n+ result[self._node.name] = ParameterValue(type=self._node.type, value=v)\n+\n+\n+@dataclass\n+class RangeListIdentifierNode(Node):\n+ name: str\n+ type: ParameterValueType\n+ range: list[str]\n+ _len: int = field(init=False, repr=False, compare=False)\n+\n+ def __post_init__(self):\n+ self._len = len(self.range)\n+\n+ def __len__(self) -> int:\n+ return self._len\n+\n+ def __getitem__(self, index: int) -> TaskParameterSet:\n+ return {self.name: ParameterValue(type=self.type, value=self.range[index])}\n+\n+ def iter(self) -> RangeListIdentifierNodeIterator:\n+ return RangeListIdentifierNodeIterator(self)\n+\n+\n+class RangeExpressionIdentifierNodeIterator(NodeIterator):\n+ \"\"\"Iterator for a RangeExpressionIdentifierNode\n+\n+ Attributes:\n+ _it: Iterator for the corresponding task parameter\n+ _parameter: The RangeExpressionIdentifierNode this is iterating over.\n+ \"\"\"\n+\n+ _it: Iterator[int]\n+ _node: RangeExpressionIdentifierNode\n+\n+ def __init__(self, node: RangeExpressionIdentifierNode):\n+ self._node = node\n+ self.reset_iter()\n+\n+ def reset_iter(self) -> None:\n+ self._it = iter(self._node.range_expression)\n+\n+ def next(self, result: TaskParameterSet) -> None:\n+ # Raises: StopIteration\n+ v = next(self._it)\n+ result[self._node.name] = ParameterValue(type=self._node.type, value=str(v))\n+\n+\n+@dataclass\n+class RangeExpressionIdentifierNode(Node):\n+ name: str\n+ type: ParameterValueType\n+ range: str\n+ range_expression: IntRangeExpression = field(init=False, repr=False, compare=False)\n+ _len: int = field(init=False, repr=False, compare=False)\n+\n+ def __post_init__(self):\n+ self.range_expression = RangeExpressionParser().parse(self.range)\n+ self._len = len(self.range_expression)\n+\n+ def __len__(self) -> int:\n+ return self._len\n+\n+ def __getitem__(self, index: int) -> TaskParameterSet:\n+ return {self.name: ParameterValue(type=self.type, value=str(self.range_expression[index]))}\n+\n+ def iter(self) -> RangeExpressionIdentifierNodeIterator:\n+ return RangeExpressionIdentifierNodeIterator(self)"}, {"sha": "09ee6b227ab9c1701bc687d39a8eaef101dcbd60", "filename": "src/openjd/model/_symbol_table.py", "status": "added", "additions": 72, "deletions": 0, "changes": 72, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_symbol_table.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_symbol_table.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_symbol_table.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,72 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from __future__ import annotations\n+\n+from typing import AbstractSet as _AbstractSet\n+from typing import Any, Optional, Union\n+\n+__all__ = [\"SymbolTable\"]\n+\n+\n+class SymbolTable:\n+ \"\"\"\n+ Class used to represent the available symbols that can be used for interpolation in the current context.\n+ \"\"\"\n+\n+ _table: dict[str, Any]\n+\n+ def __init__(self, *, source: Optional[Union[SymbolTable, dict[str, Any]]] = None):\n+ \"\"\"Initialize the SymbolTable\n+\n+ Args:\n+ source (Optional[Union[SymbolTable, dict[str, Any]]], optional): If provided then this\n+ gets initialized with the contents of the given source. Defaults to None.\n+ \"\"\"\n+ self._table = dict()\n+ if source is not None:\n+ if isinstance(source, SymbolTable):\n+ self._table.update(source._table)\n+ elif isinstance(source, dict):\n+ self._table.update(source)\n+ else:\n+ raise TypeError(f\"Cannot initialize with type {type(source)}\")\n+\n+ def __contains__(self, symbol: str) -> bool:\n+ return symbol in self._table\n+\n+ def __getitem__(self, symbol: str) -> Any:\n+ return self._table[symbol]\n+\n+ def __setitem__(self, symbol: str, value: Any) -> None:\n+ if not isinstance(symbol, str):\n+ raise TypeError(\"Symbol must be a string\")\n+ self._table[symbol] = value\n+\n+ @property\n+ def symbols(self) -> _AbstractSet[str]:\n+ \"\"\"\n+ Returns:\n+ Set[str]: The set of symbols defined in this symbol table\n+ \"\"\"\n+ return self._table.keys()\n+\n+ def union(self, *symtabs: Union[SymbolTable, dict[str, Any]]) -> SymbolTable:\n+ \"\"\"Create a new SymbolTable that is the union of this SymbolTable with\n+ the given ones.\n+\n+ If a specific symbol is defined in more than one SymbolTable then the\n+ last defined value takes precidence.\n+\n+ Returns:\n+ SymbolTable: A new SymbolTable.\n+ \"\"\"\n+ retval = SymbolTable()\n+ retval._table.update(self._table)\n+ for symtab in symtabs:\n+ if isinstance(symtab, SymbolTable):\n+ retval._table.update(symtab._table)\n+ elif isinstance(symtab, dict):\n+ retval._table.update(symtab)\n+ else:\n+ raise TypeError(f\"Cannot union with type {type(symtab)}\")\n+ return retval"}, {"sha": "0bffb1b3fabb79dd80464c4d43720ba951db72c5", "filename": "src/openjd/model/_tokenstream.py", "status": "added", "additions": 213, "deletions": 0, "changes": 213, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_tokenstream.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_tokenstream.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_tokenstream.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,213 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import re\n+from collections import namedtuple\n+from dataclasses import dataclass\n+from enum import Enum\n+from typing import Sequence, Type\n+\n+from ._errors import TokenError\n+\n+__all__ = [\"TokenType\", \"Token\", \"TokenStream\"]\n+\n+\n+class TokenType(Enum):\n+ r\"\"\"Types of tokens that can be recognized by the lexical analysis.\n+\n+ NAME = identifier ([^\\d\\W][\\w]*)\n+ DOT = '.' character\n+ STAR = '*' character\n+ LPAREN = '(' character\n+ RPAREN = ')' character\n+ COMMA = ',' character\n+ POSTINT = identifier ([0-9]+)\n+ HYPHEN = '-' character\n+ COLON = ':' character\n+ \"\"\"\n+\n+ NAME = \"NAME\"\n+ DOT = \"DOT\"\n+ STAR = \"STAR\"\n+ LPAREN = \"LPAREN\"\n+ RPAREN = \"RPAREN\"\n+ COMMA = \"COMMA\"\n+ POSINT = \"POSINT\"\n+ HYPHEN = \"HYPHEN\"\n+ COLON = \"COLON\"\n+\n+\n+# Regular expressions for recognizing each of the tokens during lexical analysis.\n+TokenSpec = namedtuple(\"TokenSpec\", \"name, pattern\")\n+token_specification = (\n+ # [^\\d\\W] = _ or unicode non-digit letter\n+ # [\\w] = _ or unicode letter including digits\n+ TokenSpec(TokenType.NAME.value, r\"[^\\d\\W][\\w]*\"),\n+ TokenSpec(TokenType.DOT.value, r\"\\.\"),\n+ TokenSpec(TokenType.STAR.value, r\"\\*\"),\n+ TokenSpec(TokenType.LPAREN.value, r\"\\(\"),\n+ TokenSpec(TokenType.RPAREN.value, r\"\\)\"),\n+ TokenSpec(TokenType.COMMA.value, r\",\"),\n+ TokenSpec(TokenType.POSINT.value, r\"[0-9]+\"), # only 0 and positive integers\n+ TokenSpec(TokenType.HYPHEN.value, r\"-\"),\n+ TokenSpec(TokenType.COLON.value, r\":\"),\n+ TokenSpec(\"NONVALID\", r\".\"), # Must be last in the list\n+)\n+\n+# Precompile a regular expression matcher that will recognize each of the tokens.\n+# A specific token match is identified by the name of the match group; the name\n+# will match the value of the corresponding TokenType enum\n+lexer_regex = \"|\".join(f\"(?P<{pair.name}>{pair.pattern})\" for pair in token_specification)\n+lexer_matcher = re.compile(lexer_regex)\n+\n+\n+@dataclass\n+class Token:\n+ \"\"\"Base class for every token recognized by the lexical analysis.\n+\n+ Attributes:\n+ value (str): Text that the token represents.\n+ start (int): Position in the input string of the start of the token.\n+ end (int): Position in the input string of the end of the token.\n+ \"\"\"\n+\n+ value: str\n+ start: int\n+ end: int\n+\n+\n+class TokenStream:\n+ \"\"\"An instance of this class will perform a lexical analysis of a given string\n+ and makes available methods for consuming with the resulting token stream in\n+ a way suitable for LL(n) parsers.\n+\n+ Attributes:\n+ None\n+ \"\"\"\n+\n+ _tokens: list[Token]\n+ \"\"\"The tokens for the given expression\"\"\"\n+\n+ _pos: int\n+ \"\"\"Position in _tokens that the stream is currently at.\"\"\"\n+\n+ _expr: str\n+ \"\"\"The expression that we're tokenizing.\"\"\"\n+\n+ def __init__(self, expr: str, *, supported_tokens: dict[TokenType, Type[Token]]):\n+ \"\"\"Initialize the TokenStream\n+\n+ Args:\n+ expr (str): The expression to stream tokens from.\n+ supported_tokens (dict[TokenType, Type[Token]]): A mapping of token type to\n+ Token class for the token types that this tokenstream will support.\n+\n+ Raises:\n+ TokenError: If a badly formed or unsupported token is encountered in the expression.\n+ \"\"\"\n+ # We allow any amount of whitespace, including a multi-line\n+ # expression. Simplify the expr by replacing each whitespace\n+ # blocks in the expr with a single space.\n+ expr = re.sub(r\"\\s+\", \" \", expr)\n+ lexer = Lexer(expr, supported_tokens=supported_tokens)\n+\n+ # Take the expr from the Tokenizer so that we have the same string as it\n+ # inclusive of any modifications made by the Tokenizer (e.g. stripping whitespace)\n+ self._expr = lexer.expr\n+\n+ # Raises: TokenError\n+ self._tokens = list(lexer.lex())\n+\n+ self._pos = 0\n+\n+ @property\n+ def expr(self) -> str:\n+ \"\"\"Get the expression being tokenized.\"\"\"\n+ return self._expr\n+\n+ @property\n+ def expr_position(self) -> int:\n+ \"\"\"Get the current position of the token stream within the expression string\"\"\"\n+ if self.at_end():\n+ return len(self._expr)\n+ # We're at the start position of the current token.\n+ return self._tokens[self._pos].start\n+\n+ def next(self) -> Token:\n+ \"\"\"Consume the next Token from the token stream.\n+\n+ Raises:\n+ IndexError: When no tokens remain.\n+\n+ Returns:\n+ Token: The next token in the stream\n+ \"\"\"\n+ if self._pos < len(self._tokens):\n+ ret = self._tokens[self._pos]\n+ self._pos += 1\n+ return ret\n+ raise IndexError()\n+\n+ def lookahead(self, amount: int) -> Token:\n+ \"\"\"Peek at the token 'amount' steps ahead in the stream. Does not\n+ advance the token stream or consume the returned token.\n+\n+ Args:\n+ amount (int): Number of tokens to look ahead.\n+\n+ Raises:\n+ IndexError: When there is no token at the requested position in the stream.\n+\n+ Returns:\n+ Token: The token 'amount' steps ahead in the stream.\n+ \"\"\"\n+ if amount < 0:\n+ raise ValueError(f\"Argument amount must be >= 0. Got {amount}\")\n+ pos = self._pos + amount\n+ if pos < len(self._tokens):\n+ return self._tokens[pos]\n+ raise IndexError()\n+\n+ def at_end(self) -> bool:\n+ \"\"\"\n+ Returns:\n+ bool: True if no tokens remain in the stream.\n+ \"\"\"\n+ return self._pos == len(self._tokens)\n+\n+\n+class Lexer:\n+ _supported_tokens: dict[TokenType, Type[Token]]\n+\n+ def __init__(self, expr: str, *, supported_tokens: dict[TokenType, Type[Token]]) -> None:\n+ \"\"\"Args:\n+ expr (str): String interpolation expression to tokenize.\n+ Note: Only space characters allowed for whitespace.\n+ \"\"\"\n+ self.expr = expr.strip()\n+ self._supported_tokens = supported_tokens\n+\n+ def lex(self) -> Sequence[Token]:\n+ \"\"\"\n+ Lex all tokens from the expression this lexer was created for.\n+\n+ Raises:\n+ TokenError: If a bad or unsupported Token is encountered.\n+ \"\"\"\n+ results: list[Token] = []\n+ for match in lexer_matcher.finditer(self.expr):\n+ value = match.group()\n+ if value == \" \":\n+ # Skip whitespace\n+ continue\n+\n+ start = match.start()\n+ end = match.end()\n+ try:\n+ kind = TokenType(match.lastgroup)\n+ results.append(self._supported_tokens[kind](value, start, end))\n+ except (ValueError, KeyError):\n+ # ValueError = Resolving the enum failed => Nonvalid character in expression\n+ # KeyError = Lookup in _supported_tokens failed => Token not supported in this lex\n+ raise TokenError(self.expr, value, start)\n+\n+ return results"}, {"sha": "b8e8c5b8c31ca9dfb3b4b3a27528dcd3eee510f4", "filename": "src/openjd/model/_types.py", "status": "added", "additions": 269, "deletions": 0, "changes": 269, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_types.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2F_types.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2F_types.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,269 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from __future__ import annotations\n+\n+import sys\n+from abc import ABC, abstractmethod\n+from dataclasses import dataclass, field\n+from enum import Enum\n+from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional, Type\n+\n+from pydantic import BaseModel, Extra\n+\n+from ._symbol_table import SymbolTable\n+\n+if TYPE_CHECKING:\n+ # Avoiding a circular import\n+ from .v2023_09 import Job as Job_2023_09\n+ from .v2023_09 import JobTemplate as JobTemplate_2023_09\n+ from .v2023_09 import Step as Step_2023_09\n+ from .v2023_09 import StepParameterSpace as StepParameterSpace_2023_09\n+\n+ JobTemplate = JobTemplate_2023_09\n+ Job = Job_2023_09\n+ StepParameterSpace = StepParameterSpace_2023_09\n+ Step = Step_2023_09\n+else:\n+ JobTemplate = Any\n+ Job = Any\n+ StepParameterSpace = Any\n+ Step = Any\n+\n+__all__ = (\n+ \"DefinesTemplateVariables\",\n+ \"Job\",\n+ \"JobParameterInterface\",\n+ \"JobParameterValues\",\n+ \"JobTemplate\",\n+ \"OpenJDModel\",\n+ \"ParameterValue\",\n+ \"ParameterValueType\",\n+ \"SchemaVersion\",\n+ \"Step\",\n+ \"StepParameterSpace\",\n+ \"TaskParameterSet\",\n+)\n+\n+\n+if sys.version_info >= (3, 10):\n+ dataclass_kwargs = {\"slots\": True, \"kw_only\": True}\n+else:\n+ dataclass_kwargs = dict[str, Any]()\n+\n+\n+class ParameterValueType(str, Enum):\n+ STRING = \"STRING\"\n+ INT = \"INT\"\n+ FLOAT = \"FLOAT\"\n+ PATH = \"PATH\"\n+\n+\n+@dataclass(frozen=True, **dataclass_kwargs)\n+class ParameterValue:\n+ type: ParameterValueType\n+ # All values are strings regardless of types.\n+ # We typecast as needed during processing based on the type\n+ # of the parameter value.\n+ value: str\n+\n+\n+TaskParameterSet = dict[str, ParameterValue]\n+JobParameterInputValues = dict[str, str]\n+JobParameterValues = dict[str, ParameterValue]\n+\n+\n+class SchemaVersion(str, Enum):\n+ \"\"\"Enumerant of all Open Job Description specification versions supported by this library.\n+\n+ Special values:\n+ UNDEFINED -- Purely for internal testing.\n+\n+ Versions:\n+ v2023_09\n+ \"\"\"\n+\n+ UNDEFINED = \"UNDEFINED\"\n+ v2023_09 = \"jobtemplate-2023-09\"\n+\n+\n+class ResolutionScope(str, Enum):\n+ \"\"\"Template variable definition and usage scopes:\n+ TEMPLATE - The Job Template scope.\n+ Variables defined in this scope are available in the TEMPLATE, SESSION, and TASK scopes.\n+ SESSION - The Session scope.\n+ Variables defined in this scope are available in the WORKER, and TASK scopes.\n+ TASK - The Task scope.\n+ Variables defined in this scope are only available in the TASK scope.\n+ \"\"\"\n+\n+ TEMPLATE = \"TEMPLATE\"\n+ SESSION = \"SESSION\"\n+ TASK = \"TASK\"\n+\n+\n+@dataclass(frozen=True, eq=False, **dataclass_kwargs)\n+class TemplateVariableDef:\n+ \"\"\"The prefix and scope for a variable definition.\"\"\"\n+\n+ prefix: str\n+ resolves: ResolutionScope\n+\n+\n+class DefinesTemplateVariables:\n+ \"\"\"Metadata for the template variables that an Open Job Description model defines.\n+\n+ Attributes:\n+ symbol_prefix (str): This controls the prefix of newly defined template variables,\n+ like \"Task.Param.\". By default these concatenate to match how models are nested.\n+ A \"|\" prefix discards the parent scope prefix.\n+ defines -- A set of variable prefixes to define the variable using, and the scopes into\n+ which those variables are defined.\n+ field (str): If provided, adds a template variable based on a field in the model. E.g. for a\n+ job parameter, the scope prefix is \"Param.\" and the field is \"name\", so if the model has\n+ \"MyParameter\" for its name, it produces the variable \"Param.MyParameter\". A special\n+ value \"__key__\", not currently used by any model, indicates the name should come\n+ from the dictionary key above the model object.\n+ inject (set[str]): This adds specific names not generated from model fields, like the\n+ \"Session.WorkingDirectory\" name, into the scope of the model.\n+ A \"|\" prefix discards the parent scope prefix.\n+ The given symbols are always injected into the current variable scope.\n+ \"\"\"\n+\n+ def __init__(\n+ self,\n+ *,\n+ symbol_prefix: str = \"\",\n+ defines: set[TemplateVariableDef] = set(),\n+ field: str = \"\",\n+ inject: set[str] = set(),\n+ ):\n+ self.symbol_prefix = symbol_prefix\n+ self.defines = defines\n+ self.field = field\n+ self.inject = inject\n+\n+ def __repr__(self) -> str:\n+ return f\"DefinesTemplateVariables(symbol_prefix={self.symbol_prefix!r}, defines={self.defines!r}, field={self.field!r}, inject={self.inject!r})\"\n+\n+\n+@dataclass(frozen=True, eq=False, **dataclass_kwargs)\n+class JobCreateAsMetadata:\n+ # Only one of the following may be non-None\n+ # model: Union[Type[\"OpenJDModel\"], Callable[[\"OpenJDModel\"], Type[\"OpenJDModel\"]]]\n+ model: Optional[Type[\"OpenJDModel\"]] = field(default=None)\n+ callable: Optional[Callable[[\"OpenJDModel\"], Type[\"OpenJDModel\"]]] = field(default=None)\n+\n+\n+@dataclass(frozen=True, eq=False, **dataclass_kwargs)\n+class JobCreationMetadata:\n+ \"\"\"Metadata for creating a job out of a job template.\n+ This metadata instructs the recursive algorithm as to what special\n+ treatment the model needs during translation from Template to Job.\n+ \"\"\"\n+\n+ resolve_fields: set[str] = field(default_factory=set)\n+ \"\"\"The names of fields in the model that may contain FormatStrings, and\n+ if it does then those FormatStrings must be resolved into strings when\n+ creating a job.\n+ We support resolving fields that are:\n+ 1. FormatStrings\n+ 2. lists of FormatStrings\n+ 3. lists of a mix of FormatStrings and non-FormatStrings (e.g. ints,floats,regular-strings,etc)\n+ \"\"\"\n+\n+ create_as: Optional[JobCreateAsMetadata] = field(default=None)\n+ \"\"\"The class to create the model as during instantiation. Options:\n+ 1. None -- create as the model class itself.\n+ 2. create_as.model is not None -- create as the given model class.\n+ Use-cases: JobTemplate creates as a Job, which has a different definition for Job Parameters\n+ and has fewer fields.\n+ 3. create_as.callable is not None -- invoke the function and create as the class returned.\n+ arg0 = The instance that is being instantiated\n+ arg1 = The symbol table for the instantiation.\n+ Use-case: Conditionally selecting a TaskParameter model class based on how the range\n+ of the Task parameter is defined (list or expression)\n+ \"\"\"\n+\n+ exclude_fields: set[str] = field(default_factory=set)\n+ \"\"\"A set of fields that are ignored when processing the model. The model that is created will\n+ not be provided values, or kwargs even, for these fields.\n+ \"\"\"\n+\n+ adds_fields: Optional[Callable[[str, \"OpenJDModel\", SymbolTable], dict[str, Any]]] = field(\n+ default=None\n+ )\n+ \"\"\"This property defines a callable that uses the instantiation context (i.e. SymbolTable) and\n+ can materialize new fields that are not already present in the model.\n+ arg0 - The model key where this model was found.\n+ arg1 - The model that is adding a value.\n+ arg2 - The symbol table used in the instantiation.\n+ Use-case: Transforming Job Parameters from their Template form to Job form; we inject the\n+ value of the parameter from the SymbolTable into the Job.\n+ \"\"\"\n+\n+ reshape_field_to_dict: dict[str, str] = field(default_factory=dict)\n+ \"\"\"This instructs the instantation code to reshape the given list fields into dict fields.\n+ key: name of the field to reshape.\n+ value: field name within the list item to use as the dictionary key.\n+ \"\"\"\n+\n+ rename_fields: dict[str, str] = field(default_factory=dict)\n+ \"\"\"This instructs the instantiation code to rename the given fields.\n+ \"\"\"\n+\n+\n+class OpenJDModel(BaseModel):\n+ # See: https://docs.pydantic.dev/usage/model_config/\n+ class Config:\n+ # Forbid extra fields in the input\n+ extra = Extra.forbid\n+\n+ # Make the model instances immutable\n+ frozen = True\n+\n+ # The specific schema version that the model implements.\n+ _version: ClassVar[SchemaVersion] # deprecated\n+ version: ClassVar[SchemaVersion]\n+\n+ # ----\n+ # Metadata used for defining template variables for use in FormatStrings\n+\n+ # The variable scope of this model and all submodels, recursively, that don't redefine their own scope.\n+ _template_variable_scope: Optional[ResolutionScope] = None\n+\n+ # This specifies how the model generates template variables, see details in the\n+ # docstring for DefinesTemplateVariables.\n+ _template_variable_definitions: ClassVar[DefinesTemplateVariables] = DefinesTemplateVariables()\n+\n+ # This specifies, for each field that substitutes template variables, which other fields\n+ # they come from. {\"\": {\"\", ...}, ...}\n+ # Template variable destination fields:\n+ # \"\" means the field gets variables from the provided list of source fields.\n+ # \"__export__\" means that the parent scope gets variables from the provided list of source fields.\n+ # Template variable source fields:\n+ # \"\" provides the field's exported variables.\n+ # \"__self__\" provides the variables exported by this model via `__template_variable_definitions`.\n+ _template_variable_sources: ClassVar[dict[str, set[str]]] = {}\n+\n+ # ----\n+ # Metadata used in the creation of a Job from a Job Template\n+\n+ # Metadata for creating a job out of a job template.\n+ # This metadata instructs the recursive algorithm as to what special\n+ # treatment the model needs during translation from Template to Job.\n+ _job_creation_metadata: ClassVar[JobCreationMetadata] = JobCreationMetadata()\n+\n+\n+class JobParameterInterface(ABC):\n+ @abstractmethod\n+ def _check_constraints(self, value: Any) -> None:\n+ \"\"\"Given a value, check that the value meets the constraints of the\n+ Job Parameter's definition.\n+\n+ Returns:\n+ True - If the value meets all constraints.\n+\n+ Raises:\n+ ValueError if the value does not meet at least one constraint\n+ \"\"\"\n+ pass"}, {"sha": "7ef21167c622a4902beed4671228e6949a1fe389", "filename": "src/openjd/model/py.typed", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2Fpy.typed", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2Fpy.typed", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2Fpy.typed?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1 @@\n+# Marker file that indicates this package supports typing"}, {"sha": "48a0686fa374fd22ed885e66e4eb82fdd9fdb16b", "filename": "src/openjd/model/v2023_09/__init__.py", "status": "added", "additions": 158, "deletions": 0, "changes": 158, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2Fv2023_09%2F__init__.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2Fv2023_09%2F__init__.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2Fv2023_09%2F__init__.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,158 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+\n+from ._model import (\n+ STANDARD_AMOUNT_CAPABILITIES,\n+ STANDARD_ATTRIBUTE_CAPABILITIES,\n+ Action,\n+ AllowedFloatParameterList,\n+ AllowedIntParameterList,\n+ AllowedParameterStringValueList,\n+ AmountCapabilityName,\n+ AmountRequirement,\n+ AmountRequirementTemplate,\n+ ArgListType,\n+ ArgString,\n+ AttributeCapabilityList,\n+ AttributeCapabilityName,\n+ AttributeCapabilityValue,\n+ AttributeRequirement,\n+ AttributeRequirementTemplate,\n+ CancelationMethodNotifyThenTerminate,\n+ CancelationMethodTerminate,\n+ CancelationMode,\n+ CombinationExpr,\n+ CommandString,\n+ DataString,\n+ Description,\n+ EmbeddedFiles,\n+ EmbeddedFileText,\n+ EmbeddedFileTypes,\n+ Environment,\n+ EnvironmentActions,\n+ EnvironmentName,\n+ EnvironmentScript,\n+ EnvironmentVariableNameString,\n+ EnvironmentVariableValueString,\n+ FileDialogFilterPatternStringValue,\n+ Filename,\n+ FloatRangeList,\n+ FloatTaskParameterDefinition,\n+ FormatString,\n+ HostRequirements,\n+ HostRequirementsTemplate,\n+ Identifier,\n+ IntRangeList,\n+ IntTaskParameterDefinition,\n+ Job,\n+ JobEnvironmentsList,\n+ JobFloatParameterDefinition,\n+ JobIntParameterDefinition,\n+ JobName,\n+ JobParameter,\n+ JobParameterDefinitionList,\n+ JobParameterType,\n+ JobPathParameterDefinition,\n+ JobStringParameterDefinition,\n+ JobTemplate,\n+ JobTemplateName,\n+ ParameterStringValue,\n+ PathTaskParameterDefinition,\n+ RangeExpressionTaskParameterDefinition,\n+ RangeListTaskParameterDefinition,\n+ Step,\n+ StepActions,\n+ StepEnvironmentList,\n+ StepName,\n+ StepParameterSpace,\n+ StepParameterSpaceDefinition,\n+ StepScript,\n+ StepTemplate,\n+ StepTemplateList,\n+ StringRangeList,\n+ StringTaskParameterDefinition,\n+ TaskParameterList,\n+ TaskParameterStringValue,\n+ TaskParameterStringValueAsJob,\n+ TaskParameterType,\n+ UserInterfaceLabelStringValue,\n+ ValueReferenceConstants,\n+)\n+\n+__all__ = (\n+ \"STANDARD_AMOUNT_CAPABILITIES\",\n+ \"STANDARD_ATTRIBUTE_CAPABILITIES\",\n+ \"Action\",\n+ \"AllowedFloatParameterList\",\n+ \"AllowedIntParameterList\",\n+ \"AllowedParameterStringValueList\",\n+ \"AmountCapabilityName\",\n+ \"AmountRequirement\",\n+ \"AmountRequirementTemplate\",\n+ \"ArgListType\",\n+ \"ArgString\",\n+ \"AttributeCapabilityList\",\n+ \"AttributeCapabilityName\",\n+ \"AttributeCapabilityValue\",\n+ \"AttributeRequirement\",\n+ \"AttributeRequirementTemplate\",\n+ \"CancelationMethodNotifyThenTerminate\",\n+ \"CancelationMethodTerminate\",\n+ \"CancelationMode\",\n+ \"CombinationExpr\",\n+ \"CommandString\",\n+ \"DataString\",\n+ \"Description\",\n+ \"EmbeddedFiles\",\n+ \"EmbeddedFileText\",\n+ \"EmbeddedFileTypes\",\n+ \"Environment\",\n+ \"EnvironmentActions\",\n+ \"EnvironmentScript\",\n+ \"EnvironmentName\",\n+ \"EnvironmentVariableNameString\",\n+ \"EnvironmentVariableValueString\",\n+ \"FileDialogFilterPatternStringValue\",\n+ \"Filename\",\n+ \"FloatRangeList\",\n+ \"FloatTaskParameterDefinition\",\n+ \"FormatString\",\n+ \"HostRequirements\",\n+ \"HostRequirementsTemplate\",\n+ \"Identifier\",\n+ \"IntRangeList\",\n+ \"IntTaskParameterDefinition\",\n+ \"Job\",\n+ \"JobIntParameterDefinition\",\n+ \"JobFloatParameterDefinition\",\n+ \"JobName\",\n+ \"JobEnvironmentsList\",\n+ \"JobParameter\",\n+ \"JobParameterDefinitionList\",\n+ \"JobParameterType\",\n+ \"JobPathParameterDefinition\",\n+ \"JobStringParameterDefinition\",\n+ \"JobTemplate\",\n+ \"JobTemplateName\",\n+ \"ParameterStringValue\",\n+ \"PathTaskParameterDefinition\",\n+ \"RangeExpressionTaskParameterDefinition\",\n+ \"RangeListTaskParameterDefinition\",\n+ \"Step\",\n+ \"StepActions\",\n+ \"StepEnvironmentList\",\n+ \"StepName\",\n+ \"StepParameterSpace\",\n+ \"StepParameterSpaceDefinition\",\n+ \"StepScript\",\n+ \"StepTemplate\",\n+ \"StepTemplateList\",\n+ \"StringRangeList\",\n+ \"StringTaskParameterDefinition\",\n+ \"TaskParameterList\",\n+ \"TaskParameterStringValue\",\n+ \"TaskParameterStringValueAsJob\",\n+ \"TaskParameterType\",\n+ \"UserInterfaceLabelStringValue\",\n+ \"ValueReferenceConstants\",\n+)"}, {"sha": "3a600ac4f58c36e342a12efa235414e59fcce098", "filename": "src/openjd/model/v2023_09/_model.py", "status": "added", "additions": 2293, "deletions": 0, "changes": 2293, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2Fv2023_09%2F_model.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/src%2Fopenjd%2Fmodel%2Fv2023_09%2F_model.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/src%2Fopenjd%2Fmodel%2Fv2023_09%2F_model.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,2293 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from __future__ import annotations\n+\n+import re\n+from decimal import Decimal, InvalidOperation\n+from enum import Enum\n+from graphlib import CycleError, TopologicalSorter\n+from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional, Type, Union, cast\n+\n+from pydantic import (\n+ Field,\n+ PositiveInt,\n+ PositiveFloat,\n+ StrictBool,\n+ StrictInt,\n+ ValidationError,\n+ conint,\n+ conlist,\n+ constr,\n+ root_validator,\n+ validator,\n+)\n+from pydantic.error_wrappers import ErrorWrapper\n+\n+from .._format_strings import FormatString\n+from .._errors import ExpressionError, TokenError\n+from .._capabilities import (\n+ validate_amount_capability_name,\n+ validate_attribute_capability_name,\n+)\n+from .._internal import (\n+ CombinationExpressionParser,\n+ RangeExpressionParser,\n+ validate_model_template_variable_references,\n+ validate_unique_elements,\n+)\n+from .._types import (\n+ DefinesTemplateVariables,\n+ JobCreateAsMetadata,\n+ JobCreationMetadata,\n+ JobParameterInterface,\n+ OpenJDModel,\n+ ResolutionScope,\n+ SchemaVersion,\n+ TemplateVariableDef,\n+)\n+\n+\n+class OpenJDModel_v2023_09(OpenJDModel): # noqa: N801\n+ version = SchemaVersion.v2023_09\n+\n+\n+class ValueReferenceConstants(Enum):\n+ \"\"\"Prefixes used when referencing values in format strings.\"\"\"\n+\n+ JOB_PARAMETER_PREFIX = \"Param\"\n+ \"\"\"Prefix for referencing processed Job Parameters.\n+ \"\"\"\n+\n+ JOB_PARAMETER_RAWPREFIX = \"RawParam\"\n+ \"\"\"Prefix for referencing Job Parameters' input value.\n+ \"\"\"\n+\n+ ENV_FILE_PREFIX = \"Env.File\"\n+ \"\"\"Prefix for referencing an Environment's embedded files.\n+ \"\"\"\n+\n+ TASK_FILE_PREFIX = \"Task.File\"\n+ \"\"\"Prefix for referencing an embedded file that is defined within\n+ a Step Script.\n+ \"\"\"\n+\n+ TASK_PARAMETER_PREFIX = \"Task.Param\"\n+ \"\"\"Prefix for referencing a processed Task Parameter's value.\n+ \"\"\"\n+\n+ TASK_PARAMETER_RAWPREFIX = \"Task.RawParam\"\n+ \"\"\"Prefix for referencing Task Parameter's input value.\n+ \"\"\"\n+\n+ WORKING_DIRECTORY = \"Session.WorkingDirectory\"\n+ \"\"\"The reference to the Session Working Directory.\n+ This will resolve to the fully qualified temporary directory on disk\n+ that is being used as the working directory for the Session.\n+ \"\"\"\n+\n+ HAS_PATH_MAPPING_RULES = \"Session.HasPathMappingRules\"\n+ \"\"\"The reference to whether or not a Task/Environment run\n+ has path mapping rules available.\n+ Value of this value will be either: \"true\" or \"false\"\n+ ( case sensitive )\n+ \"\"\"\n+\n+ PATH_MAPPING_RULES_FILE = \"Session.PathMappingRulesFile\"\n+ \"\"\"A value that resolves to the fully qualified file location\n+ of a JSON file that contains the path mapping rules. This file will\n+ be in the Session's Working Directory.\n+ If there are no path mapping rules, then this file will contain\n+ only: {}\n+ \"\"\"\n+\n+\n+# ==================================================================\n+# ============================= String types =======================\n+# ==================================================================\n+\n+# All unicode characters except for those in the Cc unicode character\n+# category.\n+# Cc category =\n+# C0 = 0x00-0x1F\n+# https://www.unicode.org/charts/PDF/U0000.pdf\n+# DEL character (0x7F)\n+# C1 = 0x80-0x9F\n+# https://www.unicode.org/charts/PDF/U0080.pdf\n+_Cc_characters = r\"\\u0000-\\u001F\\u007F-\\u009F\"\n+_standard_string_regex = f\"(?-m:^[^{_Cc_characters}]+\\Z)\"\n+\n+# Latin alphanumeric, starting with a letter\n+_identifier_regex = r\"(?-m:^[A-Za-z_][A-Za-z0-9_]*\\Z)\"\n+\n+# Regex for defining file filter patterns allowed for use in file dialogs.\n+# 1. Allowable values: \"*\", \"*.*\", and \"*.[:file-extension-chars:]+\".\n+# The characters that :file-extension-chars: can take on are any unicode character except:\n+# a. The Cc unicode character category.\n+# b. Path separators \"\\\" and \"/\".\n+# c. Wildcard characters \"*\", \"?\", \"[\", \"]\".\n+# d. Characters commonly disallowed in paths \"#\", \"%\", \"&\", \"{\", \"}\", \"<\", \">\",\n+# \"$\", \"!\", \"'\", \"\\\"\", \":\", \"@\", \"`\", \"|\", \"=\".\n+_file_dialog_filter_pattern_regex = f\"(?-m:^(?:\\\\*|\\\\*\\\\.\\\\*|\\\\*\\\\.[^{_Cc_characters}\\\\/\\\\*\\\\?\\\\[\\\\]#%&\\\\{{\\\\}}<>\\\\$\\\\!\\\\'\\\\\\\":@`\\\\|=]+)\\Z)\"\n+\n+\n+class JobTemplateName(FormatString):\n+ _min_length = 1\n+\n+\n+if TYPE_CHECKING:\n+ JobName = str\n+ Identifier = str\n+ Description = str\n+ EnvironmentName = str\n+ StepName = str\n+ ParameterStringValue = str\n+else:\n+ JobName = constr(min_length=1, max_length=128, strict=True, regex=_standard_string_regex)\n+ Identifier = constr(min_length=1, max_length=64, strict=True, regex=_identifier_regex)\n+ Description = constr(\n+ min_length=1,\n+ max_length=2048,\n+ strict=True,\n+ # All unicode except the [Cc] (control characters) category\n+ # Allow CR, LF, and TAB.\n+ regex=f\"(?-m:^(?:[^{_Cc_characters}]|[\\r\\n\\t])+\\Z)\",\n+ )\n+ EnvironmentName = constr(min_length=1, max_length=64, strict=True, regex=_standard_string_regex)\n+ StepName = constr(min_length=1, max_length=64, strict=True, regex=_standard_string_regex)\n+ ParameterStringValue = constr(min_length=0, max_length=1024, strict=True)\n+\n+# ==================================================================\n+# ============================= Script types =======================\n+# ==================================================================\n+\n+\n+# ---------------------------- Action type -------------------------\n+\n+\n+class CommandString(FormatString):\n+ _min_length = 1\n+ # All unicode except the [Cc] (control characters) category\n+ _regex = f\"(?-m:^[^{_Cc_characters}]+\\Z)\"\n+\n+\n+class ArgString(FormatString):\n+ # All unicode except the [Cc] (control characters) category\n+ # Allow CR, LF, and TAB.\n+ _regex = f\"(?-m:^[^{_Cc_characters}]*\\Z)\"\n+\n+\n+class CancelationMode(str, Enum):\n+ NOTIFY_THEN_TERMINATE = \"NOTIFY_THEN_TERMINATE\"\n+ TERMINATE = \"TERMINATE\"\n+\n+\n+if TYPE_CHECKING:\n+ NotifyPeriodType = int\n+else:\n+ NotifyPeriodType = conint(ge=1, le=600)\n+\n+\n+class CancelationMethodNotifyThenTerminate(OpenJDModel_v2023_09):\n+ \"\"\"Notify-then-terminate cancelation mode for an Action.\n+\n+ On Posix systems \u2014 Send a SIGTERM, followed by waiting for the notify period in\n+ seconds, and then sending SIGKILL to the entire process tree if the command is\n+ still running.\n+\n+ On Windows systems \u2014 Send a CTRL_C, followed by waiting for the notify period in\n+ seconds, and then Terminating the entire process tree if the command is still running.\n+\n+ Prior to sending the first signal, a file called cancel.info is written to the session\n+ working directory. The contents of this file provide an ISO 8601 time in UTC, in the form\n+ --T::Z,\n+ at which the notify period will end. The format of this file is:\n+\n+ ```\n+ NotifyEnd = --
T::Z\n+ ```\n+\n+ Attributes:\n+ mode (\"NOTIFY_THEN_TERMINATE\"): The mode of the cancelation to use.\n+ notifyPeriodInSeconds (Optional[int]): Defines the maximum number of seconds between\n+ the two signals. It is possible that the actual duration allowed in a particular\n+ cancel event will be less than this amount if circumstances warrant.\n+ Maximum value: 600\n+ Defaults:\n+ 120 for onRun StepScript Action\n+ 30 for all other Actions\n+ \"\"\"\n+\n+ mode: Literal[CancelationMode.NOTIFY_THEN_TERMINATE]\n+ notifyPeriodInSeconds: Optional[NotifyPeriodType] = None # noqa: N815\n+\n+\n+class CancelationMethodTerminate(OpenJDModel_v2023_09):\n+ \"\"\"Terminate cancelation mode for an Action.\n+\n+ On Posix systems \u2014 Send SIGKILL to the entire process tree when a cancel is requested.\n+\n+ On Windows systems - Terminate the entire process tree when a cancel is requested.\n+\n+ Attributes:\n+ mode (\"TERMINATE\"): The mode of the cancelation to use.\n+ \"\"\"\n+\n+ mode: Literal[CancelationMode.TERMINATE]\n+\n+\n+if TYPE_CHECKING:\n+ ArgListType = list[ArgString]\n+else:\n+ ArgListType = conlist(ArgString, min_items=1)\n+\n+\n+class Action(OpenJDModel_v2023_09):\n+ \"\"\"An Action to run.\n+\n+ Attributes:\n+ command (FormatString): The command/executable that will be run.\n+ args (Optional[list[FormatString]]): The arguments that are provided to the command\n+ when it is run.\n+ timeout (Optional[int]): Maximum allowed runtime of the Action in seconds.\n+ Default: No timeout\n+ cancelation (Optional[Union[CancelationMethodNotifyThenTerminate, CancelationMethodTerminate]]):\n+ If defined, provides details regarding how this action should be canceled.\n+ Default: CancelationMethodTerminate\n+ \"\"\"\n+\n+ command: CommandString\n+ args: Optional[ArgListType] = None\n+ timeout: Optional[PositiveInt] = None\n+ cancelation: Optional[\n+ Union[CancelationMethodNotifyThenTerminate, CancelationMethodTerminate]\n+ ] = Field(None, discriminator=\"mode\")\n+\n+\n+class StepActions(OpenJDModel_v2023_09):\n+ \"\"\"The Actions for Tasks of a Step.\n+\n+ Attributes:\n+ onRun (Action): Action to run when running a single Task.\n+ \"\"\"\n+\n+ onRun: Action # noqa: N815\n+\n+\n+class EnvironmentActions(OpenJDModel_v2023_09):\n+ \"\"\"The Actions to run at various stages of running an Environment.\n+\n+ Attributes:\n+ onEnter (Optional[Action]): Action to run when entering the environment\n+ as part of a Session.\n+ onExit (Optional[Action]): Action to run when exiting the environment\n+ in a Session.\n+\n+ Note: Must define at least one of onEnter or onExit\n+ \"\"\"\n+\n+ onEnter: Optional[Action] = Field(None) # noqa: N815\n+ onExit: Optional[Action] = Field(None) # noqa: N815\n+\n+ @root_validator(pre=True)\n+ def _requires_oneof(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ \"\"\"A validator that runs on the model data before parsing.\"\"\"\n+ on_enter = values.get(\"onEnter\")\n+ on_exit = values.get(\"onExit\")\n+ if on_enter is None and on_exit is None:\n+ raise ValueError(\"Must define one of: onEnter or onExit\")\n+ return values\n+\n+\n+# --------------------- Embedded Files type -------------------------\n+\n+\n+class EmbeddedFileTypes(str, Enum):\n+ TEXT = \"TEXT\"\n+\n+\n+if TYPE_CHECKING:\n+ Filename = str\n+else:\n+ # TODO - regex of allowable filename characters\n+ Filename = constr(min_length=1, max_length=64, strict=True)\n+\n+\n+class DataString(FormatString):\n+ _min_length = 1\n+\n+\n+class EmbeddedFileText(OpenJDModel_v2023_09):\n+ \"\"\"A plain text file embedded directly into the Job Template.\n+ This file is materialized to a subdirectory of a Session's working directory\n+ when running a corresponding Action in the Session.\n+\n+ Attributes:\n+ name (Identifier): A name by which the embedded file is referenced.\n+ type (\"TEXT\"): The type of the emdedded file: plain text.\n+ filename (Optional[str]): The filename to write the file as.\n+ Default: Randomly generated filename.\n+ runnable (Optional[bool]): A True value indicates that the written file\n+ will have its execute-permissions set.\n+ Default: False\n+ data (FormatString): The text data to write to the file.\n+ \"\"\"\n+\n+ name: Identifier\n+ type: Literal[EmbeddedFileTypes.TEXT]\n+ data: DataString\n+ filename: Optional[Filename] = None\n+ runnable: Optional[StrictBool] = None\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"File.\", resolves=ResolutionScope.SESSION)},\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\n+ \"__export__\": {\"__self__\"},\n+ \"data\": {\"__self__\"},\n+ }\n+\n+\n+# --------------------- Script types ----------------------------\n+\n+if TYPE_CHECKING:\n+ EmbeddedFiles = list[EmbeddedFileText]\n+else:\n+ EmbeddedFiles = conlist(EmbeddedFileText, min_items=1)\n+\n+\n+class StepScript(OpenJDModel_v2023_09):\n+ \"\"\"The Step Script is the information on what Actions to perform when running\n+ a Task for a Step.\n+\n+ Attributes:\n+ embeddedFiles (Optional[list[EmbeddedFileText]]): List of text files embedded\n+ into the script. These will be written to disk prior to running each of the\n+ Actions in the script.\n+ actions (StepActions): The actions to run when running a Task for the Step.\n+ \"\"\"\n+\n+ actions: StepActions\n+ embeddedFiles: Optional[EmbeddedFiles] = None # noqa: N815\n+\n+ _template_variable_scope = ResolutionScope.TASK\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ symbol_prefix=\"|Task.\",\n+ inject={\n+ f\"|{ValueReferenceConstants.WORKING_DIRECTORY.value}\",\n+ f\"|{ValueReferenceConstants.HAS_PATH_MAPPING_RULES.value}\",\n+ f\"|{ValueReferenceConstants.PATH_MAPPING_RULES_FILE.value}\",\n+ },\n+ )\n+ _template_variable_sources = {\n+ \"actions\": {\"embeddedFiles\", \"__self__\"},\n+ \"embeddedFiles\": {\"embeddedFiles\", \"__self__\"},\n+ }\n+\n+ @validator(\"embeddedFiles\")\n+ def _unique_names(cls, v: Optional[EmbeddedFiles]) -> Optional[EmbeddedFiles]:\n+ if v is not None:\n+ return validate_unique_elements(v, item_value=lambda v: v.name, property=\"name\")\n+ return v\n+\n+\n+class EnvironmentScript(OpenJDModel_v2023_09):\n+ \"\"\"The Environment Script is the information on what Actions to perform when running\n+ an Environment within a Session.\n+\n+ Attributes:\n+ embeddedFiles (Optional[list[EmbeddedFileText]]): List of text files embedded\n+ into the script. These will be written to disk prior to running each of the\n+ Actions in the script.\n+ actions (EnvironmentActions): The actions to run when at various stages of the Environment's\n+ lifecycle.\n+ \"\"\"\n+\n+ actions: EnvironmentActions\n+ embeddedFiles: Optional[EmbeddedFiles] = None # noqa: N815\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ symbol_prefix=\"|Env.\",\n+ inject={\n+ f\"|{ValueReferenceConstants.WORKING_DIRECTORY.value}\",\n+ f\"|{ValueReferenceConstants.HAS_PATH_MAPPING_RULES.value}\",\n+ f\"|{ValueReferenceConstants.PATH_MAPPING_RULES_FILE.value}\",\n+ },\n+ )\n+ _template_variable_sources = {\n+ \"actions\": {\"embeddedFiles\", \"__self__\"},\n+ \"embeddedFiles\": {\"embeddedFiles\", \"__self__\"},\n+ }\n+\n+ @validator(\"embeddedFiles\")\n+ def _unique_names(cls, v: Optional[EmbeddedFiles]) -> Optional[EmbeddedFiles]:\n+ if v is not None:\n+ return validate_unique_elements(v, item_value=lambda v: v.name, property=\"name\")\n+ return v\n+\n+\n+# ==================================================================\n+# ========================== Task Parameters =======================\n+# ==================================================================\n+\n+\n+class TaskParameterStringValue(FormatString):\n+ \"\"\"A FormatString as an element of a Task's range list.\"\"\"\n+\n+ # Note: No maximum length. The max string length is enforced\n+ # as a TaskParameterStringValueAsJob type after the template\n+ # has been instantiated in to a Job, and this format string\n+ # has been evaluated.\n+ pass\n+\n+\n+class TaskParameterType(str, Enum):\n+ INT = \"INT\"\n+ FLOAT = \"FLOAT\"\n+ STRING = \"STRING\"\n+ PATH = \"PATH\"\n+\n+\n+class RangeString(FormatString):\n+ _min_length = 1\n+\n+\n+if TYPE_CHECKING:\n+ # Note: Ordering within the Unions is important. Pydantic will try to match in\n+ # the order given.\n+ IntRangeList = list[Union[int, TaskParameterStringValue]]\n+ FloatRangeList = list[Union[Decimal, TaskParameterStringValue]]\n+ StringRangeList = list[TaskParameterStringValue]\n+ TaskParameterStringValueAsJob = str\n+else:\n+ IntRangeList = conlist(Union[int, TaskParameterStringValue], min_items=1, max_items=1024)\n+ FloatRangeList = conlist(Union[Decimal, TaskParameterStringValue], min_items=1, max_items=1024)\n+ StringRangeList = conlist(TaskParameterStringValue, min_items=1, max_items=1024)\n+ TaskParameterStringValueAsJob = constr(min_length=0, max_length=1024)\n+\n+TaskRangeList = list[TaskParameterStringValueAsJob]\n+TaskRangeExpression = RangeString\n+\n+\n+# Target model for task parameters when instantiating a job.\n+class RangeListTaskParameterDefinition(OpenJDModel_v2023_09):\n+ # element type of items in the range\n+ type: TaskParameterType\n+ range: TaskRangeList\n+\n+\n+class RangeExpressionTaskParameterDefinition(OpenJDModel_v2023_09):\n+ # element type of items in the range\n+ type: TaskParameterType\n+ range: TaskRangeExpression\n+\n+ @validator(\"range\")\n+ def _validate_range_expression(cls, value: Any) -> Any:\n+ \"\"\"At this point, the format expressions have been resolved\n+ and we can determine if it's a valid RangeExpression\"\"\"\n+ try:\n+ RangeExpressionParser().parse(value)\n+ except Exception as e:\n+ raise ValueError(str(e))\n+\n+ return value\n+\n+\n+class IntTaskParameterDefinition(OpenJDModel_v2023_09):\n+ \"\"\"Definition of an integer-typed Task Parameter and its value range.\n+\n+ Attributes:\n+ name (Identifier): A name by which the parameter is referenced.\n+ type (TaskParameterType.INT): Descriminator to identify the type of the parameter.\n+ range (IntRangeList | RangeString): The list of values that the parameter takes on.\n+ \"\"\"\n+\n+ name: Identifier\n+ type: Literal[TaskParameterType.INT]\n+ # Note: Ordering here is important. Pydantic will try to match in\n+ # the order given.\n+ range: Union[IntRangeList, RangeString]\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={\n+ TemplateVariableDef(prefix=\"|Task.Param.\", resolves=ResolutionScope.TASK),\n+ TemplateVariableDef(prefix=\"|Task.RawParam.\", resolves=ResolutionScope.TASK),\n+ },\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+\n+ def _get_range_task_param_type(model: Any) -> Type[OpenJDModel]:\n+ if isinstance(model.range, RangeString):\n+ return RangeExpressionTaskParameterDefinition\n+ return RangeListTaskParameterDefinition\n+\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(callable=_get_range_task_param_type),\n+ resolve_fields={\"range\"},\n+ exclude_fields={\"name\"},\n+ )\n+\n+ @validator(\"range\", pre=True)\n+ def _validate_range_element_type(cls, value: Any) -> Any:\n+ # pydandic will automatically type coerse values into integers. We explicitly\n+ # want to reject non-integer values, so this *pre* validator validates the\n+ # value *before* pydantic tries to type coerse it.\n+ # We do allow coersion from a string since we want to allow \"1\", and\n+ # \"1.2\" or \"a\" will fail the type coersion\n+ if isinstance(value, list):\n+ errors = list[ErrorWrapper]()\n+ for v in value:\n+ if isinstance(v, bool) or not isinstance(v, (int, str)):\n+ errors.append(\n+ ErrorWrapper(\n+ ValueError(\"Value must be an integer or integer string.\"), (\"range\", v)\n+ )\n+ )\n+ if errors:\n+ raise ValidationError(errors, IntTaskParameterDefinition)\n+ elif isinstance(value, RangeString):\n+ # TODO: nothing to do - it's guaranteed to be a format string at this point\n+ pass\n+\n+ return value\n+\n+ @validator(\"range\")\n+ def _validate_range_elements(cls, value: Any) -> Any:\n+ if isinstance(value, list):\n+ errors = list[ErrorWrapper]()\n+ for v in value:\n+ if isinstance(v, TaskParameterStringValue):\n+ # A TaskParameterStringValue is a FormatString.\n+ # FormatString.expressions is the list of all expressions in the format string\n+ # ( e.g. \"{{ Param.Foo }}\").\n+ # Reject the string if it contains any expressions.\n+ if len(v.expressions) == 0:\n+ errors.append(\n+ ErrorWrapper(\n+ ValueError(\"String literal must contain an integer.\"), (\"range\", v)\n+ )\n+ )\n+ if errors:\n+ raise ValidationError(errors, IntTaskParameterDefinition)\n+ else:\n+ # If there are no format expressions, we can validate the range expression.\n+ # otherwise we defer to the RangeExressionTaskParameter model when\n+ # they've all been evaluated\n+ if len(value.expressions) == 0:\n+ try:\n+ RangeExpressionParser().parse(value)\n+ except Exception as e:\n+ raise ValueError(str(e))\n+ return value\n+\n+\n+class FloatTaskParameterDefinition(OpenJDModel_v2023_09):\n+ \"\"\"Definition of a float-typed Task Parameter and its value range.\n+\n+ Attributes:\n+ name (Identifier): A name by which the parameter is referenced.\n+ type (TaskParameterType.FLOAT): Descriminator to identify the type of the parameter.\n+ range (FloatRangeList): The list of values that the parameter takes on.\n+ \"\"\"\n+\n+ name: Identifier\n+ type: Literal[TaskParameterType.FLOAT]\n+ range: FloatRangeList\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={\n+ TemplateVariableDef(prefix=\"|Task.Param.\", resolves=ResolutionScope.TASK),\n+ TemplateVariableDef(prefix=\"|Task.RawParam.\", resolves=ResolutionScope.TASK),\n+ },\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=RangeListTaskParameterDefinition),\n+ resolve_fields={\"range\"},\n+ exclude_fields={\"name\"},\n+ )\n+\n+ @validator(\"range\", each_item=True, pre=True)\n+ def _validate_range_element_type(cls, v: Any) -> Any:\n+ # pydandic will automatically type coerse values into floats. We explicitly\n+ # want to reject non-integer values, so this *pre* validator validates the\n+ # value *before* pydantic tries to type coerse it.\n+ # We do allow coersion from a string since we want to allow \"1\", and\n+ # \"1.2\" or \"a\" will fail the type coersion\n+ if isinstance(v, bool) or not isinstance(v, (int, float, str)):\n+ raise ValueError(\"Item must be a float, int, or float string.\")\n+ return v\n+\n+ @validator(\"range\", each_item=True)\n+ def _validate_range_elements(\n+ cls, v: Union[Decimal, TaskParameterStringValue]\n+ ) -> Union[Decimal, TaskParameterStringValue]:\n+ if isinstance(v, TaskParameterStringValue):\n+ # A TaskParameterStringValue is a FormatString.\n+ # FormatString.expressions is the list of all expressions in the format string\n+ # ( e.g. \"{{ Param.Foo }}\").\n+ # Reject the string if it contains any expressions.\n+ if len(v.expressions) == 0:\n+ raise ValueError(\"String literal must contain an integer or float.\")\n+ return v\n+\n+\n+class StringTaskParameterDefinition(OpenJDModel_v2023_09):\n+ \"\"\"Definition of a string-typed Task Parameter and its value range.\n+\n+ Attributes:\n+ name (Identifier): A name by which the parameter is referenced.\n+ type (TaskParameterType.STRING): Descriminator to identify the type of the parameter.\n+ range (StringRangeList): The list of values that the parameter takes on.\n+ \"\"\"\n+\n+ name: Identifier\n+ type: Literal[TaskParameterType.STRING]\n+ range: StringRangeList\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={\n+ TemplateVariableDef(prefix=\"|Task.Param.\", resolves=ResolutionScope.TASK),\n+ TemplateVariableDef(prefix=\"|Task.RawParam.\", resolves=ResolutionScope.TASK),\n+ },\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=RangeListTaskParameterDefinition),\n+ resolve_fields={\"range\"},\n+ exclude_fields={\"name\"},\n+ )\n+\n+\n+class PathTaskParameterDefinition(OpenJDModel_v2023_09):\n+ \"\"\"Definition of a path-typed Task Parameter and its value range.\n+\n+ Attributes:\n+ name (Identifier): A name by which the parameter is referenced.\n+ type (TaskParameterType.PATH): Descriminator to identify the type of the parameter.\n+ range (StringRangeList): The list of values that the parameter takes on.\n+ \"\"\"\n+\n+ name: Identifier\n+ type: Literal[TaskParameterType.PATH]\n+ range: StringRangeList\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={\n+ TemplateVariableDef(prefix=\"|Task.Param.\", resolves=ResolutionScope.TASK),\n+ TemplateVariableDef(prefix=\"|Task.RawParam.\", resolves=ResolutionScope.TASK),\n+ },\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=RangeListTaskParameterDefinition),\n+ resolve_fields={\"range\"},\n+ exclude_fields={\"name\"},\n+ )\n+\n+\n+TaskParameterDefinition = Union[\n+ IntTaskParameterDefinition,\n+ FloatTaskParameterDefinition,\n+ StringTaskParameterDefinition,\n+ PathTaskParameterDefinition,\n+]\n+\n+if TYPE_CHECKING:\n+ TaskParameterList = list[TaskParameterDefinition]\n+ CombinationExpr = str\n+else:\n+ TaskParameterList = conlist(TaskParameterDefinition, min_items=1, max_items=16)\n+ # Limit the CombinationExpr to characters allowed in an Identifier plus whitespace\n+ # and the operator characters.\n+ CombinationExpr = constr(\n+ min_length=1, max_length=1280, strict=True, regex=r\"(?-m:^[A-Za-z0-9\\*\\(\\), ]+\\Z)\"\n+ )\n+\n+TaskRangeParameter = Union[RangeListTaskParameterDefinition, RangeExpressionTaskParameterDefinition]\n+\n+\n+# Target model for step template when instantiating a job.\n+class StepParameterSpace(OpenJDModel_v2023_09):\n+ # Note: taskParameterDefinitions is a dict here to make it easier to work with\n+ # programatically (e.g. finding the TaskRangeParameterDefinition for a given\n+ # identifier)\n+ taskParameterDefinitions: dict[Identifier, TaskRangeParameter]\n+ combination: Optional[CombinationExpr] = None\n+\n+\n+class StepParameterSpaceDefinition(OpenJDModel_v2023_09):\n+ \"\"\"Definition of a Step's parameter space. The parameter space is the multidimensional\n+ space of all possible task parameter sets that tasks will be run with.\n+\n+ Attributes:\n+ parameters (TaskParameterList): Declaration of all of the task parameters.\n+ combination (Optional[str]): Combination string that instructs how to build the parameter\n+ space from the task parameters and their ranges.\n+ \"\"\"\n+\n+ taskParameterDefinitions: TaskParameterList\n+ combination: Optional[CombinationExpr] = None\n+\n+ _template_variable_sources = {\"__export__\": {\"taskParameterDefinitions\"}}\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=StepParameterSpace),\n+ reshape_field_to_dict={\"taskParameterDefinitions\": \"name\"},\n+ )\n+\n+ @validator(\"taskParameterDefinitions\")\n+ def _validate_parameters(cls, v: TaskParameterList) -> TaskParameterList:\n+ # Must have a unique name for each Task parameter\n+ return validate_unique_elements(v, item_value=lambda v: v.name, property=\"name\")\n+\n+ @root_validator\n+ def _validate_combination(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ if values.get(\"combination\") is None:\n+ return values\n+ if values.get(\"taskParameterDefinitions\") is None:\n+ return values\n+\n+ parameter_list: TaskParameterList = cast(\n+ TaskParameterList, values[\"taskParameterDefinitions\"]\n+ )\n+ combination: CombinationExpr = cast(CombinationExpr, values[\"combination\"])\n+\n+ # Ensure that the 'combination' string:\n+ # a) is a properly formed combination expression; and\n+ # b) references all available task parameters exactly once each\n+\n+ try:\n+ parse_tree = CombinationExpressionParser().parse(combination)\n+ except (ExpressionError, TokenError) as e:\n+ raise ValueError(str(e))\n+\n+ expr_identifiers = list[str]()\n+ parse_tree.collect_identifiers(expr_identifiers)\n+ unique_expr_identifiers = set(expr_identifiers)\n+ parameter_names = [param.name for param in parameter_list]\n+ unique_parameter_names = set(parameter_names)\n+\n+ errors = list[ErrorWrapper]()\n+ if len(unique_expr_identifiers) < len(unique_parameter_names):\n+ # Missing some parameter identifiers in the expression\n+ missing = sorted(list(unique_parameter_names - unique_expr_identifiers))\n+ errors.append(\n+ ErrorWrapper(\n+ ValueError(f\"Expression missing parameters: {','.join(missing)}\"),\n+ (\"combination\",),\n+ )\n+ )\n+ if len(unique_parameter_names) < len(unique_expr_identifiers):\n+ # Have some extra parameters referenced in the expression\n+ extra = sorted(list(unique_expr_identifiers - unique_parameter_names))\n+ errors.append(\n+ ErrorWrapper(\n+ ValueError(f\"Expression references undefined parameters: {','.join(extra)}\"),\n+ (\"combination\",),\n+ )\n+ )\n+ if len(expr_identifiers) != len(unique_expr_identifiers):\n+ # Some parameter names are used more than once in the expression\n+ duplicates = sorted(\n+ [id for id in expr_identifiers if id not in unique_expr_identifiers]\n+ )\n+ errors.append(\n+ ErrorWrapper(\n+ ValueError(\n+ f\"Expression can only reference each parameter once: {','.join(duplicates)} \"\n+ ),\n+ (\"combination\",),\n+ )\n+ )\n+\n+ if errors:\n+ raise ValidationError(errors, StepParameterSpaceDefinition)\n+\n+ return values\n+\n+\n+# ==================================================================\n+# ====================== Environments Variables ====================\n+# ==================================================================\n+\n+if TYPE_CHECKING:\n+ EnvironmentVariableNameString = str\n+else:\n+ EnvironmentVariableNameString = constr(\n+ min_length=1, max_length=256, regex=r\"(?-m:^[a-zA-Z_][a-zA-Z0-9_]*\\Z)\"\n+ )\n+\n+\n+class EnvironmentVariableValueString(FormatString):\n+ _max_length = 2048\n+\n+\n+EnvironmentVariableObject = dict[EnvironmentVariableNameString, EnvironmentVariableValueString]\n+\n+\n+# ==================================================================\n+# ========================== Environments ==========================\n+# ==================================================================\n+\n+\n+class Environment(OpenJDModel_v2023_09):\n+ \"\"\"Definition of an Environment. Environments are entered at the start of a Session, and\n+ exited at the end of a Session. They are a vehicle for amortizing expensive or time-consuming\n+ setup and tear-down operations in the worker's environment before and after a sequence of Tasks.\n+\n+ Attributes:\n+ name (EnvironmentName): A name by which the Environment is referenced.\n+ description (Optional[str]): A free form string that can be used to describe the environment.\n+ It has no functional purpose, but may appear in UI elements.\n+ script (Optional[EnvironmentScript]): The information on what Actions to perform when running an\n+ Environment within a Session.\n+ variables (Optional[EnvironmentVariableObject]): The environment variables that should be set when\n+ running an Environment within a Session.\n+ \"\"\"\n+\n+ name: EnvironmentName\n+ script: Optional[EnvironmentScript] = None\n+ variables: Optional[EnvironmentVariableObject] = None\n+ description: Optional[Description] = None\n+\n+ _template_variable_scope = ResolutionScope.SESSION\n+\n+ @root_validator(pre=True)\n+ def _validate_has_script_or_variables(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ if values.get(\"script\") is None and values.get(\"variables\") is None:\n+ raise ValueError(\"Environment must have either a script or variables.\")\n+ return values\n+\n+ @validator(\"variables\")\n+ def _validate_variables(\n+ cls, variables: Optional[EnvironmentVariableObject]\n+ ) -> Optional[EnvironmentVariableObject]:\n+ if variables is None:\n+ return variables\n+ if len(variables) == 0:\n+ raise ValueError(\"Environment variables cannot be an empty object.\")\n+ return variables\n+\n+\n+# ==================================================================\n+# ========================== Job Parameters ========================\n+# ==================================================================\n+\n+\n+class JobParameterType(str, Enum):\n+ STRING = \"STRING\"\n+ PATH = \"PATH\"\n+ INT = \"INT\"\n+ FLOAT = \"FLOAT\"\n+\n+\n+if TYPE_CHECKING:\n+ AllowedParameterStringValueList = list[ParameterStringValue]\n+ AllowedIntParameterList = list[int]\n+ AllowedFloatParameterList = list[Decimal]\n+ UserInterfaceLabelStringValue = str\n+ FileDialogFilterPatternStringValue = str\n+ FileDialogFilterPatternStringValueList = list[FileDialogFilterPatternStringValue]\n+else:\n+ AllowedParameterStringValueList = conlist(ParameterStringValue, min_items=1)\n+ AllowedIntParameterList = conlist(int, min_items=1)\n+ AllowedFloatParameterList = conlist(Decimal, min_items=1)\n+ UserInterfaceLabelStringValue = constr(\n+ min_length=1, max_length=64, strict=True, regex=_standard_string_regex\n+ )\n+ FileDialogFilterPatternStringValue = constr(\n+ min_length=1, max_length=20, strict=True, regex=_file_dialog_filter_pattern_regex\n+ )\n+ FileDialogFilterPatternStringValueList = conlist(\n+ FileDialogFilterPatternStringValue, min_items=1, max_items=20\n+ )\n+\n+\n+# Target model for a job parameter when instantiating a job.\n+class JobParameter(OpenJDModel_v2023_09):\n+ type: JobParameterType\n+ value: str\n+ description: Optional[Description] = None\n+\n+\n+class StringUserInterfaceControl(str, Enum):\n+ LINE_EDIT = \"LINE_EDIT\"\n+ MULTILINE_EDIT = \"MULTILINE_EDIT\"\n+ DROPDOWN_LIST = \"DROPDOWN_LIST\"\n+ CHECK_BOX = \"CHECK_BOX\"\n+ HIDDEN = \"HIDDEN\"\n+\n+\n+# These are the permitted sets of values that can be in a string job parameter 'allowedValues'\n+# when the user interface control is CHECK_BOX.\n+ALLOWED_VALUES_FOR_CHECK_BOX = ({\"TRUE\", \"FALSE\"}, {\"YES\", \"NO\"}, {\"ON\", \"OFF\"}, {\"1\", \"0\"})\n+\n+\n+class JobStringParameterDefinitionUserInterface(OpenJDModel_v2023_09):\n+ \"\"\"User interface attributes for a job string parameter.\n+\n+ Attributes:\n+ control (StringUserInterfaceControl): The user interface control to use when editing this parameter.\n+ label (Optional[UserInterfaceLabelStringValue]): The label to display for the user interface control. Defaults\n+ to the `name` of the parameter.\n+ groupLabel (Optional[UserInterfaceLabelStringValue]): The label of the group box to place the user interface\n+ control in.\n+ \"\"\"\n+\n+ control: StringUserInterfaceControl\n+ label: Optional[UserInterfaceLabelStringValue]\n+ groupLabel: Optional[UserInterfaceLabelStringValue]\n+\n+\n+class JobStringParameterDefinition(OpenJDModel_v2023_09, JobParameterInterface):\n+ \"\"\"A Job Parameter of type string.\n+\n+ Attributes:\n+ name (Identifier): A name by which the parameter is referenced.\n+ type (JobParameterType.STRING): Descriminator to identify the type of the parameter\n+ userInterface (Optional[JobStringParameterDefinitionUserInterface]): User interface properties\n+ for this parameter\n+ description (Optional[Description]): A free form string that can be used to describe\n+ the parameter. It has no functional purpose, but may appear in UI elements.\n+ default (Optional[ParameterStringValue]): Default value for the parameter if a value\n+ is not provided.\n+ allowedValues (Optional[AllowedParameterStringValueList]): Explicit list of values that the\n+ parameter is allowed to take on.\n+ minLength (Optional[int]): Minimum string length of the parameter value.\n+ maxLength (Optional[int]): Maximum string length of the parameter value.\n+ \"\"\"\n+\n+ name: Identifier\n+ type: Literal[JobParameterType.STRING]\n+ userInterface: Optional[JobStringParameterDefinitionUserInterface]\n+ description: Optional[Description] = None\n+ # Note: Ordering of the following fields is essential for the validators to work correctly.\n+ minLength: Optional[StrictInt] = None # noqa: N815\n+ maxLength: Optional[StrictInt] = None # noqa: N815\n+ allowedValues: Optional[AllowedParameterStringValueList] = None # noqa: N815\n+ default: Optional[ParameterStringValue] = None\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={\n+ TemplateVariableDef(prefix=\"|Param.\", resolves=ResolutionScope.TEMPLATE),\n+ TemplateVariableDef(prefix=\"|RawParam.\", resolves=ResolutionScope.TEMPLATE),\n+ },\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=JobParameter),\n+ exclude_fields={\n+ \"name\",\n+ \"userInterface\",\n+ \"minLength\",\n+ \"maxLength\",\n+ \"allowedValues\",\n+ \"default\",\n+ },\n+ adds_fields=lambda key, this, symtab: {\n+ \"value\": symtab[f\"RawParam.{cast(JobStringParameterDefinition,this).name}\"]\n+ },\n+ )\n+\n+ @validator(\"minLength\")\n+ def _validate_min_length(cls, v: Optional[int]) -> Optional[int]:\n+ if v is None:\n+ return v\n+ if v <= 0:\n+ raise ValueError(\"Required: 0 < minLength.\")\n+ return v\n+\n+ @validator(\"maxLength\")\n+ def _validate_max_length(cls, v: Optional[int], values: dict[str, Any]) -> Optional[int]:\n+ if v is None:\n+ return v\n+ if v <= 0:\n+ raise ValueError(\"Required: 0 < maxLength.\")\n+ min_length = values.get(\"minLength\")\n+ if min_length is None:\n+ return v\n+ if min_length > v:\n+ raise ValueError(\"Required: minLength <= maxLength.\")\n+ return v\n+\n+ @validator(\"allowedValues\", each_item=True)\n+ def _validate_allowed_values_item(\n+ cls, v: ParameterStringValue, values: dict[str, Any]\n+ ) -> ParameterStringValue:\n+ min_length = values.get(\"minLength\")\n+ if min_length is not None:\n+ if len(v) < min_length:\n+ raise ValueError(\"Value is shorter than minLength.\")\n+ max_length = values.get(\"maxLength\")\n+ if max_length is not None:\n+ if len(v) > max_length:\n+ raise ValueError(\"Value is longer than maxLength.\")\n+ return v\n+\n+ @validator(\"default\")\n+ def _validate_default(\n+ cls, v: ParameterStringValue, values: dict[str, Any]\n+ ) -> ParameterStringValue:\n+ min_length = values.get(\"minLength\")\n+ if min_length is not None:\n+ if len(v) < min_length:\n+ raise ValueError(\"Value is shorter than minLength.\")\n+ max_length = values.get(\"maxLength\")\n+ if max_length is not None:\n+ if len(v) > max_length:\n+ raise ValueError(\"Value is longer than maxLength.\")\n+\n+ allowed_values = values.get(\"allowedValues\")\n+ if allowed_values is not None:\n+ if v not in allowed_values:\n+ raise ValueError(\"Must be an allowed value.\")\n+ return v\n+\n+ @root_validator\n+ def _validate_user_interface_compatibility(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ # validate that the user interface control is compatible with the value constraints\n+ if values.get(\"userInterface\"):\n+ user_interface_control = values[\"userInterface\"].control\n+ if values.get(\"allowedValues\") and user_interface_control in (\n+ StringUserInterfaceControl.LINE_EDIT,\n+ StringUserInterfaceControl.MULTILINE_EDIT,\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} cannot be used when 'allowedValues' is provided\"\n+ )\n+ if (\n+ not values.get(\"allowedValues\")\n+ and user_interface_control == StringUserInterfaceControl.DROPDOWN_LIST\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} requires that 'allowedValues' be provided\"\n+ )\n+ if user_interface_control == StringUserInterfaceControl.CHECK_BOX:\n+ allowed_values = set(v.upper() for v in values.get(\"allowedValues\", []))\n+ if allowed_values not in ALLOWED_VALUES_FOR_CHECK_BOX:\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} requires that 'allowedValues' be \"\n+ + f\"one of {ALLOWED_VALUES_FOR_CHECK_BOX} (case and order insensitive)\"\n+ )\n+ return values\n+\n+ # override\n+ def _check_constraints(self, value: Any) -> None:\n+ if value is None:\n+ raise ValueError(f\"No value given for {self.name}.\")\n+ if not isinstance(value, str):\n+ raise ValueError(f\"Value ({value}) for parameter {self.name} must be string type.\")\n+ if self.allowedValues and value not in self.allowedValues:\n+ raise ValueError(f\"Parameter {self.name} value ({value}) not in allowedValues.\")\n+ if self.minLength and len(value) < self.minLength:\n+ raise ValueError(\n+ f\"Value ({value}), with length {len(value)}, for parameter {self.name} value must be at least {self.minLength} characters.\"\n+ )\n+ if self.maxLength and self.maxLength < len(value):\n+ raise ValueError(\n+ f\"Value ({value}), with length {len(value)}, for parameter {self.name} value must be at most {self.maxLength} characters.\"\n+ )\n+\n+\n+class PathUserInterfaceControl(str, Enum):\n+ CHOOSE_INPUT_FILE = \"CHOOSE_INPUT_FILE\"\n+ CHOOSE_OUTPUT_FILE = \"CHOOSE_OUTPUT_FILE\"\n+ CHOOSE_DIRECTORY = \"CHOOSE_DIRECTORY\"\n+ DROPDOWN_LIST = \"DROPDOWN_LIST\"\n+ HIDDEN = \"HIDDEN\"\n+\n+\n+class JobPathParameterDefinitionObjectType(str, Enum):\n+ FILE = \"FILE\"\n+ DIRECTORY = \"DIRECTORY\"\n+\n+\n+class JobPathParameterDefinitionDataFlow(str, Enum):\n+ NONE = \"NONE\"\n+ IN = \"IN\"\n+ OUT = \"OUT\"\n+ INOUT = \"INOUT\"\n+\n+\n+class JobPathParameterDefinitionFileFilter(OpenJDModel_v2023_09):\n+ \"\"\"User interface attributes for a single file filter in a file choice dialog.\n+\n+ Attributes:\n+ label (UserInterfaceLabelStringValue): The label for this file filter, e.g. \"Image Files\" or \"All Files\".\n+ patterns (list[FileDialogFilterPatternStringValue]): A list of possible glob file patterns for files to show.\n+ e.g. [\"*.jpg\", \"*.png\"]\n+ \"\"\"\n+\n+ label: UserInterfaceLabelStringValue\n+ patterns: FileDialogFilterPatternStringValueList\n+\n+\n+if TYPE_CHECKING:\n+ JobPathParameterDefinitionFileFilterList = list[JobPathParameterDefinitionFileFilter]\n+else:\n+ JobPathParameterDefinitionFileFilterList = conlist(\n+ JobPathParameterDefinitionFileFilter, min_items=1, max_items=20\n+ )\n+\n+\n+class JobPathParameterDefinitionUserInterface(OpenJDModel_v2023_09):\n+ \"\"\"User interface attributes for a job path parameter.\n+\n+ Attributes:\n+ control (PathUserInterfaceControl): The user interface control to use when editing this parameter.\n+ label (Optional[UserInterfaceLabelStringValue]): The label to display for the user interface control. Defaults\n+ to the `name` of the parameter.\n+ groupLabel (Optional[UserInterfaceLabelStringValue]): The label of the group box to place the user interface\n+ control in.\n+ fileFilters (Optional[list[JobPathParameterDefinitionFileFilter]]): Can be provided when the uiControl is \u201cCHOOSE_INPUT_FILE\u201d or\n+ \u201cCHOOSE_OUTPUT_FILE\u201d. Defines the file filters that are shown in the file choice dialog.\n+ Maximum of 20 filters.\n+ fileFilterDefault (Optional[JobPathParameterDefinitionFileFilter]): Can be provided when the uiControl is \u201cCHOOSE_INPUT_FILE\u201d or\n+ \u201cCHOOSE_OUTPUT_FILE\u201d. The default file filter that\u2019s shown in the file choice dialog.\n+ \"\"\"\n+\n+ control: PathUserInterfaceControl\n+ label: Optional[UserInterfaceLabelStringValue]\n+ groupLabel: Optional[UserInterfaceLabelStringValue]\n+ fileFilters: Optional[JobPathParameterDefinitionFileFilterList]\n+ fileFilterDefault: Optional[JobPathParameterDefinitionFileFilter]\n+\n+\n+class JobPathParameterDefinition(OpenJDModel_v2023_09, JobParameterInterface):\n+ \"\"\"A Job Parameter of type path.\n+\n+ Attributes:\n+ name (Identifier): A name by which the parameter is referenced.\n+ type (JobParameterType.PATH): Descriminator to identify the type of the parameter\n+ objectType (Optional[JobPathParameterDefinitionObjectType]): The type of object the path represents,\n+ either a FILE or a DIRECTORY.\n+ dataFlow (Optional[JobPathParameterDefinitionDataFlow]): Whether the object the path represents\n+ serves as input, output or both for the job.\n+ userInterface (Optional[JobPathParameterDefinitionUserInterface]): User interface properties\n+ for this parameter\n+ description (Optional[Description]): A free form string that can be used to describe\n+ the parameter. It has no functional purpose, but may appear in UI elements.\n+ default (Optional[ParameterStringValue]): Default value for the parameter if a value\n+ is not provided.\n+ allowedValues (Optional[AllowedParameterStringValueList]): Explicit list of values that the\n+ parameter is allowed to take on.\n+ minLength (Optional[int]): Minimum string length of the parameter value.\n+ maxLength (Optional[int]): Maximum string length of the parameter value.\n+ \"\"\"\n+\n+ name: Identifier\n+ type: Literal[JobParameterType.PATH]\n+ objectType: Optional[JobPathParameterDefinitionObjectType]\n+ dataFlow: Optional[JobPathParameterDefinitionDataFlow]\n+ userInterface: Optional[JobPathParameterDefinitionUserInterface]\n+ description: Optional[Description] = None\n+ # Note: Ordering of the following fields is essential for the validators to work correctly.\n+ minLength: Optional[StrictInt] = None # noqa: N815\n+ maxLength: Optional[StrictInt] = None # noqa: N815\n+ allowedValues: Optional[AllowedParameterStringValueList] = None # noqa: N815\n+ default: Optional[ParameterStringValue] = None\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={\n+ TemplateVariableDef(prefix=\"|Param.\", resolves=ResolutionScope.SESSION),\n+ TemplateVariableDef(prefix=\"|RawParam.\", resolves=ResolutionScope.TEMPLATE),\n+ },\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=JobParameter),\n+ exclude_fields={\n+ \"name\",\n+ \"objectType\",\n+ \"dataFlow\",\n+ \"userInterface\",\n+ \"minLength\",\n+ \"maxLength\",\n+ \"allowedValues\",\n+ \"default\",\n+ },\n+ adds_fields=lambda key, this, symtab: {\n+ \"value\": symtab[f\"RawParam.{cast(JobStringParameterDefinition,this).name}\"]\n+ },\n+ )\n+\n+ @validator(\"minLength\")\n+ def _validate_min_length(cls, v: Optional[int]) -> Optional[int]:\n+ if v is None:\n+ return v\n+ if v <= 0:\n+ raise ValueError(\"Required: 0 < minLength.\")\n+ return v\n+\n+ @validator(\"maxLength\")\n+ def _validate_max_length(cls, v: Optional[int], values: dict[str, Any]) -> Optional[int]:\n+ if v is None:\n+ return v\n+ if v <= 0:\n+ raise ValueError(\"Required: 0 < maxLength.\")\n+ min_length = values.get(\"minLength\")\n+ if min_length is None:\n+ return v\n+ if min_length > v:\n+ raise ValueError(\"Required: minLength <= maxLength.\")\n+ return v\n+\n+ @validator(\"allowedValues\", each_item=True)\n+ def _validate_allowed_values_item(\n+ cls, v: ParameterStringValue, values: dict[str, Any]\n+ ) -> ParameterStringValue:\n+ min_length = values.get(\"minLength\")\n+ if min_length is not None:\n+ if len(v) < min_length:\n+ raise ValueError(\"Value is shorter than minLength.\")\n+ max_length = values.get(\"maxLength\")\n+ if max_length is not None:\n+ if len(v) > max_length:\n+ raise ValueError(\"Value is longer than maxLength.\")\n+ return v\n+\n+ @validator(\"default\")\n+ def _validate_default(\n+ cls, v: ParameterStringValue, values: dict[str, Any]\n+ ) -> ParameterStringValue:\n+ min_length = values.get(\"minLength\")\n+ if min_length is not None:\n+ if len(v) < min_length:\n+ raise ValueError(\"Value is shorter than minLength.\")\n+ max_length = values.get(\"maxLength\")\n+ if max_length is not None:\n+ if len(v) > max_length:\n+ raise ValueError(\"Value is longer than maxLength.\")\n+\n+ allowed_values = values.get(\"allowedValues\")\n+ if allowed_values is not None:\n+ if v not in allowed_values:\n+ raise ValueError(\"Must be an allowed value.\")\n+ return v\n+\n+ @root_validator\n+ def _validate_user_interface_compatibility(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ # validate that the user interface control is compatible with the value constraints\n+ if values.get(\"userInterface\"):\n+ user_interface_control = values[\"userInterface\"].control\n+ if values.get(\"allowedValues\") and user_interface_control in (\n+ PathUserInterfaceControl.CHOOSE_INPUT_FILE,\n+ PathUserInterfaceControl.CHOOSE_OUTPUT_FILE,\n+ PathUserInterfaceControl.CHOOSE_DIRECTORY,\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} cannot be used when 'allowedValues' is provided\"\n+ )\n+ if (\n+ not values.get(\"allowedValues\")\n+ and user_interface_control == PathUserInterfaceControl.DROPDOWN_LIST\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} requires that 'allowedValues' be provided\"\n+ )\n+ if (\n+ values[\"userInterface\"].fileFilters or values[\"userInterface\"].fileFilterDefault\n+ ) and user_interface_control not in [\n+ PathUserInterfaceControl.CHOOSE_INPUT_FILE,\n+ PathUserInterfaceControl.CHOOSE_OUTPUT_FILE,\n+ ]:\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} cannot be used when 'fileFilters'\"\n+ + \" or 'fileFilterDefault is provided\"\n+ )\n+ if (\n+ values.get(\"objectType\") == JobPathParameterDefinitionObjectType.FILE\n+ and user_interface_control == PathUserInterfaceControl.CHOOSE_DIRECTORY\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} cannot be used with 'objectType' of FILE\"\n+ )\n+ if values.get(\n+ \"objectType\"\n+ ) == JobPathParameterDefinitionObjectType.DIRECTORY and user_interface_control in [\n+ PathUserInterfaceControl.CHOOSE_INPUT_FILE,\n+ PathUserInterfaceControl.CHOOSE_OUTPUT_FILE,\n+ ]:\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} cannot be used with 'objectType' of DIRECTORY\"\n+ )\n+\n+ return values\n+\n+ # override\n+ def _check_constraints(self, value: Any) -> None:\n+ if value is None:\n+ raise ValueError(f\"No value given for {self.name}.\")\n+ if not isinstance(value, str):\n+ raise ValueError(f\"Value ({value}) for parameter {self.name} must be string type.\")\n+ if self.allowedValues and value not in self.allowedValues:\n+ raise ValueError(f\"Parameter {self.name} value ({value}) not in allowedValues.\")\n+ if self.minLength and len(value) < self.minLength:\n+ raise ValueError(\n+ f\"Value ({value}), with length {len(value)}, for parameter {self.name} value must be at least {self.minLength} characters.\"\n+ )\n+ if self.maxLength and self.maxLength < len(value):\n+ raise ValueError(\n+ f\"Value ({value}), with length {len(value)}, for parameter {self.name} value must be at most {self.maxLength} characters.\"\n+ )\n+\n+\n+class IntUserInterfaceControl(str, Enum):\n+ SPIN_BOX = \"SPIN_BOX\"\n+ DROPDOWN_LIST = \"DROPDOWN_LIST\"\n+ HIDDEN = \"HIDDEN\"\n+\n+\n+class JobIntParameterDefinitionUserInterface(OpenJDModel_v2023_09):\n+ \"\"\"User interface attributes for a job int parameter.\n+\n+ Attributes:\n+ control (IntUserInterfaceControl): The user interface control to use when editing this parameter.\n+ label (Optional[UserInterfaceLabelStringValue]): The label to display for the user interface control. Defaults\n+ to the `name` of the parameter.\n+ groupLabel (Optional[UserInterfaceLabelStringValue]): The label of the group box to place the user interface\n+ control in.\n+ singleStepDelta (Optional[PositiveInt]): How much the value changes for a single step modification, such\n+ as selecting an up or down arrow in the user interface control.\n+ \"\"\"\n+\n+ control: IntUserInterfaceControl\n+ label: Optional[UserInterfaceLabelStringValue]\n+ groupLabel: Optional[UserInterfaceLabelStringValue]\n+ singleStepDelta: Optional[PositiveInt]\n+\n+\n+class JobIntParameterDefinition(OpenJDModel_v2023_09):\n+ \"\"\"A Job Parameter of type integer.\n+\n+ Attributes:\n+ name (Identifier): A name by which the parameter is referenced.\n+ type (JobParameterType.INT): Descriminator to identify the type of the parameter\n+ userInterface (Optional[JobPathParameterDefinitionUserInterface]): User interface properties\n+ for this parameter\n+ description (Optional[Description]): A free form string that can be used to describe\n+ the parameter. It has no functional purpose, but may appear in UI elements.\n+ default (Optional[int]): Default value for the parameter if a value\n+ is not provided.\n+ allowedValues (Optional[AllowedIntParameterList]): Explicit list of values that the\n+ parameter is allowed to take on.\n+ minValue (Optional[int]): Minimum value that the parameter is allowed to be.\n+ maxValue (Optional[int]): Minimum value that the parameter is allowed to be.\n+ \"\"\"\n+\n+ name: Identifier\n+ type: Literal[JobParameterType.INT]\n+ userInterface: Optional[JobIntParameterDefinitionUserInterface]\n+ description: Optional[Description] = None\n+ # Note: Ordering of the following fields is essential for the validators to work correctly.\n+ minValue: Optional[int] = None # noqa: N815\n+ maxValue: Optional[int] = None # noqa: N815\n+ allowedValues: Optional[AllowedIntParameterList] = None # noqa: N815\n+ default: Optional[PositiveInt] = None\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={\n+ TemplateVariableDef(prefix=\"|Param.\", resolves=ResolutionScope.TEMPLATE),\n+ TemplateVariableDef(prefix=\"|RawParam.\", resolves=ResolutionScope.TEMPLATE),\n+ },\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=JobParameter),\n+ exclude_fields={\n+ \"name\",\n+ \"userInterface\",\n+ \"minValue\",\n+ \"maxValue\",\n+ \"allowedValues\",\n+ \"default\",\n+ },\n+ adds_fields=lambda key, this, symtab: {\n+ \"value\": symtab[f\"RawParam.{cast(JobIntParameterDefinition,this).name}\"]\n+ },\n+ )\n+\n+ @classmethod\n+ def _precheck_is_int_type(cls, v: Any) -> None:\n+ # prevent floats, bools, and other types from coercing into an int.\n+ # strings that contain floats are handled by pydantic's checks.\n+ if not isinstance(v, (int, str)) or isinstance(v, bool):\n+ raise ValueError(\"Value must be an integer or integer string.\")\n+\n+ @validator(\"minValue\", pre=True)\n+ def _validate_min_value_type(cls, v: Optional[Any]) -> Optional[Any]:\n+ if v is None:\n+ return v\n+ cls._precheck_is_int_type(v)\n+ return v\n+\n+ @validator(\"maxValue\", pre=True)\n+ def _validate_max_value_type(cls, v: Optional[Any]) -> Optional[Any]:\n+ if v is None:\n+ return v\n+ cls._precheck_is_int_type(v)\n+ return v\n+\n+ @validator(\"allowedValues\", each_item=True, pre=True)\n+ def _validate_allowed_values_item_type(cls, v: Any) -> Optional[Any]:\n+ cls._precheck_is_int_type(v)\n+ return v\n+\n+ @validator(\"default\", pre=True)\n+ def _validate_default_value_type(cls, v: Optional[Any]) -> Optional[Any]:\n+ if v is None:\n+ return v\n+ cls._precheck_is_int_type(v)\n+ return v\n+\n+ @validator(\"maxValue\")\n+ def _validate_max_value(cls, v: Optional[int], values: dict[str, Any]) -> Optional[int]:\n+ if v is None:\n+ return v\n+ min_value = values.get(\"minValue\")\n+ if min_value is None:\n+ return v\n+ if min_value > v:\n+ raise ValueError(\"Required: minValue <= maxValue.\")\n+ return v\n+\n+ @validator(\"allowedValues\", each_item=True)\n+ def _validate_allowed_values_item(cls, v: int, values: dict[str, Any]) -> int:\n+ min_value = values.get(\"minValue\")\n+ if min_value is not None:\n+ if v < min_value:\n+ raise ValueError(\"Value less than minValue.\")\n+ max_value = values.get(\"maxValue\")\n+ if max_value is not None:\n+ if v > max_value:\n+ raise ValueError(\"Value larger than maxValue.\")\n+ return v\n+\n+ @validator(\"default\")\n+ def _validate_default(cls, v: int, values: dict[str, Any]) -> int:\n+ min_value = values.get(\"minValue\")\n+ if min_value is not None:\n+ if v < min_value:\n+ raise ValueError(\"Value less than minValue.\")\n+ max_value = values.get(\"maxValue\")\n+ if max_value is not None:\n+ if v > max_value:\n+ raise ValueError(\"Value larger than maxValue.\")\n+\n+ allowed_values = values.get(\"allowedValues\")\n+ if allowed_values is not None:\n+ if v not in allowed_values:\n+ raise ValueError(\"Must be an allowed value.\")\n+ return v\n+\n+ @root_validator\n+ def _validate_user_interface_compatibility(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ # validate that the user interface control is compatible with the value constraints\n+ if values.get(\"userInterface\"):\n+ user_interface_control = values[\"userInterface\"].control\n+ if (\n+ values.get(\"allowedValues\")\n+ and user_interface_control == IntUserInterfaceControl.SPIN_BOX\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} cannot be used when 'allowedValues' is provided\"\n+ )\n+ if (\n+ not values.get(\"allowedValues\")\n+ and user_interface_control == IntUserInterfaceControl.DROPDOWN_LIST\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} requires that 'allowedValues' be provided\"\n+ )\n+ if (\n+ values[\"userInterface\"].singleStepDelta\n+ and user_interface_control != IntUserInterfaceControl.SPIN_BOX\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} cannot be used when 'singleStepDelta' is provided\"\n+ )\n+\n+ return values\n+\n+ # override\n+ def _check_constraints(self, value: Any) -> None:\n+ if value is None:\n+ raise ValueError(f\"No value given for {self.name}.\")\n+ if not isinstance(value, (str, int)) or isinstance(value, bool):\n+ raise ValueError(\n+ f\"Value ({value}) for parameter {self.name} must an integer or integer string.\"\n+ )\n+ if isinstance(value, str):\n+ try:\n+ value = int(value)\n+ except ValueError:\n+ raise ValueError(\n+ f\"Value ({value}) for parameter {self.name} must an integer or integer string.\"\n+ )\n+ if self.allowedValues and value not in self.allowedValues:\n+ raise ValueError(f\"Parameter {self.name} value ({value}) not in allowedValues.\")\n+ if self.minValue and value < self.minValue:\n+ raise ValueError(\n+ f\"Value ({value}) for parameter {self.name} must be at least {self.minValue}.\"\n+ )\n+ if self.maxValue and self.maxValue < value:\n+ raise ValueError(\n+ f\"Value ({value}) for parameter {self.name} must be at most {self.maxValue}.\"\n+ )\n+\n+\n+class FloatUserInterfaceControl(str, Enum):\n+ SPIN_BOX = \"SPIN_BOX\"\n+ DROPDOWN_LIST = \"DROPDOWN_LIST\"\n+ HIDDEN = \"HIDDEN\"\n+\n+\n+class JobFloatParameterDefinitionUserInterface(OpenJDModel_v2023_09):\n+ \"\"\"User interface attributes for a job float parameter.\n+\n+ Attributes:\n+ control (FloatUserInterfaceControl): The user interface control to use when editing this parameter.\n+ label (Optional[UserInterfaceLabelStringValue]): The label to display for the user interface control. Defaults\n+ to the `name` of the parameter.\n+ groupLabel (Optional[UserInterfaceLabelStringValue]): The label of the group box to place the user interface\n+ control in.\n+ decimals (Optional[PositiveInt]): decimals \u2014 This is the number of places editable after the decimal point.\n+ If decimals is not provided then an adaptive decimal mode will be used.\n+ singleStepDelta (Optional[PositiveFloat]): How much the value changes for a single step modification, such\n+ as selecting an up or down arrow in the user interface control. If decimals is provided, this is an\n+ absolute value, otherwise it is the fraction of the current value to use as an adaptive step.\n+ \"\"\"\n+\n+ control: FloatUserInterfaceControl\n+ label: Optional[UserInterfaceLabelStringValue]\n+ groupLabel: Optional[UserInterfaceLabelStringValue]\n+ decimals: Optional[PositiveInt]\n+ singleStepDelta: Optional[PositiveFloat]\n+\n+\n+class JobFloatParameterDefinition(OpenJDModel_v2023_09):\n+ \"\"\"A Job Parameter of type float.\n+\n+ Attributes:\n+ name (Identifier): A name by which the parameter is referenced.\n+ type (JobParameterType.FLOAT): Descriminator to identify the type of the parameter\n+ userInterface (Optional[JobPathParameterDefinitionUserInterface]): User interface properties\n+ for this parameter.\n+ description (Optional[Description]): A free form string that can be used to describe\n+ the parameter. It has no functional purpose, but may appear in UI elements.\n+ default (Optional[Decimal]): Default value for the parameter if a value\n+ is not provided.\n+ allowedValues (Optional[AllowedFloatParameterList]): Explicit list of values that the\n+ parameter is allowed to take on.\n+ minValue (Optional[Decimal]): Minimum value that the parameter is allowed to be.\n+ maxValue (Optional[Decimal]): Minimum value that the parameter is allowed to be.\n+ \"\"\"\n+\n+ name: Identifier\n+ type: Literal[JobParameterType.FLOAT]\n+ userInterface: Optional[JobFloatParameterDefinitionUserInterface]\n+ description: Optional[Description] = None\n+ # Note: Ordering of the following fields is essential for the validators to work correctly.\n+ minValue: Optional[Decimal] = None # noqa: N815\n+ maxValue: Optional[Decimal] = None # noqa: N815\n+ allowedValues: Optional[AllowedFloatParameterList] = None # noqa: N815\n+ default: Optional[Decimal] = None\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={\n+ TemplateVariableDef(prefix=\"|Param.\", resolves=ResolutionScope.TEMPLATE),\n+ TemplateVariableDef(prefix=\"|RawParam.\", resolves=ResolutionScope.TEMPLATE),\n+ },\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=JobParameter),\n+ exclude_fields={\n+ \"name\",\n+ \"userInterface\",\n+ \"minValue\",\n+ \"maxValue\",\n+ \"allowedValues\",\n+ \"default\",\n+ },\n+ adds_fields=lambda key, this, symtab: {\n+ \"value\": symtab[f\"RawParam.{cast(JobFloatParameterDefinition,this).name}\"]\n+ },\n+ )\n+\n+ @validator(\"maxValue\")\n+ def _validate_max_value(cls, v: Optional[Decimal], values: dict[str, Any]) -> Optional[Decimal]:\n+ if v is None:\n+ return v\n+ min_value = values.get(\"minValue\")\n+ if min_value is None:\n+ return v\n+ if min_value > v:\n+ raise ValueError(\"Required: minValue <= maxValue.\")\n+ return v\n+\n+ @validator(\"allowedValues\", each_item=True)\n+ def _validate_allowed_values_item(cls, v: Decimal, values: dict[str, Any]) -> Decimal:\n+ min_value = values.get(\"minValue\")\n+ if min_value is not None:\n+ if v < min_value:\n+ raise ValueError(\"Value less than minValue.\")\n+ max_value = values.get(\"maxValue\")\n+ if max_value is not None:\n+ if v > max_value:\n+ raise ValueError(\"Value larger than maxValue.\")\n+ return v\n+\n+ @validator(\"default\")\n+ def _validate_default(cls, v: Decimal, values: dict[str, Any]) -> Decimal:\n+ min_value = values.get(\"minValue\")\n+ if min_value is not None:\n+ if v < min_value:\n+ raise ValueError(\"Value less than minValue.\")\n+ max_value = values.get(\"maxValue\")\n+ if max_value is not None:\n+ if v > max_value:\n+ raise ValueError(\"Value larger than maxValue.\")\n+\n+ allowed_values = values.get(\"allowedValues\")\n+ if allowed_values is not None:\n+ if v not in allowed_values:\n+ raise ValueError(\"Must be an allowed value.\")\n+ return v\n+\n+ @root_validator\n+ def _validate_user_interface_compatibility(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ # validate that the user interface control is compatible with the value constraints\n+ if values.get(\"userInterface\"):\n+ user_interface_control = values[\"userInterface\"].control\n+ if (\n+ values.get(\"allowedValues\")\n+ and user_interface_control == FloatUserInterfaceControl.SPIN_BOX\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} cannot be used when 'allowedValues' is provided\"\n+ )\n+ if (\n+ not values.get(\"allowedValues\")\n+ and user_interface_control == FloatUserInterfaceControl.DROPDOWN_LIST\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} requires that 'allowedValues' be provided\"\n+ )\n+ if (\n+ values[\"userInterface\"].singleStepDelta\n+ and user_interface_control != FloatUserInterfaceControl.SPIN_BOX\n+ ):\n+ raise ValueError(\n+ f\"User interface control {user_interface_control.name} cannot be used when 'singleStepDelta' is provided\"\n+ )\n+\n+ return values\n+\n+ # override\n+ def _check_constraints(self, value: Any) -> None:\n+ if value is None:\n+ raise ValueError(f\"No value given for {self.name}.\")\n+ if not isinstance(value, (str, int, float, Decimal)) or isinstance(value, bool):\n+ raise ValueError(f\"Value ({value}) for parameter {self.name} must be floating point.\")\n+ try:\n+ # note: translate to string so that floats don't round poorly.\n+ # e.g. Decimal(1.2) == Decimal('1.1999999999999999555910790149937383830547332763671875')\n+ # Decimal(str(1.2)) == Decimal('1.2')\n+ value = Decimal(str(value))\n+ except InvalidOperation:\n+ raise ValueError(f\"Value ({value}) for parameter {self.name} must be floating point.\")\n+ if self.allowedValues and value not in self.allowedValues:\n+ raise ValueError(f\"Parameter {self.name} value ({value}) not in allowedValues.\")\n+ if self.minValue and value < self.minValue:\n+ raise ValueError(\n+ f\"Value ({value}) for parameter {self.name} must be at least {self.minValue}.\"\n+ )\n+ if self.maxValue and self.maxValue < value:\n+ raise ValueError(\n+ f\"Value ({value}) for parameter {self.name} must be at most {self.maxValue}.\"\n+ )\n+\n+\n+# ==================================================================\n+# =================== Step Requires/Capabilities ===================\n+# ==================================================================\n+\n+STANDARD_ATTRIBUTE_CAPABILITIES: dict[str, Any] = {\n+ \"attr.worker.os.family\": {\"values\": {\"linux\", \"windows\", \"macos\"}, \"multivalued\": False},\n+ \"attr.worker.cpu.arch\": {\"values\": {\"x86_64\", \"arm64\"}, \"multivalued\": False},\n+}\n+_STANDARD_ATTRIBUTE_CAPABILITIES_NAMES = list(STANDARD_ATTRIBUTE_CAPABILITIES.keys())\n+STANDARD_AMOUNT_CAPABILITIES: dict[str, Any] = {\n+ \"amount.worker.vcpu\": {},\n+ \"amount.worker.memory\": {},\n+ \"amount.worker.gpu\": {},\n+ \"amount.worker.gpu.memory\": {},\n+ \"amount.worker.disk.scratch\": {},\n+}\n+_STANDARD_AMOUNT_CAPABILITIES_NAMES = list(STANDARD_AMOUNT_CAPABILITIES.keys())\n+\n+\n+class AmountCapabilityName(FormatString):\n+ \"\"\"The name of an amount capability.\"\"\"\n+\n+ _min_length = 1\n+ _max_length = 100\n+\n+\n+class AttributeCapabilityName(FormatString):\n+ \"\"\"The name of an attrubute capability.\"\"\"\n+\n+ _min_length = 1\n+ _max_length = 100\n+\n+\n+class AttributeCapabilityValue(FormatString):\n+ _min_length = 1\n+\n+\n+if TYPE_CHECKING:\n+ AttributeCapabilityList = list[AttributeCapabilityValue]\n+else:\n+ AttributeCapabilityList = conlist(AttributeCapabilityValue, min_items=1, max_items=50)\n+\n+\n+class AmountRequirement(OpenJDModel_v2023_09):\n+ \"\"\"An amount requirement entry for a step, to specify which\n+ quanifiable host capabilities the step requires.\n+\n+ Amount capabilities are the mechanism for defining\n+ a counted or measured attribute of the worker for a Step\n+ to require, such as number of CPUs, amount of memory, or\n+ number of licenses from a shared network license server.\n+\n+ The values for amount capabilities can be either integer\n+ or floating point. The latter enables use cases like sharing\n+ VCPUs up to a limit, e.g. setting \"amount.worker.vcpu\" to 0.25.\n+\n+ Note: This is the instantiated version of AttributeRequirementTemplate\n+ \"\"\"\n+\n+ name: str\n+ min: Optional[Decimal]\n+ max: Optional[Decimal]\n+\n+ @root_validator(pre=True)\n+ def validate_concrete_model(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ # Reuse the AmountRequirementTemplate validation. Because all the template\n+ # variables have been substituted, it will now run validation it couldn't\n+ # before.\n+ AmountRequirementTemplate.parse_obj(values)\n+ return values\n+\n+\n+class AmountRequirementTemplate(OpenJDModel_v2023_09):\n+ \"\"\"An amount requirement entry for a step, to specify which\n+ quanifiable host capabilities the step requires.\n+\n+ Amount capabilities are the mechanism for defining\n+ a counted or measured attribute of the worker for a Step\n+ to require, such as number of CPUs, amount of memory, or\n+ number of licenses from a shared network license server.\n+\n+ The values for amount capabilities can be either integer\n+ or floating point. The latter enables use cases like sharing\n+ VCPUs up to a limit, e.g. setting \"amount.worker.vcpu\" to 0.25.\n+ \"\"\"\n+\n+ name: AmountCapabilityName\n+ min: Optional[Decimal]\n+ max: Optional[Decimal]\n+\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=AmountRequirement),\n+ resolve_fields={\n+ \"name\",\n+ },\n+ )\n+\n+ @validator(\"name\")\n+ def _validate_name(cls, v: str) -> str:\n+ validate_amount_capability_name(\n+ capability_name=v, standard_capabilities=_STANDARD_AMOUNT_CAPABILITIES_NAMES\n+ )\n+ return v\n+\n+ @validator(\"min\")\n+ def _validate_min(cls, v: Optional[Decimal], values: dict[str, Any]) -> Optional[Decimal]:\n+ if v is None:\n+ return v\n+ if v < 0:\n+ raise ValueError(f\"Value {v} must be zero or greater\")\n+ return v\n+\n+ @validator(\"max\")\n+ def _validate_max(cls, v: Optional[Decimal], values: dict[str, Any]) -> Optional[Decimal]:\n+ if v is None:\n+ return v\n+ if v <= 0:\n+ raise ValueError(\"Value must be greater than 0\")\n+ v_min = values.get(\"min\")\n+ if v_min is not None and v_min > v:\n+ raise ValueError(\"Value for 'max' must be greater or equal to 'min'\")\n+ return v\n+\n+ @root_validator(pre=True)\n+ def _validate_has_one_optional(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ if not (\"min\" in values or \"max\" in values):\n+ raise ValueError(\"At least one of 'min' or 'max' must be defined.\")\n+ return values\n+\n+\n+class AttributeRequirement(OpenJDModel_v2023_09):\n+ \"\"\"An attribute requirement entry for a step, to specify which\n+ property or abstract host capabilities the step requires.\n+\n+ Attribute capabilities are the mechanism for defining an\n+ attribute of the worker for a Step to require, such as its\n+ CPU architecture.\n+\n+ Note: This is the instantiated version of AttributeRequirementTemplate\n+ \"\"\"\n+\n+ name: str\n+ anyOf: Optional[list[str]]\n+ allOf: Optional[list[str]]\n+\n+ @root_validator(pre=True)\n+ def validate_concrete_model(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ # Reuse the AttributeRequirementTemplate validation. Because all the template\n+ # variables have been substituted, it will now run validation it couldn't\n+ # before.\n+ AttributeRequirementTemplate.parse_obj(values)\n+ return values\n+\n+\n+class AttributeRequirementTemplate(OpenJDModel_v2023_09):\n+ \"\"\"An attribute requirement entry for a step, to specify which\n+ host capabilities the step requires from.\n+\n+ Attribute capabilities are the mechanism for defining an\n+ attribute of the worker for a Step to require, such as its\n+ CPU architecture.\n+ \"\"\"\n+\n+ name: AttributeCapabilityName\n+ anyOf: Optional[AttributeCapabilityList] # noqa: N815\n+ allOf: Optional[AttributeCapabilityList] # noqa: N815\n+\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=AttributeRequirement),\n+ resolve_fields={\"name\", \"anyOf\", \"allOf\"},\n+ )\n+\n+ _attribute_capability_value_regex: ClassVar[re.Pattern] = re.compile(\n+ r\"(?-m:^(?:[a-zA-Z_][a-zA-Z0-9_\\-]*)\\Z)\"\n+ )\n+ _attribute_capability_value_max_length: int = 100\n+\n+ @validator(\"name\")\n+ def _validate_name(cls, v: str) -> str:\n+ validate_attribute_capability_name(\n+ capability_name=v, standard_capabilities=_STANDARD_ATTRIBUTE_CAPABILITIES_NAMES\n+ )\n+ return v\n+\n+ @classmethod\n+ def _validate_attribute_list(\n+ cls, v: AttributeCapabilityList, values: dict[str, Any], is_allof: bool\n+ ) -> None:\n+ capability_name = values[\"name\"].lower()\n+ standard_capability = STANDARD_ATTRIBUTE_CAPABILITIES.get(capability_name, {})\n+ if standard_capability:\n+ if is_allof and not standard_capability[\"multivalued\"] and len(v) > 1:\n+ raise ValueError(\n+ f\"Standard capability {capability_name} cannot have multiple values at once.\"\n+ )\n+ for item in v:\n+ # If it has expressions like \"{{ Param.SomeValue }}\", will\n+ # validate when those values are substituted.\n+ if len(item.expressions) > 0:\n+ continue\n+ if item not in standard_capability[\"values\"]:\n+ raise ValueError(\n+ f\"Values must be from {' '.join(standard_capability['values'])}\"\n+ )\n+ else:\n+ for item in v:\n+ # If it has expressions like \"{{ Param.SomeValue }}\", will\n+ # validate when those values are substituted.\n+ if len(item.expressions) > 0:\n+ continue\n+ if not cls._attribute_capability_value_regex.match(item):\n+ raise ValueError(f\"Value {item} is not a valid attribute capability value.\")\n+ if len(item) > cls._attribute_capability_value_max_length:\n+ raise ValueError(\n+ f\"Value {item} exceeds {cls._attribute_capability_value_max_length} character length limit.\"\n+ )\n+\n+ @validator(\"allOf\")\n+ def _validate_allof(\n+ cls, v: Optional[AttributeCapabilityList], values: dict[str, Any]\n+ ) -> Optional[AttributeCapabilityList]:\n+ if v is None:\n+ return v\n+ cls._validate_attribute_list(v, values, True)\n+ return v\n+\n+ @validator(\"anyOf\")\n+ def _validate_anyof(\n+ cls, v: Optional[AttributeCapabilityList], values: dict[str, Any]\n+ ) -> Optional[AttributeCapabilityList]:\n+ if v is None:\n+ return v\n+ cls._validate_attribute_list(v, values, False)\n+ return v\n+\n+ @root_validator(pre=True)\n+ def _validate_has_one_optional(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ if not (\"anyOf\" in values or \"allOf\" in values):\n+ raise ValueError(\"At least one of 'anyOf' or 'allOf' must be defined.\")\n+ return values\n+\n+\n+class HostRequirements(OpenJDModel_v2023_09):\n+ amounts: Optional[list[AmountRequirement]] = None\n+ attributes: Optional[list[AttributeRequirement]] = None\n+\n+\n+class HostRequirementsTemplate(OpenJDModel_v2023_09):\n+ amounts: Optional[list[AmountRequirementTemplate]] = None\n+ attributes: Optional[list[AttributeRequirementTemplate]] = None\n+\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=HostRequirements)\n+ )\n+\n+ _max_allowed_requirements: int = 50\n+\n+ @validator(\"amounts\")\n+ def _validate_amounts(\n+ cls, v: Optional[list[AmountRequirementTemplate]]\n+ ) -> Optional[list[AmountRequirementTemplate]]:\n+ if v is None:\n+ return v\n+ if len(v) == 0:\n+ raise ValueError(\"List must contain at least one element or not be defined.\")\n+ return v\n+\n+ @validator(\"attributes\")\n+ def _validate_attributes(\n+ cls, v: Optional[list[AttributeRequirementTemplate]]\n+ ) -> Optional[list[AttributeRequirementTemplate]]:\n+ if v is None:\n+ return v\n+ if len(v) == 0:\n+ raise ValueError(\"List must contain at least one element or not be defined.\")\n+ return v\n+\n+ @root_validator\n+ def _validate(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ if not (\"amounts\" in values or \"attributes\" in values):\n+ raise ValueError(\n+ \"Must define at least one of 'amounts' or 'attributes' if defining this property.\"\n+ )\n+ amounts = values.get(\"amounts\")\n+ attributes = values.get(\"attributes\")\n+ total_amounts = len(amounts) if amounts is not None else 0\n+ total_attributes = len(attributes) if attributes is not None else 0\n+ total = total_amounts + total_attributes\n+ if total > cls._max_allowed_requirements:\n+ raise ValueError(\n+ f\"The total number of requirements must not exceed {cls._max_allowed_requirements}. {total} requirements defined.\"\n+ )\n+ return values\n+\n+\n+# ==================================================================\n+# ========================== Template Types ========================\n+# ==================================================================\n+\n+\n+class StepDependency(OpenJDModel_v2023_09):\n+ dependsOn: StepName\n+\n+\n+if TYPE_CHECKING:\n+ StepEnvironmentList = list[Environment]\n+ StepDependenciesList = list[StepDependency]\n+else:\n+ StepEnvironmentList = conlist(Environment, min_items=1)\n+ StepDependenciesList = conlist(StepDependency, min_items=1)\n+\n+\n+# Target model for a StepTemplate when instantiating a job.\n+class Step(OpenJDModel_v2023_09):\n+ name: StepName\n+ script: StepScript\n+ description: Optional[Description] = None\n+ stepEnvironments: Optional[StepEnvironmentList] = None\n+ parameterSpace: Optional[StepParameterSpace] = None # noqa: N815\n+ hostRequirements: Optional[HostRequirements] = None\n+ dependencies: Optional[StepDependenciesList] = None\n+\n+\n+class StepTemplate(OpenJDModel_v2023_09):\n+ \"\"\"Definition of a single Step within a Job Template.\n+\n+ Attributes:\n+ name (StepName): The name by which the Step is referenced\n+ description (Optional[str]): A free form string that can be used to describe the Step.\n+ It has no functional purpose, but may appear in UI elements.\n+ script (StepScript): The information on what Actions to perform when running Tasks\n+ of the Step.\n+ stepEnvironments (Optional[StepEnvironmentList]): A list of the environments required to\n+ run Tasks that use this Step Script. This is an ordered list; environments are\n+ started in the order provided, and ended in the reverse order.\n+ parameterSpace (Optional[StepParameterSpaceDefinition]): Definition of the Step's parameter space.\n+ hostRequirements (Optional[HostRequirementsTemplate]): The capabilities that a host requires for\n+ this Step to run on it.\n+ dependencies (Optional[StepDependenciesList]): A list of this Step's dependencies.\n+ \"\"\"\n+\n+ name: StepName\n+ description: Optional[Description] = None\n+ script: StepScript\n+ stepEnvironments: Optional[StepEnvironmentList] = None\n+ parameterSpace: Optional[StepParameterSpaceDefinition] = None # noqa: N815\n+ hostRequirements: Optional[HostRequirementsTemplate] = None\n+ dependencies: Optional[StepDependenciesList] = None\n+\n+ _template_variable_sources = {\n+ \"script\": {\"__self__\", \"parameterSpace\"},\n+ \"stepEnvironments\": {\"__self__\"},\n+ }\n+ _job_creation_metadata = JobCreationMetadata(create_as=JobCreateAsMetadata(model=Step))\n+\n+ @validator(\"dependencies\")\n+ def _validate_no_duplicate_deps(\n+ cls, v: Optional[StepDependenciesList]\n+ ) -> Optional[StepDependenciesList]:\n+ if v is None:\n+ return v\n+ deps = set(v)\n+ if len(deps) != len(v):\n+ raise ValueError(\"Duplicate dependencies are not allowed.\")\n+ return v\n+\n+ @validator(\"stepEnvironments\")\n+ def _unique_environment_names(\n+ cls, v: Optional[StepEnvironmentList]\n+ ) -> Optional[StepEnvironmentList]:\n+ if v is not None:\n+ return validate_unique_elements(v, item_value=lambda v: v.name, property=\"name\")\n+ return v\n+\n+ @root_validator\n+ def _validate_no_self_dependency(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ # Dependency of the step upon itself is not allowed.\n+ deps: StepDependenciesList = values.get(\"dependencies\", [])\n+ if not deps:\n+ return values\n+ stepname = values.get(\"name\")\n+ if any(dep.dependsOn == stepname for dep in deps):\n+ raise ValueError(\"A step cannot depend upon itself.\")\n+ return values\n+\n+\n+if TYPE_CHECKING:\n+ StepTemplateList = list[StepTemplate]\n+ JobParameterDefinitionList = list[\n+ Union[\n+ JobIntParameterDefinition,\n+ JobFloatParameterDefinition,\n+ JobStringParameterDefinition,\n+ JobPathParameterDefinition,\n+ ]\n+ ]\n+ JobEnvironmentsList = list[Environment]\n+else:\n+ StepTemplateList = conlist(StepTemplate, min_items=1)\n+ JobParameterDefinitionList = conlist(\n+ Union[\n+ JobIntParameterDefinition,\n+ JobFloatParameterDefinition,\n+ JobStringParameterDefinition,\n+ JobPathParameterDefinition,\n+ ],\n+ min_items=1,\n+ max_items=50,\n+ )\n+ JobEnvironmentsList = conlist(Environment, min_items=1)\n+\n+\n+JobParameters = dict[Identifier, JobParameter]\n+\n+\n+# Target model for a JobTemplate when instantiating a job.\n+class Job(OpenJDModel_v2023_09):\n+ name: JobName\n+ steps: list[Step]\n+ description: Optional[Description] = None\n+ parameters: Optional[JobParameters] = None\n+ jobEnvironments: Optional[JobEnvironmentsList] = None\n+\n+\n+class JobTemplate(OpenJDModel_v2023_09):\n+ \"\"\"Definition of an Open Job Description Job Template.\n+\n+ Attributes:\n+ specificationVersion (SchemaVersion.v2023_09): The OpenJD schema version that\n+ whose data model this follows.\n+ name (JobTemplateName): The name of Jobs constructed by this template.\n+ steps (StepTemplateList): The Step Templates that comprise the Job Template.\n+ description (Optional[str]): A free form string that can be used to describe the Job.\n+ It has no functional purpose, but may appear in UI elements.\n+ parameterDefinitions (Optional[JobParameterDefinitionList]): The job parameters that are available to Jobs\n+ created with this template.\n+ jobEnvironments (Optional[JobEnvironmentsList]): Definitions of Environments that are run at the start\n+ of every Session running Tasks in this Job.\n+ schemaStr (Optional[str]): Ignored. Allowed for compatibility with json editing IDEs.\n+ \"\"\"\n+\n+ specificationVersion: Literal[SchemaVersion.v2023_09] # noqa: N815\n+ name: JobTemplateName\n+ steps: StepTemplateList\n+ description: Optional[Description] = None\n+ parameterDefinitions: Optional[JobParameterDefinitionList] = Field(None, descriminator=\"type\")\n+ jobEnvironments: Optional[JobEnvironmentsList] = None\n+ # Note: Cannot call the field 'schema'; it masks a base class field\n+ schemaStr: Optional[str] = Field(None, alias=\"$schema\") # noqa: N815\n+\n+ _template_variable_scope = ResolutionScope.TEMPLATE\n+ _template_variable_sources = {\n+ \"name\": {\"parameterDefinitions\"},\n+ \"steps\": {\"parameterDefinitions\"},\n+ \"jobEnvironments\": {\"parameterDefinitions\"},\n+ }\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=Job),\n+ resolve_fields={\"name\"},\n+ exclude_fields={\"specificationVersion\", \"schemaStr\"},\n+ reshape_field_to_dict={\"parameterDefinitions\": \"name\"},\n+ rename_fields={\"parameterDefinitions\": \"parameters\"},\n+ )\n+\n+ @validator(\"steps\")\n+ def _unique_step_names(cls, v: StepTemplateList) -> StepTemplateList:\n+ return validate_unique_elements(v, item_value=lambda v: v.name, property=\"name\")\n+\n+ @validator(\"parameterDefinitions\")\n+ def _unique_parameter_names(\n+ cls, v: Optional[JobParameterDefinitionList]\n+ ) -> Optional[JobParameterDefinitionList]:\n+ if v is not None:\n+ return validate_unique_elements(v, item_value=lambda v: v.name, property=\"name\")\n+ return v\n+\n+ @validator(\"jobEnvironments\")\n+ def _unique_environment_names(\n+ cls, v: Optional[JobEnvironmentsList]\n+ ) -> Optional[JobEnvironmentsList]:\n+ if v is not None:\n+ return validate_unique_elements(v, item_value=lambda v: v.name, property=\"name\")\n+ return v\n+\n+ @root_validator\n+ def _validate_template_variable_references(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ errors = validate_model_template_variable_references(cls, values)\n+ if errors:\n+ raise ValidationError(errors, JobTemplate)\n+ return values\n+\n+ @root_validator\n+ def _validate_no_step_dependency_cycles(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ depgraph = dict[str, set[str]]()\n+ steplist = values.get(\"steps\", [])\n+ for step in steplist:\n+ if step.dependencies is not None:\n+ dependsOn = set[str](dep.dependsOn for dep in step.dependencies)\n+ depgraph[step.name] = dependsOn\n+\n+ sorter = TopologicalSorter(depgraph)\n+ try:\n+ # Raises CycleError\n+ sorter.prepare()\n+ except CycleError as exc:\n+ cycle = \" -> \".join(exc.args[1])\n+ raise ValueError(f\"Step dependencies form a cycle: {cycle}\") from None\n+\n+ return values\n+\n+ @root_validator\n+ def _validate_step_deps_exist(cls, values: dict[str, Any]) -> dict[str, Any]:\n+ # Check that the deps referenced by all steps actually exist\n+\n+ steplist = values.get(\"steps\", [])\n+ if not steplist:\n+ return values\n+\n+ errors = list[ErrorWrapper]()\n+ stepnames = set[str](step.name for step in steplist)\n+ for i, step in enumerate(steplist):\n+ if step.dependencies is not None:\n+ for j, dep in enumerate(step.dependencies):\n+ if dep.dependsOn not in stepnames:\n+ errors.append(\n+ ErrorWrapper(\n+ ValueError(f\"Unknown step '{dep.dependsOn}'\"),\n+ # The path to the problematic dependsOn value\n+ (\"step\", i, \"dependencies\", j, \"dependsOn\"),\n+ )\n+ )\n+\n+ if errors:\n+ raise ValidationError(errors, JobTemplate)\n+\n+ return values\n+\n+ @root_validator\n+ def _validate_env_names_dont_match_step_env_names(\n+ cls, values: dict[str, Any]\n+ ) -> dict[str, Any]:\n+ # Check that if we have job-level Environments defined that none of the defined Step-level\n+ # environments have the same name.\n+ # Names must be unique between Steps & Jobs.\n+\n+ steplist = values.get(\"steps\", [])\n+ if not steplist:\n+ return values\n+\n+ envlist = values.get(\"jobEnvironments\", [])\n+ if not envlist:\n+ return values\n+\n+ job_env_names = set(env.name for env in cast(JobEnvironmentsList, envlist))\n+\n+ errors = list[ErrorWrapper]()\n+ for i, step in enumerate(steplist):\n+ if step.stepEnvironments is not None:\n+ for j, env in enumerate(step.stepEnvironments):\n+ if env.name in job_env_names:\n+ errors.append(\n+ ErrorWrapper(\n+ ValueError(\n+ f\"Name {env.name} must differ from the names of Environments defined at the root of the template.\"\n+ ),\n+ # The path to the problematic environment name\n+ (\"step\", i, \"stepEnvironments\", j, \"name\"),\n+ )\n+ )\n+\n+ if errors:\n+ raise ValidationError(errors, JobTemplate)\n+\n+ return values"}, {"sha": "8d929cc86d4cee38bb56224a89d095bcbdcdfbf0", "filename": "test/openjd/model/__init__.py", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F__init__.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F__init__.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2F__init__.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved."}, {"sha": "8d929cc86d4cee38bb56224a89d095bcbdcdfbf0", "filename": "test/openjd/model/_internal/__init__.py", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2F__init__.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2F__init__.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2F_internal%2F__init__.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved."}, {"sha": "a6d4dd1e16503d3c4d5c54108c57b0cda6b98efc", "filename": "test/openjd/model/_internal/test_combination_expr.py", "status": "added", "additions": 65, "deletions": 0, "changes": 65, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_combination_expr.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_combination_expr.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_combination_expr.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,65 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import pytest\n+\n+from openjd.model import ExpressionError, TokenError\n+from openjd.model._internal import CombinationExpressionParser\n+\n+\n+class TestTaskParameterSpaceParser:\n+ @pytest.mark.parametrize(\n+ \"given,expected\",\n+ [\n+ # (given, expected)\n+ (\"A\", \"A\"),\n+ # Product\n+ (\"A * B\", \"Product(A, B)\"),\n+ (\"A * B * C * D * E\", \"Product(A, B, C, D, E)\"),\n+ # Association\n+ (\"(A, B)\", \"Assoc(A, B)\"),\n+ (\"(A, B, C, D, E)\", \"Assoc(A, B, C, D, E)\"),\n+ # Combinations\n+ (\"A * (B, C)\", \"Product(A, Assoc(B, C))\"),\n+ (\"(B, C) * A\", \"Product(Assoc(B, C), A)\"),\n+ (\"(A * B, C * D)\", \"Assoc(Product(A, B), Product(C, D))\"),\n+ (\"((A, B), (C, D))\", \"Assoc(Assoc(A, B), Assoc(C, D))\"),\n+ ],\n+ )\n+ def test_successful_parses(self, given, expected):\n+ # GIVEN\n+ parser = CombinationExpressionParser()\n+\n+ # WHEN\n+ result = parser.parse(given)\n+\n+ # THEN\n+ assert repr(result) == expected, given\n+ assert str(result) == given\n+\n+ @pytest.mark.parametrize(\"given\", [\"A A\", \"* A\", \"A * *\", \"(A, B C)\"])\n+ def test_raises_tokenerror(self, given):\n+ # GIVEN\n+ parser = CombinationExpressionParser()\n+\n+ # THEN\n+ with pytest.raises(TokenError):\n+ parser.parse(given)\n+\n+ @pytest.mark.parametrize(\n+ \"given\",\n+ [\n+ \"\",\n+ \"(A, B\",\n+ \"A * ,\",\n+ \"(A)\",\n+ \"(A\",\n+ \"A *\",\n+ ],\n+ )\n+ def test_raises_expressionerror(self, given):\n+ # GIVEN\n+ parser = CombinationExpressionParser()\n+\n+ # THEN\n+ with pytest.raises(ExpressionError):\n+ parser.parse(given)"}, {"sha": "61a35c5b20ebd50d63953cd370128e7fded6d64c", "filename": "test/openjd/model/_internal/test_create_job.py", "status": "added", "additions": 655, "deletions": 0, "changes": 655, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_create_job.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_create_job.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_create_job.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,655 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from dataclasses import dataclass\n+from decimal import Decimal\n+from typing import Optional, Union, cast\n+\n+import pytest\n+from pydantic import PositiveInt, ValidationError\n+\n+from openjd.model import SymbolTable\n+from openjd.model._format_strings import FormatString\n+from openjd.model import SchemaVersion\n+from openjd.model._internal._create_job import instantiate_model\n+from openjd.model._types import (\n+ JobCreateAsMetadata,\n+ JobCreationMetadata,\n+ OpenJDModel,\n+)\n+\n+\n+class BaseModelForTesting(OpenJDModel):\n+ # Specific version doesn't matter for these tests\n+ _version = SchemaVersion.UNDEFINED\n+\n+\n+class TestInternalCreateJobNoMetadata:\n+ \"\"\"Tests of the internal create-job instantiation with models\n+ that do not have any create-job metadata.\n+ This tests our basic construction and case handling for most of\n+ the model entities that the traversal will see.\n+ \"\"\"\n+\n+ def test_model_of_scalars(self) -> None:\n+ # Test of a single model of scalars. There is no recursion involved in the\n+ # traversal of this.\n+\n+ # GIVEN\n+ class Model(BaseModelForTesting):\n+ a: int\n+ b: str\n+ c: Decimal\n+\n+ model = Model(a=1, b=\"two\", c=\"3.5\")\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == model\n+ assert result is not model\n+\n+ def test_model_with_optional(self) -> None:\n+ # Test of a model that contains optional fields where we don't have a value\n+ # for one of them\n+\n+ # GIVEN\n+ class Model(BaseModelForTesting):\n+ a: Optional[int] = None\n+ b: Optional[str] = None\n+ c: Decimal\n+\n+ model = Model(a=1, c=\"3.5\")\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ result = cast(Model, instantiate_model(model, symtab))\n+\n+ # THEN\n+ assert model.b is None\n+ assert result == model\n+ assert result is not model\n+\n+ def test_recursion(self) -> None:\n+ # Test of basic recursion with no collection field types.\n+\n+ # GIVEN\n+ class InnerModel(BaseModelForTesting):\n+ a: int\n+ b: str\n+\n+ class Model(BaseModelForTesting):\n+ inner: InnerModel\n+ c: str\n+\n+ inner_model = InnerModel(a=1, b=\"two\")\n+ model = Model(c=\"see\", inner=inner_model)\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ result = cast(Model, instantiate_model(model, symtab))\n+\n+ # THEN\n+ assert result == model\n+ assert result.inner is not inner_model\n+\n+ def test_model_has_list_non_models(self) -> None:\n+ # Test that we properly instantiate a model that contains lists of non-models.\n+\n+ # GIVEN\n+ @dataclass(frozen=True)\n+ class NonModelType:\n+ f: str\n+\n+ class Model(BaseModelForTesting):\n+ i: list[int]\n+ i2: list[NonModelType]\n+\n+ model = Model(i=[1, 2, 3], i2=[NonModelType(\"one\"), NonModelType(\"two\")])\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ result = cast(Model, instantiate_model(model, symtab))\n+\n+ # THEN\n+ assert result == model\n+ assert result.i is not model.i\n+ assert result.i2 is not model.i2\n+ assert all(model.i[i] is result.i[i] for i in range(0, len(model.i)))\n+ assert all(model.i2[i] is result.i2[i] for i in range(0, len(model.i2)))\n+\n+ def test_model_has_list_of_models(self) -> None:\n+ # Test that we properly instantiate a model that contains a list of other models.\n+\n+ # GIVEN\n+ class Inner(BaseModelForTesting):\n+ f: str\n+\n+ class Model(BaseModelForTesting):\n+ ii: list[Inner]\n+\n+ model = Model(ii=[{\"f\": \"one\"}, {\"f\": \"two\"}])\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ result = cast(Model, instantiate_model(model, symtab))\n+\n+ # THEN\n+ assert result == model\n+ assert all(result.ii[i] is not model.ii[i] for i in range(0, len(model.ii)))\n+\n+ def test_model_has_dict_of_nonmodels(self) -> None:\n+ # Test that we properly instantiate a model that contains a dict whose values are not models.\n+\n+ # GIVEN\n+ @dataclass(frozen=True)\n+ class NonModelType:\n+ f: str\n+\n+ class Model(BaseModelForTesting):\n+ d1: dict[str, int]\n+ d2: dict[str, NonModelType]\n+\n+ model = Model(\n+ d1={\"k1\": 1, \"k2\": 2},\n+ d2={\n+ \"kk1\": NonModelType(\"one\"),\n+ \"kk2\": NonModelType(\"two\"),\n+ },\n+ )\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ result = cast(Model, instantiate_model(model, symtab))\n+\n+ # THEN\n+ assert result == model\n+ assert all(result.d1[k] is model.d1[k] for k in model.d1)\n+ assert all(result.d2[k] is model.d2[k] for k in model.d2)\n+\n+ def test_model_has_dict_of_models(self) -> None:\n+ # Test that we properly instantiate a model that contains a dict whose values are models.\n+\n+ # GIVEN\n+ class Inner(BaseModelForTesting):\n+ f: str\n+\n+ class Model(BaseModelForTesting):\n+ d1: dict[str, Inner]\n+\n+ model = Model(\n+ d1={\"k1\": {\"f\": \"one\"}, \"k2\": {\"f\": \"two\"}},\n+ )\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ result = cast(Model, instantiate_model(model, symtab))\n+\n+ # THEN\n+ assert result == model\n+ assert all(result.d1[k] is not model.d1[k] for k in model.d1)\n+\n+\n+class TestInternalCreateJobResolvesFormatStrings:\n+ \"\"\"Tests that JobCreationMetadata.resolve_fields is respected.\n+ We support resolving fields that are:\n+ 1. FormatStrings\n+ 2. lists of FormatStrings\n+ 3. lists of a mix of FormatStrings and non-FormatStrings (e.g. ints,floats,regular-strings,etc)\n+ \"\"\"\n+\n+ def test_as_field(self) -> None:\n+ # Test that we resolve the desired format strings when they are the value of a field.\n+\n+ # GIVEN\n+ f1 = FormatString(\"{{ Param.V }}\")\n+ f2 = FormatString(\"{{ Param.V2 }}\")\n+\n+ class Model(BaseModelForTesting):\n+ f1: FormatString\n+ f2: FormatString\n+\n+ _job_creation_metadata = JobCreationMetadata(resolve_fields={\"f1\"})\n+\n+ model = Model(f1=f1, f2=f2)\n+ symtab = SymbolTable(source={\"Param.V\": \"ValueOfV\"})\n+ expected = Model(f1=\"ValueOfV\", f2=f2)\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == expected\n+\n+ def test_within_list(self) -> None:\n+ # Test that we resolve the desired format strings when they are located within a list field.\n+\n+ # GIVEN\n+ f1 = FormatString(\"{{ Param.V }}\")\n+ f2 = FormatString(\"{{ Param.V2 }}\")\n+\n+ class Model(BaseModelForTesting):\n+ f1: list[FormatString]\n+ f2: FormatString\n+\n+ _job_creation_metadata = JobCreationMetadata(resolve_fields={\"f1\"})\n+\n+ model = Model(f1=[f1, f1, f1], f2=f2)\n+ symtab = SymbolTable(source={\"Param.V\": \"ValueOfV\"})\n+ expected = Model(f1=[\"ValueOfV\", \"ValueOfV\", \"ValueOfV\"], f2=f2)\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == expected\n+\n+ def test_within_mixed_list(self) -> None:\n+ # Test that we resolve the desired format strings when they are located within a list field,\n+ # amongst other values that are not format strings.\n+\n+ # GIVEN\n+ f1 = FormatString(\"{{ Param.V }}\")\n+ f2 = FormatString(\"{{ Param.V2 }}\")\n+\n+ class Model(BaseModelForTesting):\n+ f1: list[Union[int, FormatString]]\n+ f2: FormatString\n+\n+ _job_creation_metadata = JobCreationMetadata(resolve_fields={\"f1\"})\n+\n+ model = Model(f1=[f1, 12], f2=f2)\n+ symtab = SymbolTable(source={\"Param.V\": \"ValueOfV\"})\n+ expected = Model(f1=[\"ValueOfV\", 12], f2=f2)\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == expected\n+\n+\n+class TestInternalCreateJobCreateAs:\n+ \"\"\"Tests that a model will instantiate as a given model class rather than the model's class.\"\"\"\n+\n+ def test_given_model(self) -> None:\n+ # Test that we use a given specific model class when provided.\n+\n+ # GIVEN\n+ class TargetModel(BaseModelForTesting):\n+ f: str\n+\n+ class Model(BaseModelForTesting):\n+ f: str\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetModel)\n+ )\n+\n+ model = Model(f=\"some string\")\n+ symtab = SymbolTable()\n+ expected = TargetModel(f=\"some string\")\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == expected\n+\n+ def test_given_callable(self) -> None:\n+ # Test that we derive the model class to use from a callable when it's given.\n+\n+ # GIVEN\n+ class TargetModel(BaseModelForTesting):\n+ f: str\n+\n+ class Model(BaseModelForTesting):\n+ f: str\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(callable=lambda m: TargetModel)\n+ )\n+\n+ model = Model(f=\"some string\")\n+ symtab = SymbolTable()\n+ expected = TargetModel(f=\"some string\")\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == expected\n+\n+\n+class TestInternalCreateJobExcludeField:\n+ \"\"\"Test that the given excluded fields are respected when instantiating a model.\"\"\"\n+\n+ def test(self) -> None:\n+ # GIVEN\n+ class TargetModel(BaseModelForTesting):\n+ f: str\n+\n+ class Model(BaseModelForTesting):\n+ f: str\n+ e: str\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetModel), exclude_fields={\"e\"}\n+ )\n+\n+ model = Model(f=\"one\", e=\"ignore\")\n+ symtab = SymbolTable()\n+ expected = TargetModel(f=\"one\")\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == expected\n+\n+\n+class TestInternalCreateJobAddsFields:\n+ \"\"\"Test that we use a provided callable to materialize new fields & their values.\"\"\"\n+\n+ def test(self) -> None:\n+ # GIVEN\n+ class TargetModel(BaseModelForTesting):\n+ name: str\n+ type: str\n+ n1: str\n+ n2: str\n+\n+ class Model(BaseModelForTesting):\n+ name: str\n+ type: str\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetModel),\n+ adds_fields=lambda key, model, symtab: {\n+ \"n1\": key,\n+ \"n2\": symtab[f\"Param.{cast(Model, model).name}\"],\n+ },\n+ )\n+\n+ model = Model(name=\"Foo\", type=\"INT\")\n+ symtab = SymbolTable(source={\"Param.Foo\": \"FooValue\"})\n+ expected = TargetModel(name=\"Foo\", type=\"INT\", n1=\"\", n2=\"FooValue\")\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == expected\n+\n+\n+class TestInternalCreateJobReshapes:\n+ \"\"\"Test that we reshape list fields into a dict when requested.\"\"\"\n+\n+ def test(self) -> None:\n+ # GIVEN\n+ class InnerModelTarget(BaseModelForTesting):\n+ f: str\n+\n+ class TargetModel(BaseModelForTesting):\n+ inner: dict[str, InnerModelTarget]\n+\n+ class InnerModel(BaseModelForTesting):\n+ name: str\n+ f: str\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=InnerModelTarget), exclude_fields={\"name\"}\n+ )\n+\n+ class Model(BaseModelForTesting):\n+ inner: list[InnerModel]\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetModel),\n+ reshape_field_to_dict={\"inner\": \"name\"},\n+ )\n+\n+ inner1 = InnerModel(name=\"foo\", f=\"foo-value\")\n+ inner2 = InnerModel(name=\"bar\", f=\"bar-value\")\n+ model = Model(inner=[inner1, inner2])\n+ symtab = SymbolTable()\n+ expected_inner1 = InnerModelTarget(f=\"foo-value\")\n+ expected_inner2 = InnerModelTarget(f=\"bar-value\")\n+ expected = TargetModel(inner={\"foo\": expected_inner1, \"bar\": expected_inner2})\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == expected\n+\n+\n+class TestInternalCreateJobRenames:\n+ \"\"\"Test that we rename fields when requested.\"\"\"\n+\n+ def test(self) -> None:\n+ # GIVEN\n+ class TargetModel(BaseModelForTesting):\n+ renamed: str\n+\n+ class Model(BaseModelForTesting):\n+ named: str\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetModel), rename_fields={\"named\": \"renamed\"}\n+ )\n+\n+ model = Model(named=\"foo\")\n+ symtab = SymbolTable()\n+ expected = TargetModel(renamed=\"foo\")\n+\n+ # WHEN\n+ result = instantiate_model(model, symtab)\n+\n+ # THEN\n+ assert result == expected\n+\n+\n+class TestInternalCreateJobExceptions:\n+ \"\"\"Testing that exceptions are raised & captured properly when instantiating a model.\n+ The strategy with these tests is that we'll create a model that translates into a different\n+ model class when instantiated. The model data will be such that it doesn't pass validation\n+ in the target model, and this will raise an exception when the target model is constructed.\n+ \"\"\"\n+\n+ def test_simple(self) -> None:\n+ # Simple test. No recursion. No collections.\n+\n+ # GIVEN\n+ class TargetModel(BaseModelForTesting):\n+ vv: PositiveInt\n+ ff: FormatString\n+\n+ class Model(BaseModelForTesting):\n+ vv: int\n+ ff: FormatString\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetModel), resolve_fields={\"ff\"}\n+ )\n+\n+ model = Model(vv=-10, ff=\"{{ Param.V }}\")\n+ symtab = SymbolTable(\n+ source={\"Param.V\": \"{{ Foo.Bar\"} # a bad format string to fire an exception\n+ )\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ instantiate_model(model, symtab)\n+ exc = excinfo.value\n+ errors = exc.errors()\n+\n+ # THEN\n+ assert len(errors) == 2\n+ locs = [err[\"loc\"] for err in errors]\n+ assert (\"vv\",) in locs\n+ assert (\"ff\",) in locs\n+\n+ def test_nested(self) -> None:\n+ # Testing exceptions from models nested within a model\n+\n+ # GIVEN\n+ class TargetInner(BaseModelForTesting):\n+ vv: PositiveInt\n+ ff: FormatString\n+\n+ class TargetModel(BaseModelForTesting):\n+ ii: TargetInner\n+\n+ class InnerModel(BaseModelForTesting):\n+ vv: int\n+ ff: FormatString\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetInner), resolve_fields={\"ff\"}\n+ )\n+\n+ class Model(BaseModelForTesting):\n+ ii: InnerModel\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetModel)\n+ )\n+\n+ model = Model(ii={\"vv\": -10, \"ff\": \"{{ Param.V }}\"})\n+ symtab = SymbolTable(\n+ source={\"Param.V\": \"{{ Foo.Bar\"} # a bad format string to fire an exception\n+ )\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ instantiate_model(model, symtab)\n+ exc = excinfo.value\n+ errors = exc.errors()\n+\n+ # THEN\n+ assert len(errors) == 2\n+ locs = [err[\"loc\"] for err in errors]\n+ assert (\"ii\", \"vv\") in locs\n+ assert (\"ii\", \"ff\") in locs\n+\n+ def test_within_list(self) -> None:\n+ # Test that the errors within list elements are correctly captured\n+\n+ # GIVEN\n+ class TargetInner(BaseModelForTesting):\n+ vv: PositiveInt\n+ ff: FormatString\n+\n+ class InnerModel(BaseModelForTesting):\n+ vv: int\n+ ff: FormatString\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetInner), resolve_fields={\"ff\"}\n+ )\n+\n+ class Model(BaseModelForTesting):\n+ ii: list[InnerModel]\n+\n+ model = Model(ii=[{\"vv\": -10, \"ff\": \"{{ Param.V }}\"}, {\"vv\": -5, \"ff\": \"{{ Param.V }}\"}])\n+ symtab = SymbolTable(\n+ source={\"Param.V\": \"{{ Foo.Bar\"} # a bad format string to fire an exception\n+ )\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ instantiate_model(model, symtab)\n+ exc = excinfo.value\n+ errors = exc.errors()\n+\n+ # THEN\n+ assert len(errors) == 4\n+ locs = [err[\"loc\"] for err in errors]\n+ assert (\"ii\", 0, \"vv\") in locs\n+ assert (\"ii\", 0, \"ff\") in locs\n+ assert (\"ii\", 1, \"vv\") in locs\n+ assert (\"ii\", 1, \"ff\") in locs\n+\n+ def test_within_reshape_list(self) -> None:\n+ # Test that the errors within list elements are correctly captured when that list is being\n+ # reshaped into a dict.\n+\n+ # GIVEN\n+ class TargetInner(BaseModelForTesting):\n+ vv: PositiveInt\n+ ff: FormatString\n+\n+ class TargetModel(BaseModelForTesting):\n+ ii: dict[str, TargetInner]\n+\n+ class InnerModel(BaseModelForTesting):\n+ name: str\n+ vv: int\n+ ff: FormatString\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetInner),\n+ exclude_fields={\"name\"},\n+ resolve_fields={\"ff\"},\n+ )\n+\n+ class Model(BaseModelForTesting):\n+ ii: list[InnerModel]\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetModel),\n+ reshape_field_to_dict={\"inner\": \"name\"},\n+ )\n+\n+ model = Model(\n+ ii=[\n+ {\"name\": \"foo\", \"vv\": -10, \"ff\": \"{{ Param.V }}\"},\n+ {\"name\": \"bar\", \"vv\": -5, \"ff\": \"{{ Param.V }}\"},\n+ ]\n+ )\n+ symtab = SymbolTable(\n+ source={\"Param.V\": \"{{ Foo.Bar\"} # a bad format string to fire an exception\n+ )\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ instantiate_model(model, symtab)\n+ exc = excinfo.value\n+ errors = exc.errors()\n+\n+ # THEN\n+ assert len(errors) == 4\n+ locs = [err[\"loc\"] for err in errors]\n+ assert (\"ii\", 0, \"vv\") in locs\n+ assert (\"ii\", 0, \"ff\") in locs\n+ assert (\"ii\", 1, \"vv\") in locs\n+ assert (\"ii\", 1, \"ff\") in locs\n+\n+ def test_within_dict(self) -> None:\n+ # Test that the errors within dictionary elements are correctly captured\n+\n+ # GIVEN\n+ class TargetInner(BaseModelForTesting):\n+ vv: PositiveInt\n+ ff: FormatString\n+\n+ class InnerModel(BaseModelForTesting):\n+ vv: int\n+ ff: FormatString\n+ _job_creation_metadata = JobCreationMetadata(\n+ create_as=JobCreateAsMetadata(model=TargetInner),\n+ resolve_fields={\"ff\"},\n+ )\n+\n+ class Model(BaseModelForTesting):\n+ dd: dict[str, InnerModel]\n+\n+ model = Model(\n+ dd={\"foo\": {\"vv\": -10, \"ff\": \"{{ Param.V }}\"}, \"bar\": {\"vv\": -5, \"ff\": \"{{ Param.V }}\"}}\n+ )\n+ symtab = SymbolTable(\n+ source={\"Param.V\": \"{{ Foo.Bar\"} # a bad format string to fire an exception\n+ )\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ instantiate_model(model, symtab)\n+ exc = excinfo.value\n+ errors = exc.errors()\n+\n+ # THEN\n+ assert len(errors) == 4\n+ locs = [err[\"loc\"] for err in errors]\n+ assert (\"dd\", \"foo\", \"vv\") in locs\n+ assert (\"dd\", \"foo\", \"ff\") in locs\n+ assert (\"dd\", \"bar\", \"vv\") in locs\n+ assert (\"dd\", \"bar\", \"ff\") in locs"}, {"sha": "85500abbcc307498a23fb55ec5074b14c703c516", "filename": "test/openjd/model/_internal/test_model_variable_references.py", "status": "added", "additions": 498, "deletions": 0, "changes": 498, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_model_variable_references.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_model_variable_references.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_model_variable_references.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,498 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import cast\n+\n+import pytest\n+\n+from openjd.model._format_strings import FormatString\n+from openjd.model import parse_model\n+from openjd.model._internal import validate_model_template_variable_references\n+from openjd.model._types import (\n+ DefinesTemplateVariables,\n+ OpenJDModel,\n+ ResolutionScope,\n+ TemplateVariableDef,\n+)\n+\n+# arg2 = Whether a var defined in the arg0 scope is available in the arg1 scope.\n+# TEMPLATE scope -> referenced in only TEMPLATE, SESSION, and TASK scope\n+# SESSION scope -> referenced in only SESSION and TASK scope\n+# TASK scope -> referenced in only TASK scope\n+SCOPE_AVAILABILITY = [\n+ pytest.param(\n+ ResolutionScope.TEMPLATE, ResolutionScope.TEMPLATE, True, id=\"avail-template-template\"\n+ ),\n+ pytest.param(\n+ ResolutionScope.TEMPLATE, ResolutionScope.SESSION, True, id=\"avail-template-session\"\n+ ),\n+ pytest.param(ResolutionScope.TEMPLATE, ResolutionScope.TASK, True, id=\"avail-template-task\"),\n+ pytest.param(\n+ ResolutionScope.SESSION, ResolutionScope.TEMPLATE, False, id=\"notavail-session-template\"\n+ ),\n+ pytest.param(\n+ ResolutionScope.SESSION, ResolutionScope.SESSION, True, id=\"avail-session-session\"\n+ ),\n+ pytest.param(ResolutionScope.SESSION, ResolutionScope.TASK, True, id=\"avail-session-session\"),\n+ pytest.param(\n+ ResolutionScope.TASK, ResolutionScope.TEMPLATE, False, id=\"notavail-task-template\"\n+ ),\n+ pytest.param(ResolutionScope.TASK, ResolutionScope.SESSION, False, id=\"notavail-task-session\"),\n+ pytest.param(ResolutionScope.TASK, ResolutionScope.TASK, True, id=\"avail-task-task\"),\n+]\n+\n+\n+class TestVariableScope:\n+ \"\"\"Tests that a variable defined in a specific scope is referenceable in the correct scopes.\"\"\"\n+\n+ @pytest.mark.parametrize(\"def_scope, ref_scope, available\", SCOPE_AVAILABILITY)\n+ def test_available_in_self(\n+ self, def_scope: ResolutionScope, ref_scope: ResolutionScope, available: bool\n+ ) -> None:\n+ # A variabled defined in a scope must be referenceable in __self__ in the appropriate scopes.\n+\n+ # GIVEN\n+ class BaseModel(OpenJDModel):\n+ name: str\n+ ref: FormatString\n+ _template_variable_scope = ref_scope\n+ _template_variable_sources = {\"ref\": {\"__self__\"}}\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Param.\", resolves=def_scope)},\n+ field=\"name\",\n+ )\n+\n+ data = {\"name\": \"Foo\", \"ref\": \"{{ Param.Foo }}\"}\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == (0 if available else 1)\n+\n+ @pytest.mark.parametrize(\"def_scope, ref_scope, available\", SCOPE_AVAILABILITY)\n+ def test_available_in_submodel(\n+ self, def_scope: ResolutionScope, ref_scope: ResolutionScope, available: bool\n+ ) -> None:\n+ # A variable defined in a scope in a base model is made available in the appropriate scopes in a submodel\n+\n+ # GIVEN\n+ class SubModel(OpenJDModel):\n+ field: FormatString\n+ _template_variable_scope = ref_scope\n+\n+ class BaseModel(OpenJDModel):\n+ name: str\n+ sub: SubModel\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Param.\", resolves=def_scope)},\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\n+ \"sub\": {\"__self__\"},\n+ }\n+\n+ data = {\n+ \"name\": \"Foo\",\n+ \"sub\": {\"field\": \"{{ Param.Foo }}\"},\n+ }\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == (0 if available else 1)\n+\n+ @pytest.mark.parametrize(\"def_scope, ref_scope, available\", SCOPE_AVAILABILITY)\n+ def test_export_to_parent(\n+ self, def_scope: ResolutionScope, ref_scope: ResolutionScope, available: bool\n+ ) -> None:\n+ # A variable exported by a submodel is made available to the parent in the appropriate scope.\n+\n+ # GIVEN\n+ class SubModel(OpenJDModel):\n+ name: str\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Param.\", resolves=def_scope)},\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+\n+ class BaseModel(OpenJDModel):\n+ ref: FormatString\n+ sub: SubModel\n+\n+ _template_variable_scope = ref_scope\n+ _template_variable_sources = {\n+ \"ref\": {\"sub\"},\n+ }\n+\n+ data = {\n+ \"ref\": \"{{ Param.Foo }}\",\n+ \"sub\": {\"name\": \"Foo\"},\n+ }\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == (0 if available else 1)\n+\n+\n+def test_non_export_not_available() -> None:\n+ # Test that if a submodel defines a variable but doesn't export it, then\n+ # it's not available in the parent.\n+\n+ # GIVEN\n+ class Def(OpenJDModel):\n+ name: str\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Param.\", resolves=ResolutionScope.TEMPLATE)},\n+ field=\"name\",\n+ )\n+\n+ class BaseModel(OpenJDModel):\n+ defn: Def\n+ ref: FormatString\n+ _template_variable_scope = ResolutionScope.TEMPLATE\n+ _template_variable_sources = {\"ref\": {\"defn\"}}\n+\n+ data = {\"defn\": {\"name\": \"Foo\"}, \"ref\": \"{{ Param.Foo }}\"}\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == 1\n+\n+\n+class TestSymbolPrefixNesting:\n+ \"\"\"Tests that symbol prefixes can be properly nested into submodels.\"\"\"\n+\n+ def test_subprefix(self) -> None:\n+ # Test that the variable defined in a submodel has the prefix defined in the parent\n+\n+ # GIVEN\n+ class Submodel(OpenJDModel):\n+ name: str\n+ ref: FormatString\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"Param.\", resolves=ResolutionScope.TEMPLATE)},\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"ref\": {\"__self__\"}}\n+\n+ class BaseModel(OpenJDModel):\n+ sub: Submodel\n+ _template_variable_scope = ResolutionScope.TEMPLATE\n+ _template_variable_definitions = DefinesTemplateVariables(symbol_prefix=\"Root.\")\n+\n+ data = {\"sub\": {\"name\": \"Foo\", \"ref\": \"{{ Root.Param.Foo }}\"}}\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == 0\n+\n+ def test_prefix_reset_in_def(self) -> None:\n+ # Test that resetting a prefix during a variable definition ignores the parent prefix\n+\n+ # GIVEN\n+ class Submodel(OpenJDModel):\n+ name: str\n+ ref: FormatString\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Sub.\", resolves=ResolutionScope.TEMPLATE)},\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"ref\": {\"__self__\"}}\n+\n+ class BaseModel(OpenJDModel):\n+ sub: Submodel\n+ _template_variable_scope = ResolutionScope.TEMPLATE\n+ _template_variable_definitions = DefinesTemplateVariables(symbol_prefix=\"Root.\")\n+\n+ data = {\"sub\": {\"name\": \"Foo\", \"ref\": \"{{ Sub.Foo }}\"}}\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == 0\n+\n+ def test_prefix_reset_in_model(self) -> None:\n+ # Test that resetting a prefix in the submodel ignores the parent prefix\n+\n+ # GIVEN\n+ class Submodel(OpenJDModel):\n+ name: str\n+ ref: FormatString\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ symbol_prefix=\"|Sub.\",\n+ defines={TemplateVariableDef(prefix=\"Inner.\", resolves=ResolutionScope.TEMPLATE)},\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\"ref\": {\"__self__\"}}\n+\n+ class BaseModel(OpenJDModel):\n+ sub: Submodel\n+ _template_variable_scope = ResolutionScope.TEMPLATE\n+ _template_variable_definitions = DefinesTemplateVariables(symbol_prefix=\"Root.\")\n+\n+ data = {\"sub\": {\"name\": \"Foo\", \"ref\": \"{{ Sub.Inner.Foo }}\"}}\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == 0\n+\n+\n+class TestInjectSymbol:\n+ \"\"\"Test that injected symbols are referencable at the correct scope.\"\"\"\n+\n+ @pytest.mark.parametrize(\"def_scope, ref_scope, available\", SCOPE_AVAILABILITY)\n+ def test(self, def_scope: ResolutionScope, ref_scope: ResolutionScope, available: bool) -> None:\n+ # Test that we can reference an injected symbol in the scopes that it's supposed to be available within.\n+\n+ # GIVEN\n+ class Submodel(OpenJDModel):\n+ ref: FormatString\n+ _template_variable_scope = ref_scope\n+ _template_variable_sources = {\"ref\": {\"__self__\"}}\n+\n+ class BaseModel(OpenJDModel):\n+ sub: Submodel\n+ _template_variable_scope = def_scope\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ symbol_prefix=\"Root.\", inject={\"Foo\", \"|New.Bar\"}\n+ )\n+ _template_variable_sources = {\"sub\": {\"__self__\"}}\n+\n+ data = {\"sub\": {\"ref\": \"{{ Root.Foo }} {{ New.Bar }}\"}}\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == (0 if available else 2)\n+\n+\n+class TestListField:\n+ \"\"\"Test that if we have a field that's a list that we check its elements correctly.\"\"\"\n+\n+ @pytest.mark.parametrize(\"def_scope, ref_scope, available\", SCOPE_AVAILABILITY)\n+ def test_available_in_model(\n+ self, def_scope: ResolutionScope, ref_scope: ResolutionScope, available: bool\n+ ) -> None:\n+ # Test that if we have a field that's a list of submodels that the variable is available in the\n+ # appropriate scopes in that submodel.\n+\n+ # GIVEN\n+ class SubModel(OpenJDModel):\n+ field: FormatString\n+ _template_variable_scope = ref_scope\n+\n+ class BaseModel(OpenJDModel):\n+ name: str\n+ sub: list[SubModel]\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Param.\", resolves=def_scope)},\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\n+ \"sub\": {\"__self__\"},\n+ }\n+\n+ data = {\n+ \"name\": \"Foo\",\n+ \"sub\": [\n+ {\"field\": \"{{ Param.Foo }}\"},\n+ {\"field\": \"{{ Param.Foo }}\"},\n+ {\"field\": \"{{ Param.Foo }}\"},\n+ ],\n+ }\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == (0 if available else 3)\n+\n+ @pytest.mark.parametrize(\"def_scope, ref_scope, available\", SCOPE_AVAILABILITY)\n+ def test_available_in_string(\n+ self, def_scope: ResolutionScope, ref_scope: ResolutionScope, available: bool\n+ ) -> None:\n+ # Test that if we have a field that's a list of FormatStrings that the variable is available in the\n+ # appropriate scopes in that submodel.\n+\n+ # GIVEN\n+ class BaseModel(OpenJDModel):\n+ name: str\n+ ref: list[FormatString]\n+ _template_variable_scope = ref_scope\n+ _template_variable_sources = {\"ref\": {\"__self__\"}}\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Param.\", resolves=def_scope)},\n+ field=\"name\",\n+ )\n+\n+ data = {\"name\": \"Foo\", \"ref\": [\"{{ Param.Foo }}\", \"{{ Param.Foo }}\", \"{{ Param.Foo }}\"]}\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == (0 if available else 3)\n+\n+\n+class TestDictField:\n+ \"\"\"Test that if we have a field that's a dict that we check its elements correctly.\"\"\"\n+\n+ @pytest.mark.parametrize(\"def_scope, ref_scope, available\", SCOPE_AVAILABILITY)\n+ def test_available_in_model(\n+ self, def_scope: ResolutionScope, ref_scope: ResolutionScope, available: bool\n+ ) -> None:\n+ # Test that if we have a field that's a dict of submodels that the variable is available in the\n+ # appropriate scopes in that submodel.\n+\n+ # GIVEN\n+ class SubModel(OpenJDModel):\n+ field: FormatString\n+ _template_variable_scope = ref_scope\n+\n+ class BaseModel(OpenJDModel):\n+ name: str\n+ sub: dict[str, SubModel]\n+\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Param.\", resolves=def_scope)},\n+ field=\"name\",\n+ )\n+ _template_variable_sources = {\n+ \"sub\": {\"__self__\"},\n+ }\n+\n+ data = {\n+ \"name\": \"Foo\",\n+ \"sub\": {\n+ \"a\": {\"field\": \"{{ Param.Foo }}\"},\n+ \"b\": {\"field\": \"{{ Param.Foo }}\"},\n+ \"c\": {\"field\": \"{{ Param.Foo }}\"},\n+ },\n+ }\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == (0 if available else 3)\n+\n+ @pytest.mark.parametrize(\"def_scope, ref_scope, available\", SCOPE_AVAILABILITY)\n+ def test_available_in_string(\n+ self, def_scope: ResolutionScope, ref_scope: ResolutionScope, available: bool\n+ ) -> None:\n+ # Test that if we have a field that's a list of FormatStrings that the variable is available in the\n+ # appropriate scopes in that submodel.\n+\n+ # GIVEN\n+ class BaseModel(OpenJDModel):\n+ name: str\n+ ref: dict[str, FormatString]\n+ _template_variable_scope = ref_scope\n+ _template_variable_sources = {\"ref\": {\"__self__\"}}\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Param.\", resolves=def_scope)},\n+ field=\"name\",\n+ )\n+\n+ data = {\n+ \"name\": \"Foo\",\n+ \"ref\": {\"a\": \"{{ Param.Foo }}\", \"b\": \"{{ Param.Foo }}\", \"c\": \"{{ Param.Foo }}\"},\n+ }\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == (0 if available else 3)\n+\n+\n+@pytest.mark.parametrize(\"def_scope, ref_scope, available\", SCOPE_AVAILABILITY)\n+def test_dict_key_as_name(\n+ def_scope: ResolutionScope, ref_scope: ResolutionScope, available: bool\n+) -> None:\n+ # Test that a dictionary key can be correctly used as a symbol name available in the appropriate scopes.\n+\n+ # GIVEN\n+ class SubModel(OpenJDModel):\n+ value: str\n+ _template_variable_definitions = DefinesTemplateVariables(\n+ defines={TemplateVariableDef(prefix=\"|Param.\", resolves=def_scope)},\n+ field=\"__key__\",\n+ )\n+ _template_variable_sources = {\"__export__\": {\"__self__\"}}\n+\n+ class BaseModel(OpenJDModel):\n+ ref: FormatString\n+ sub: dict[str, SubModel]\n+\n+ _template_variable_scope = ref_scope\n+ _template_variable_sources = {\n+ \"ref\": {\"sub\"},\n+ }\n+\n+ data = {\n+ \"ref\": \"{{ Param.Foo }} {{ Param.Bar }}\",\n+ \"sub\": {\n+ \"Foo\": {\"value\": \"v1\"},\n+ \"Bar\": {\"value\": \"v2\"},\n+ },\n+ }\n+ model = parse_model(model=BaseModel, obj=data)\n+\n+ # WHEN\n+ errors = validate_model_template_variable_references(\n+ cast(OpenJDModel, type(model)), dict(model._iter())\n+ )\n+\n+ # THEN\n+ assert len(errors) == (0 if available else 2)"}, {"sha": "36ff092c895c088c9cc61c1c49e21c1c8e1b93a0", "filename": "test/openjd/model/_internal/test_range_expr.py", "status": "added", "additions": 363, "deletions": 0, "changes": 363, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_range_expr.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_range_expr.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2F_internal%2Ftest_range_expr.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,363 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from itertools import zip_longest\n+\n+import pytest\n+\n+from openjd.model import ExpressionError, TokenError\n+from openjd.model._internal import (\n+ IntRange,\n+ IntRangeExpression,\n+ RangeExpressionParser,\n+)\n+\n+\n+class TestRangeExpressionParser:\n+ def test_propagates_error(self) -> None:\n+ # GIVEN\n+ parser = RangeExpressionParser()\n+\n+ # THEN\n+ with pytest.raises(TokenError):\n+ parser.parse(\"!\")\n+\n+ def test_fails_empty(self) -> None:\n+ # GIVEN\n+ parser = RangeExpressionParser()\n+\n+ # THEN\n+ with pytest.raises(ExpressionError):\n+ parser.parse(\"\")\n+\n+ @pytest.mark.parametrize(\n+ \"range_expr\",\n+ [\n+ pytest.param(\"1-a\", id=\"non-valid character at end\"),\n+ pytest.param(\"b-1\", id=\"non-valid character at start\"),\n+ pytest.param(\"--12\", id=\"missing start\"),\n+ pytest.param(\"1-\", id=\"missing end\"),\n+ pytest.param(\"1-,3-4\", id=\"missing end in first range\"),\n+ pytest.param(\"1-10,11-\", id=\"misisng end in second range\"),\n+ pytest.param(\"--1-10\", id=\"extra hyphen in front of start\"),\n+ pytest.param(\"1---10\", id=\"extra hyphen in front of end\"),\n+ pytest.param(\"1--10:--5\", id=\"extra hyphen in front of step\"),\n+ pytest.param(\"1-2,,3-4\", id=\"extra comma between ranges\"),\n+ pytest.param(\"1-:2,\", id=\"trailing comma\"),\n+ pytest.param(\"1-2:\", id=\"missing step\"),\n+ pytest.param(\"2:\", id=\"trailing colon\"),\n+ pytest.param(\":2\", id=\"leading colon\"),\n+ pytest.param(\":\", id=\"just a colon\"),\n+ pytest.param(\"1-2 4-5\", id=\"missing comma between ranges\"),\n+ pytest.param(\"1-24-5\", id=\"extra number at the end\"),\n+ pytest.param(\"1-2:1 -5\", id=\"missing comma before second range\"),\n+ pytest.param(\"1-2:0\", id=\"step cannot be 0\"),\n+ pytest.param(\"1-0:1\", id=\"the inclusive offset does not make this range valid\"),\n+ pytest.param(\"0-1:-1\", id=\"total length 0 for pos range and neg step\"),\n+ pytest.param(\"2-0:1\", id=\"total length 0 for neg range and post step\"),\n+ pytest.param(\"0-1, 1-2:-1\", id=\"has length, but incorrect negative step\"),\n+ pytest.param(\"2-1:-1, 2-0:1\", id=\"has length, but incorrect positive step\"),\n+ ],\n+ )\n+ def test_not_valid_expression(self, range_expr: str) -> None:\n+ # GIVEN\n+ parser = RangeExpressionParser()\n+\n+ # THEN\n+ with pytest.raises(ExpressionError):\n+ parser.parse(range_expr)\n+\n+ @pytest.mark.parametrize(\n+ \"range_expr\",\n+ [\n+ pytest.param(\"-9999999\"),\n+ pytest.param(\"-100\"),\n+ pytest.param(\"-1\"),\n+ pytest.param(\"0\"),\n+ pytest.param(\"1\"),\n+ pytest.param(\"100\"),\n+ pytest.param(\"9999999\"),\n+ ],\n+ )\n+ def test_only_start(self, range_expr: str) -> None:\n+ # GIVEN\n+ parser = RangeExpressionParser()\n+\n+ # WHEN\n+ full_range = parser.parse(range_expr)\n+\n+ # THEN\n+ assert len(full_range) == 1\n+ for i in full_range:\n+ assert i == int(range_expr) == full_range.start == full_range.end\n+\n+ @pytest.mark.parametrize(\n+ \"range_expr, expected_range_expr\",\n+ [\n+ pytest.param(\"\\t0 - 1 :\\t1, 2 -\\t100 : 1\", \"0-1:1,2-100:1\"),\n+ ],\n+ )\n+ def test_ignore_whitespace(self, range_expr: str, expected_range_expr: str) -> None:\n+ # GIVEN\n+ parser = RangeExpressionParser()\n+\n+ # WHEN\n+ with_whitespace = parser.parse(range_expr)\n+ without_whitepsace = parser.parse(expected_range_expr)\n+\n+ # THEN\n+ assert with_whitespace == without_whitepsace\n+\n+ @pytest.mark.parametrize(\n+ \"range_expr,start,end,length\",\n+ [pytest.param(\"1-100\", 1, 100, 100)],\n+ )\n+ def test_parse_one_positive_range_no_step(\n+ self, range_expr: str, start: int, end: int, length: int\n+ ) -> None:\n+ # GIVEN\n+ parser = RangeExpressionParser()\n+\n+ # WHEN\n+ full_range = parser.parse(range_expr)\n+\n+ # THEN\n+ assert len(full_range) == length\n+ assert full_range.start == min(start, end)\n+ assert full_range.end == max(start, end)\n+\n+ @pytest.mark.parametrize(\n+ \"range_expr,start,end,total_range\",\n+ [\n+ pytest.param(\"1-100,101-200\", 1, 200, 200),\n+ pytest.param(\"0-1,3-4,7-9,10\", 0, 10, 8),\n+ pytest.param(\"20-29,0-9,10-19\", 0, 29, 30),\n+ ],\n+ )\n+ def test_parse_multiple_positive_non_overlapping_ranges(\n+ self, range_expr: str, start: int, end: int, total_range: int\n+ ) -> None:\n+ # GIVEN\n+ parser = RangeExpressionParser()\n+\n+ # WHEN\n+ full_range = parser.parse(range_expr)\n+\n+ # THEN\n+ assert full_range.start == start\n+ assert full_range.end == end\n+ assert len(full_range) == total_range\n+\n+ @pytest.mark.parametrize(\n+ \"range_expr\",\n+ [\n+ pytest.param(\"1-10,1-10\", id=\"complete overlap\"),\n+ pytest.param(\"10-1:-1,10-1:-1\", id=\"descending complete overlap\"),\n+ pytest.param(\"-10--1,-10--1\", id=\"negative complete overlap\"),\n+ pytest.param(\"-1--10:-1,-1--10:-1\", id=\"negative descending complete overlap\"),\n+ pytest.param(\"1-10,2-9\", id=\"complete overlap, subset\"),\n+ pytest.param(\"1-10,9-19\", id=\"partial overlap\"),\n+ pytest.param(\"9-19,1-10\", id=\"partial overlap, reverse order\"),\n+ pytest.param(\"1-10:1,10-1:-1\", id=\"ascending and descending overlap\"),\n+ pytest.param(\"-1--10:-1,-10--19:-1\", id=\"negative partial overlap\"),\n+ ],\n+ )\n+ def test_parse_overlapping_ranges(self, range_expr: str) -> None:\n+ # GIVEN\n+ parser = RangeExpressionParser()\n+\n+ # WHEN / THEN\n+ with pytest.raises(ExpressionError):\n+ parser.parse(range_expr)\n+\n+\n+class TestIntRangeExpression:\n+ def test_range_sorting(self):\n+ # GIVEN\n+ first = IntRange(start=-9, end=0)\n+ second = IntRange(start=1, end=10)\n+ third = IntRange(start=11, end=20)\n+\n+ sorted_ranges = [first, second, third]\n+\n+ # WHEN\n+ full_range = IntRangeExpression([third, second, first])\n+\n+ # THEN\n+ for actual, expected in zip_longest(full_range.ranges, sorted_ranges):\n+ assert actual == expected\n+\n+ def test_sorting_with_descending_ranges(self):\n+ # GIVEN\n+ first = IntRange(start=-10, end=-19, step=-1)\n+ second = IntRange(start=-1, end=-9, step=-1)\n+ third = IntRange(start=10, end=0, step=-1)\n+\n+ sorted_ranges = [first, second, third]\n+\n+ # WHEN\n+ full_range = IntRangeExpression([second, third, first])\n+\n+ # THEN\n+ for actual, expected in zip_longest(full_range.ranges, sorted_ranges):\n+ assert actual == expected\n+\n+ def test_sorting_mixed_ascending_and_descending_ranges(self):\n+ # GIVEN\n+ first = IntRange(start=-9, end=-7, step=1)\n+ second = IntRange(start=1, end=-6, step=-1)\n+ third = IntRange(start=2, end=9, step=1)\n+\n+ sorted_ranges = [first, second, third]\n+\n+ # WHEN\n+ full_range = IntRangeExpression([second, first, third])\n+\n+ # THEN\n+ for actual, expected in zip_longest(full_range.ranges, sorted_ranges):\n+ assert actual == expected\n+\n+ @pytest.mark.parametrize(\n+ \"index\",\n+ [\n+ pytest.param(20, id=\"longer than length\"),\n+ pytest.param(-21, id=\"negative index - longer than length\"),\n+ pytest.param(100, id=\"much longer\"),\n+ pytest.param(-101, id=\"negative - much longer\"),\n+ ],\n+ )\n+ def test_range_expression_getitem_out_of_bounds(self, index):\n+ # GIVEN\n+ first = IntRange(start=-5, end=0, step=1)\n+ second = IntRange(start=5, end=10, step=1)\n+ third = IntRange(start=13, end=20, step=1)\n+\n+ range_expression = IntRangeExpression([third, second, first])\n+\n+ # WHEN / THEN\n+ with pytest.raises(IndexError):\n+ range_expression[index]\n+\n+ @pytest.mark.parametrize(\n+ \"index, expected_item\",\n+ [\n+ pytest.param(0, -5, id=\"first range - first item\"),\n+ pytest.param(2, -3, id=\"first range\"),\n+ pytest.param(5, 0, id=\"second range\"),\n+ pytest.param(15, 16, id=\"third range\"),\n+ pytest.param(19, 20, id=\"third range - last item\"),\n+ pytest.param(-1, 20, id=\"negative index - first item\"),\n+ pytest.param(-20, -5, id=\"negative index - last item\"),\n+ ],\n+ )\n+ def test_range_expression_getitem(self, index, expected_item):\n+ # GIVEN\n+ first = IntRange(start=-5, end=0, step=1)\n+ second = IntRange(start=5, end=10, step=1)\n+ third = IntRange(start=13, end=20, step=1)\n+\n+ range_expression = IntRangeExpression([third, second, first])\n+\n+ # WHEN\n+ actual = range_expression[index]\n+\n+ for i, r in enumerate(range_expression):\n+ print(i, r)\n+\n+ # THEN\n+ assert actual == expected_item\n+\n+ @pytest.mark.parametrize(\n+ \"range_expr\",\n+ [\n+ pytest.param(\"1-10,11-20\"),\n+ ],\n+ )\n+ def test_iterable(self, range_expr: str) -> None:\n+ # GIVEN / WHEN\n+ parser: RangeExpressionParser = RangeExpressionParser()\n+ full_range: IntRangeExpression = parser.parse(range_expr)\n+ expected_range: range = range(full_range.start, full_range.end + 1, 1)\n+\n+ # THEN\n+ for actual, expected in zip_longest(full_range, expected_range):\n+ assert actual == expected\n+\n+ def test_read_only_properties(self) -> None:\n+ # GIVEN\n+ full_range: IntRangeExpression = IntRangeExpression([IntRange(start=0, end=10, step=1)])\n+ original_ranges_contents: list[IntRange] = full_range.ranges\n+\n+ # WHEN\n+ full_range.ranges.append(IntRange(start=1, end=2, step=1))\n+\n+ # THEN\n+ assert original_ranges_contents == full_range.ranges == [IntRange(start=0, end=10, step=1)]\n+\n+ # WHEN\n+ full_range.ranges[0] = IntRange(start=1, end=2, step=1)\n+\n+ # THEN\n+ assert original_ranges_contents == full_range.ranges == [IntRange(start=0, end=10, step=1)]\n+\n+ # WHEN / THEN\n+ with pytest.raises(AttributeError):\n+ full_range.start = 1 # type: ignore\n+\n+ with pytest.raises(AttributeError):\n+ full_range.end = 1 # type: ignore\n+\n+ with pytest.raises(AttributeError):\n+ full_range.ranges = [] # type: ignore\n+\n+\n+class TestIntRange:\n+ def test_comparisons(self):\n+ # GIVEN / WHEN / THEN\n+ # start, end, and step are the same, therefore equal and not less/greater than\n+ assert IntRange(start=0, end=0, step=1) == IntRange(start=0, end=0)\n+ assert not IntRange(start=0, end=0) < IntRange(start=0, end=0)\n+ assert not IntRange(start=0, end=0) > IntRange(start=0, end=0)\n+\n+ # start is different\n+ assert IntRange(start=0, end=1) < IntRange(start=1, end=1)\n+\n+ # start is the same, other end is bigger\n+ assert IntRange(start=0, end=0) < IntRange(start=0, end=1)\n+\n+ # start and end are same, other step is bigger\n+ assert IntRange(start=0, end=0, step=1) < IntRange(start=0, end=0, step=2)\n+\n+ def test_length(self):\n+ # GIVEN / WHEN / THEN\n+ # positive ascending\n+ assert len(IntRange(start=0, end=0, step=1)) == 1\n+ assert len(IntRange(start=0, end=10, step=1)) == 11\n+ assert len(IntRange(start=0, end=10, step=2)) == 6\n+\n+ # negative ascending\n+ assert len(IntRange(start=-3, end=-1, step=1)) == 3\n+ assert len(IntRange(start=-3, end=1, step=1)) == 5\n+ assert len(IntRange(start=-3, end=1, step=2)) == 3\n+\n+ # positive descending\n+ assert len(IntRange(start=0, end=0, step=-1)) == 1\n+ assert len(IntRange(start=10, end=-5, step=-1)) == 16\n+ assert len(IntRange(start=10, end=-5, step=-2)) == 8\n+\n+ # negative descending\n+ assert len(IntRange(start=-3, end=-7, step=-1)) == 5\n+ assert len(IntRange(start=-3, end=-7, step=-2)) == 3\n+\n+ def test_read_only_properties(self) -> None:\n+ # GIVEN\n+ range: IntRange = IntRange(start=0, end=10, step=1)\n+\n+ # WHEN / THEN\n+ with pytest.raises(AttributeError):\n+ range.start = 1 # type: ignore\n+\n+ with pytest.raises(AttributeError):\n+ range.end = 1 # type: ignore\n+\n+ with pytest.raises(AttributeError):\n+ range.step = 1 # type: ignore"}, {"sha": "8d929cc86d4cee38bb56224a89d095bcbdcdfbf0", "filename": "test/openjd/model/format_strings/__init__.py", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2F__init__.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2F__init__.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fformat_strings%2F__init__.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved."}, {"sha": "8de1bf3b347a1d8432e2ee10c238ecdae886e271", "filename": "test/openjd/model/format_strings/test_dyn_constrained_str.py", "status": "added", "additions": 186, "deletions": 0, "changes": 186, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_dyn_constrained_str.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_dyn_constrained_str.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_dyn_constrained_str.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,186 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import re\n+\n+import pytest\n+from pydantic import BaseModel, ValidationError\n+\n+from openjd.model._format_strings._dyn_constrained_str import DynamicConstrainedStr\n+\n+\n+class TestDyanamicConstrainedStr:\n+ def test_no_constraints(self) -> None:\n+ # Ensure that the validators correctly implement\n+ # having no constraint applied.\n+\n+ # GIVEN\n+ class Model(BaseModel):\n+ s: DynamicConstrainedStr\n+\n+ # WHEN\n+ Model.parse_obj({\"s\": \"123\"})\n+\n+ # THEN\n+ # raised no error\n+\n+ def test_encodes_as_str(self) -> None:\n+ # Make sure that none of the constraint fields like\n+ # _min_length get output when encoding a Model\n+\n+ # GIVEN\n+ class Model(BaseModel):\n+ s: DynamicConstrainedStr\n+\n+ model = Model(s=\"12\")\n+\n+ # WHEN\n+ as_dict = model.dict()\n+\n+ # THEN\n+ assert as_dict == {\"s\": \"12\"}\n+\n+ def test_no_type_coersion(self) -> None:\n+ # Ensure that non-strings aren't converted into strings.\n+\n+ # GIVEN\n+ class Model(BaseModel):\n+ s: DynamicConstrainedStr\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ Model.parse_obj({\"s\": 123})\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == 1\n+\n+ def test_min_length_success(self) -> None:\n+ # Make sure that strings that are long enough pass validation\n+\n+ # GIVEN\n+ class StrType(DynamicConstrainedStr):\n+ _min_length = 10\n+\n+ class Model(BaseModel):\n+ s: StrType\n+\n+ # WHEN\n+ Model.parse_obj({\"s\": \"0\" * 10})\n+\n+ # THEN\n+ # raised no error\n+\n+ def test_too_short(self) -> None:\n+ # Make sure that strings that are too short fail validation\n+\n+ # GIVEN\n+ class StrType(DynamicConstrainedStr):\n+ _min_length = 10\n+\n+ class Model(BaseModel):\n+ s: StrType\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ Model.parse_obj({\"s\": \"0\" * 9})\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == 1\n+\n+ def test_max_length_success(self) -> None:\n+ # Make sure that strings that are long enough pass validation\n+\n+ # GIVEN\n+ class StrType(DynamicConstrainedStr):\n+ _max_length = 10\n+\n+ class Model(BaseModel):\n+ s: StrType\n+\n+ # WHEN\n+ Model.parse_obj({\"s\": \"0\" * 10})\n+\n+ # THEN\n+ # raised no error\n+\n+ def test_too_long(self) -> None:\n+ # Make sure that strings that are too short fail validation\n+\n+ # GIVEN\n+ class StrType(DynamicConstrainedStr):\n+ _max_length = 10\n+\n+ class Model(BaseModel):\n+ s: StrType\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ Model.parse_obj({\"s\": \"0\" * 11})\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == 1\n+\n+ def test_regex_match_str(self) -> None:\n+ # Test a string that matches a regex defined as a string\n+\n+ # GIVEN\n+ class StrType(DynamicConstrainedStr):\n+ _regex = r\"0+\"\n+\n+ class Model(BaseModel):\n+ s: StrType\n+\n+ # WHEN\n+ Model.parse_obj({\"s\": \"0\" * 10})\n+\n+ # THEN\n+ # no errors raised\n+\n+ def test_regex_fail_str(self) -> None:\n+ # Test a string that does not validate against a regex defined as a string\n+\n+ # GIVEN\n+ class StrType(DynamicConstrainedStr):\n+ _regex = r\"0+\"\n+\n+ class Model(BaseModel):\n+ s: StrType\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ Model.parse_obj({\"s\": \"1\" * 10})\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == 1\n+\n+ def test_regex_match(self) -> None:\n+ # Test a string that matches a regex defined as a compiled regex\n+\n+ # GIVEN\n+ class StrType(DynamicConstrainedStr):\n+ _regex = re.compile(r\"0+\")\n+\n+ class Model(BaseModel):\n+ s: StrType\n+\n+ # WHEN\n+ Model.parse_obj({\"s\": \"0\" * 10})\n+\n+ # THEN\n+ # no errors raised\n+\n+ def test_regex_fail(self) -> None:\n+ # Test a string that does not validate against a regex defined as a compiled regex\n+\n+ # GIVEN\n+ class StrType(DynamicConstrainedStr):\n+ _regex = re.compile(r\"0+\")\n+\n+ class Model(BaseModel):\n+ s: StrType\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ Model.parse_obj({\"s\": \"1\" * 10})\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == 1"}, {"sha": "e42b3de713b739929ac17a77abab0d3c474a9b79", "filename": "test/openjd/model/format_strings/test_expression.py", "status": "added", "additions": 99, "deletions": 0, "changes": 99, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_expression.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_expression.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_expression.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,99 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from unittest.mock import patch\n+\n+import pytest\n+\n+from openjd.model import ExpressionError, SymbolTable, TokenError, ValidationError\n+from openjd.model._format_strings._expression import InterpolationExpression\n+from openjd.model._format_strings._parser import Parser\n+\n+\n+class TestInterpolationExpression:\n+ def test_init_builds_expr_tree(self):\n+ with patch.object(Parser, \"parse\") as mock:\n+ # WHEN\n+ InterpolationExpression(\"Foo.Bar\")\n+\n+ # THEN\n+ mock.assert_called_once_with(\"Foo.Bar\")\n+\n+ def test_init_reraises_parse_error(self):\n+ # GIVEN\n+ expr = \"..\"\n+\n+ # THEN\n+ with pytest.raises(TokenError):\n+ InterpolationExpression(expr)\n+\n+ def test_init_reraises_tokenizer_error(self):\n+ # GIVEN\n+ expr = \"!!\"\n+\n+ # THEN\n+ with pytest.raises(TokenError):\n+ InterpolationExpression(expr)\n+\n+ def test_validate_success(self):\n+ # GIVEN\n+ symtab = SymbolTable()\n+ symtab[\"Test.Name\"] = \"value\"\n+\n+ # WHEN\n+ expr = InterpolationExpression(\"Test.Name\")\n+\n+ # THEN\n+ try:\n+ expr.validate(symtab=symtab)\n+ except ValidationError:\n+ pytest.fail(\"Incorrectly identified expression as nonvalid.\")\n+\n+ def test_validate_fails(self):\n+ # GIVEN\n+ symtab = SymbolTable()\n+ symtab[\"Test.Name\"] = \"value\"\n+\n+ # WHEN\n+ expr = InterpolationExpression(\"Test.Fail\")\n+\n+ # THEN\n+ with pytest.raises(ValidationError) as exc:\n+ expr.validate(symtab=symtab)\n+\n+ assert \"Test.Fail\" in str(exc), \"Name should be in validation error\"\n+\n+ def test_evaluate_success(self):\n+ # GIVEN\n+ symtab = SymbolTable()\n+ symtab[\"Test.Name\"] = \"value\"\n+ expr = InterpolationExpression(\"Test.Name\")\n+\n+ # WHEN\n+ result = expr.evaluate(symtab=symtab)\n+\n+ # THEN\n+ assert result == \"value\"\n+\n+ def test_evaluate_fails(self):\n+ # GIVEN\n+ symtab = SymbolTable()\n+ symtab[\"Test.Name\"] = \"value\"\n+\n+ # WHEN\n+ expr = InterpolationExpression(\"Test.Fail\")\n+\n+ # THEN\n+ with pytest.raises(ExpressionError) as exc:\n+ expr.evaluate(symtab=symtab)\n+\n+ assert \"Test.Fail\" in str(exc), \"Name should be in validation error\"\n+\n+ def test_evaluate_badtype(self):\n+ # GIVEN\n+ symtab = SymbolTable()\n+ symtab[\"Test.Name\"] = {\"foo\": \"bar\"}\n+ expr = InterpolationExpression(\"Test.Name\")\n+\n+ # THEN\n+ with pytest.raises(ExpressionError):\n+ expr.evaluate(symtab=symtab)"}, {"sha": "b2fff041461b6ef402e59ba957592aecaa2d8ccf", "filename": "test/openjd/model/format_strings/test_format_string.py", "status": "added", "additions": 233, "deletions": 0, "changes": 233, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_format_string.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_format_string.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_format_string.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,233 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import pytest\n+\n+from openjd.model import SymbolTable\n+from openjd.model._format_strings import FormatString, FormatStringError\n+\n+\n+def test_original_value():\n+ # GIVEN\n+ input = \"input\"\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+\n+ # THEN\n+ assert format_string.original_value == input\n+\n+\n+def test_expression_property():\n+ # GIVEN\n+ input = \"a{{ Test.val }}\"\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+\n+ # THEN\n+ assert len(format_string.expressions) == 1\n+ assert format_string.expressions[0].start_pos == 1\n+ assert format_string.expressions[0].end_pos == len(input)\n+ assert format_string.expressions[0].expression is not None\n+ assert format_string.expressions[0].expression.expr == \" Test.val \"\n+\n+\n+@pytest.mark.parametrize(\n+ \"input\",\n+ [\n+ \"Test.val}}\",\n+ \"{Test.val}}\",\n+ \"{{Test.val\",\n+ \"{{Test.val}\",\n+ \"{{Test.val}} {{\",\n+ \"{{Test.val}} }}\",\n+ \"}} {{Test.val}}\",\n+ \"{{Test*val}}\",\n+ ],\n+)\n+def test_nonvalid_strings(input):\n+ # THEN\n+ with pytest.raises(FormatStringError, match=\"Failed to parse interpolation expression\"):\n+ FormatString(input)\n+\n+\n+class TestFormatStringResolve:\n+ def test_empty_string(self):\n+ # GIVEN\n+ input = \"\"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+\n+ # THEN\n+ assert format_string.resolve(symtab=symtab) == \"\"\n+\n+ def test_no_expressions(self):\n+ # GIVEN\n+ input = \"input\"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+\n+ # THEN\n+ assert format_string.resolve(symtab=symtab) == \"input\"\n+\n+ def test_single_expr_no_space(self):\n+ # GIVEN\n+ input = \"{{Test.val}}\"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = 4\n+\n+ # THEN\n+ assert format_string.resolve(symtab=symtab) == \"4\"\n+\n+ def test_single_expr_with_space(self):\n+ # GIVEN\n+ input = \" {{Test.val}} \"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = 4\n+\n+ # THEN\n+ assert format_string.resolve(symtab=symtab) == \" 4 \"\n+\n+ def test_with_spaces_on_both_sides(self):\n+ # GIVEN\n+ input = \" {{ Test.val }} \"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = 4\n+\n+ # THEN\n+ assert format_string.resolve(symtab=symtab) == \" 4 \"\n+\n+ def test_multiple_expressions(self):\n+ # GIVEN\n+ input = \" {{ Test.val }}-{{ Test.end}} \"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = 4\n+ symtab[\"Test.end\"] = 10\n+\n+ # THEN\n+ assert format_string.resolve(symtab=symtab) == \" 4-10 \"\n+\n+ def test_with_floating_point(self):\n+ # GIVEN\n+ input = \" {{ Test.val }}-{{ Test.end}} \"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = 4.098\n+ symtab[\"Test.end\"] = 10\n+\n+ # THEN\n+ assert format_string.resolve(symtab=symtab) == \" 4.098-10 \"\n+\n+ def test_with_string(self):\n+ # GIVEN\n+ input = \" {{ Test.val }}-{{ Test.end}} \"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = 4.098\n+ symtab[\"Test.end\"] = \"hello1\"\n+\n+ # THEN\n+ assert format_string.resolve(symtab=symtab) == \" 4.098-hello1 \"\n+\n+ def test_without_entry_in_table(self):\n+ # GIVEN\n+ input = \" {{ Test.val }}-{{ Test.end}} \"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = 4.098\n+\n+ # THEN\n+ with pytest.raises(FormatStringError, match=\"Failed to parse interpolation expression\"):\n+ format_string.resolve(symtab=symtab)\n+\n+\n+class TestFormatStringValidate:\n+ @pytest.mark.parametrize(\"input\", [\"\", \"input\"])\n+ def test_correct_validation_with_empty_table(self, input):\n+ # GIVEN\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+\n+ # THEN\n+ assert format_string.validate(symtab=symtab) == []\n+\n+ @pytest.mark.parametrize(\"input\", [\"{{Test.val}}\", \" {{Test.val}} \", \" {{ Test.val }} \"])\n+ def test_correct_validation_with_table(self, input):\n+ # GIVEN\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = 4\n+\n+ # THEN\n+ assert format_string.validate(symtab=symtab) == []\n+\n+ @pytest.mark.parametrize(\n+ \"input,val,end\",\n+ [\n+ (\" {{ Test.val }}-{{ Test.end}} \", 4, 10),\n+ (\" {{ Test.val }}-{{ Test.end}} \", 4.098, 10),\n+ (\" {{ Test.val }}-{{ Test.end}} \", 4.098, \"hello1\"),\n+ ],\n+ )\n+ def test_multiple_expressions(self, input, val, end):\n+ # GIVEN\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = val\n+ symtab[\"Test.end\"] = end\n+\n+ # THEN\n+ assert format_string.validate(symtab=symtab) == []\n+\n+ def test_without_one_entry_in_table(self):\n+ # GIVEN\n+ input = \" {{ Test.val }}-{{ Test.end}} \"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ symtab[\"Test.val\"] = 4.098\n+ errors = format_string.validate(symtab=symtab)\n+\n+ # THEN\n+ assert len(errors) == 1\n+\n+ def test_without_multiple_entries_in_table(self):\n+ # GIVEN\n+ input = \" {{ Test.val }}-{{ Test.end}} \"\n+ symtab = SymbolTable()\n+\n+ # WHEN\n+ format_string = FormatString(input)\n+ errors = format_string.validate(symtab=symtab)\n+\n+ # THEN\n+ assert len(errors) == 2"}, {"sha": "2894bb290cef20c9164ee30d01bd5be70de1abda", "filename": "test/openjd/model/format_strings/test_node.py", "status": "added", "additions": 69, "deletions": 0, "changes": 69, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_node.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_node.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_node.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,69 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import pytest\n+\n+from openjd.model import SymbolTable, ValidationError\n+from openjd.model._format_strings._nodes import FullNameNode\n+\n+\n+class TestFullNameNode:\n+ def test_validate_success(self):\n+ # GIVEN\n+ symtab = SymbolTable()\n+ symtab[\"Test.Name\"] = \"value\"\n+\n+ # WHEN\n+ node = FullNameNode(\"Test.Name\")\n+\n+ # THEN\n+ try:\n+ node.validate(symtab=symtab)\n+ except ValidationError:\n+ pytest.fail(\"Incorrectly identified expression as nonvalid.\")\n+\n+ def test_validate_fails(self):\n+ # GIVEN\n+ symtab = SymbolTable()\n+ symtab[\"Test.Name\"] = \"value\"\n+\n+ # WHEN\n+ node = FullNameNode(\"Test.Fail\")\n+\n+ # THEN\n+ with pytest.raises(ValidationError) as exc:\n+ node.validate(symtab=symtab)\n+\n+ assert \"Test.Fail\" in str(exc), \"Name should be in validation error\"\n+\n+ def test_evaluate_success(self):\n+ # GIVEN\n+ symtab = SymbolTable()\n+ symtab[\"Test.Name\"] = \"value\"\n+ node = FullNameNode(\"Test.Name\")\n+\n+ # WHEN\n+ result = node.evaluate(symtab=symtab)\n+\n+ # THEN\n+ assert result == \"value\"\n+\n+ def test_evaluate_fails(self):\n+ # GIVEN\n+ symtab = SymbolTable()\n+ symtab[\"Test.Name\"] = \"value\"\n+\n+ # WHEN\n+ node = FullNameNode(\"Test.Fail\")\n+\n+ # THEN\n+ with pytest.raises(ValidationError) as exc:\n+ node.evaluate(symtab=symtab)\n+\n+ assert \"Test.Fail\" in str(exc), \"Name should be in validation error\"\n+\n+ def test_repr(self):\n+ # GIVEN\n+ node = FullNameNode(\"Test.Name\")\n+\n+ # THEN\n+ assert str(node) == \"FullName(Test.Name)\""}, {"sha": "3e4b8d8bc6bd2009270b47ad0e7ac796cca05b12", "filename": "test/openjd/model/format_strings/test_parser.py", "status": "added", "additions": 46, "deletions": 0, "changes": 46, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_parser.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_parser.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fformat_strings%2Ftest_parser.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,46 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import pytest\n+\n+from openjd.model import ExpressionError, TokenError\n+from openjd.model._format_strings._nodes import FullNameNode\n+from openjd.model._format_strings._parser import Parser\n+\n+\n+class TestParser:\n+ def test_propagates_error(self):\n+ # GIVEN\n+ parser = Parser()\n+\n+ # THEN\n+ with pytest.raises(TokenError):\n+ parser.parse(\"!\")\n+\n+ @pytest.mark.parametrize(\"name\", [\"Foo\", \"Foo.Bar\", \"Foo.Bar.Baz\", \"Foo.Bar.Baz.Wuz\"])\n+ def test_parse_names(self, name):\n+ # GIVEN\n+ parser = Parser()\n+\n+ # WHEN\n+ result = parser.parse(name)\n+\n+ # THEN\n+ assert isinstance(result, FullNameNode)\n+ assert result.name == name\n+\n+ def test_fails_empty(self):\n+ # GIVEN\n+ parser = Parser()\n+\n+ # THEN\n+ with pytest.raises(ExpressionError):\n+ parser.parse(\"\")\n+\n+ @pytest.mark.parametrize(\"text\", [\".\", \"Foo.\", \"Foo..\", \"Foo.Bar Foo\", \"Foo.Bar .\"])\n+ def test_fails_nonvalid(self, text):\n+ # GIVEN\n+ parser = Parser()\n+\n+ # THEN\n+ with pytest.raises(ExpressionError):\n+ parser.parse(text)"}, {"sha": "405bee9e3c99f3e5ad62d06d68580ac71ccefd5f", "filename": "test/openjd/model/test_capabilities.py", "status": "added", "additions": 128, "deletions": 0, "changes": 128, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_capabilities.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_capabilities.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_capabilities.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,128 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import pytest\n+import string\n+from typing import Union\n+\n+from openjd.model import validate_amount_capability_name, validate_attribute_capability_name\n+from openjd.model.v2023_09 import FormatString\n+\n+TEST_BUILTIN_AMOUNTS: list[str] = [\n+ \"amount.worker.foo\",\n+ \"amount.job.foo\",\n+ \"amount.step.foo\",\n+ \"amount.task.foo\",\n+]\n+TEST_BUILTIN_ATTRIBUTES: list[str] = [\n+ \"attr.worker.foo\",\n+ \"attr.job.foo\",\n+ \"attr.step.foo\",\n+ \"attr.task.foo\",\n+]\n+\n+\n+def _success_test_values(prefix: str) -> list:\n+ return (\n+ [\n+ pytest.param(f\"{prefix}.worker.foo\", id=\"builtin worker\"),\n+ pytest.param(f\"{prefix}.job.foo\", id=\"builtin job\"),\n+ pytest.param(f\"{prefix}.step.foo\", id=\"builtin step\"),\n+ pytest.param(f\"{prefix}.task.foo\", id=\"builtin task\"),\n+ pytest.param(f\"{prefix}.custom\", id=\"customer-defined\"),\n+ pytest.param(f\"vendor:{prefix}.custom\", id=\"vendor-defined\"),\n+ pytest.param(f\"{prefix.upper()}.WORKER.FOO\", id=\"caps\"),\n+ pytest.param(f\"VENDOR:{prefix.upper()}.CUSTOM\", id=\"caps vendor\"),\n+ pytest.param(FormatString(f\"{prefix}.worker.foo\"), id=\"format string no expression\"),\n+ pytest.param(\n+ FormatString(f\"{prefix.upper()}.WORKER.FOO\"), id=\"caps format string no expression\"\n+ ),\n+ pytest.param(FormatString(\"{{ Param.Foo }}\"), id=\"format string with expression\"),\n+ pytest.param(\n+ FormatString(f\"{prefix}.{{{{ Param.Foo }}}}\"), id=\"format string partial expression\"\n+ ),\n+ ]\n+ + [ # Test the vendor regex\n+ pytest.param(f\"{letter}az09_:{prefix}.custom\", id=f\"vendor starts {letter}\")\n+ for letter in \"_az\"\n+ ]\n+ + [ # Test the name regex, first segment\n+ pytest.param(f\"{prefix}.{letter}az09_\", id=f\"segment starts {letter}\")\n+ for letter in \"_az\"\n+ ]\n+ + [ # Test the name regex, second segment\n+ pytest.param(f\"{prefix}.segment.{letter}az09_\", id=f\"2nd segment starts {letter}\")\n+ for letter in \"_az\"\n+ ]\n+ )\n+\n+\n+def _error_test_values(prefix: str, other_prefix: str) -> list:\n+ return (\n+ [\n+ pytest.param(f\"vendor:{prefix}.worker.foo\", id=\"vendor scoped builtin\"),\n+ pytest.param(f\"{other_prefix}.worker.foo\", id=f\"must start with {prefix}\"),\n+ pytest.param(f\"{prefix}.worker.notreserved\", id=\"reserved worker scope\"),\n+ pytest.param(f\"{prefix}.job.notreserved\", id=\"reserved job scope\"),\n+ pytest.param(f\"{prefix}.step.notreserved\", id=\"reserved step scope\"),\n+ pytest.param(f\"{prefix}.task.notreserved\", id=\"reserved task scope\"),\n+ pytest.param(\"foo.custom\", id=\"bad prefix\"),\n+ pytest.param(f\"{prefix}.worker.foo\\n\", id=\"ends in newline\"),\n+ pytest.param(f\"{prefix}.worker.foo\\n\\n\", id=\"ends in two newline\"),\n+ ]\n+ + [\n+ pytest.param(f\"{letter}:{prefix}.custom\", id=f\"vendor start {letter}\")\n+ for letter in sorted(list(set(string.digits + string.punctuation) - set(\"_\")))\n+ ]\n+ + [\n+ pytest.param(f\"v{letter}:{prefix}.custom\", id=f\"vendor contains {letter}\")\n+ for letter in sorted(list(set(string.punctuation) - set(\"_\")))\n+ ]\n+ + [\n+ pytest.param(f\"{prefix}.{letter}\", id=f\"name start {letter}\")\n+ for letter in sorted(list(set(string.digits + string.punctuation) - set(\"_\")))\n+ ]\n+ + [\n+ pytest.param(f\"{prefix}.v{letter}\", id=f\"name contains {letter}\")\n+ for letter in sorted(list(set(string.punctuation) - set(\"_\")))\n+ ]\n+ )\n+\n+\n+class TestValidateAmountCapabilityName:\n+ @pytest.mark.parametrize(\"value\", _success_test_values(\"amount\"))\n+ def test_success(self, value: Union[str, FormatString]) -> None:\n+ # WHEN\n+ validate_amount_capability_name(\n+ capability_name=value, standard_capabilities=TEST_BUILTIN_AMOUNTS\n+ )\n+\n+ # THEN\n+ # does not raise\n+\n+ @pytest.mark.parametrize(\"value\", _error_test_values(\"amount\", \"attr\"))\n+ def test_errors(self, value: Union[str, FormatString]) -> None:\n+ # THEN\n+ with pytest.raises(ValueError):\n+ validate_amount_capability_name(\n+ capability_name=value, standard_capabilities=TEST_BUILTIN_AMOUNTS\n+ )\n+\n+\n+class TestValidateAttributeCapabilityName:\n+ @pytest.mark.parametrize(\"value\", _success_test_values(\"attr\"))\n+ def test_success(self, value: Union[str, FormatString]) -> None:\n+ # WHEN\n+ validate_attribute_capability_name(\n+ capability_name=value, standard_capabilities=TEST_BUILTIN_ATTRIBUTES\n+ )\n+\n+ # THEN\n+ # does not raise\n+\n+ @pytest.mark.parametrize(\"value\", _error_test_values(\"attr\", \"amount\"))\n+ def test_errors(self, value: Union[str, FormatString]) -> None:\n+ # THEN\n+ with pytest.raises(ValueError):\n+ validate_attribute_capability_name(\n+ capability_name=value, standard_capabilities=TEST_BUILTIN_ATTRIBUTES\n+ )"}, {"sha": "0d6a6232e11af05c8b9bac38312c0a0b6b47f344", "filename": "test/openjd/model/test_create_job.py", "status": "added", "additions": 199, "deletions": 0, "changes": 199, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_create_job.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_create_job.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_create_job.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,199 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import pytest\n+\n+from openjd.model import (\n+ JobParameterInputValues,\n+ ParameterValue,\n+ ParameterValueType,\n+ preprocess_job_parameters,\n+)\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import (\n+ JobParameterType as JobParameterType_2023_09,\n+)\n+from openjd.model.v2023_09 import JobTemplate as JobTemplate_2023_09\n+\n+minimal_job_template_2023_09 = _parse_model(\n+ model=JobTemplate_2023_09,\n+ obj={\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"name\",\n+ \"steps\": [{\"name\": \"step\", \"script\": {\"actions\": {\"onRun\": {\"command\": \"do thing\"}}}}],\n+ },\n+)\n+\n+\n+class TestPreprocessJobParameters_2023_09: # noqa: N801\n+ \"\"\"Tests for preprocess_job_parameters with the 2023-09 schema.\"\"\"\n+\n+ @pytest.mark.parametrize(\n+ \"param_type\",\n+ [pytest.param(param.value, id=f\"{param.value} type\") for param in JobParameterType_2023_09],\n+ )\n+ def test_handles_parameter_type(self, param_type: str) -> None:\n+ # Test that we can process all known kinds of parameters\n+\n+ # GIVEN\n+ job_parameter_values: JobParameterInputValues = {\"Foo\": \"12\"}\n+ job_template = JobTemplate_2023_09(\n+ specificationVersion=\"jobtemplate-2023-09\",\n+ name=\"test\",\n+ steps=minimal_job_template_2023_09.steps,\n+ parameterDefinitions=[{\"name\": \"Foo\", \"type\": param_type}],\n+ )\n+\n+ # WHEN\n+ result = preprocess_job_parameters(\n+ job_template=job_template, job_parameter_values=job_parameter_values\n+ )\n+\n+ # THEN\n+ assert len(result) == 1\n+ assert \"Foo\" in result\n+ assert result[\"Foo\"].value == \"12\"\n+ assert result[\"Foo\"].type == ParameterValueType(param_type)\n+\n+ def test_reports_extra(self) -> None:\n+ # Test that we get errors if we have extra job parameters defined.\n+\n+ # GIVEN\n+ job_parameter_values: JobParameterInputValues = {\"ThisIsUnknown\": \"value\"}\n+ job_template = JobTemplate_2023_09(\n+ specificationVersion=\"jobtemplate-2023-09\",\n+ name=\"test\",\n+ steps=minimal_job_template_2023_09.steps,\n+ )\n+\n+ # WHEN\n+ with pytest.raises(ValueError) as excinfo:\n+ preprocess_job_parameters(\n+ job_template=job_template, job_parameter_values=job_parameter_values\n+ )\n+\n+ # THEN\n+ assert (\n+ \"Job parameter values provided for parameters that are not defined in the template: ThisIsUnknown\"\n+ in str(excinfo.value)\n+ )\n+\n+ def test_reports_missing(self) -> None:\n+ # Test that we get errors if we have missed defining job parameters\n+\n+ # GIVEN\n+ job_parameter_values: JobParameterInputValues = dict()\n+ job_template = JobTemplate_2023_09(\n+ specificationVersion=\"jobtemplate-2023-09\",\n+ name=\"test\",\n+ parameterDefinitions=[{\"name\": \"ThisIsNotDefined\", \"type\": \"STRING\"}],\n+ steps=minimal_job_template_2023_09.steps,\n+ )\n+\n+ # WHEN\n+ with pytest.raises(ValueError) as excinfo:\n+ preprocess_job_parameters(\n+ job_template=job_template, job_parameter_values=job_parameter_values\n+ )\n+\n+ # THEN\n+ assert \"Values missing for required job parameters: ThisIsNotDefined\" in str(excinfo.value)\n+\n+ def test_collects_defaults(self) -> None:\n+ # Test that we add values for missing job parameters that have\n+ # defaults defined.\n+\n+ # GIVEN\n+ job_parameter_values: JobParameterInputValues = {}\n+ job_template = JobTemplate_2023_09(\n+ specificationVersion=\"jobtemplate-2023-09\",\n+ name=\"test\",\n+ parameterDefinitions=[{\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"defaultValue\"}],\n+ steps=minimal_job_template_2023_09.steps,\n+ )\n+\n+ # WHEN\n+ result = preprocess_job_parameters(\n+ job_template=job_template, job_parameter_values=job_parameter_values\n+ )\n+\n+ # THEN\n+ assert \"Foo\" in result\n+ assert result[\"Foo\"] == ParameterValue(type=ParameterValueType.STRING, value=\"defaultValue\")\n+\n+ def test_ignores_defaults(self) -> None:\n+ # Test that we do not add values for job parameters that have\n+ # defaults defined, but that we've already defined.\n+\n+ # GIVEN\n+ job_parameter_values: JobParameterInputValues = {\"Foo\": \"FooValue\"}\n+ job_template = JobTemplate_2023_09(\n+ specificationVersion=\"jobtemplate-2023-09\",\n+ name=\"test\",\n+ parameterDefinitions=[{\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"defaultValue\"}],\n+ steps=minimal_job_template_2023_09.steps,\n+ )\n+\n+ # WHEN\n+ result = preprocess_job_parameters(\n+ job_template=job_template, job_parameter_values=job_parameter_values\n+ )\n+\n+ # THEN\n+ assert \"Foo\" in result\n+ assert result[\"Foo\"] == ParameterValue(type=ParameterValueType.STRING, value=\"FooValue\")\n+\n+ def test_checks_contraints(self) -> None:\n+ # Test that we see errors if a constraint is violated.\n+\n+ # GIVEN\n+ job_parameter_values: JobParameterInputValues = {\"Foo\": \"two\"}\n+ job_template = JobTemplate_2023_09(\n+ specificationVersion=\"jobtemplate-2023-09\",\n+ name=\"test\",\n+ parameterDefinitions=[{\"name\": \"Foo\", \"type\": \"STRING\", \"maxLength\": 1}],\n+ steps=minimal_job_template_2023_09.steps,\n+ )\n+\n+ # WHEN\n+ with pytest.raises(ValueError) as excinfo:\n+ preprocess_job_parameters(\n+ job_template=job_template, job_parameter_values=job_parameter_values\n+ )\n+\n+ # THEN\n+ assert \"parameter Foo value must be at most 1 characters\" in str(excinfo.value)\n+ assert len(str(excinfo.value).split(\"\\n\")) == 1\n+\n+ def test_collects_multiple_errors(self) -> None:\n+ # Test that see all errors if we have multiple in the same run.\n+\n+ # GIVEN\n+ job_parameter_values: JobParameterInputValues = {\n+ \"Foo\": \"two\", # Too long of a value\n+ \"Bar\": \"three\", # An extra parameter\n+ # missing buz\n+ }\n+ job_template = JobTemplate_2023_09(\n+ specificationVersion=\"jobtemplate-2023-09\",\n+ name=\"test\",\n+ parameterDefinitions=[\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"maxLength\": 1},\n+ {\"name\": \"Buz\", \"type\": \"STRING\"},\n+ ],\n+ steps=minimal_job_template_2023_09.steps,\n+ )\n+\n+ # WHEN\n+ with pytest.raises(ValueError) as excinfo:\n+ preprocess_job_parameters(\n+ job_template=job_template, job_parameter_values=job_parameter_values\n+ )\n+\n+ # THEN\n+ assert \"parameter Foo value must be at most 1 characters\" in str(excinfo.value)\n+ assert (\n+ \"Job parameter values provided for parameters that are not defined in the template: Bar\"\n+ in str(excinfo.value)\n+ )\n+ assert \"Values missing for required job parameters: Buz\" in str(excinfo.value)\n+ assert len(str(excinfo.value).split(\"\\n\")) == 3"}, {"sha": "f75edf55ff91e838eca739cdb1e914851bd319e3", "filename": "test/openjd/model/test_errors.py", "status": "added", "additions": 54, "deletions": 0, "changes": 54, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_errors.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_errors.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_errors.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,54 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from openjd.model import (\n+ DecodeValidationError,\n+ ExpressionError,\n+ TokenError,\n+ UnsupportedSchema,\n+ ValidationError,\n+)\n+\n+\n+class TestUnsupportedSchema:\n+ def test_msg(self):\n+ # GIVEN\n+ error = UnsupportedSchema(\"version\")\n+\n+ # THEN\n+ assert str(error) == \"Unsupported schema version: version\"\n+\n+\n+class TestDecodeValidationError:\n+ def test_msg(self):\n+ # GIVEN\n+ error = DecodeValidationError(\"Test message\")\n+\n+ # THEN\n+ assert str(error) == \"Test message\"\n+\n+\n+class TestValidationError:\n+ def test_msg(self):\n+ # GIVEN\n+ error = ValidationError(\"Test message\")\n+\n+ # THEN\n+ assert str(error) == \"Test message\"\n+\n+\n+class TestExpressionError:\n+ def test_msg(self):\n+ # GIVEN\n+ error = ExpressionError(\"Test message\")\n+\n+ # THEN\n+ assert str(error) == \"Test message\"\n+\n+\n+class TestTokenError:\n+ def test_msg(self):\n+ # GIVEN\n+ error = TokenError(\"0123456789\", \"5\", 5)\n+\n+ # THEN\n+ assert str(error) == \"Unexpected '5' in '0123456789' after '01234'\""}, {"sha": "f1f500fc3711eb06010d824bdf13b9d758722f69", "filename": "test/openjd/model/test_importable.py", "status": "added", "additions": 9, "deletions": 0, "changes": 9, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_importable.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_importable.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_importable.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,9 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+\n+def test_openjd_importable():\n+ import openjd # noqa: F401\n+\n+\n+def test_importable():\n+ import openjd.model # noqa: F401"}, {"sha": "82dd885e6f5c2448840f3eb64b49a88cff7438f0", "filename": "test/openjd/model/test_lexer.py", "status": "added", "additions": 102, "deletions": 0, "changes": 102, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_lexer.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_lexer.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_lexer.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,102 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from unittest.mock import patch\n+\n+import pytest\n+\n+from openjd.model import TokenError\n+from openjd.model._tokenstream import Lexer, Token, TokenType\n+\n+\n+class DotToken(Token):\n+ pass\n+\n+\n+class NameToken(Token):\n+ pass\n+\n+\n+_tokenmap = {TokenType.NAME: NameToken, TokenType.DOT: DotToken}\n+\n+\n+class TestLexer:\n+ def test_initialize_does_not_lex(self):\n+ with patch.object(Lexer, \"lex\") as mocked:\n+ # Given\n+\n+ # When\n+ Lexer(\"text\", supported_tokens=_tokenmap)\n+\n+ # Then\n+ mocked.assert_not_called()\n+\n+ @pytest.mark.parametrize(\"token\", [\"-\", \"+\", \"=\", \"*\", \"/\", \"'string'\"])\n+ def test_lex_nonvalid_tokens(self, token):\n+ # Given\n+\n+ # When\n+ tok = Lexer(token, supported_tokens=_tokenmap)\n+\n+ # Then\n+ with pytest.raises(TokenError):\n+ tok.lex()\n+\n+ @pytest.mark.parametrize(\n+ \"text\", [\"Job\", \"Task\", \"Test1\", \"multiple_words\", \"unicode_\u00c4\", \"\u00c4_unicode\", \"_Test\"]\n+ )\n+ def test_lex_name(self, text):\n+ # GIVEN\n+ tok = Lexer(text, supported_tokens=_tokenmap)\n+\n+ # WHEN\n+ tokens = tok.lex()\n+\n+ # THEN\n+ assert len(tokens) == 1\n+ assert isinstance(tokens[0], NameToken)\n+ assert tokens[0].value == text\n+\n+ def test_lex_dot(self):\n+ # GIVEN\n+ tok = Lexer(\".\", supported_tokens=_tokenmap)\n+\n+ # WHEN\n+ tokens = tok.lex()\n+\n+ # THEN\n+ assert len(tokens) == 1\n+ assert isinstance(tokens[0], DotToken)\n+\n+ @pytest.mark.parametrize(\n+ \"input,token_count\",\n+ [(\"test\", 1), (\".\", 1), (\"test.\", 2), (\".test\", 2), (\"..test..\", 5), (\"word1.word2\", 3)],\n+ )\n+ def test_multiple_valid_tokens(self, input, token_count):\n+ # Given\n+ # When\n+ tok = Lexer(input, supported_tokens=_tokenmap)\n+\n+ # Then\n+ assert len(tok.lex()) == token_count\n+\n+ @pytest.mark.parametrize(\"text\", [\"1Test\", \"^Test\"])\n+ def test_handles_nonvalid_tokens(self, text):\n+ # Given\n+ tok = Lexer(text, supported_tokens=_tokenmap)\n+\n+ # THEN\n+ with pytest.raises(TokenError):\n+ tok.lex()\n+\n+ def test_handles_emptystring(self):\n+ # GIVEN\n+ expr = \"\"\n+\n+ # WHEN\n+ tok = Lexer(expr, supported_tokens=_tokenmap)\n+\n+ # THEN\n+ try:\n+ tok.lex()\n+ except: # noqa: E722\n+ pytest.fail(\"Should not raise exception\")"}, {"sha": "eb5eccba86f0ba578d78d3ae42417860a3421269", "filename": "test/openjd/model/test_parse.py", "status": "added", "additions": 97, "deletions": 0, "changes": 97, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_parse.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_parse.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_parse.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,97 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import json\n+from typing import Any, Type\n+\n+import pytest\n+import yaml\n+\n+from openjd.model import (\n+ DecodeValidationError,\n+ DocumentType,\n+ decode_template,\n+ document_string_to_object,\n+)\n+from openjd.model._types import OpenJDModel\n+from openjd.model.v2023_09 import JobTemplate as JobTemplate_2023_09\n+\n+\n+class TestDocStringToObject:\n+ @pytest.mark.parametrize(\n+ \"document,doctype,expected\",\n+ [\n+ pytest.param(\n+ json.dumps({\"key\": \"value\"}), DocumentType.JSON, {\"key\": \"value\"}, id=\"json doc\"\n+ ),\n+ pytest.param(\n+ yaml.safe_dump({\"key\": \"value\"}), DocumentType.YAML, {\"key\": \"value\"}, id=\"yaml doc\"\n+ ),\n+ ],\n+ )\n+ def test_success(self, document: str, doctype: DocumentType, expected: dict[str, Any]) -> None:\n+ # WHEN\n+ result = document_string_to_object(document=document, document_type=doctype)\n+\n+ # THEN\n+ assert result == expected\n+\n+ @pytest.mark.parametrize(\n+ \"document,doctype\",\n+ [\n+ pytest.param(json.dumps([1, 2, 3]), DocumentType.JSON, id=\"json doc\"),\n+ pytest.param(yaml.safe_dump([1, 2, 3]), DocumentType.YAML, id=\"yaml doc\"),\n+ ],\n+ )\n+ def test_not_a_dict(self, document: str, doctype: DocumentType) -> None:\n+ # THEN\n+ with pytest.raises(DecodeValidationError):\n+ document_string_to_object(document=document, document_type=doctype)\n+\n+ @pytest.mark.parametrize(\n+ \"document,doctype\",\n+ [\n+ pytest.param(\"{\", DocumentType.JSON, id=\"json doc\"),\n+ pytest.param(\"-\", DocumentType.YAML, id=\"yaml doc\"),\n+ ],\n+ )\n+ def test_bad_parse(self, document: str, doctype: DocumentType) -> None:\n+ # THEN\n+ with pytest.raises(DecodeValidationError):\n+ document_string_to_object(document=document, document_type=doctype)\n+\n+\n+class TestDecodeTemplate:\n+ @pytest.mark.parametrize(\n+ \"template\",\n+ [\n+ pytest.param({\"notspecversion\": \"badvalue\"}, id=\"missing specificationVersion field\"),\n+ pytest.param({\"specificationVersion\": \"badvalue\"}, id=\"unknown version\"),\n+ ],\n+ )\n+ def test_fail_cases(self, template: dict[str, Any]) -> None:\n+ # THEN\n+ with pytest.raises(DecodeValidationError):\n+ decode_template(template=template)\n+\n+ @pytest.mark.parametrize(\n+ \"template,expected_class\",\n+ [\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"name\",\n+ \"steps\": [\n+ {\"name\": \"step\", \"script\": {\"actions\": {\"onRun\": {\"command\": \"do thing\"}}}}\n+ ],\n+ },\n+ JobTemplate_2023_09,\n+ id=\"2023-09\",\n+ ),\n+ ],\n+ )\n+ def test_success(self, template: dict[str, Any], expected_class: Type[OpenJDModel]) -> None:\n+ # WHEN\n+ result = decode_template(template=template)\n+\n+ # THEN\n+ assert isinstance(result, expected_class)"}, {"sha": "5d345dcc9114640ea1a924d16d754967a0cb9a6f", "filename": "test/openjd/model/test_step_dependency_graph.py", "status": "added", "additions": 114, "deletions": 0, "changes": 114, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_step_dependency_graph.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_step_dependency_graph.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_step_dependency_graph.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,114 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any, Optional\n+\n+from openjd.model import ( # StepDependencyGraphNode,; ,\n+ StepDependencyGraph,\n+ StepDependencyGraphStepToStepEdge,\n+ create_job,\n+ parse_model,\n+)\n+from openjd.model.v2023_09 import JobTemplate as JobTemplate_2023_09\n+\n+\n+class TestStepDependencyGraph_2023_09:\n+ def create_step_template(\n+ self, name: str, dependsOn: Optional[set[str]] = None\n+ ) -> dict[str, Any]:\n+ \"\"\"A helper for generating step template data.\"\"\"\n+ toreturn: dict[str, Any] = {\n+ \"name\": name,\n+ \"script\": {\"actions\": {\"onRun\": {\"command\": \"foo\"}}},\n+ }\n+ if dependsOn:\n+ toreturn[\"dependencies\"] = [{\"dependsOn\": dep} for dep in dependsOn]\n+ return toreturn\n+\n+ def test_empty_graph(self) -> None:\n+ # GIVEN\n+ template_data = {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Job\",\n+ \"steps\": [\n+ self.create_step_template(\"Foo\"),\n+ self.create_step_template(\"Bar\"),\n+ self.create_step_template(\"Buz\"),\n+ ],\n+ }\n+ job_template = parse_model(model=JobTemplate_2023_09, obj=template_data)\n+ job = create_job(job_template=job_template, job_parameter_values=dict())\n+\n+ # WHEN\n+ result = StepDependencyGraph(job=job)\n+\n+ # THEN\n+ assert len(result._nodes) == 3\n+ for name in (\"Foo\", \"Bar\", \"Buz\"):\n+ node = result.step_node(stepname=name)\n+ assert node.step.name == name\n+ assert len(node.in_edges) == 0\n+ assert len(node.out_edges) == 0\n+\n+ def test_with_deps(self) -> None:\n+ # GIVEN\n+ template_data = {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Job\",\n+ \"steps\": [\n+ self.create_step_template(\"Foo\", {\"Buz\"}),\n+ self.create_step_template(\"Bar\", {\"Foo\", \"Buz\"}),\n+ self.create_step_template(\"Buz\"),\n+ ],\n+ }\n+ job_template = parse_model(model=JobTemplate_2023_09, obj=template_data)\n+ job = create_job(job_template=job_template, job_parameter_values=dict())\n+\n+ # WHEN\n+ result = StepDependencyGraph(job=job)\n+\n+ # THEN\n+ assert len(result._nodes) == 3\n+\n+ # Check Foo's deps\n+ node = result.step_node(stepname=\"Foo\")\n+ assert node.step.name == \"Foo\"\n+\n+ assert len(node.in_edges) == 1\n+ edge = node.in_edges[0]\n+ assert type(edge) is StepDependencyGraphStepToStepEdge\n+ assert edge.origin.step.name == \"Buz\"\n+ assert edge.dependent.step.name == \"Foo\"\n+\n+ assert len(node.out_edges) == 1\n+ edge = node.out_edges[0]\n+ assert type(edge) is StepDependencyGraphStepToStepEdge\n+ assert edge.origin.step.name == \"Foo\"\n+ assert edge.dependent.step.name == \"Bar\"\n+\n+ # Check Bar's deps\n+ node = result.step_node(stepname=\"Bar\")\n+ assert node.step.name == \"Bar\"\n+\n+ assert len(node.in_edges) == 2\n+ edge1, edge2 = node.in_edges\n+ assert type(edge1) is StepDependencyGraphStepToStepEdge\n+ assert type(edge2) is StepDependencyGraphStepToStepEdge\n+ assert edge1.origin.step.name == \"Foo\" or edge2.origin.step.name == \"Foo\"\n+ assert edge1.origin.step.name == \"Buz\" or edge2.origin.step.name == \"Buz\"\n+ assert edge1.dependent.step.name == \"Bar\"\n+ assert edge2.dependent.step.name == \"Bar\"\n+\n+ assert len(node.out_edges) == 0\n+\n+ # Check Buz's deps\n+ node = result.step_node(stepname=\"Buz\")\n+ assert node.step.name == \"Buz\"\n+ assert len(node.in_edges) == 0\n+ assert len(node.out_edges) == 2\n+ edge1, edge2 = node.out_edges\n+ assert type(edge1) is StepDependencyGraphStepToStepEdge\n+ assert type(edge2) is StepDependencyGraphStepToStepEdge\n+ assert edge1.origin.step.name == \"Buz\"\n+ assert edge2.origin.step.name == \"Buz\"\n+ assert edge1.dependent.step.name == \"Foo\" or edge2.dependent.step.name == \"Foo\"\n+ assert edge1.dependent.step.name == \"Bar\" or edge2.dependent.step.name == \"Bar\""}, {"sha": "1be56e57a82a180b43ad32f3b1910dc6a3430410", "filename": "test/openjd/model/test_step_param_space_iter.py", "status": "added", "additions": 448, "deletions": 0, "changes": 448, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_step_param_space_iter.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_step_param_space_iter.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_step_param_space_iter.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,448 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Callable, Union\n+\n+import pytest\n+\n+from openjd.model import (\n+ ParameterValue,\n+ ParameterValueType,\n+ StepParameterSpaceIterator,\n+)\n+from openjd.model.v2023_09 import (\n+ RangeExpressionTaskParameterDefinition as RangeExpressionTaskParameterDefinition_2023_09,\n+)\n+from openjd.model.v2023_09 import (\n+ RangeListTaskParameterDefinition as RangeListTaskParameterDefinition_2023_09,\n+)\n+from openjd.model.v2023_09 import (\n+ StepParameterSpace as StepParameterSpace_2023_09,\n+)\n+\n+RangeTaskParameter = Union[\n+ RangeListTaskParameterDefinition_2023_09, RangeExpressionTaskParameterDefinition_2023_09\n+]\n+\n+\n+class TestStepParameterSpaceIterator_2023_09: # noqa: N801\n+ @pytest.mark.parametrize(\n+ \"range_int_param\",\n+ [\n+ RangeListTaskParameterDefinition_2023_09(type=ParameterValueType.INT, range=[1, 2]),\n+ RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"1-2\"\n+ ),\n+ ],\n+ )\n+ def test_names(self, range_int_param):\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": range_int_param,\n+ \"Param2\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.STRING, range=[\"a\", \"b\", \"c\"]\n+ ),\n+ }\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ assert result.names == set((\"Param1\", \"Param2\"))\n+\n+ @pytest.mark.parametrize(\n+ \"range_int_param\",\n+ [\n+ RangeListTaskParameterDefinition_2023_09(type=ParameterValueType.INT, range=[1, 2]),\n+ RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"1-2\"\n+ ),\n+ ],\n+ )\n+ def test_single_param_iteration(self, range_int_param):\n+ # GIVEN\n+ expected = [1, 2]\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": range_int_param,\n+ }\n+ )\n+ iterator = StepParameterSpaceIterator(space=space)\n+\n+ # WHEN\n+ it = iter(iterator)\n+\n+ # THEN\n+ for i in range(len(expected)):\n+ assert {\n+ \"Param1\": ParameterValue(type=ParameterValueType.INT, value=str(expected[i]))\n+ } == next(it), f\"i = {i}\"\n+ with pytest.raises(StopIteration):\n+ next(it)\n+\n+ @pytest.mark.parametrize(\"param_range\", [[10], [10, 11, 12, 13, 14, 15]])\n+ def test_single_param_getelem(self, param_range):\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=param_range\n+ ),\n+ }\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ with pytest.raises(IndexError):\n+ result[len(param_range)]\n+ with pytest.raises(IndexError):\n+ result[-len(param_range) - 1]\n+ expected = [\n+ {\"Param1\": ParameterValue(type=ParameterValueType.INT, value=str(v))}\n+ for v in param_range\n+ ]\n+ assert [result[i] for i in range(0, len(param_range))] == expected\n+ range_reversed = param_range.copy()\n+ range_reversed.reverse()\n+ expected.reverse()\n+ assert [result[-i - 1] for i in range(0, len(param_range))] == expected\n+\n+ @pytest.mark.parametrize(\n+ \"given, expected\",\n+ [\n+ ([1, 2, 3], 3),\n+ (\"1-5\", 5),\n+ ([\"a\", \"b\", \"c\", \"d\"], 4),\n+ ],\n+ )\n+ def test_single_param_len(self, given, expected) -> None:\n+ # GIVEN\n+ range_int_param: RangeTaskParameter\n+ if isinstance(given, list):\n+ range_int_param = RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=given\n+ )\n+ elif isinstance(given, str):\n+ range_int_param = RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=given\n+ )\n+\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": range_int_param,\n+ }\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ assert len(result) == expected\n+ # Test twice. We do some caching of lengths. Test the caching flows.\n+ assert len(result) == expected\n+\n+ @pytest.mark.parametrize(\n+ \"range_int_param\",\n+ [\n+ RangeListTaskParameterDefinition_2023_09(type=ParameterValueType.INT, range=[1, 2]),\n+ RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"1-2\"\n+ ),\n+ ],\n+ )\n+ def test_defaults_product(\n+ self, range_int_param: RangeListTaskParameterDefinition_2023_09\n+ ) -> None:\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": range_int_param,\n+ \"Param2\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.STRING, range=[\"a\", \"b\"]\n+ ),\n+ }\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ # The combination_expr should default to \"Param1 * Param2\"\n+ assert len(result) == 2 * 2\n+ element: Callable[[int, str], dict[str, ParameterValue]] = lambda p1, p2: {\n+ \"Param1\": ParameterValue(type=ParameterValueType.INT, value=str(p1)),\n+ \"Param2\": ParameterValue(type=ParameterValueType.STRING, value=str(p2)),\n+ }\n+ expected_values = (\n+ element(1, \"a\"),\n+ element(1, \"b\"),\n+ element(2, \"a\"),\n+ element(2, \"b\"),\n+ )\n+ assert expected_values == tuple(v for v in result)\n+\n+ def test_product_iteration(self) -> None:\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=[1, 2]\n+ ),\n+ \"Param2\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.STRING, range=[\"a\", \"b\", \"c\"]\n+ ),\n+ \"Param3\": RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"-1 - -2 : -1\"\n+ ),\n+ },\n+ combination=\"Param1 * Param2 * Param3\",\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ element: Callable[[int, str, int], dict[str, ParameterValue]] = lambda p1, p2, p3: {\n+ \"Param1\": ParameterValue(type=ParameterValueType.INT, value=str(p1)),\n+ \"Param2\": ParameterValue(type=ParameterValueType.STRING, value=str(p2)),\n+ \"Param3\": ParameterValue(type=ParameterValueType.INT, value=str(p3)),\n+ }\n+ expected_values = [\n+ element(1, \"a\", -1),\n+ element(1, \"a\", -2),\n+ element(1, \"b\", -1),\n+ element(1, \"b\", -2),\n+ element(1, \"c\", -1),\n+ element(1, \"c\", -2),\n+ element(2, \"a\", -1),\n+ element(2, \"a\", -2),\n+ element(2, \"b\", -1),\n+ element(2, \"b\", -2),\n+ element(2, \"c\", -1),\n+ element(2, \"c\", -2),\n+ ]\n+ assert expected_values == [v for v in result]\n+\n+ def test_product_len(self):\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"1-2:1\"\n+ ),\n+ \"Param2\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.STRING, range=[\"a\", \"b\", \"c\"]\n+ ),\n+ \"Param3\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=[-1, -2]\n+ ),\n+ },\n+ combination=\"Param1 * Param2 * Param3\",\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ assert len(result) == 2 * 3 * 2\n+ # Test twice. We do some caching of lengths. Test the caching flows.\n+ assert len(result) == 2 * 3 * 2\n+\n+ def test_product_getitem(self) -> None:\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=[1, 2]\n+ ),\n+ \"Param2\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.STRING, range=[\"a\", \"b\", \"c\"]\n+ ),\n+ \"Param3\": RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"-1--2:-1\"\n+ ),\n+ },\n+ combination=\"Param1 * Param2 * Param3\",\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ element: Callable[[int, str, int], dict[str, ParameterValue]] = lambda p1, p2, p3: {\n+ \"Param1\": ParameterValue(type=ParameterValueType.INT, value=str(p1)),\n+ \"Param2\": ParameterValue(type=ParameterValueType.STRING, value=str(p2)),\n+ \"Param3\": ParameterValue(type=ParameterValueType.INT, value=str(p3)),\n+ }\n+ expected_values = [\n+ element(1, \"a\", -1),\n+ element(1, \"a\", -2),\n+ element(1, \"b\", -1),\n+ element(1, \"b\", -2),\n+ element(1, \"c\", -1),\n+ element(1, \"c\", -2),\n+ element(2, \"a\", -1),\n+ element(2, \"a\", -2),\n+ element(2, \"b\", -1),\n+ element(2, \"b\", -2),\n+ element(2, \"c\", -1),\n+ element(2, \"c\", -2),\n+ ]\n+ with pytest.raises(IndexError):\n+ result[len(expected_values)]\n+ with pytest.raises(IndexError):\n+ result[-len(expected_values) - 1]\n+ assert expected_values == [result[i] for i in range(0, len(expected_values))]\n+ expected_reversed = expected_values.copy()\n+ expected_reversed.reverse()\n+ assert expected_reversed == [result[-i - 1] for i in range(0, len(expected_values))]\n+\n+ def test_associate_iteration(self) -> None:\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"1-4\"\n+ ),\n+ \"Param2\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.STRING, range=[\"a\", \"b\", \"c\", \"d\"]\n+ ),\n+ \"Param3\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=[-1, -2, -3, -4]\n+ ),\n+ },\n+ combination=\"(Param1, Param2, Param3)\",\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ element: Callable[[int, str, int], dict[str, ParameterValue]] = lambda p1, p2, p3: {\n+ \"Param1\": ParameterValue(type=ParameterValueType.INT, value=str(p1)),\n+ \"Param2\": ParameterValue(type=ParameterValueType.STRING, value=str(p2)),\n+ \"Param3\": ParameterValue(type=ParameterValueType.INT, value=str(p3)),\n+ }\n+ expected_values = [\n+ element(1, \"a\", -1),\n+ element(2, \"b\", -2),\n+ element(3, \"c\", -3),\n+ element(4, \"d\", -4),\n+ ]\n+ assert expected_values == [v for v in result]\n+\n+ def test_associate_len(self) -> None:\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=[1, 2, 3, 4]\n+ ),\n+ \"Param2\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.STRING, range=[\"a\", \"b\", \"c\", \"d\"]\n+ ),\n+ \"Param3\": RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"-1--4:-1\"\n+ ),\n+ },\n+ combination=\"(Param1, Param2, Param3)\",\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ assert len(result) == 4\n+ # Test twice. We do some caching of lengths. Test the caching flows.\n+ assert len(result) == 4\n+\n+ def test_associate_getitem(self) -> None:\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"1-4\"\n+ ),\n+ \"Param2\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.STRING, range=[\"a\", \"b\", \"c\", \"d\"]\n+ ),\n+ \"Param3\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=[-1, -2, -3, -4]\n+ ),\n+ },\n+ combination=\"(Param1, Param2, Param3)\",\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ element: Callable[[int, str, int], dict[str, ParameterValue]] = lambda p1, p2, p3: {\n+ \"Param1\": ParameterValue(type=ParameterValueType.INT, value=str(p1)),\n+ \"Param2\": ParameterValue(type=ParameterValueType.STRING, value=str(p2)),\n+ \"Param3\": ParameterValue(type=ParameterValueType.INT, value=str(p3)),\n+ }\n+ expected_values = [\n+ element(1, \"a\", -1),\n+ element(2, \"b\", -2),\n+ element(3, \"c\", -3),\n+ element(4, \"d\", -4),\n+ ]\n+ with pytest.raises(IndexError):\n+ result[len(expected_values)]\n+ with pytest.raises(IndexError):\n+ result[-len(expected_values) - 1]\n+ assert expected_values == [result[i] for i in range(0, len(expected_values))]\n+ expected_reversed = expected_values.copy()\n+ expected_reversed.reverse()\n+ assert expected_reversed == [result[-i - 1] for i in range(0, len(expected_values))]\n+\n+ def test_nested_expr_iteration(self) -> None:\n+ # A more deeply nested test to hit all of the recursive edge cases.\n+ # Namely ensure that we hit the iterator resets in the implementation.\n+\n+ # GIVEN\n+ space = StepParameterSpace_2023_09(\n+ taskParameterDefinitions={\n+ \"Param1\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=[1, 2]\n+ ),\n+ \"Param2\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.STRING, range=[\"a\", \"b\", \"c\", \"d\"]\n+ ),\n+ \"Param3\": RangeExpressionTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=\"10-11\"\n+ ),\n+ \"Param4\": RangeListTaskParameterDefinition_2023_09(\n+ type=ParameterValueType.INT, range=[20, 21]\n+ ),\n+ },\n+ combination=\"Param1 * ( Param2, Param3 * Param4 )\",\n+ )\n+\n+ # WHEN\n+ result = StepParameterSpaceIterator(space=space)\n+\n+ # THEN\n+ element: Callable[\n+ [int, str, int, int], dict[str, ParameterValue]\n+ ] = lambda p1, p2, p3, p4: {\n+ \"Param1\": ParameterValue(type=ParameterValueType.INT, value=str(p1)),\n+ \"Param2\": ParameterValue(type=ParameterValueType.STRING, value=str(p2)),\n+ \"Param3\": ParameterValue(type=ParameterValueType.INT, value=str(p3)),\n+ \"Param4\": ParameterValue(type=ParameterValueType.INT, value=str(p4)),\n+ }\n+ expected_values = [\n+ element(1, \"a\", 10, 20),\n+ element(1, \"b\", 10, 21),\n+ element(1, \"c\", 11, 20),\n+ element(1, \"d\", 11, 21),\n+ element(2, \"a\", 10, 20),\n+ element(2, \"b\", 10, 21),\n+ element(2, \"c\", 11, 20),\n+ element(2, \"d\", 11, 21),\n+ ]\n+ assert expected_values == [v for v in result]"}, {"sha": "580e0f2cdfa74f6f1eeb2992a9d7c06bbbd2e915", "filename": "test/openjd/model/test_symbol_table.py", "status": "added", "additions": 139, "deletions": 0, "changes": 139, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_symbol_table.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_symbol_table.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_symbol_table.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,139 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+\n+import pytest\n+\n+from openjd.model import SymbolTable\n+\n+\n+class TestSymbolTable:\n+ def test_bad_symbol_type(self):\n+ table = SymbolTable()\n+ with pytest.raises(TypeError):\n+ table[4] = 12 # type: ignore # The point is to verify incorrect type\n+\n+ def test_copy_construct_from_symtab(self):\n+ # GIVEN\n+ given = SymbolTable()\n+ given[\"Test.Symtab1\"] = \"One\"\n+ given[\"Test.Symtab2\"] = 1\n+\n+ # WHEN\n+ result = SymbolTable(source=given)\n+\n+ # THEN\n+ assert result.symbols == set((\"Test.Symtab1\", \"Test.Symtab2\"))\n+ assert result[\"Test.Symtab1\"] == \"One\"\n+ assert result[\"Test.Symtab2\"] == 1\n+\n+ def test_copy_construct_from_dict(self):\n+ # GIVEN\n+ given = {\"Test.Symtab1\": \"One\", \"Test.Symtab2\": 1}\n+\n+ # WHEN\n+ result = SymbolTable(source=given)\n+\n+ # THEN\n+ assert result.symbols == set((\"Test.Symtab1\", \"Test.Symtab2\"))\n+ assert result[\"Test.Symtab1\"] == \"One\"\n+ assert result[\"Test.Symtab2\"] == 1\n+\n+ def test_copy_construct_from_badtype(self) -> None:\n+ # GIVEN\n+ given: list[str] = list()\n+\n+ # THEN\n+ with pytest.raises(TypeError):\n+ SymbolTable(source=given) # type: ignore # Purpose is to check type validation\n+\n+ @pytest.mark.parametrize(\"value\", [0, 4, 7.4, \"Value\"])\n+ def test_add_value(self, value):\n+ table = SymbolTable()\n+ table[\"Test\"] = value\n+\n+ symbols = table.symbols\n+ assert {\"Test\"} == symbols\n+ assert \"Test\" in table, \"Test __contains__\"\n+ assert table[\"Test\"] == value\n+\n+ def test_union(self):\n+ # GIVEN\n+ symtab1 = SymbolTable()\n+ symtab1[\"Test.Symtab1\"] = \"One\"\n+ symtab1[\"Overlap1\"] = 1\n+ symtab2 = SymbolTable()\n+ symtab2[\"Test.Symtab2\"] = \"Two\"\n+ symtab2[\"Overlap1\"] = 2\n+ symtab2[\"Overlap2\"] = 2\n+\n+ # WHEN\n+ result = symtab1.union(symtab2)\n+\n+ # THEN\n+ assert result is not symtab1\n+ symbols = result.symbols\n+ assert {\"Test.Symtab1\", \"Test.Symtab2\", \"Overlap1\", \"Overlap2\"} == symbols\n+ assert result[\"Test.Symtab1\"] == \"One\"\n+ assert result[\"Test.Symtab2\"] == \"Two\"\n+ assert result[\"Overlap1\"] == 2, \"Later arguments win duplicates\"\n+ assert result[\"Overlap2\"] == 2\n+\n+ def test_union_dict(self) -> None:\n+ # GIVEN\n+ symtab1 = SymbolTable()\n+ symtab1[\"Test.Symtab1\"] = \"One\"\n+ symtab1[\"Overlap1\"] = 1\n+ symtab2: dict[str, Any] = dict()\n+ symtab2[\"Test.Symtab2\"] = \"Two\"\n+ symtab2[\"Overlap1\"] = 2\n+ symtab2[\"Overlap2\"] = 2\n+\n+ # WHEN\n+ result = symtab1.union(symtab2)\n+\n+ # THEN\n+ assert result is not symtab1\n+ symbols = result.symbols\n+ assert {\"Test.Symtab1\", \"Test.Symtab2\", \"Overlap1\", \"Overlap2\"} == symbols\n+ assert result[\"Test.Symtab1\"] == \"One\"\n+ assert result[\"Test.Symtab2\"] == \"Two\"\n+ assert result[\"Overlap1\"] == 2, \"Later arguments win duplicates\"\n+ assert result[\"Overlap2\"] == 2\n+\n+ def test_union_bad_type(self) -> None:\n+ # GIVEN\n+ symtab1 = SymbolTable()\n+ symtab1[\"Test.Symtab1\"] = \"One\"\n+ symtab1[\"Overlap1\"] = 1\n+ symtab2: list[str] = list()\n+\n+ # THEN\n+ with pytest.raises(TypeError):\n+ symtab1.union(symtab2) # type: ignore # Purpose is to validate type check\n+\n+ def test_union_multiple(self):\n+ # GIVEN\n+ symtab1 = SymbolTable()\n+ symtab1[\"Test.Symtab1\"] = \"One\"\n+ symtab1[\"Overlap1\"] = 1\n+ symtab2 = SymbolTable()\n+ symtab2[\"Test.Symtab2\"] = \"Two\"\n+ symtab2[\"Overlap1\"] = 2\n+ symtab2[\"Overlap2\"] = 2\n+ symtab3 = SymbolTable()\n+ symtab3[\"Test.Symtab3\"] = \"Three\"\n+ symtab3[\"Overlap2\"] = 3\n+\n+ # WHEN\n+ result = symtab1.union(symtab2, symtab3)\n+\n+ # THEN\n+ assert result is not symtab1\n+ symbols = result.symbols\n+ assert {\"Test.Symtab1\", \"Test.Symtab2\", \"Test.Symtab3\", \"Overlap1\", \"Overlap2\"} == symbols\n+ assert result[\"Test.Symtab1\"] == \"One\"\n+ assert result[\"Test.Symtab2\"] == \"Two\"\n+ assert result[\"Test.Symtab3\"] == \"Three\"\n+ assert result[\"Overlap1\"] == 2, \"Later arguments win duplicates\"\n+ assert result[\"Overlap2\"] == 3, \"Later arguments win duplicates\""}, {"sha": "992d3cdf666a433d8ef93e323b5894a2ce8d2010", "filename": "test/openjd/model/test_tokenstream.py", "status": "added", "additions": 111, "deletions": 0, "changes": 111, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_tokenstream.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Ftest_tokenstream.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Ftest_tokenstream.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,111 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from unittest.mock import patch\n+\n+import pytest\n+\n+from openjd.model import TokenError\n+from openjd.model._tokenstream import Lexer, Token, TokenStream, TokenType\n+\n+\n+class DotToken(Token):\n+ pass\n+\n+\n+class NameToken(Token):\n+ pass\n+\n+\n+_tokenmap = {TokenType.NAME: NameToken, TokenType.DOT: DotToken}\n+\n+\n+class TestTokenStream:\n+ def test_next(self):\n+ # GIVEN\n+ expr = \"Foo.Bar\"\n+\n+ # WHEN\n+ tokstream = TokenStream(expr, supported_tokens=_tokenmap)\n+\n+ # THEN\n+ # We expect the token stream to be:\n+ # [NameToken(\"Foo\"), DotToken, NameToken(\"Bar\")]\n+ tok = tokstream.next()\n+ assert isinstance(tok, NameToken)\n+ assert tok.value == \"Foo\"\n+ tok = tokstream.next()\n+ assert isinstance(tok, DotToken)\n+ tok = tokstream.next()\n+ assert isinstance(tok, NameToken)\n+ assert tok.value == \"Bar\"\n+ assert tokstream.at_end() is True\n+ with pytest.raises(IndexError):\n+ tokstream.next()\n+\n+ def test_get_position(self):\n+ # GIVEN\n+ expr = \"Foo.Bar\"\n+\n+ # WHEN\n+ tokstream = TokenStream(expr, supported_tokens=_tokenmap)\n+\n+ # THEN\n+ # We expect the token stream to be:\n+ # [NameToken(\"Foo\"), DotToken, NameToken(\"Bar\")]\n+ assert tokstream.expr_position == 0\n+ tokstream.next()\n+ assert tokstream.expr_position == 3\n+ tokstream.next()\n+ assert tokstream.expr_position == 4\n+ tokstream.next()\n+ assert tokstream.expr_position == 7\n+ assert tokstream.at_end() is True\n+\n+ def test_lookahead(self):\n+ # GIVEN\n+ expr = \"Foo.Bar\"\n+\n+ # WHEN\n+ tokstream = TokenStream(expr, supported_tokens=_tokenmap)\n+\n+ # THEN\n+ # We expect the token stream to be:\n+ # [NameToken(\"Foo\"), DotToken, NameToken(\"Bar\")]\n+ with pytest.raises(ValueError):\n+ tokstream.lookahead(-1)\n+ tok = tokstream.lookahead(0)\n+ assert isinstance(tok, NameToken)\n+ assert tok.value == \"Foo\"\n+ tok = tokstream.lookahead(1)\n+ assert isinstance(tok, DotToken)\n+ tok = tokstream.lookahead(2)\n+ assert isinstance(tok, NameToken)\n+ assert tok.value == \"Bar\"\n+ with pytest.raises(IndexError):\n+ tokstream.lookahead(3)\n+\n+ def test_propagates_error(self):\n+ with patch.object(Lexer, \"lex\") as mock:\n+ # GIVEN\n+ mock.side_effect = TokenError(\"mocked expr\", \"mocked\", 0)\n+\n+ # THEN\n+ with pytest.raises(TokenError):\n+ TokenStream(\"Foo.Bar\", supported_tokens=_tokenmap)\n+\n+ def test_tokenize_whitespace(self):\n+ # GIVEN\n+ expr = \" Name1\\t\\t\\t \\n\\n\\nName2 \"\n+\n+ # WHEN\n+ tokstream = TokenStream(expr, supported_tokens=_tokenmap)\n+\n+ # THEN\n+ tok = tokstream.next()\n+ assert isinstance(tok, NameToken)\n+ assert tok.value == \"Name1\"\n+ tok = tokstream.next()\n+ assert isinstance(tok, NameToken)\n+ assert tok.value == \"Name2\"\n+ assert tokstream.at_end() is True\n+ assert tokstream.expr == \"Name1 Name2\""}, {"sha": "8d929cc86d4cee38bb56224a89d095bcbdcdfbf0", "filename": "test/openjd/model/v2023_09/__init__.py", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2F__init__.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2F__init__.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2F__init__.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved."}, {"sha": "e4c150bf103a35db27b4f7c24db59e453f493924", "filename": "test/openjd/model/v2023_09/test_action.py", "status": "added", "additions": 206, "deletions": 0, "changes": 206, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_action.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_action.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_action.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,206 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import Action, EnvironmentActions, StepActions\n+\n+\n+class TestAction:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"command\": \"1\"}, id=\"command min len\"),\n+ pytest.param({\"command\": \"1\" * (32 * 1024)}, id=\"command really long len\"),\n+ pytest.param({\"command\": \"{{ Job.Parameter.Foo }}\"}, id=\"command format string\"),\n+ pytest.param({\"command\": \"foo\", \"args\": [\"\"]}, id=\"arg min item len\"),\n+ pytest.param({\"command\": \"foo\", \"args\": [\"1\" * (32 * 1024)]}, id=\"arg really long len\"),\n+ pytest.param({\"command\": \"foo\", \"args\": [\"1\"] * (32 * 64)}, id=\"arg many items\"),\n+ pytest.param(\n+ {\"command\": \"foo\", \"args\": [\"{{ Job.Parameter.Foo }}\"]}, id=\"arg arg format string\"\n+ ),\n+ pytest.param({\"command\": \"foo\", \"timeout\": 1}, id=\"timeout min value\"),\n+ pytest.param({\"command\": \"foo\", \"timeout\": 600}, id=\"timeout max value\"),\n+ pytest.param({\"command\": \"foo\", \"timeout\": \"1\"}, id=\"timeout intstring\"),\n+ pytest.param(\n+ {\"command\": \"foo\", \"cancelation\": {\"mode\": \"TERMINATE\"}}, id=\"cancel terminate\"\n+ ),\n+ pytest.param(\n+ {\n+ \"command\": \"foo\",\n+ \"cancelation\": {\"mode\": \"NOTIFY_THEN_TERMINATE\", \"notifyPeriodInSeconds\": 1},\n+ },\n+ id=\"cancel notify min value\",\n+ ),\n+ pytest.param(\n+ {\n+ \"command\": \"foo\",\n+ \"cancelation\": {\"mode\": \"NOTIFY_THEN_TERMINATE\", \"notifyPeriodInSeconds\": \"1\"},\n+ },\n+ id=\"cancel notify as string\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description Actions\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our Action model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=Action, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"command\": \"foo\", \"extra\": 12}, id=\"unknown key\"),\n+ pytest.param({\"command\": \"\"}, id=\"command too short\"),\n+ pytest.param(\n+ {\"command\": \"{{ Job.Parameter.Foo \"}, id=\"command malformed format string\"\n+ ),\n+ pytest.param({\"command\": 1}, id=\"command not a string\"),\n+ pytest.param({\"command\": \"1\", \"args\": []}, id=\"args no items\"),\n+ pytest.param({\"command\": \"1\", \"args\": [12]}, id=\"args item not string\"),\n+ pytest.param({\"command\": \"1\", \"timeout\": 0}, id=\"timeout too small\"),\n+ pytest.param({\"command\": \"1\", \"timeout\": 601}, id=\"timeout too large\"),\n+ pytest.param({\"command\": \"1\", \"timeout\": 0.5}, id=\"timeout not int\"),\n+ pytest.param({\"command\": \"1\", \"timeout\": \"0.5\"}, id=\"timeout not intstring\"),\n+ pytest.param({\"command\": \"1\", \"cancelation\": \"TERMINATE\"}, id=\"cancelation not obj\"),\n+ pytest.param(\n+ {\"command\": \"1\", \"cancelation\": {\"mode\": \"UNKNOWN\"}}, id=\"cancelation unknown mode\"\n+ ),\n+ pytest.param(\n+ {\"command\": \"1\", \"cancelation\": {\"mode\": \"terminate\"}},\n+ id=\"cancelation terminate lowercase\",\n+ ),\n+ pytest.param(\n+ {\"command\": \"1\", \"cancelation\": {\"mode\": \"notify_then_terminate\"}},\n+ id=\"cancelation notify-terminate lowercase\",\n+ ),\n+ pytest.param(\n+ {\n+ \"command\": \"1\",\n+ \"cancelation\": {\"mode\": \"NOTIFY_THEN_TERMINATE\", \"notifyPeriodInSeconds\": 0},\n+ },\n+ id=\"cancelation notify too small\",\n+ ),\n+ pytest.param(\n+ {\n+ \"command\": \"1\",\n+ \"cancelation\": {\"mode\": \"NOTIFY_THEN_TERMINATE\", \"notifyPeriodInSeconds\": 0.5},\n+ },\n+ id=\"cancelation notify is float\",\n+ ),\n+ pytest.param(\n+ {\n+ \"command\": \"1\",\n+ \"cancelation\": {\n+ \"mode\": \"NOTIFY_THEN_TERMINATE\",\n+ \"notifyPeriodInSeconds\": \"0.5\",\n+ },\n+ },\n+ id=\"cancelation notify not intstring\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description Actions.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=StepActions, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestStepActions:\n+ @pytest.mark.parametrize(\n+ \"data\", (pytest.param({\"onRun\": {\"command\": \"foo\"}}, id=\"has required\"),)\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description StepActions\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our StepActions model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=StepActions, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"onRun\": {\"command\": \"foo\"}, \"onUnknown\": \"blah\"}, id=\"unknown field\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description StepActions.\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=Action, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestEnvironmentActions:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"onEnter\": {\"command\": \"foo\"}}, id=\"has onEnter\"),\n+ pytest.param({\"onExit\": {\"command\": \"foo\"}}, id=\"has onExit\"),\n+ # For making sure our pre-validator logic is correct\n+ pytest.param(\n+ {\n+ \"onEnter\": {\"command\": \"foo\"},\n+ \"onExit\": {\"command\": \"foo\"},\n+ },\n+ id=\"has both\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description StepActions\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our StepActions model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=EnvironmentActions, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"onEnter\": {\"command\": \"foo\"}, \"onUnknown\": \"blah\"}, id=\"unknown field\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description StepActions.\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=EnvironmentActions, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0"}, {"sha": "b10e98cc5a70b3e07e79d10d8082c6d68bdbe1e7", "filename": "test/openjd/model/v2023_09/test_create.py", "status": "added", "additions": 396, "deletions": 0, "changes": 396, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_create.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_create.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_create.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,396 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+# Testing for the model metadata annotations that assist in generating a Job from the\n+# Job Template\n+\n+from openjd.model import ParameterValue, ParameterValueType, create_job\n+from openjd.model.v2023_09 import (\n+ Action,\n+ AmountRequirement,\n+ AmountRequirementTemplate,\n+ AttributeRequirement,\n+ AttributeRequirementTemplate,\n+ CancelationMethodNotifyThenTerminate,\n+ CancelationMethodTerminate,\n+ EmbeddedFileText,\n+ Environment,\n+ EnvironmentActions,\n+ EnvironmentScript,\n+ FloatTaskParameterDefinition,\n+ HostRequirements,\n+ HostRequirementsTemplate,\n+ IntTaskParameterDefinition,\n+ Job,\n+ JobFloatParameterDefinition,\n+ JobIntParameterDefinition,\n+ JobParameter,\n+ JobStringParameterDefinition,\n+ JobTemplate,\n+ RangeExpressionTaskParameterDefinition,\n+ RangeListTaskParameterDefinition,\n+ Step,\n+ StepActions,\n+ StepParameterSpace,\n+ StepParameterSpaceDefinition,\n+ StepScript,\n+ StepTemplate,\n+ StringTaskParameterDefinition,\n+)\n+\n+\n+class TestCreateJob:\n+ def test(self) -> None:\n+ # One big test that does everything relevant for the create-job annotations.\n+ # Should be the only test that we need.\n+ #\n+ # Key things:\n+ # 1) Every format string has a job parameter reference - only some should be\n+ # evaluated when creating jobs\n+ # Specifically, only job name & task parameter range values should be evaluated.\n+ # 2) Every entity and every field that exists is defined at least once.\n+ # 3) Testing of _internal.create_job covers corner cases & exceptions; we don't worry\n+ # about those here.\n+\n+ # GIVEN\n+ extra_kwargs = {\"$schema\": \"blah \"} # special snowflake due to field naming\n+ template = JobTemplate(\n+ **extra_kwargs,\n+ specificationVersion=\"jobtemplate-2023-09\",\n+ name=\"{{ Param.StringParam }}\",\n+ description=\"job description\",\n+ jobEnvironments=[\n+ Environment(\n+ name=\"JobEnv\",\n+ description=\"desc\",\n+ script=EnvironmentScript(\n+ embeddedFiles=[\n+ EmbeddedFileText(\n+ name=\"File\",\n+ type=\"TEXT\",\n+ data=\"some data {{ Param.IntParam }}\",\n+ filename=\"filename.txt\",\n+ runnable=False,\n+ )\n+ ],\n+ actions=EnvironmentActions(\n+ onEnter=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodTerminate(mode=\"TERMINATE\"),\n+ ),\n+ onExit=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodNotifyThenTerminate(\n+ mode=\"NOTIFY_THEN_TERMINATE\", notifyPeriodInSeconds=30\n+ ),\n+ ),\n+ ),\n+ ),\n+ )\n+ ],\n+ parameterDefinitions=[\n+ JobStringParameterDefinition(\n+ name=\"StringParam\",\n+ type=\"STRING\",\n+ description=\"desc\",\n+ minLength=1,\n+ maxLength=20,\n+ allowedValues=[\"TheJobName\", \"TheOtherJobName\"],\n+ default=\"TheOtherJobName\",\n+ ),\n+ JobStringParameterDefinition(\n+ name=\"AttrCapabilityName\",\n+ type=\"STRING\",\n+ description=\"desc\",\n+ minLength=1,\n+ maxLength=20,\n+ default=\"attr.mycapability\",\n+ ),\n+ JobStringParameterDefinition(\n+ name=\"AmountCapabilityName\",\n+ type=\"STRING\",\n+ description=\"desc\",\n+ minLength=1,\n+ maxLength=20,\n+ default=\"amount.mycapability\",\n+ ),\n+ JobIntParameterDefinition(\n+ name=\"RangeExpressionParam\",\n+ type=\"INT\",\n+ description=\"desc\",\n+ minValue=0,\n+ maxValue=100,\n+ allowedValues=[3, 75],\n+ default=75,\n+ ),\n+ JobIntParameterDefinition(\n+ name=\"IntParam\",\n+ type=\"INT\",\n+ description=\"desc\",\n+ minValue=0,\n+ maxValue=100,\n+ allowedValues=[5, 10, 20],\n+ default=20,\n+ ),\n+ JobFloatParameterDefinition(\n+ name=\"FloatParam\",\n+ type=\"FLOAT\",\n+ description=\"desc\",\n+ minValue=0.0,\n+ maxValue=100.5,\n+ allowedValues=[5, 10, \"20.0\"],\n+ default=20,\n+ ),\n+ ],\n+ steps=[\n+ StepTemplate(\n+ name=\"StepName\",\n+ description=\"desc\",\n+ stepEnvironments=[\n+ Environment(\n+ name=\"StepEnv\",\n+ description=\"desc\",\n+ script=EnvironmentScript(\n+ embeddedFiles=[\n+ EmbeddedFileText(\n+ name=\"File\",\n+ type=\"TEXT\",\n+ data=\"some data {{ Param.IntParam }}\",\n+ filename=\"filename.txt\",\n+ runnable=False,\n+ )\n+ ],\n+ actions=EnvironmentActions(\n+ onEnter=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodTerminate(mode=\"TERMINATE\"),\n+ ),\n+ onExit=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodNotifyThenTerminate(\n+ mode=\"NOTIFY_THEN_TERMINATE\", notifyPeriodInSeconds=30\n+ ),\n+ ),\n+ ),\n+ ),\n+ ),\n+ ],\n+ parameterSpace=StepParameterSpaceDefinition(\n+ taskParameterDefinitions=[\n+ IntTaskParameterDefinition(\n+ name=\"ParamE\",\n+ type=\"INT\",\n+ range=\"2 - {{ Param.RangeExpressionParam }}\",\n+ ),\n+ IntTaskParameterDefinition(\n+ name=\"ParamI\", type=\"INT\", range=[0, \"{{ Param.IntParam }}\"]\n+ ),\n+ FloatTaskParameterDefinition(\n+ name=\"ParamF\", type=\"FLOAT\", range=[1.1, \"{{ Param.FloatParam }}\"]\n+ ),\n+ StringTaskParameterDefinition(\n+ name=\"ParamS\",\n+ type=\"STRING\",\n+ range=[\"foo\", \"{{ Param.StringParam }}\"],\n+ ),\n+ ],\n+ combination=\"ParamS * ParamF * ParamI * ParamE\",\n+ ),\n+ script=StepScript(\n+ embeddedFiles=[\n+ EmbeddedFileText(\n+ name=\"File\",\n+ type=\"TEXT\",\n+ data=\"some data {{ Param.IntParam }}\",\n+ filename=\"filename.txt\",\n+ runnable=False,\n+ )\n+ ],\n+ actions=StepActions(\n+ onRun=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodTerminate(mode=\"TERMINATE\"),\n+ )\n+ ),\n+ ),\n+ hostRequirements=HostRequirementsTemplate(\n+ amounts=[\n+ AmountRequirementTemplate(name=\"amount.worker.vcpu\", min=3, max=8),\n+ AmountRequirementTemplate(name=\"{{Param.AmountCapabilityName}}\", min=2),\n+ ],\n+ attributes=[\n+ AttributeRequirementTemplate(\n+ name=\"attr.worker.os.family\", anyOf=[\"linux\"]\n+ ),\n+ AttributeRequirementTemplate(\n+ name=\"{{Param.AttrCapabilityName}}\", allOf=[\"{{Param.StringParam}}\"]\n+ ),\n+ ],\n+ ),\n+ )\n+ ],\n+ )\n+ job_parameter_values = {\n+ \"IntParam\": ParameterValue(type=ParameterValueType.INT, value=\"10\"),\n+ \"FloatParam\": ParameterValue(type=ParameterValueType.FLOAT, value=\"10\"),\n+ \"RangeExpressionParam\": ParameterValue(type=ParameterValueType.STRING, value=\"3\"),\n+ # StringParam intentionally left undefined so that we get the default value\n+ }\n+\n+ # WHEN\n+ result = create_job(job_template=template, job_parameter_values=job_parameter_values)\n+\n+ # THEN\n+ expected = Job(\n+ name=\"TheOtherJobName\",\n+ description=\"job description\",\n+ jobEnvironments=[\n+ Environment(\n+ name=\"JobEnv\",\n+ description=\"desc\",\n+ script=EnvironmentScript(\n+ embeddedFiles=[\n+ EmbeddedFileText(\n+ name=\"File\",\n+ type=\"TEXT\",\n+ data=\"some data {{ Param.IntParam }}\",\n+ filename=\"filename.txt\",\n+ runnable=False,\n+ )\n+ ],\n+ actions=EnvironmentActions(\n+ onEnter=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodTerminate(mode=\"TERMINATE\"),\n+ ),\n+ onExit=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodNotifyThenTerminate(\n+ mode=\"NOTIFY_THEN_TERMINATE\", notifyPeriodInSeconds=30\n+ ),\n+ ),\n+ ),\n+ ),\n+ )\n+ ],\n+ parameters={\n+ \"StringParam\": JobParameter(\n+ type=\"STRING\", description=\"desc\", value=\"TheOtherJobName\"\n+ ),\n+ \"AttrCapabilityName\": JobParameter(\n+ type=\"STRING\", description=\"desc\", value=\"attr.mycapability\"\n+ ),\n+ \"AmountCapabilityName\": JobParameter(\n+ type=\"STRING\", description=\"desc\", value=\"amount.mycapability\"\n+ ),\n+ \"RangeExpressionParam\": JobParameter(type=\"INT\", description=\"desc\", value=\"3\"),\n+ \"IntParam\": JobParameter(type=\"INT\", description=\"desc\", value=\"10\"),\n+ \"FloatParam\": JobParameter(type=\"FLOAT\", description=\"desc\", value=\"10\"),\n+ },\n+ steps=[\n+ Step(\n+ name=\"StepName\",\n+ description=\"desc\",\n+ stepEnvironments=[\n+ Environment(\n+ name=\"StepEnv\",\n+ description=\"desc\",\n+ script=EnvironmentScript(\n+ embeddedFiles=[\n+ EmbeddedFileText(\n+ name=\"File\",\n+ type=\"TEXT\",\n+ data=\"some data {{ Param.IntParam }}\",\n+ filename=\"filename.txt\",\n+ runnable=False,\n+ )\n+ ],\n+ actions=EnvironmentActions(\n+ onEnter=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodTerminate(mode=\"TERMINATE\"),\n+ ),\n+ onExit=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodNotifyThenTerminate(\n+ mode=\"NOTIFY_THEN_TERMINATE\", notifyPeriodInSeconds=30\n+ ),\n+ ),\n+ ),\n+ ),\n+ ),\n+ ],\n+ parameterSpace=StepParameterSpace(\n+ taskParameterDefinitions={\n+ \"ParamE\": RangeExpressionTaskParameterDefinition(\n+ type=\"INT\", range=\"2 - 3\"\n+ ),\n+ \"ParamI\": RangeListTaskParameterDefinition(\n+ type=\"INT\", range=[\"0\", \"10\"]\n+ ),\n+ \"ParamF\": RangeListTaskParameterDefinition(\n+ type=\"FLOAT\", range=[\"1.1\", \"10\"]\n+ ),\n+ \"ParamS\": RangeListTaskParameterDefinition(\n+ type=\"STRING\", range=[\"foo\", \"TheOtherJobName\"]\n+ ),\n+ },\n+ combination=\"ParamS * ParamF * ParamI * ParamE\",\n+ ),\n+ script=StepScript(\n+ embeddedFiles=[\n+ EmbeddedFileText(\n+ name=\"File\",\n+ type=\"TEXT\",\n+ data=\"some data {{ Param.IntParam }}\",\n+ filename=\"filename.txt\",\n+ runnable=False,\n+ )\n+ ],\n+ actions=StepActions(\n+ onRun=Action(\n+ command=\"{{ Param.IntParam }}\",\n+ args=[\"{{ Param.FloatParam }}\"],\n+ timeout=10,\n+ cancelation=CancelationMethodTerminate(mode=\"TERMINATE\"),\n+ )\n+ ),\n+ ),\n+ hostRequirements=HostRequirements(\n+ amounts=[\n+ AmountRequirement(name=\"amount.worker.vcpu\", min=3, max=8),\n+ AmountRequirement(name=\"amount.mycapability\", min=2),\n+ ],\n+ attributes=[\n+ AttributeRequirement(name=\"attr.worker.os.family\", anyOf=[\"linux\"]),\n+ AttributeRequirement(\n+ name=\"attr.mycapability\", allOf=[\"TheOtherJobName\"]\n+ ),\n+ ],\n+ ),\n+ )\n+ ],\n+ )\n+\n+ # Note: The dict compare generates an easier to read diff if there's a test failure.\n+ # It is not essential to the test.\n+ assert result.dict() == expected.dict()\n+ # This is the important assertion.\n+ assert result == expected"}, {"sha": "24f2dda53cb7a57f98ebce86874688fc384eb6ae", "filename": "test/openjd/model/v2023_09/test_embedded.py", "status": "added", "additions": 79, "deletions": 0, "changes": 79, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_embedded.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_embedded.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_embedded.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,79 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import EmbeddedFileText\n+\n+\n+class TestEmbeddedFileText:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"Foo\", \"type\": \"TEXT\", \"data\": \"some text\"}, id=\"all required\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"TEXT\", \"data\": \"1\"}, id=\"data min length\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"TEXT\", \"data\": \"1\" * (32 * 1024)}, id=\"data long length\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"TEXT\", \"data\": \"some text\", \"filename\": \"1\"},\n+ id=\"filename min length\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"TEXT\", \"data\": \"some text\", \"filename\": \"1\" * 64},\n+ id=\"filename max length\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"TEXT\", \"data\": \"some text\", \"runnable\": True},\n+ id=\"runnable\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description EmbeddedFileText\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our EmbeddedFileText model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=EmbeddedFileText, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"text\", \"data\": \"some text\"}, id=\"unknown type\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"TEXT\", \"data\": \"\"}, id=\"data too short\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"TEXT\", \"data\": \"some text\", \"filename\": \"\"},\n+ id=\"filename too short\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"TEXT\", \"data\": \"some text\", \"filename\": \"f\" * 65},\n+ id=\"filename too long\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"TEXT\", \"data\": \"some text\", \"runnable\": \"True\"},\n+ id=\"runnable must be bool\",\n+ ),\n+ # TODO - tests for filename allowed characters\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description EmbeddedFileText.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=EmbeddedFileText, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0"}, {"sha": "24350ccb0f37158b421130317a333679b7a74f4e", "filename": "test/openjd/model/v2023_09/test_environments.py", "status": "added", "additions": 86, "deletions": 0, "changes": 86, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_environments.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_environments.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_environments.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,86 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import Environment\n+\n+# A minimal environment script to reference in tests\n+ENV_SCRIPT = {\"actions\": {\"onEnter\": {\"command\": \"foo\"}}}\n+ENV_VARIABLE = {\"FOO\": \"BAR\", \"BAZ\": \"QUX\"}\n+\n+\n+class TestEnvironment:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"Foo\", \"script\": ENV_SCRIPT}, id=\"all required\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"description\": \"text\", \"script\": ENV_SCRIPT}, id=\"with description\"\n+ ),\n+ pytest.param({\"name\": \"Foo\", \"variables\": ENV_VARIABLE}),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description Environment\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our Environment model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=Environment, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"Foo\", \"script\": ENV_SCRIPT, \"unknown\": \"key\"}, id=\"unknown key\"),\n+ pytest.param({\"script\": ENV_SCRIPT}, id=\"missing name\"),\n+ pytest.param({\"name\": 12, \"script\": ENV_SCRIPT}, id=\"name not string\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"description\": 12, \"script\": ENV_SCRIPT},\n+ id=\"description not string\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"variables\": {\"2FOO\": \"BAR\"}}, id=\"variable name starts with digit\"\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description Environment.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=Environment, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"Foo\"}, id=\"missing script and variables\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"script\": ENV_SCRIPT, \"variables\": {}}, id=\"empty variables\"\n+ ),\n+ ),\n+ )\n+ def test_validation_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description Environment.\n+ # - Neither variables or a script\n+ # - Empty variables\n+\n+ # WHEN\n+ with pytest.raises(ValueError):\n+ _parse_model(\n+ model=Environment,\n+ obj=data,\n+ )"}, {"sha": "21e6f47285e95145b8a2fa587a38f2706fcbed05", "filename": "test/openjd/model/v2023_09/test_job_parameters.py", "status": "added", "additions": 1788, "deletions": 0, "changes": 1788, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_job_parameters.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_job_parameters.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_job_parameters.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,1788 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from decimal import Decimal\n+from typing import Any\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import (\n+ JobFloatParameterDefinition,\n+ JobIntParameterDefinition,\n+ JobPathParameterDefinition,\n+ JobStringParameterDefinition,\n+)\n+\n+\n+class TestJobStringParameterDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"Foo\", \"type\": \"STRING\"}, id=\"minimal required\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"description\": \"some test\"}, id=\"description\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"some value\"}, id=\"has default\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"minLength\": 1}, id=\"smallest min length\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"maxLength\": 1}, id=\"smallest max length\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"allowedValues\": [\"a\"]}, id=\"has allowedValues\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"minLength\": 1, \"maxLength\": 1}, id=\"min = max\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"minLength\": 1, \"maxLength\": 2}, id=\"min < max\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"allowedValues\": [\"aa\"], \"minLength\": 2},\n+ id=\"allowed is min length\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"allowedValues\": [\"aa\"], \"maxLength\": 2},\n+ id=\"allowed is max length\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"aa\", \"minLength\": 2},\n+ id=\"default is minLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"aa\", \"maxLength\": 2},\n+ id=\"default is maxLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"aa\", \"allowedValues\": [\"aa\", \"bb\"]},\n+ id=\"default is allowed\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"description\": \"aa\\nbb\\ncc\\r\\ndd\\t\\ttabs\\n\"},\n+ id=\"description with newlines and tabs\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"control\": \"LINE_EDIT\"}},\n+ id=\"user interface LINE_EDIT\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"control\": \"MULTILINE_EDIT\"}},\n+ id=\"user interface MULTILINE_EDIT\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"control\": \"HIDDEN\"}},\n+ id=\"user interface HIDDEN\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"DROPDOWN_LIST\"},\n+ \"allowedValues\": [\"aa\"],\n+ },\n+ id=\"user interface DROPDOWN_LIST\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"CHECK_BOX\"},\n+ \"allowedValues\": [\"True\", \"False\"],\n+ },\n+ id=\"user interface CHECKBOX with True/False\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"CHECK_BOX\"},\n+ \"allowedValues\": [\"False\", \"True\"],\n+ },\n+ id=\"user interface CHECKBOX with False/True\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"CHECK_BOX\"},\n+ \"allowedValues\": [\"OFF\", \"ON\"],\n+ },\n+ id=\"user interface CHECKBOX with OFF/ON\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"CHECK_BOX\"},\n+ \"allowedValues\": [\"yes\", \"no\"],\n+ },\n+ id=\"user interface CHECKBOX with yes/no\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"CHECK_BOX\"},\n+ \"allowedValues\": [\"0\", \"1\"],\n+ },\n+ id=\"user interface CHECKBOX with 0/1\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\n+ \"control\": \"HIDDEN\",\n+ \"label\": \"Foo Label\",\n+ \"groupLabel\": \"Bar\",\n+ },\n+ \"default\": \"aa\",\n+ \"allowedValues\": [\"aa\", \"bb\"],\n+ \"minLength\": 1,\n+ \"maxLength\": 3,\n+ },\n+ id=\"all fields\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description JobStringParameterDefinition\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our JobStringParameterDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=JobStringParameterDefinition, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"FLOAT\"}, id=\"wrong type\"),\n+ pytest.param({\"name\": \"Foo\"}, id=\"missing type\"),\n+ pytest.param({\"type\": \"STRING\"}, id=\"missing name\"),\n+ pytest.param({\"name\": 12, \"type\": \"STRING\"}, id=\"name not a string\"),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"description\": 12}, id=\"description not string\"\n+ ),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"STRING\", \"default\": 12}, id=\"default not string\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"minLength\": 1.2}, id=\"min length float\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"maxLength\": 1.2}, id=\"max length float\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"minLength\": \"1\"}, id=\"min length string\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"maxLength\": \"1\"}, id=\"max length string\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"allowedValues\": []}, id=\"allowedValues too small\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"allowedValues\": [12]},\n+ id=\"allowedValues item not string\",\n+ ),\n+ #\n+ pytest.param({\"name\": \"Foo\", \"type\": \"STRING\", \"minLength\": 0}, id=\"0 < min\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"STRING\", \"maxLength\": 0}, id=\"0 < max\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"minLength\": 2, \"maxLength\": 1}, id=\"min > max\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"allowedValues\": [\"aa\"], \"minLength\": 3},\n+ id=\"allowed less than min length\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"allowedValues\": [\"aa\"], \"maxLength\": 1},\n+ id=\"allowed exceeds max length\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"aa\", \"minLength\": 3},\n+ id=\"default less than minLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"aa\", \"maxLength\": 1},\n+ id=\"default exceeds maxLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"cc\", \"allowedValues\": [\"aa\", \"bb\"]},\n+ id=\"default not allowed\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"control\": \"UNSUPPORTED\"}},\n+ id=\"unsupported user interface control\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"label\": \"\\n\"}},\n+ id=\"wrong character in user interface label\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"label\": \"\"}},\n+ id=\"user interface label too short\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"label\": \"a\" * 65}},\n+ id=\"user interface label too long\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"groupLabel\": \"\"}},\n+ id=\"user interface groupLabel too short\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"groupLabel\": \"a\" * 65}},\n+ id=\"user interface groupLabel too long\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"LINE_EDIT\"},\n+ \"allowedValues\": [\"aa\"],\n+ },\n+ id=\"user interface LINE_EDIT can't have allowedValues\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"MULTILINE_EDIT\"},\n+ \"allowedValues\": [\"aa\"],\n+ },\n+ id=\"user interface MULTILINE_EDIT can't have allowedValues\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"userInterface\": {\"control\": \"DROPDOWN_LIST\"}},\n+ id=\"user interface DROPDOWN_LIST requires allowedValues\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"CHECK_BOX\"},\n+ \"allowedValues\": [\"Ture\", \"False\"],\n+ },\n+ id=\"user interface CHECKBOX with unsupported Ture/False\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"CHECK_BOX\"},\n+ \"allowedValues\": [\"Ture\"],\n+ },\n+ id=\"user interface CHECKBOX with too few allowedValues\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"userInterface\": {\"control\": \"CHECK_BOX\"},\n+ \"allowedValues\": [\"True\", \"False\", \"On\", \"Off\"],\n+ },\n+ id=\"user interface CHECKBOX with too many allowedValues\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description JobStringParameterDefinition.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=JobStringParameterDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+ @pytest.mark.parametrize(\n+ \"value,parameter\",\n+ [\n+ pytest.param(\n+ \"value\", JobStringParameterDefinition(name=\"Foo\", type=\"STRING\"), id=\"passes type\"\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobStringParameterDefinition(name=\"Foo\", type=\"STRING\", minLength=1),\n+ id=\"min length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobStringParameterDefinition(name=\"Foo\", type=\"STRING\", minLength=5),\n+ id=\"min length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobStringParameterDefinition(name=\"Foo\", type=\"STRING\", maxLength=5),\n+ id=\"max length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobStringParameterDefinition(name=\"Foo\", type=\"STRING\", maxLength=15),\n+ id=\"max length\",\n+ ),\n+ pytest.param(\n+ \"value1\",\n+ JobStringParameterDefinition(\n+ name=\"Foo\", type=\"STRING\", allowedValues=[\"value1\", \"value2\"]\n+ ),\n+ id=\"allowed value 1\",\n+ ),\n+ pytest.param(\n+ \"value2\",\n+ JobStringParameterDefinition(\n+ name=\"Foo\", type=\"STRING\", allowedValues=[\"value1\", \"value2\"]\n+ ),\n+ id=\"allowed value 2\",\n+ ),\n+ ],\n+ )\n+ def test_check_constraints_noraise(\n+ self, value: Any, parameter: JobStringParameterDefinition\n+ ) -> None:\n+ # WHEN\n+ # will raise if the value doesn't pass the checks\n+ parameter._check_constraints(value)\n+\n+ # THEN\n+ assert True\n+\n+ @pytest.mark.parametrize(\n+ \"value,parameter\",\n+ [\n+ pytest.param(\n+ None, JobStringParameterDefinition(name=\"Foo\", type=\"STRING\"), id=\"none type\"\n+ ),\n+ pytest.param(\n+ 12, JobStringParameterDefinition(name=\"Foo\", type=\"STRING\"), id=\"int type\"\n+ ),\n+ pytest.param(\n+ True, JobStringParameterDefinition(name=\"Foo\", type=\"STRING\"), id=\"bool type\"\n+ ),\n+ pytest.param(\n+ 1.2, JobStringParameterDefinition(name=\"Foo\", type=\"STRING\"), id=\"float type\"\n+ ),\n+ pytest.param(\n+ Decimal(1),\n+ JobStringParameterDefinition(name=\"Foo\", type=\"STRING\"),\n+ id=\"decimal type\",\n+ ),\n+ pytest.param(\n+ list(), JobStringParameterDefinition(name=\"Foo\", type=\"STRING\"), id=\"list type\"\n+ ),\n+ pytest.param(\n+ dict(), JobStringParameterDefinition(name=\"Foo\", type=\"STRING\"), id=\"dict type\"\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobStringParameterDefinition(name=\"Foo\", type=\"STRING\", minLength=6),\n+ id=\"min length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobStringParameterDefinition(name=\"Foo\", type=\"STRING\", maxLength=4),\n+ id=\"max length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobStringParameterDefinition(\n+ name=\"Foo\", type=\"STRING\", allowedValues=[\"value1\", \"value2\"]\n+ ),\n+ id=\"allowed value\",\n+ ),\n+ ],\n+ )\n+ def test_check_constraints_raises(\n+ self, value: Any, parameter: JobStringParameterDefinition\n+ ) -> None:\n+ # WHEN\n+ with pytest.raises(ValueError):\n+ parameter._check_constraints(value)\n+\n+\n+class TestJobPathParameterDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\"}, id=\"minimal required\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"description\": \"some test\"}, id=\"description\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"default\": \"some value\"}, id=\"has default\"\n+ ),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\", \"minLength\": 1}, id=\"smallest min length\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\", \"maxLength\": 1}, id=\"smallest max length\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"allowedValues\": [\"a\"]}, id=\"has allowedValues\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"minLength\": 1, \"maxLength\": 1}, id=\"min = max\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"minLength\": 1, \"maxLength\": 2}, id=\"min < max\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"allowedValues\": [\"aa\"], \"minLength\": 2},\n+ id=\"allowed is min length\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"allowedValues\": [\"aa\"], \"maxLength\": 2},\n+ id=\"allowed is max length\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"default\": \"aa\", \"minLength\": 2},\n+ id=\"default is minLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"default\": \"aa\", \"maxLength\": 2},\n+ id=\"default is maxLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"default\": \"aa\", \"allowedValues\": [\"aa\", \"bb\"]},\n+ id=\"default is allowed\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"description\": \"aa\\nbb\\ncc\\r\\ndd\\t\\ttabs\\n\"},\n+ id=\"description with newlines and tabs\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"control\": \"CHOOSE_INPUT_FILE\"}},\n+ id=\"user interface CHOOSE_INPUT_FILE\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"control\": \"CHOOSE_OUTPUT_FILE\"}},\n+ id=\"user interface CHOOSE_OUTPUT_FILE\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"control\": \"CHOOSE_DIRECTORY\"}},\n+ id=\"user interface CHOOSE_DIRECTORY\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"control\": \"HIDDEN\"}},\n+ id=\"user interface HIDDEN\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\"control\": \"DROPDOWN_LIST\"},\n+ \"allowedValues\": [\"/aa/bb\"],\n+ },\n+ id=\"user interface DROPDOWN_LIST\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_INPUT_FILE\",\n+ \"fileFilters\": [{\"label\": \"All Files\", \"patterns\": [\"*.*\"]}],\n+ \"fileFilterDefault\": {\n+ \"label\": \"Some Files\",\n+ \"patterns\": [\"*.jpg\", \"*.png\"],\n+ },\n+ },\n+ },\n+ id=\"user interface CHOOSE_INPUT_FILE with file filters\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_OUTPUT_FILE\",\n+ \"fileFilters\": [{\"label\": \"All Files\", \"patterns\": [\"*\", \"*.*\"]}],\n+ \"fileFilterDefault\": {\n+ \"label\": \"Some Files\",\n+ \"patterns\": [\"*.jpg\", \"*.png\", \"*.c++\", \"*.psppalette\"],\n+ },\n+ },\n+ },\n+ id=\"user interface CHOOSE_OUTPUT_FILE with file filters\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"objectType\": \"FILE\",\n+ \"userInterface\": {\"control\": \"CHOOSE_INPUT_FILE\"},\n+ },\n+ id=\"path object type FILE with CHOOSE_INPUT_FILE\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"objectType\": \"FILE\",\n+ \"userInterface\": {\"control\": \"CHOOSE_OUTPUT_FILE\"},\n+ },\n+ id=\"path object type FILE with CHOOSE_OUTPUT_FILE\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"objectType\": \"DIRECTORY\",\n+ \"userInterface\": {\"control\": \"CHOOSE_DIRECTORY\"},\n+ },\n+ id=\"path object type DIRECTORY with CHOOSE_DRECTORY\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"dataFlow\": \"NONE\"},\n+ id=\"path data flow NONE\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"dataFlow\": \"IN\"},\n+ id=\"path data flow IN\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"dataFlow\": \"OUT\"},\n+ id=\"path data flow OUT\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"dataFlow\": \"INOUT\"},\n+ id=\"path data flow INOUT\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"objectType\": \"DIRECTORY\",\n+ \"dataFlow\": \"INOUT\",\n+ \"userInterface\": {\n+ \"control\": \"DROPDOWN_LIST\",\n+ \"label\": \"Foo Label\",\n+ \"groupLabel\": \"Foo Group\",\n+ },\n+ \"default\": \"aa\",\n+ \"allowedValues\": [\"aa\", \"bb\"],\n+ \"minLength\": 1,\n+ \"maxLength\": 3,\n+ },\n+ id=\"all fields\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description JobPathParameterDefinition\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our JobPathParameterDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=JobPathParameterDefinition, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"FLOAT\"}, id=\"wrong type\"),\n+ pytest.param({\"name\": \"Foo\"}, id=\"missing type\"),\n+ pytest.param({\"type\": \"PATH\"}, id=\"missing name\"),\n+ pytest.param({\"name\": 12, \"type\": \"PATH\"}, id=\"name not a string\"),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"description\": 12}, id=\"description not string\"\n+ ),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\", \"default\": 12}, id=\"default not string\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\", \"minLength\": 1.2}, id=\"min length float\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\", \"maxLength\": 1.2}, id=\"max length float\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\", \"minLength\": \"1\"}, id=\"min length string\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\", \"maxLength\": \"1\"}, id=\"max length string\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"allowedValues\": []}, id=\"allowedValues too small\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"allowedValues\": [12]},\n+ id=\"allowedValues item not string\",\n+ ),\n+ #\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\", \"minLength\": 0}, id=\"0 < min\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"PATH\", \"maxLength\": 0}, id=\"0 < max\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"minLength\": 2, \"maxLength\": 1}, id=\"min > max\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"allowedValues\": [\"aa\"], \"minLength\": 3},\n+ id=\"allowed less than min length\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"allowedValues\": [\"aa\"], \"maxLength\": 1},\n+ id=\"allowed exceeds max length\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"default\": \"aa\", \"minLength\": 3},\n+ id=\"default less than minLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"default\": \"aa\", \"maxLength\": 1},\n+ id=\"default exceeds maxLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"default\": \"cc\", \"allowedValues\": [\"aa\", \"bb\"]},\n+ id=\"default not allowed\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"control\": \"UNSUPPORTED\"}},\n+ id=\"unsupported user interface control\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"label\": \"\\n\"}},\n+ id=\"wrong character in user interface label\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"label\": \"\"}},\n+ id=\"user interface label too short\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"label\": \"a\" * 65}},\n+ id=\"user interface label too long\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"groupLabel\": \"\"}},\n+ id=\"user interface groupLabel too short\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"groupLabel\": \"a\" * 65}},\n+ id=\"user interface groupLabel too long\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\"control\": \"CHOOSE_INPUT_FILE\"},\n+ \"allowedValues\": [\"aa\"],\n+ },\n+ id=\"user interface CHOOSE_INPUT_FILE can't have allowedValues\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\"control\": \"CHOOSE_OUTPUT_FILE\"},\n+ \"allowedValues\": [\"aa\"],\n+ },\n+ id=\"user interface CHOOSE_OUTPUT_FILE can't have allowedValues\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\"control\": \"CHOOSE_DIRECTORY\"},\n+ \"allowedValues\": [\"aa\"],\n+ },\n+ id=\"user interface CHOOSE_DIRECTORY can't have allowedValues\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_DIRECTORY\",\n+ \"fileFilters\": [{\"label\": \"All Files\", \"patterns\": [\"*.*\"]}],\n+ },\n+ },\n+ id=\"user interface CHOOSE_DIRECTORY can't have fileFilters\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_DIRECTORY\",\n+ \"fileFilterDefault\": {\n+ \"label\": \"Some Files\",\n+ \"patterns\": [\"*.jpg\", \"*.png\"],\n+ },\n+ },\n+ },\n+ id=\"user interface CHOOSE_DIRECTORY can't have fileFilterDefault\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"DROPDOWN_LIST\",\n+ \"fileFilters\": [{\"label\": \"All Files\", \"patterns\": [\"*.*\"]}],\n+ },\n+ \"allowedValues\": [\"aa\"],\n+ },\n+ id=\"user interface DROPDOWN_LIST can't have fileFilters\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"DROPDOWN_LIST\",\n+ \"fileFilterDefault\": {\n+ \"label\": \"Some Files\",\n+ \"patterns\": [\"*.jpg\", \"*.png\"],\n+ },\n+ },\n+ \"allowedValues\": [\"aa\"],\n+ },\n+ id=\"user interface DROPDOWN_LIST can't have fileFilterDefault\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"userInterface\": {\"control\": \"DROPDOWN_LIST\"}},\n+ id=\"user interface DROPDOWN_LIST requires allowedValues\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_INPUT_FILE\",\n+ \"fileFilters\": [{\"label\": \"\", \"patterns\": [\"*.*\"]}],\n+ },\n+ },\n+ id=\"user interface file filter name too small\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_INPUT_FILE\",\n+ \"fileFilters\": [{\"label\": \"a\" * 65, \"patterns\": [\"*.*\"]}],\n+ },\n+ },\n+ id=\"user interface file filter name too large\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_INPUT_FILE\",\n+ \"fileFilters\": [{\"label\": \"All Files\", \"patterns\": []}],\n+ },\n+ },\n+ id=\"user interface file filter pattern list too small\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_INPUT_FILE\",\n+ \"fileFilters\": [{\"label\": \"All Files\", \"patterns\": [\"*.*\"] * 21}],\n+ },\n+ },\n+ id=\"user interface file filter pattern list too large\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_INPUT_FILE\",\n+ \"fileFilters\": [],\n+ },\n+ },\n+ id=\"user interface file filter list too small\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_INPUT_FILE\",\n+ \"fileFilters\": [{\"label\": \"All Files\", \"patterns\": [\"*.*\"]}] * 21,\n+ },\n+ },\n+ id=\"user interface file filter list too large\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"objectType\": \"DIRECTORY\",\n+ \"userInterface\": {\"control\": \"CHOOSE_INPUT_FILE\"},\n+ },\n+ id=\"path object type DIRECTORY incompatible with CHOOSE_INPUT_FILE\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"objectType\": \"DIRECTORY\",\n+ \"userInterface\": {\"control\": \"CHOOSE_OUTPUT_FILE\"},\n+ },\n+ id=\"path object type DIRECTORY incompatible with CHOOSE_OUTPUT_FILE\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"objectType\": \"FILE\",\n+ \"userInterface\": {\"control\": \"CHOOSE_DIRECTORY\"},\n+ },\n+ id=\"path object type FILE incompatible with CHOOSE_DIRECTORY\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"objectType\": \"UNSUPPORTED\"},\n+ id=\"path object type unsupported\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"PATH\", \"dataFlow\": \"UNSUPPORTED\"},\n+ id=\"path data flow unsupported\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_INPUT_FILE\",\n+ \"fileFilters\": [{\"label\": \"X\", \"patterns\": [\"**\"]}],\n+ },\n+ },\n+ id=\"user interface file filter unsupported '**' pattern\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"PATH\",\n+ \"userInterface\": {\n+ \"control\": \"CHOOSE_INPUT_FILE\",\n+ \"fileFilters\": [{\"label\": \"X\", \"patterns\": [\"*.?\"]}],\n+ },\n+ },\n+ id=\"user interface file filter unsupported '*.?' pattern\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description JobPathParameterDefinition.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=JobPathParameterDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+ @pytest.mark.parametrize(\n+ \"value,parameter\",\n+ [\n+ pytest.param(\n+ \"value\", JobPathParameterDefinition(name=\"Foo\", type=\"PATH\"), id=\"passes type\"\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobPathParameterDefinition(name=\"Foo\", type=\"PATH\", minLength=1),\n+ id=\"min length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobPathParameterDefinition(name=\"Foo\", type=\"PATH\", minLength=5),\n+ id=\"min length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobPathParameterDefinition(name=\"Foo\", type=\"PATH\", maxLength=5),\n+ id=\"max length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobPathParameterDefinition(name=\"Foo\", type=\"PATH\", maxLength=15),\n+ id=\"max length\",\n+ ),\n+ pytest.param(\n+ \"value1\",\n+ JobPathParameterDefinition(\n+ name=\"Foo\", type=\"PATH\", allowedValues=[\"value1\", \"value2\"]\n+ ),\n+ id=\"allowed value 1\",\n+ ),\n+ pytest.param(\n+ \"value2\",\n+ JobPathParameterDefinition(\n+ name=\"Foo\", type=\"PATH\", allowedValues=[\"value1\", \"value2\"]\n+ ),\n+ id=\"allowed value 2\",\n+ ),\n+ ],\n+ )\n+ def test_check_constraints_noraise(\n+ self, value: Any, parameter: JobPathParameterDefinition\n+ ) -> None:\n+ # WHEN\n+ # will raise if the value doesn't pass the checks\n+ parameter._check_constraints(value)\n+\n+ # THEN\n+ assert True\n+\n+ @pytest.mark.parametrize(\n+ \"value,parameter\",\n+ [\n+ pytest.param(None, JobPathParameterDefinition(name=\"Foo\", type=\"PATH\"), id=\"none type\"),\n+ pytest.param(12, JobPathParameterDefinition(name=\"Foo\", type=\"PATH\"), id=\"int type\"),\n+ pytest.param(True, JobPathParameterDefinition(name=\"Foo\", type=\"PATH\"), id=\"bool type\"),\n+ pytest.param(1.2, JobPathParameterDefinition(name=\"Foo\", type=\"PATH\"), id=\"float type\"),\n+ pytest.param(\n+ Decimal(1), JobPathParameterDefinition(name=\"Foo\", type=\"PATH\"), id=\"decimal type\"\n+ ),\n+ pytest.param(\n+ list(), JobPathParameterDefinition(name=\"Foo\", type=\"PATH\"), id=\"list type\"\n+ ),\n+ pytest.param(\n+ dict(), JobPathParameterDefinition(name=\"Foo\", type=\"PATH\"), id=\"dict type\"\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobPathParameterDefinition(name=\"Foo\", type=\"PATH\", minLength=6),\n+ id=\"min length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobPathParameterDefinition(name=\"Foo\", type=\"PATH\", maxLength=4),\n+ id=\"max length\",\n+ ),\n+ pytest.param(\n+ \"value\",\n+ JobPathParameterDefinition(\n+ name=\"Foo\", type=\"PATH\", allowedValues=[\"value1\", \"value2\"]\n+ ),\n+ id=\"allowed value\",\n+ ),\n+ ],\n+ )\n+ def test_check_constraints_raises(\n+ self, value: Any, parameter: JobPathParameterDefinition\n+ ) -> None:\n+ # WHEN\n+ with pytest.raises(ValueError):\n+ parameter._check_constraints(value)\n+\n+\n+class TestJobIntParameterDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\"}, id=\"minimal required\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"description\": \"some text\"}, id=\"description\"\n+ ),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\", \"default\": 1}, id=\"has default as int\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": \"1\"}, id=\"has default as string\"\n+ ),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\", \"minValue\": 1}, id=\"has min value as int\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"minValue\": \"1\"}, id=\"has min value as string\"\n+ ),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\", \"maxValue\": 1}, id=\"has max value as int\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"maxValue\": \"1\"}, id=\"has max value as string\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": [1]}, id=\"has allowedValues int\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": [\"1\"]},\n+ id=\"has allowedValues string\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"minValue\": 1, \"maxValue\": 1}, id=\"min = max\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"minValue\": 1, \"maxValue\": 2}, id=\"min < max\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": [2], \"minValue\": 2},\n+ id=\"allowed is min value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": [2], \"maxValue\": 2},\n+ id=\"allowed is max value\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": 2, \"minValue\": 2},\n+ id=\"default is min value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": 2, \"maxValue\": 2},\n+ id=\"default is max value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": 2, \"allowedValues\": [1, \"2\"]},\n+ id=\"default is allowed\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"userInterface\": {\"control\": \"SPIN_BOX\"}},\n+ id=\"user interface SPIN_BOX\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"INT\",\n+ \"userInterface\": {\"control\": \"SPIN_BOX\", \"singleStepDelta\": 3},\n+ },\n+ id=\"user interface SPIN_BOX\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"userInterface\": {\"control\": \"HIDDEN\"}},\n+ id=\"user interface HIDDEN\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"INT\",\n+ \"userInterface\": {\"control\": \"DROPDOWN_LIST\"},\n+ \"allowedValues\": [1],\n+ },\n+ id=\"user interface DROPDOWN_LIST\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"INT\",\n+ \"userInterface\": {\n+ \"control\": \"DROPDOWN_LIST\",\n+ \"label\": \"Foo Label\",\n+ \"groupLabel\": \"Group Label\",\n+ },\n+ \"default\": 1,\n+ \"allowedValues\": [1, \"2\"],\n+ \"minValue\": 1,\n+ \"maxValue\": 3,\n+ },\n+ id=\"all fields\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description JobIntParameterDefinition\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our JobIntParameterDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=JobIntParameterDefinition, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"STRING\"}, id=\"wrong type\"),\n+ pytest.param({\"name\": \"Foo\"}, id=\"missing type\"),\n+ pytest.param({\"type\": \"INT\"}, id=\"missing name\"),\n+ pytest.param({\"name\": 12, \"type\": \"INT\"}, id=\"name not a string\"),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"description\": 12}, id=\"description not string\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": []}, id=\"allowedValues too small\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": [\"aa\"]},\n+ id=\"allowedValues item not number\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": [\"1.2\"]},\n+ id=\"allowedValues item not int string\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": [True]},\n+ id=\"allowedValues item a bool\",\n+ ),\n+ #\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\", \"minValue\": True}, id=\"min a bool\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\", \"minValue\": 1.1}, id=\"min a float\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\", \"minValue\": \"1.1\"}, id=\"min a float str\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\", \"maxValue\": True}, id=\"max a bool\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\", \"maxValue\": 1.1}, id=\"max a float\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"INT\", \"maxValue\": \"1.1\"}, id=\"max a float str\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"minValue\": 2, \"maxValue\": 1}, id=\"min > max\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": [2], \"minValue\": 3},\n+ id=\"allowed less than min value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"allowedValues\": [2], \"maxValue\": 1},\n+ id=\"allowed exceeds max value\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": True},\n+ id=\"default a bool\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": 1.1},\n+ id=\"default a float\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": \"1.1\"},\n+ id=\"default a float str\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": 2, \"minValue\": 3},\n+ id=\"default less than min value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": 2, \"maxLength\": 1},\n+ id=\"default exceeds max value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"default\": 0, \"allowedValues\": [1, 2]},\n+ id=\"default not allowed\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"aa\", \"minLength\": 3},\n+ id=\"default less than minLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"aa\", \"maxLength\": 1},\n+ id=\"default exceeds maxLength\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"STRING\", \"default\": \"cc\", \"allowedValues\": [\"aa\", \"bb\"]},\n+ id=\"default not allowed\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"userInterface\": {\"control\": \"UNSUPPORTED\"}},\n+ id=\"unsupported user interface control\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"userInterface\": {\"label\": \"\\n\"}},\n+ id=\"wrong character in user interface label\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"userInterface\": {\"label\": \"\"}},\n+ id=\"user interface label too short\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"userInterface\": {\"label\": \"a\" * 65}},\n+ id=\"user interface label too long\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"userInterface\": {\"groupLabel\": \"\"}},\n+ id=\"user interface groupLabel too short\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"userInterface\": {\"groupLabel\": \"a\" * 65}},\n+ id=\"user interface groupLabel too long\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"INT\",\n+ \"userInterface\": {\"control\": \"SPIN_BOX\"},\n+ \"allowedValues\": [1],\n+ },\n+ id=\"user interface SPIN_BOX can't have allowedValues\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"INT\",\n+ \"userInterface\": {\"control\": \"HIDDEN\", \"singleStepDelta\": 3},\n+ },\n+ id=\"user interface HIDDEN cannot use singleStepDelta\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"INT\",\n+ \"userInterface\": {\"control\": \"DROPDOWN_LIST\", \"singleStepDelta\": 3},\n+ \"allowedValues\": [1, 2],\n+ },\n+ id=\"user interface DROPDOWN_LIST cannot use singleStepDelta\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"userInterface\": {\"control\": \"DROPDOWN_LIST\"}},\n+ id=\"user interface DROPDOWN_LIST requires allowedValues\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description JobIntParameterDefinition.\n+ # - Constraint tests\n+ # - extra field test\n+ # - type cooersion\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=JobIntParameterDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+ @pytest.mark.parametrize(\n+ \"value,parameter\",\n+ [\n+ pytest.param(\n+ 5, JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"passes type int\"\n+ ),\n+ pytest.param(\n+ \"5\", JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"passes type str\"\n+ ),\n+ pytest.param(\n+ 5, JobIntParameterDefinition(name=\"Foo\", type=\"INT\", minValue=0), id=\"min value\"\n+ ),\n+ pytest.param(\n+ 5, JobIntParameterDefinition(name=\"Foo\", type=\"INT\", minValue=5), id=\"min value\"\n+ ),\n+ pytest.param(\n+ 5, JobIntParameterDefinition(name=\"Foo\", type=\"INT\", maxValue=5), id=\"max value\"\n+ ),\n+ pytest.param(\n+ 5, JobIntParameterDefinition(name=\"Foo\", type=\"INT\", maxValue=15), id=\"max value\"\n+ ),\n+ pytest.param(\n+ 5,\n+ JobIntParameterDefinition(name=\"Foo\", type=\"INT\", allowedValues=[5, 6]),\n+ id=\"allowed value 5\",\n+ ),\n+ pytest.param(\n+ 6,\n+ JobIntParameterDefinition(name=\"Foo\", type=\"INT\", allowedValues=[5, 6]),\n+ id=\"allowed value 6\",\n+ ),\n+ pytest.param(\n+ \"5\",\n+ JobIntParameterDefinition(name=\"Foo\", type=\"INT\", allowedValues=[5, 6]),\n+ id=\"allowed value 5 str\",\n+ ),\n+ pytest.param(\n+ \"6\",\n+ JobIntParameterDefinition(name=\"Foo\", type=\"INT\", allowedValues=[5, 6]),\n+ id=\"allowed value 6 str\",\n+ ),\n+ pytest.param(\n+ 5,\n+ JobIntParameterDefinition(name=\"Foo\", type=\"INT\", allowedValues=[\"5\", \"6\"]),\n+ id=\"allowed values are str\",\n+ ),\n+ ],\n+ )\n+ def test_check_constraints_noraise(\n+ self, value: Any, parameter: JobIntParameterDefinition\n+ ) -> None:\n+ # WHEN\n+ # will raise if the value doesn't pass the checks\n+ parameter._check_constraints(value)\n+\n+ # THEN\n+ assert True\n+\n+ @pytest.mark.parametrize(\n+ \"value,parameter\",\n+ [\n+ pytest.param(None, JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"none type\"),\n+ pytest.param(\"foo\", JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"bad string\"),\n+ pytest.param(\n+ \"1.2\", JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"float string\"\n+ ),\n+ pytest.param(True, JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"bool type\"),\n+ pytest.param(1.2, JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"float type\"),\n+ pytest.param(list(), JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"list type\"),\n+ pytest.param(dict(), JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"dict type\"),\n+ pytest.param(\n+ Decimal(1), JobIntParameterDefinition(name=\"Foo\", type=\"INT\"), id=\"decimal type\"\n+ ),\n+ pytest.param(\n+ 5, JobIntParameterDefinition(name=\"Foo\", type=\"INT\", minValue=6), id=\"min value\"\n+ ),\n+ pytest.param(\n+ 5, JobIntParameterDefinition(name=\"Foo\", type=\"INT\", maxValue=4), id=\"max value\"\n+ ),\n+ pytest.param(\n+ 4,\n+ JobIntParameterDefinition(name=\"Foo\", type=\"INT\", allowedValues=[5, 6]),\n+ id=\"allowed value\",\n+ ),\n+ pytest.param(\n+ 4,\n+ JobIntParameterDefinition(name=\"Foo\", type=\"INT\", allowedValues=[\"5\", \"6\"]),\n+ id=\"allowed value\",\n+ ),\n+ pytest.param(\n+ \"4\",\n+ JobIntParameterDefinition(name=\"Foo\", type=\"INT\", allowedValues=[5, 6]),\n+ id=\"allowed value\",\n+ ),\n+ pytest.param(\n+ \"4\",\n+ JobIntParameterDefinition(name=\"Foo\", type=\"INT\", allowedValues=[\"5\", \"6\"]),\n+ id=\"allowed value\",\n+ ),\n+ ],\n+ )\n+ def test_check_constraints_raises(\n+ self, value: Any, parameter: JobIntParameterDefinition\n+ ) -> None:\n+ # WHEN\n+ with pytest.raises(ValueError):\n+ parameter._check_constraints(value)\n+\n+\n+class TestJobFloatParameterDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"Foo\", \"type\": \"FLOAT\"}, id=\"minimal required\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"description\": \"some text\"}, id=\"description\"\n+ ),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": 1}, id=\"has default as int\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": 1.2}, id=\"has default as float\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": \"1.2\"}, id=\"has default as string\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"minValue\": 1}, id=\"has min value as int\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"minValue\": 1.2}, id=\"has min value as float\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"minValue\": \"1.2\"}, id=\"has min value as string\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"maxValue\": 1}, id=\"has max value as int\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"maxValue\": 1.2}, id=\"has max value as float\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"maxValue\": \"1.2\"}, id=\"has max value as string\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": [1]}, id=\"has allowedValues int\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": [1.2]},\n+ id=\"has allowedValues float\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": [\"1.2\"]},\n+ id=\"has allowedValues string\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"minValue\": 1, \"maxValue\": 1}, id=\"min = max\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"minValue\": 1, \"maxValue\": 2}, id=\"min < max\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": [2], \"minValue\": 2},\n+ id=\"allowed is min value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": [2], \"maxValue\": 2},\n+ id=\"allowed is max value\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": 2, \"minValue\": 2},\n+ id=\"default is min value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": 2, \"maxValue\": 2},\n+ id=\"default is max value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": 2, \"allowedValues\": [1, \"2\"]},\n+ id=\"default is allowed\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"userInterface\": {\"control\": \"SPIN_BOX\"}},\n+ id=\"user interface SPIN_BOX\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"FLOAT\",\n+ \"userInterface\": {\"control\": \"SPIN_BOX\", \"singleStepDelta\": 3.5},\n+ },\n+ id=\"user interface SPIN_BOX\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"userInterface\": {\"control\": \"HIDDEN\"}},\n+ id=\"user interface HIDDEN\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"FLOAT\",\n+ \"userInterface\": {\"control\": \"DROPDOWN_LIST\"},\n+ \"allowedValues\": [1],\n+ },\n+ id=\"user interface DROPDOWN_LIST\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"FLOAT\",\n+ \"userInterface\": {\n+ \"control\": \"DROPDOWN_LIST\",\n+ \"label\": \"Foo Label\",\n+ \"groupLabel\": \"Group Label\",\n+ },\n+ \"default\": 1,\n+ \"allowedValues\": [1, \"2\"],\n+ \"minValue\": 1,\n+ \"maxValue\": 3,\n+ },\n+ id=\"all fields\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description JobFloatParameterDefinition\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our JobFloatParameterDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=JobFloatParameterDefinition, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"STRING\"}, id=\"wrong type\"),\n+ pytest.param({\"name\": \"Foo\"}, id=\"missing type\"),\n+ pytest.param({\"type\": \"FLOAT\"}, id=\"missing name\"),\n+ pytest.param({\"name\": 12, \"type\": \"FLOAT\"}, id=\"name not a string\"),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"description\": 12}, id=\"description not string\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": []}, id=\"allowedValues too small\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": [\"aa\"]},\n+ id=\"allowedValues item not number\",\n+ ),\n+ #\n+ pytest.param({\"name\": \"Foo\", \"type\": \"FLOAT\", \"minValue\": True}, id=\"min a bool\"),\n+ pytest.param({\"name\": \"Foo\", \"type\": \"FLOAT\", \"maxValue\": True}, id=\"max a bool\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"minValue\": 2, \"maxValue\": 1}, id=\"min > max\"\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": [True]},\n+ id=\"allowed item is a bool\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": [2], \"minValue\": 3},\n+ id=\"allowed less than min value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"allowedValues\": [2], \"maxValue\": 1},\n+ id=\"allowed exceeds max value\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": True},\n+ id=\"default is a bool\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": 2, \"minValue\": 3},\n+ id=\"default less than min value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": 2, \"maxLength\": 1},\n+ id=\"default exceeds max value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"default\": 0, \"allowedValues\": [1, 2]},\n+ id=\"default not allowed\",\n+ ),\n+ #\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"userInterface\": {\"control\": \"UNSUPPORTED\"}},\n+ id=\"unsupported user interface control\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"userInterface\": {\"label\": \"\\n\"}},\n+ id=\"wrong character in user interface label\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"userInterface\": {\"label\": \"\"}},\n+ id=\"user interface label too short\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"userInterface\": {\"label\": \"a\" * 65}},\n+ id=\"user interface label too long\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"userInterface\": {\"groupLabel\": \"\"}},\n+ id=\"user interface groupLabel too short\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"userInterface\": {\"groupLabel\": \"a\" * 65}},\n+ id=\"user interface groupLabel too long\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"FLOAT\",\n+ \"userInterface\": {\"control\": \"SPIN_BOX\"},\n+ \"allowedValues\": [1],\n+ },\n+ id=\"user interface SPIN_BOX can't have allowedValues\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"FLOAT\",\n+ \"userInterface\": {\"control\": \"HIDDEN\", \"singleStepDelta\": 3},\n+ },\n+ id=\"user interface HIDDEN cannot use singleStepDelta\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"FLOAT\",\n+ \"userInterface\": {\"control\": \"DROPDOWN_LIST\", \"singleStepDelta\": 3},\n+ \"allowedValues\": [1, 2],\n+ },\n+ id=\"user interface DROPDOWN_LIST cannot use singleStepDelta\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"type\": \"FLOAT\", \"userInterface\": {\"control\": \"DROPDOWN_LIST\"}},\n+ id=\"user interface DROPDOWN_LIST requires allowedValues\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description JobFloatParameterDefinition.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=JobFloatParameterDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+ @pytest.mark.parametrize(\n+ \"value,parameter\",\n+ [\n+ pytest.param(\n+ 5, JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"), id=\"passes type int\"\n+ ),\n+ pytest.param(\n+ \"5\", JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"), id=\"passes type str int\"\n+ ),\n+ pytest.param(\n+ 5.5, JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"), id=\"passes type float\"\n+ ),\n+ pytest.param(\n+ \"5.5\",\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"),\n+ id=\"passes type str float\",\n+ ),\n+ #\n+ pytest.param(\n+ Decimal(\"5.5\"),\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"),\n+ id=\"passes type decimal\",\n+ ),\n+ #\n+ pytest.param(\n+ 5.5,\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\", minValue=0),\n+ id=\"min value\",\n+ ),\n+ pytest.param(\n+ 5.5,\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\", minValue=5.5),\n+ id=\"min value\",\n+ ),\n+ pytest.param(\n+ 5.5,\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\", maxValue=5.5),\n+ id=\"max value\",\n+ ),\n+ pytest.param(\n+ 5.5,\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\", maxValue=15),\n+ id=\"max value\",\n+ ),\n+ #\n+ pytest.param(\n+ 1.2,\n+ JobFloatParameterDefinition(\n+ name=\"Foo\", type=\"FLOAT\", allowedValues=[Decimal(\"1.2\"), 5.5]\n+ ),\n+ id=\"allowed value 1.2 float\",\n+ ),\n+ pytest.param(\n+ 5.5,\n+ JobFloatParameterDefinition(\n+ name=\"Foo\", type=\"FLOAT\", allowedValues=[Decimal(\"1.2\"), 5.5]\n+ ),\n+ id=\"allowed value 5.5 float\",\n+ ),\n+ pytest.param(\n+ \"1.2\",\n+ JobFloatParameterDefinition(\n+ name=\"Foo\", type=\"FLOAT\", allowedValues=[Decimal(\"1.2\"), 5.5]\n+ ),\n+ id=\"allowed value 1.2 str\",\n+ ),\n+ pytest.param(\n+ \"5.5\",\n+ JobFloatParameterDefinition(\n+ name=\"Foo\", type=\"FLOAT\", allowedValues=[Decimal(\"1.2\"), 5.5]\n+ ),\n+ id=\"allowed value 5.5 str\",\n+ ),\n+ pytest.param(\n+ Decimal(\"1.2\"),\n+ JobFloatParameterDefinition(\n+ name=\"Foo\", type=\"FLOAT\", allowedValues=[Decimal(\"1.2\"), 5.5]\n+ ),\n+ id=\"allowed value 1.2 decimal\",\n+ ),\n+ pytest.param(\n+ Decimal(\"5.5\"),\n+ JobFloatParameterDefinition(\n+ name=\"Foo\", type=\"FLOAT\", allowedValues=[Decimal(\"1.2\"), 5.5]\n+ ),\n+ id=\"allowed value 5.5 decimal\",\n+ ),\n+ ],\n+ )\n+ def test_check_constraints_noraise(\n+ self, value: Any, parameter: JobFloatParameterDefinition\n+ ) -> None:\n+ # WHEN\n+ # will raise if the value doesn't pass the checks\n+ parameter._check_constraints(value)\n+\n+ # THEN\n+ assert True\n+\n+ @pytest.mark.parametrize(\n+ \"value,parameter\",\n+ [\n+ pytest.param(\n+ None, JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"), id=\"none type\"\n+ ),\n+ pytest.param(\n+ True, JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"), id=\"bool type\"\n+ ),\n+ pytest.param(\n+ list(), JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"), id=\"list type\"\n+ ),\n+ pytest.param(\n+ dict(), JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"), id=\"dict type\"\n+ ),\n+ pytest.param(\n+ \"foo\", JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\"), id=\"bad string\"\n+ ),\n+ pytest.param(\n+ 5.4,\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\", minValue=5.5),\n+ id=\"min value\",\n+ ),\n+ pytest.param(\n+ 5.6,\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\", maxValue=5.5),\n+ id=\"max value\",\n+ ),\n+ pytest.param(\n+ 4,\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\", allowedValues=[5, 6]),\n+ id=\"allowed value\",\n+ ),\n+ pytest.param(\n+ \"4\",\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\", allowedValues=[5, 6]),\n+ id=\"allowed value\",\n+ ),\n+ pytest.param(\n+ 4,\n+ JobFloatParameterDefinition(name=\"Foo\", type=\"FLOAT\", allowedValues=[\"5\", \"6\"]),\n+ id=\"allowed value\",\n+ ),\n+ ],\n+ )\n+ def test_check_constraints_raises(\n+ self, value: Any, parameter: JobFloatParameterDefinition\n+ ) -> None:\n+ # WHEN\n+ with pytest.raises(ValueError):\n+ parameter._check_constraints(value)"}, {"sha": "49586eba7e2cc98a8b50b166afbd49ff4f850434", "filename": "test/openjd/model/v2023_09/test_job_template.py", "status": "added", "additions": 368, "deletions": 0, "changes": 368, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_job_template.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_job_template.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_job_template.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,368 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import JobTemplate\n+\n+# Some minimal data to reference in tests.\n+ENV_SCRIPT = {\"actions\": {\"onEnter\": {\"command\": \"foo\"}}}\n+ENVIRONMENT = {\"name\": \"Foo\", \"script\": ENV_SCRIPT}\n+STEP_SCRIPT = {\"actions\": {\"onRun\": {\"command\": \"foo\"}}}\n+STEP_TEMPLATE = {\"name\": \"StepName\", \"script\": STEP_SCRIPT}\n+\n+\n+class TestJobTemplate:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ },\n+ id=\"minimum required\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [{\"name\": f\"S{i}\", \"script\": STEP_SCRIPT} for i in range(0, 100)],\n+ },\n+ id=\"with most steps\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"description\": \"some text\",\n+ },\n+ id=\"with description\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"parameterDefinitions\": [{\"name\": \"P\", \"type\": \"INT\"}],\n+ },\n+ id=\"with least parameters\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"parameterDefinitions\": [\n+ {\"name\": f\"P{i}\", \"type\": \"INT\"} for i in range(0, 50)\n+ ],\n+ },\n+ id=\"with most parameters\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"jobEnvironments\": [ENVIRONMENT],\n+ },\n+ id=\"with least environments\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"jobEnvironments\": [\n+ {\"name\": f\"E{i}\", \"script\": ENV_SCRIPT} for i in range(0, 10)\n+ ],\n+ },\n+ id=\"with most environments\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"jobEnvironments\": [\n+ {\"name\": f\"E{i}\", \"script\": ENV_SCRIPT} for i in range(0, 2)\n+ ],\n+ },\n+ id=\"different environment names\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"$schema\": \"some text\",\n+ },\n+ id=\"with $schema\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"StepOne\",\n+ \"script\": STEP_SCRIPT,\n+ },\n+ {\n+ \"name\": \"StepTwo\",\n+ \"script\": STEP_SCRIPT,\n+ \"dependencies\": [{\"dependsOn\": \"StepOne\"}],\n+ },\n+ ],\n+ },\n+ id=\"with step dependencies in declared order\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"StepOne\",\n+ \"script\": STEP_SCRIPT,\n+ \"dependencies\": [{\"dependsOn\": \"StepTwo\"}],\n+ },\n+ {\n+ \"name\": \"StepTwo\",\n+ \"script\": STEP_SCRIPT,\n+ },\n+ ],\n+ },\n+ id=\"with step dependencies out of declared order\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"StepOne\",\n+ \"script\": STEP_SCRIPT,\n+ \"stepEnvironments\": [\n+ {\"name\": f\"A{i}\", \"script\": ENV_SCRIPT} for i in range(0, 2)\n+ ],\n+ },\n+ {\n+ \"name\": \"StepTwo\",\n+ \"script\": STEP_SCRIPT,\n+ \"stepEnvironments\": [\n+ {\"name\": f\"B{i}\", \"script\": ENV_SCRIPT} for i in range(0, 2)\n+ ],\n+ },\n+ ],\n+ \"jobEnvironments\": [\n+ {\"name\": f\"J{i}\", \"script\": ENV_SCRIPT} for i in range(0, 2)\n+ ],\n+ },\n+ id=\"job and step env names all differ\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description JobTemplate\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our JobTemplate model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=JobTemplate, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"unknown\": \"key\",\n+ },\n+ id=\"unknown key\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ },\n+ id=\"missing spec ver\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"description\": 12,\n+ },\n+ id=\"description not string\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ },\n+ id=\"missing steps\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [],\n+ },\n+ id=\"empty steps\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [{\"name\": \"S\", \"script\": STEP_SCRIPT} for i in range(0, 2)],\n+ },\n+ id=\"duplicate step names\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"parameterDefinitions\": [],\n+ },\n+ id=\"empty parameters\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"parameterDefinitions\": [\n+ {\"name\": f\"P{i}\", \"type\": \"INT\"} for i in range(0, 51)\n+ ],\n+ },\n+ id=\"too many job parameters\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"parameterDefinitions\": [{\"name\": \"P\", \"type\": \"INT\"} for i in range(0, 2)],\n+ },\n+ id=\"duplicate parameter names\",\n+ ),\n+ #\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"jobEnvironments\": [],\n+ },\n+ id=\"empty environments\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"jobEnvironments\": [{\"name\": \"E\", \"script\": ENV_SCRIPT} for i in range(0, 2)],\n+ },\n+ id=\"duplicate environment names\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"StepOne\",\n+ \"script\": STEP_SCRIPT,\n+ \"dependencies\": [{\"dependsOn\": \"StepThree\"}],\n+ },\n+ {\n+ \"name\": \"StepTwo\",\n+ \"script\": STEP_SCRIPT,\n+ \"dependencies\": [{\"dependsOn\": \"StepOne\"}],\n+ },\n+ {\n+ \"name\": \"StepThree\",\n+ \"script\": STEP_SCRIPT,\n+ \"dependencies\": [{\"dependsOn\": \"StepTwo\"}],\n+ },\n+ ],\n+ },\n+ id=\"with step dependency cycle\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"StepOne\",\n+ \"script\": STEP_SCRIPT,\n+ },\n+ {\n+ \"name\": \"StepTwo\",\n+ \"script\": STEP_SCRIPT,\n+ \"dependencies\": [{\"dependsOn\": \"StepUnknown\"}],\n+ },\n+ ],\n+ },\n+ id=\"refs unknown step\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"StepOne\",\n+ \"script\": STEP_SCRIPT,\n+ \"stepEnvironments\": [\n+ {\"name\": f\"A{i}\", \"script\": ENV_SCRIPT} for i in range(0, 2)\n+ ],\n+ },\n+ {\n+ \"name\": \"StepTwo\",\n+ \"script\": STEP_SCRIPT,\n+ \"stepEnvironments\": [\n+ {\"name\": f\"B{i}\", \"script\": ENV_SCRIPT} for i in range(0, 2)\n+ ],\n+ },\n+ ],\n+ \"jobEnvironments\": [\n+ {\"name\": \"A0\", \"script\": ENV_SCRIPT},\n+ {\"name\": \"B0\", \"script\": ENV_SCRIPT},\n+ ],\n+ },\n+ id=\"step env name duplicates job env name\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description JobTemplate.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=JobTemplate, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0"}, {"sha": "43d35ea029d189582e9617c8a1d601914ca4e203", "filename": "test/openjd/model/v2023_09/test_parameter_space.py", "status": "added", "additions": 522, "deletions": 0, "changes": 522, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_parameter_space.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_parameter_space.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_parameter_space.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,522 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import (\n+ FloatTaskParameterDefinition,\n+ IntTaskParameterDefinition,\n+ PathTaskParameterDefinition,\n+ StepParameterSpaceDefinition,\n+ StringTaskParameterDefinition,\n+)\n+\n+\n+class TestIntTaskParameterDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]}, id=\"min len int list\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1] * 1024}, id=\"max len int list\"\n+ ),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": [\"1\"]}, id=\"int as string\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": [\"1\", 2]}, id=\"mixed int types\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [\"{{Param.Value}}\"]},\n+ id=\"format string\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1, \"2\", \"{{Param.Value}}\"]},\n+ id=\"mix of item types\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description IntTaskParameterDefinition\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our IntTaskParameterDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=IntTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ # does not raise an exception\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [1]}, id=\"wrong type\"),\n+ pytest.param({\"type\": \"INT\", \"range\": [1]}, id=\"missing name\"),\n+ pytest.param({\"name\": \"foo\", \"range\": [1]}, id=\"missing type\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\"}, id=\"missing range\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": []}, id=\"range too short\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1], \"unknown\": \"key\"}, id=\"unknown key\"\n+ ),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": [1] * 1025}, id=\"range too long\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": [1.1]}, id=\"disallow floats\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": [True]}, id=\"disallow bool\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [\"1.1\"]}, id=\"disallow float strings\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [\"{{ Job.Parameter.Foo\"]},\n+ id=\"malformed format string\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [\"notint\"]},\n+ id=\"literal string not an int\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description TaskParameterDecl.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=IntTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestFloatTaskParameterDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [1]}, id=\"min len list\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [1] * 1024}, id=\"max len list\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [1.1]}, id=\"float value\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [\"1\"]}, id=\"int as string\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [\"1.1\"]}, id=\"float as string\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [\"1\", 2, 3.3, \"3.4\"]},\n+ id=\"mixed number types\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [\"{{Param.Value}}\"]},\n+ id=\"format string\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"foo\",\n+ \"type\": \"FLOAT\",\n+ \"range\": [1, \"2\", 3.3, \"3.4\", \"{{Param.Value}}\"],\n+ },\n+ id=\"mix of item types\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description TestFloatTaskParameterDefinition\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our TestFloatTaskParameterDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=FloatTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ # does not raise an exception\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]}, id=\"wrong type\"),\n+ pytest.param({\"type\": \"FLOAT\", \"range\": [1]}, id=\"missing name\"),\n+ pytest.param({\"name\": \"foo\", \"range\": [1]}, id=\"missing type\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"FLOAT\"}, id=\"missing range\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": []}, id=\"range too short\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [1], \"unknown\": \"key\"}, id=\"unknown key\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [1] * 1025}, id=\"range too long\"\n+ ),\n+ pytest.param({\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [True]}, id=\"disallow bool\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [\"{{ Job.Parameter.Foo\"]},\n+ id=\"malformed format string\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [\"notnumber\"]},\n+ id=\"literal string not a number\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description TaskParameterDecl.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=FloatTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestStringTaskParameterDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"foo\", \"type\": \"STRING\", \"range\": [\"a\"]}, id=\"min len list\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"STRING\", \"range\": [\"a\"] * 1024}, id=\"max len list\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"STRING\", \"range\": [\"{{Param.Value}}\"]},\n+ id=\"format string\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description StringTaskParameterDefinition\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our StringTaskParameterDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=StringTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ # does not raise an exception\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]}, id=\"wrong type\"),\n+ pytest.param({\"type\": \"STRING\", \"range\": [\"a\"]}, id=\"missing name\"),\n+ pytest.param({\"name\": \"foo\", \"range\": [\"a\"]}, id=\"missing type\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"STRING\"}, id=\"missing range\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"STRING\", \"range\": []}, id=\"range too short\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"STRING\", \"range\": [\"a\"], \"unknown\": \"key\"},\n+ id=\"unknown key\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"STRING\", \"range\": [\"a\"] * 1025}, id=\"list too long\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"STRING\", \"range\": [\"{{ Job.Parameter.Foo\"]},\n+ id=\"malformed format string\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description TaskParameterDecl.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=StringTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestPathTaskParameterDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"foo\", \"type\": \"PATH\", \"range\": [\"a\"]}, id=\"min len list\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"PATH\", \"range\": [\"a\"] * 1024}, id=\"max len list\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"PATH\", \"range\": [\"{{Job.Parameter.Value}}\"]},\n+ id=\"format string\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description PathTaskParameterDefinition\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our PathTaskParameterDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=PathTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ # does not raise an exception\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]}, id=\"wrong type\"),\n+ pytest.param({\"type\": \"PATH\", \"range\": [\"a\"]}, id=\"missing name\"),\n+ pytest.param({\"name\": \"foo\", \"range\": [\"a\"]}, id=\"missing type\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"PATH\"}, id=\"missing range\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"PATH\", \"range\": []}, id=\"range too short\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"PATH\", \"range\": [\"a\"], \"unknown\": \"key\"},\n+ id=\"unknown key\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"PATH\", \"range\": [\"a\"] * 1025}, id=\"list too long\"\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"PATH\", \"range\": [\"{{ Job.Parameter.Foo\"]},\n+ id=\"malformed format string\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description TaskParameterDecl.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=PathTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestRangeExpressionTaskParameterDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": \"1\"}, id=\"one item\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": \"1-10\"}, id=\"one range of items\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": \"10--5:-1\"},\n+ id=\"one negative range of items\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": \"1-10:2\"},\n+ id=\"one range of items with steps\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": \"-5--14:-2\"},\n+ id=\"negative range with negative steps\",\n+ ),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": \"-10-0,1-10\"}, id=\"two ranges\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": \"10-1:-1,11-20:2\"},\n+ id=\"two ranges with opposite signs\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": \"1-10:2\"},\n+ id=\"one range of items with steps\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": \"{{Param.Value}}\"},\n+ id=\"format string\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"foo\",\n+ \"type\": \"INT\",\n+ \"range\": \"{{Job.Parameter.Start}}-{{Job.Parameter.End}}:{{Job.Parameter.Step}}\",\n+ },\n+ id=\"format string with multiple\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, str]) -> None:\n+ # Parsing tests of valid Open Job Description RangeExpression\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our IntTaskParameterDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=IntTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ # does not raise an exception\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"foo\", \"type\": \"STRING\", \"range\": [\"1\"]}, id=\"wrong type\"),\n+ pytest.param({\"type\": \"INT\", \"range\": \"1\"}, id=\"missing name\"),\n+ pytest.param({\"name\": \"foo\", \"range\": \"1\"}, id=\"missing type\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\"}, id=\"missing range\"),\n+ pytest.param({\"name\": \"foo\", \"type\": \"INT\", \"range\": \"\"}, id=\"range too short\"),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": \"1\", \"unknown\": \"key\"},\n+ id=\"unknown key\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": \"{{ Job.Parameter.Foo\"},\n+ id=\"malformed format string\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description TaskParameterDecl.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=IntTaskParameterDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestStepParameterSpaceDefinition:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param(\n+ {\"taskParameterDefinitions\": [{\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]}]},\n+ id=\"int parameter\",\n+ ),\n+ pytest.param(\n+ {\"taskParameterDefinitions\": [{\"name\": \"foo\", \"type\": \"FLOAT\", \"range\": [1]}]},\n+ id=\"float parameter\",\n+ ),\n+ pytest.param(\n+ {\"taskParameterDefinitions\": [{\"name\": \"foo\", \"type\": \"STRING\", \"range\": [\"1\"]}]},\n+ id=\"string parameter\",\n+ ),\n+ pytest.param(\n+ {\"taskParameterDefinitions\": [{\"name\": \"foo\", \"type\": \"PATH\", \"range\": [\"/tmp\"]}]},\n+ id=\"path parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": f\"foo{i}\", \"type\": \"INT\", \"range\": [1]} for i in range(0, 16)\n+ ]\n+ },\n+ id=\"most number of parameters\",\n+ ),\n+ pytest.param(\n+ {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]},\n+ {\"name\": \"bar\", \"type\": \"INT\", \"range\": [1]},\n+ ],\n+ \"combination\": \"foo * bar\",\n+ },\n+ id=\"with combination expr\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description StepParameterSpaceDefinition\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our StepParameterSpaceDefinition model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=StepParameterSpaceDefinition, obj=data)\n+\n+ # THEN\n+ # no exception is raised\n+\n+ @pytest.mark.parametrize(\n+ \"data,expected_num_errors\",\n+ (\n+ pytest.param({}, 1, id=\"empty object\"),\n+ pytest.param({\"taskParameterDefinitions\": []}, 1, id=\"empty parameter list\"),\n+ pytest.param(\n+ {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": f\"foo{i}\", \"type\": \"INT\", \"range\": [1]} for i in range(0, 17)\n+ ]\n+ },\n+ 1,\n+ id=\"too many parameters\",\n+ ),\n+ pytest.param(\n+ {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]},\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]},\n+ ],\n+ },\n+ 1,\n+ id=\"duplicate parameter name\",\n+ ),\n+ pytest.param(\n+ {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]},\n+ {\"name\": \"bar\", \"type\": \"INT\", \"range\": [1]},\n+ ],\n+ \"combination\": \"foo bar\",\n+ },\n+ 1,\n+ id=\"malformed combination expr\",\n+ ),\n+ pytest.param(\n+ {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]},\n+ {\"name\": \"bar\", \"type\": \"INT\", \"range\": [1]},\n+ ],\n+ \"combination\": \"foo\",\n+ },\n+ 1,\n+ id=\"combination expr doesn't reference all parameters #1\",\n+ ),\n+ pytest.param(\n+ {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]},\n+ {\"name\": \"bar\", \"type\": \"INT\", \"range\": [1]},\n+ ],\n+ \"combination\": \"foo * bar * baz\",\n+ },\n+ 1,\n+ id=\"combination expr refs undefined parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]},\n+ {\"name\": \"bar\", \"type\": \"INT\", \"range\": [1]},\n+ ],\n+ \"combination\": \"foo * bar * foo\",\n+ },\n+ 1,\n+ id=\"combination expr double refs a parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]},\n+ {\"name\": \"bar\", \"type\": \"INT\", \"range\": [1]},\n+ ],\n+ \"combination\": \"foo * foo\",\n+ },\n+ 2,\n+ id=\"combination expr double refs & missing ref\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any], expected_num_errors: int) -> None:\n+ # Failure case testing for Open Job Description StepParameterSpaceDefinition.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=StepParameterSpaceDefinition, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == expected_num_errors, str(excinfo.value)"}, {"sha": "aa1207e5182d2f1c483f846fb975027f8a868d49", "filename": "test/openjd/model/v2023_09/test_scripts.py", "status": "added", "additions": 177, "deletions": 0, "changes": 177, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_scripts.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_scripts.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_scripts.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,177 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import EnvironmentScript, StepScript\n+\n+\n+class TestStepScript:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"actions\": {\"onRun\": {\"command\": \"foo\"}}}, id=\"all required\"),\n+ pytest.param(\n+ {\n+ \"actions\": {\"onRun\": {\"command\": \"foo\"}},\n+ \"embeddedFiles\": [{\"name\": \"Foo\", \"type\": \"TEXT\", \"data\": \"data\"}],\n+ },\n+ id=\"min len embedded files\",\n+ ),\n+ pytest.param(\n+ {\n+ \"actions\": {\"onRun\": {\"command\": \"foo\"}},\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": f\"Name{i}\", # each must have a unique name\n+ \"type\": \"TEXT\",\n+ \"data\": \"data\",\n+ }\n+ for i in range(0, 5)\n+ ],\n+ },\n+ id=\"max len embedded files\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description StepScript\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our StepScript model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=StepScript, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param(\n+ {\"actions\": {\"onRun\": {\"command\": \"foo\"}}, \"unknown\": \"name\"}, id=\"unknown key\"\n+ ),\n+ pytest.param(\n+ {\n+ \"actions\": {\"onRun\": {\"command\": \"foo\"}},\n+ \"embeddedFiles\": [],\n+ },\n+ id=\"too few embedded files\",\n+ ),\n+ pytest.param(\n+ {\n+ \"actions\": {\"onRun\": {\"command\": \"foo\"}},\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": \"Name\", # each must have a unique name\n+ \"type\": \"TEXT\",\n+ \"data\": \"data\",\n+ }\n+ for i in range(0, 2)\n+ ],\n+ },\n+ id=\"embedded file duplicate names\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description StepScript.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=StepScript, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestEnvironmentScript:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"actions\": {\"onEnter\": {\"command\": \"foo\"}}}, id=\"minimal\"),\n+ pytest.param(\n+ {\n+ \"actions\": {\"onEnter\": {\"command\": \"foo\"}},\n+ \"embeddedFiles\": [{\"name\": \"Foo\", \"type\": \"TEXT\", \"data\": \"data\"}],\n+ },\n+ id=\"min len embedded files\",\n+ ),\n+ pytest.param(\n+ {\n+ \"actions\": {\"onEnter\": {\"command\": \"foo\"}},\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": f\"Name{i}\", # each must have a unique name\n+ \"type\": \"TEXT\",\n+ \"data\": \"data\",\n+ }\n+ for i in range(0, 5)\n+ ],\n+ },\n+ id=\"max len embedded files\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description EnvironmentScript\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our EnvironmentScript model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=EnvironmentScript, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param(\n+ {\"actions\": {\"onEnter\": {\"command\": \"foo\"}}, \"unknown\": \"name\"}, id=\"unknown key\"\n+ ),\n+ pytest.param(\n+ {\n+ \"actions\": {\"onEnter\": {\"command\": \"foo\"}},\n+ \"embeddedFiles\": [],\n+ },\n+ id=\"too few embedded files\",\n+ ),\n+ pytest.param(\n+ {\n+ \"actions\": {\"onEnter\": {\"command\": \"foo\"}},\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": \"Name\", # each must have a unique name\n+ \"type\": \"TEXT\",\n+ \"data\": \"data\",\n+ }\n+ for i in range(0, 2)\n+ ],\n+ },\n+ id=\"embedded file duplicate names\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description EnvironmentScript.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=EnvironmentScript, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0"}, {"sha": "acc77874e97c082ccb978c556ea2aa1d96c60a60", "filename": "test/openjd/model/v2023_09/test_step_host_requirements.py", "status": "added", "additions": 480, "deletions": 0, "changes": 480, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_step_host_requirements.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_step_host_requirements.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_step_host_requirements.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,480 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+import string\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import (\n+ AmountRequirementTemplate,\n+ AttributeRequirementTemplate,\n+ HostRequirementsTemplate,\n+)\n+\n+\n+class TestAttributeRequirementTemplate:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ # All the built-in attribute capabilities\n+ pytest.param(\n+ {\"name\": \"attr.worker.os.family\", \"anyOf\": [\"linux\"]},\n+ id=\"os family anyOf single\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.os.family\", \"anyOf\": [\"linux\", \"windows\"]},\n+ id=\"os family anyOf multiple\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.os.family\", \"allOf\": [\"linux\"]},\n+ id=\"os family allOf single\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.cpu.arch\", \"anyOf\": [\"x86_64\"]},\n+ id=\"cpu arch anyOf single\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.cpu.arch\", \"anyOf\": [\"x86_64\", \"arm64\"]},\n+ id=\"cpu arch anyOf multiple\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.cpu.arch\", \"allOf\": [\"x86_64\"]},\n+ id=\"cpu arch allOf single\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.cpu.arch\", \"allOf\": [\"{{ Param.Foo }}\"]},\n+ id=\"allOf accepts format string\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.cpu.arch\", \"anyOf\": [\"{{ Param.Foo }}\"]},\n+ id=\"anyOf accepts format string\",\n+ ),\n+ # User-defined attributes\n+ pytest.param(\n+ {\"name\": \"attr.mycapability\", \"anyOf\": [\"somevalue\"]},\n+ id=\"user defined - anyOf single\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"attr.mycapability\",\n+ \"anyOf\": [f\"value{i}\" for i in range(0, 50)],\n+ },\n+ id=\"user defined - anyOf max elements\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.mycapability\", \"allOf\": [\"somevalue\"]},\n+ id=\"user defined - allOf single\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"attr.mycapability\",\n+ \"allOf\": [f\"value{i}\" for i in range(0, 50)],\n+ },\n+ id=\"user defined - allOf max elements\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.mycapability\", \"allOf\": [\"foo\", \"bar\"], \"anyOf\": [\"buz\", \"wuz\"]},\n+ id=\"allows both anyOf and allOf\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Success case testing for Open Job Description AttributeRequirementTemplate.\n+\n+ # WHEN\n+ _parse_model(model=AttributeRequirementTemplate, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data,error_count\",\n+ (\n+ # All the built-in attribute capabilities\n+ pytest.param(\n+ {\"name\": \"attr.worker.os.family\"},\n+ 1,\n+ id=\"os family missing anyOf/allOf\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.os.family\", \"anyOf\": [\"personalos\"]},\n+ 1,\n+ id=\"os family anyOf unknown value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.os.family\", \"anyOf\": []},\n+ 1,\n+ id=\"os family anyOf empty\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.os.family\", \"allOf\": [\"linux\", \"windows\"]},\n+ 1,\n+ id=\"os family allOf multiple\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.cpu.arch\", \"allOf\": [\"x86_128\"]},\n+ 1,\n+ id=\"cpu arch allOf unknown value\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.cpu.arch\", \"allOf\": []},\n+ 1,\n+ id=\"cpu arch allOf empty\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.worker.cpu.arch\", \"allOf\": [\"x86_64\", \"arm64\"]},\n+ 1,\n+ id=\"cpu arch allOf multiple\",\n+ ),\n+ # User-defined attribute capabilities\n+ pytest.param(\n+ {\"name\": \"attr.mycapability\"},\n+ 1,\n+ id=\"user attribute capability - missing anyOf/allOf\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.mycapability\", \"anyOf\": []},\n+ 1,\n+ id=\"user attribute capability - anyOf empty\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"attr.mycapability\",\n+ \"anyOf\": [f\"value{i}\" for i in range(0, 51)],\n+ },\n+ 1,\n+ id=\"user attribute capability - anyOf too many elements\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.mycapability\", \"allOf\": []},\n+ 1,\n+ id=\"user attribute capability - allOf empty\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"attr.mycapability\",\n+ \"allOf\": [f\"value{i}\" for i in range(0, 51)],\n+ },\n+ 1,\n+ id=\"user attribute capability - allOf too many elements\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.mycapability\", \"allOf\": \"stringvalue\"},\n+ 1,\n+ id=\"user attribute capability - incorrect allOf type\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"attr.mycapability\", \"allOf\": {\"key\": \"stringvalue\"}},\n+ 1,\n+ id=\"user attribute capability - incorrect allOf type\",\n+ ),\n+ # Vendor-defined attribute capabilities\n+ pytest.param(\n+ {\"name\": \"vendor:attr.somecapability\"},\n+ 1,\n+ id=\"vendor attribute capability - missing anyOf/allOf\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"vendor:attr.somecapability\", \"anyOf\": []},\n+ 1,\n+ id=\"vendor attribute capability - anyOf empty\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"vendor:attr.somecapability\", \"allOf\": []},\n+ 1,\n+ id=\"vendor attribute capability - allOf empty\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"vendor:attr.somecapability\", \"allOf\": \"stringvalue\"},\n+ 1,\n+ id=\"vendor attribute capability - incorrect allOf type\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"vendor:attr.somecapability\", \"allOf\": {\"key\": \"stringvalue\"}},\n+ 1,\n+ id=\"vendor attribute capability - incorrect allOf type\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any], error_count: int) -> None:\n+ # Failure case testing for Open Job Description AttributeRequirementTemplate.\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=AttributeRequirementTemplate, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == error_count, str(excinfo.value)\n+\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ [\n+ pytest.param(\"a\", id=\"min length\"),\n+ pytest.param(\"a\" * 100, id=\"maximum allowed length\"),\n+ pytest.param(\n+ \"A\" + string.ascii_letters + string.digits + \"_-\", id=\"allowable characters\"\n+ ),\n+ pytest.param(\"_a\", id=\"starts with underscore\"),\n+ pytest.param(\"Aa\", id=\"starts with capital letter\"),\n+ ],\n+ )\n+ @pytest.mark.parametrize(\"field\", [\"anyOf\", \"allOf\"])\n+ def test_non_standard_attribute_capability_value_string(self, field: str, value: str) -> None:\n+ # Test the constraints on an attribute capability value within the\n+ # anyOf and allOf clauses don't raise validation errros when the value\n+ # is compliant.\n+\n+ # GIVEN\n+ data = {\"name\": \"attr.custom\", field: [value]}\n+\n+ # WHEN\n+ _parse_model(model=AttributeRequirementTemplate, obj=data)\n+\n+ # THEN\n+ # doesn't raise an exception when we parse the model\n+\n+ @pytest.mark.parametrize(\n+ \"value,error_count\",\n+ [\n+ pytest.param(\"\", 1, id=\"too short\"),\n+ pytest.param(\"a\" * 101, 1, id=\"too long\"),\n+ pytest.param(\"0a\", 1, id=\"cannot start with digit\"),\n+ ]\n+ + [\n+ pytest.param(f\"A{letter}\", 1, id=f\"'{letter}' not allowed\")\n+ for letter in sorted(\n+ list(\n+ set(string.printable)\n+ - set(string.ascii_letters)\n+ - set(string.digits)\n+ - set(\"-_\")\n+ )\n+ )\n+ ],\n+ )\n+ @pytest.mark.parametrize(\"field\", [\"anyOf\", \"allOf\"])\n+ def test_non_standard_attribute_capability_noncompliant_value_string(\n+ self, field: str, value: str, error_count: int\n+ ) -> None:\n+ # Test the constraints on an amount capability value within the\n+ # anyOf and allOf clauses raise validation errors when they're violated.\n+\n+ # GIVEN\n+ data = {\"name\": \"attr.custom\", field: [value]}\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=AmountRequirementTemplate, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == error_count, str(excinfo.value)\n+\n+\n+class TestAmountRequirementTemplate:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ # All the built-in amount capabilities\n+ pytest.param(\n+ {\"name\": \"amount.worker.gpu\", \"min\": 2},\n+ id=\"amount.worker.gpu min int\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.worker.gpu.memory\", \"min\": 2.25},\n+ id=\"amount.worker.gpu.memory min float\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.worker.disk.scratch\", \"min\": 10, \"max\": 50},\n+ id=\"amount.worker.disk.scratch min max int\",\n+ ),\n+ # User-defined amount capabilities\n+ pytest.param(\n+ {\"name\": \"amount.mycapability\", \"min\": 0.5, \"max\": 2.9},\n+ id=\"user amount capability - min max float\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.mycapability\", \"min\": 0.6, \"max\": 0.61},\n+ id=\"user amount capability - min max float close values\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.mycapability\", \"max\": 1000},\n+ id=\"user amount capability - max int\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.mycapability\", \"max\": 10.79},\n+ id=\"user amount capability - max float\",\n+ ),\n+ # Vendor-defined amount capabilities\n+ pytest.param(\n+ {\"name\": \"vendor:amount.capability\", \"min\": 0.5, \"max\": 2.9},\n+ id=\"vendor amount capability - min max float\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"vendor:amount.capability\", \"min\": 6, \"max\": 6},\n+ id=\"vendor amount capability - min max equal\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Success case testing for Open Job Description AmountRequirementTemplate.\n+\n+ # WHEN\n+ _parse_model(model=AmountRequirementTemplate, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data,error_count\",\n+ (\n+ # All the built-in amount capabilities\n+ pytest.param(\n+ {\"name\": \"amount.worker.gpu.memory\", \"min\": -2},\n+ 1,\n+ id=\"amount.worker.gpu.memory min negative int\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.worker.disk.scratch\", \"min\": -1.5},\n+ 1,\n+ id=\"amount.worker.disk.scratch min negative float\",\n+ ),\n+ # User-defined amount capabilities\n+ pytest.param(\n+ {\"name\": \"amount.mycap\", \"min\": 3, \"max\": 2},\n+ 1,\n+ id=\"user amount capability min bigger than max\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.{{Param.Cap}}\", \"min\": 3, \"max\": 2},\n+ 1,\n+ id=\"user amount capability min bigger than max\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.{{Param.Cap}}\", \"min\": 0.3, \"max\": 0.29},\n+ 1,\n+ id=\"user amount capability min bigger than max float close values\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.mycap\", \"max\": 0},\n+ 1,\n+ id=\"user amount capability max equals zero\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.{{Param.Cap}}\", \"max\": 0},\n+ 1,\n+ id=\"user amount capability max equals zero\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.mycap\", \"max\": {}},\n+ 1,\n+ id=\"user amount capability max is wrong type\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"amount.mycap\", \"min\": [1, 2]},\n+ 1,\n+ id=\"user amount capability min is wrong type\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any], error_count: int) -> None:\n+ # Failure case testing for Open Job Description AmountRequirementTemplate.\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=AmountRequirementTemplate, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == error_count, str(excinfo.value)\n+\n+\n+class TestHostRequirementsTemplate:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ [\n+ pytest.param({\"amounts\": [{\"name\": \"amount.mycap\", \"min\": 1}]}, id=\"single amount\"),\n+ pytest.param(\n+ {\"attributes\": [{\"name\": \"attr.mycap\", \"anyOf\": [\"foo\"]}]}, id=\"single amount\"\n+ ),\n+ pytest.param(\n+ {\n+ \"amounts\": [{\"name\": \"amount.mycap\", \"min\": 1}],\n+ \"attributes\": [{\"name\": \"attr.mycap\", \"anyOf\": [\"foo\"]}],\n+ },\n+ id=\"single amount & attriubute\",\n+ ),\n+ pytest.param(\n+ {\"amounts\": [{\"name\": f\"amount.mycap{i}\", \"min\": 1} for i in range(0, 50)]},\n+ id=\"maximum as only amounts\",\n+ ),\n+ pytest.param(\n+ {\n+ \"attributes\": [\n+ {\"name\": f\"attr.mycap{i}\", \"anyOf\": [\"foo\"]} for i in range(0, 50)\n+ ]\n+ },\n+ id=\"maximum as only attributes\",\n+ ),\n+ pytest.param(\n+ {\n+ \"amounts\": [{\"name\": f\"amount.mycap{i}\", \"min\": 1} for i in range(0, 25)],\n+ \"attributes\": [\n+ {\"name\": f\"attr.mycap{i}\", \"anyOf\": [\"foo\"]} for i in range(0, 25)\n+ ],\n+ },\n+ id=\"maximum as combination\",\n+ ),\n+ ],\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Success case testing for Open Job Description HostRequirementsTemplate.\n+\n+ # WHEN\n+ _parse_model(model=HostRequirementsTemplate, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data,error_count\",\n+ [\n+ pytest.param({}, 1, id=\"missing amounts & attributes\"),\n+ pytest.param({\"unknown\": \"value\"}, 1, id=\"unknown field\"),\n+ pytest.param({\"amounts\": []}, 1, id=\"too few amounts\"),\n+ pytest.param({\"attributes\": []}, 1, id=\"too few attributes\"),\n+ pytest.param(\n+ {\"amounts\": [{\"name\": f\"amount.mycap{i}\", \"min\": 1} for i in range(0, 51)]},\n+ 1,\n+ id=\"too many as only amounts\",\n+ ),\n+ pytest.param(\n+ {\n+ \"attributes\": [\n+ {\"name\": f\"attr.mycap{i}|\", \"anyOf\": [\"foo\"]} for i in range(0, 51)\n+ ]\n+ },\n+ 1,\n+ id=\"too many as only attributes\",\n+ ),\n+ pytest.param(\n+ {\n+ \"amounts\": [{\"name\": f\"amount.mycap{i}\", \"min\": 1} for i in range(0, 26)],\n+ \"attributes\": [\n+ {\"name\": f\"attr.mycap{i}\", \"anyOf\": [\"foo\"]} for i in range(0, 25)\n+ ],\n+ },\n+ 1,\n+ id=\"too many as combination\",\n+ ),\n+ ],\n+ )\n+ def test_parse_fails(self, data: dict[str, Any], error_count: int) -> None:\n+ # Failure case testing for Open Job Description AmountRequirementTemplate.\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=AmountRequirementTemplate, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == error_count, str(excinfo.value)"}, {"sha": "5bfde386760d8312a009896619387f2b80cb394c", "filename": "test/openjd/model/v2023_09/test_step_template.py", "status": "added", "additions": 150, "deletions": 0, "changes": 150, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_step_template.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_step_template.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_step_template.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,150 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import StepTemplate\n+\n+# Some minimal data to reference in tests.\n+ENV_SCRIPT = {\"actions\": {\"onEnter\": {\"command\": \"foo\"}}}\n+ENVIRONMENT = {\"name\": \"Foo\", \"script\": ENV_SCRIPT}\n+PARAMETER_SPACE = {\"parameters\": [{\"name\": \"foo\", \"type\": \"INT\", \"range\": [1]}]}\n+STEP_SCRIPT = {\"actions\": {\"onRun\": {\"command\": \"foo\"}}}\n+\n+\n+class TestStepTemplate:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": \"Foo\", \"script\": STEP_SCRIPT}, id=\"minimum required\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"script\": STEP_SCRIPT, \"description\": \"some text\"},\n+ id=\"with description\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"script\": STEP_SCRIPT, \"stepEnvironments\": [ENVIRONMENT]},\n+ id=\"with defined environment\",\n+ ),\n+ pytest.param({\"name\": \"Foo\", \"script\": STEP_SCRIPT}, id=\"with parameter space\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"script\": STEP_SCRIPT, \"dependencies\": [{\"dependsOn\": \"Bar\"}]},\n+ id=\"single dependency\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"script\": STEP_SCRIPT,\n+ \"dependencies\": [{\"dependsOn\": \"Bar\"}, {\"dependsOn\": \"Fuz\"}],\n+ },\n+ id=\"multiple dependency\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"script\": STEP_SCRIPT,\n+ \"hostRequirements\": {\n+ \"amounts\": [{\"name\": \"amount.custom\", \"min\": 1}],\n+ \"attributes\": [{\"name\": \"attr.custom\", \"anyOf\": [\"foo\"]}],\n+ },\n+ },\n+ id=\"with requirements\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"script\": STEP_SCRIPT,\n+ \"stepEnvironments\": [\n+ {\"name\": f\"E{i}\", \"script\": ENV_SCRIPT} for i in range(0, 2)\n+ ],\n+ },\n+ id=\"different environment names\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description StepTemplate\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our StepTemplate model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=StepTemplate, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({}, id=\"empty object\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"script\": STEP_SCRIPT, \"unknown\": \"key\"}, id=\"unknown key\"\n+ ),\n+ pytest.param({\"script\": STEP_SCRIPT}, id=\"missing name\"),\n+ pytest.param({\"name\": \"Foo\"}, id=\"missing script\"),\n+ pytest.param({\"name\": 12, \"script\": STEP_SCRIPT}, id=\"name not string\"),\n+ pytest.param({\"name\": \"Foo\", \"script\": {}}, id=\"script empty\"),\n+ pytest.param({\"name\": \"Foo\", \"script\": 12}, id=\"script not object\"),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"script\": STEP_SCRIPT, \"description\": 12},\n+ id=\"description not string\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"script\": STEP_SCRIPT, \"stepEnvironments\": []},\n+ id=\"too few environments\",\n+ ),\n+ pytest.param(\n+ {\"name\": \"Foo\", \"script\": STEP_SCRIPT, \"parameterSpace\": {}},\n+ id=\"parameter space empty\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"script\": STEP_SCRIPT,\n+ \"dependencies\": [{\"dependsOn\": \"Foo\"}],\n+ },\n+ id=\"self dependency\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"script\": STEP_SCRIPT,\n+ \"dependencies\": [{\"dependsOn\": \"Bar\"}, {\"dependsOn\": \"Bar\"}],\n+ },\n+ id=\"duplicate dependency\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"script\": STEP_SCRIPT,\n+ \"hostRequirements\": [\n+ {\"name\": f\"amount.custom{i}\", \"value\": 1} for i in range(0, 51)\n+ ],\n+ },\n+ id=\"too many capabilities\",\n+ ),\n+ pytest.param(\n+ {\n+ \"name\": \"Foo\",\n+ \"script\": STEP_SCRIPT,\n+ \"stepEnvironments\": [{\"name\": \"E\", \"script\": ENV_SCRIPT} for i in range(0, 2)],\n+ },\n+ id=\"duplicate env names\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # Failure case testing for Open Job Description StepTemplate.\n+ # - Constraint tests\n+ # - extra field test\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=StepTemplate, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0"}, {"sha": "6becbcd25d7e7a19ed1b488d7192d2f948b04fcf", "filename": "test/openjd/model/v2023_09/test_strings.py", "status": "added", "additions": 860, "deletions": 0, "changes": 860, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_strings.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_strings.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_strings.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,860 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+import string\n+\n+import pytest\n+from pydantic import BaseModel, ValidationError\n+\n+from openjd.model.v2023_09 import (\n+ AmountCapabilityName,\n+ ArgString,\n+ AttributeCapabilityName,\n+ CombinationExpr,\n+ CommandString,\n+ Description,\n+ EnvironmentName,\n+ EnvironmentVariableNameString,\n+ EnvironmentVariableValueString,\n+ Identifier,\n+ JobName,\n+ JobTemplateName,\n+ ParameterStringValue,\n+ StepName,\n+ TaskParameterStringValueAsJob,\n+ UserInterfaceLabelStringValue,\n+ FileDialogFilterPatternStringValue,\n+)\n+\n+\n+class JobTemplateNameModel(BaseModel):\n+ name: JobTemplateName\n+\n+\n+class JobNameModel(BaseModel):\n+ name: JobName\n+\n+\n+class EnvironmentNameModel(BaseModel):\n+ name: EnvironmentName\n+\n+\n+class EnvironmentVariableNameStringModel(BaseModel):\n+ name: EnvironmentVariableNameString\n+\n+\n+class EnvironmentVariableValueStringModel(BaseModel):\n+ value: EnvironmentVariableValueString\n+\n+\n+class StepNameModel(BaseModel):\n+ name: StepName\n+\n+\n+class IdentifierModel(BaseModel):\n+ id: Identifier\n+\n+\n+class DescriptionModel(BaseModel):\n+ desc: Description\n+\n+\n+class ParameterStringModel(BaseModel):\n+ str: ParameterStringValue\n+\n+\n+class ArgStringModel(BaseModel):\n+ arg: ArgString\n+\n+\n+class CommandStringModel(BaseModel):\n+ cmd: CommandString\n+\n+\n+class CombinationExprModel(BaseModel):\n+ expr: CombinationExpr\n+\n+\n+class TaskParameterStringValueAsJobModel(BaseModel):\n+ str: TaskParameterStringValueAsJob\n+\n+\n+class AttributeCapabilityNameModel(BaseModel):\n+ str: AttributeCapabilityName\n+\n+\n+class AmountCapabilityNameModel(BaseModel):\n+ str: AmountCapabilityName\n+\n+\n+class UserInterfaceLabelStringValueModel(BaseModel):\n+ str: UserInterfaceLabelStringValue\n+\n+\n+class FileDialogFilterPatternStringValueModel(BaseModel):\n+ str: FileDialogFilterPatternStringValue\n+\n+\n+class TestJobTemplateName:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (pytest.param(\"{{ Job.Parameter.Foo }}\", id=\"is formatstring\"),),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"name\": value}\n+\n+ # WHEN\n+ JobTemplateNameModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (pytest.param({\"name\": \"{{ Job.Parameter.Foo \"}, id=\"bad format string\"),),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ JobTemplateNameModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestJobName:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"A\", id=\"shortest\"),\n+ pytest.param(\"A\" * 128, id=\"longest\"),\n+ pytest.param(\"a0 \\u0103.:/=+-@{}\ud83d\ude00\", id=\"allowable characters\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"name\": value}\n+\n+ # WHEN\n+ JobNameModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": 12}, id=\"not string\"),\n+ pytest.param({\"name\": \"\"}, id=\"too short\"),\n+ pytest.param({\"name\": \"a\" * 129}, id=\"too long\"),\n+ pytest.param({\"name\": \"\\n\"}, id=\"no newline\"),\n+ # Just testing the boundary points of the allowable characters\n+ pytest.param({\"name\": \"\\u0000\"}, id=\"NULL disallowed\"),\n+ pytest.param({\"name\": \"\\u001F\"}, id=\"1f disallowed\"),\n+ pytest.param({\"name\": \"\\u007F\"}, id=\"DEL disallowed\"),\n+ pytest.param({\"name\": \"\\u009F\"}, id=\"9f disallowed\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ JobNameModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestStepName:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"A\", id=\"shortest\"),\n+ pytest.param(\"A\" * 64, id=\"longest\"),\n+ pytest.param(\"a0\\u0103.:/=+-@\ud83d\ude00\", id=\"allowable characters\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"name\": value}\n+\n+ # WHEN\n+ StepNameModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": 12}, id=\"not string\"),\n+ pytest.param({\"name\": \"\"}, id=\"too short\"),\n+ pytest.param({\"name\": \"a\" * 65}, id=\"too long\"),\n+ pytest.param({\"name\": \"\\n\"}, id=\"no newline\"),\n+ # Just testing the boundary points of the allowable characters\n+ pytest.param({\"name\": \"\\u0000\"}, id=\"NULL disallowed\"),\n+ pytest.param({\"name\": \"\\u001F\"}, id=\"1f disallowed\"),\n+ pytest.param({\"name\": \"\\u007F\"}, id=\"DEL disallowed\"),\n+ pytest.param({\"name\": \"\\u009F\"}, id=\"9f disallowed\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ StepNameModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestEnvironmentName:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"A\", id=\"shortest\"),\n+ pytest.param(\"A\" * 64, id=\"longest\"),\n+ pytest.param(\"a0\\u0103.:/=+-@\ud83d\ude00\", id=\"allowable characters\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"name\": value}\n+\n+ # WHEN\n+ EnvironmentNameModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"name\": 12}, id=\"not string\"),\n+ pytest.param({\"name\": \"\"}, id=\"too short\"),\n+ pytest.param({\"name\": \"a\" * 65}, id=\"too long\"),\n+ pytest.param({\"name\": \"\\n\"}, id=\"no newline\"),\n+ # Just testing the boundary points of the allowable characters\n+ pytest.param({\"name\": \"\\u0000\"}, id=\"NULL disallowed\"),\n+ pytest.param({\"name\": \"\\u001F\"}, id=\"1f disallowed\"),\n+ pytest.param({\"name\": \"\\u007F\"}, id=\"DEL disallowed\"),\n+ pytest.param({\"name\": \"\\u009F\"}, id=\"9f disallowed\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ EnvironmentNameModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestEnvironmentVariableNameString:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"A\", id=\"shortest(upper-A)\"),\n+ pytest.param(\"A\" * 256, id=\"longest(upper-A)\"),\n+ pytest.param(\"Z\", id=\"shortest(upper-Z)\"),\n+ pytest.param(\"Z\" * 256, id=\"longest(upper-Z)\"),\n+ pytest.param(\"a\", id=\"shortest(lower-a)\"),\n+ pytest.param(\"a\" * 256, id=\"longest(lower-a)\"),\n+ pytest.param(\"z\", id=\"shortest(lower-z)\"),\n+ pytest.param(\"z\" * 256, id=\"longest(lower-z)\"),\n+ pytest.param(\"A\" + \"0\" * 255, id=\"longest(trailing 0)\"),\n+ pytest.param(\"A\" + \"9\" * 255, id=\"longest(trailing 9)\"),\n+ pytest.param(\"A_\", id=\"allows underscore\"),\n+ pytest.param(\"_a\", id=\"start with underscore\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"name\": value}\n+\n+ # WHEN\n+ EnvironmentVariableNameStringModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ [\n+ pytest.param({\"name\": 12}, id=\"not string\"),\n+ pytest.param({\"name\": \"\"}, id=\"too short\"),\n+ pytest.param({\"name\": \"a\" * 257}, id=\"too long\"),\n+ pytest.param({\"name\": \" a\"}, id=\"start space\"),\n+ pytest.param({\"name\": \"a \"}, id=\"end space\"),\n+ pytest.param({\"name\": \"0\"}, id=\"no digit start(0)\"),\n+ pytest.param({\"name\": \"9\"}, id=\"no digit start(9)\"),\n+ pytest.param({\"name\": \"!foo\"}, id=\"starts alpha\"),\n+ pytest.param({\"name\": \"F!\"}, id=\"only alphanum\"),\n+ ]\n+ + [\n+ pytest.param({\"id\": f\"a{letter}\"}, id=f\"'{letter}' not allowed\")\n+ for letter in sorted(\n+ list(\n+ set(string.printable)\n+ - set(string.ascii_letters)\n+ - set(string.digits)\n+ - set(\"_\")\n+ )\n+ )\n+ ],\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ EnvironmentVariableNameStringModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestEnvironmentVariableValueString:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"\", id=\"shortest\"),\n+ pytest.param(\"A\" * 2048, id=\"longest\"),\n+ pytest.param(string.printable, id=\"many characters\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"value\": value}\n+\n+ # WHEN\n+ EnvironmentVariableValueStringModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ [\n+ pytest.param({\"value\": \"a\" * 2049}, id=\"too long\"),\n+ ],\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ EnvironmentVariableValueStringModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestIdentifier:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"A\", id=\"shortest(upper-A)\"),\n+ pytest.param(\"A\" * 64, id=\"longest(upper-A)\"),\n+ pytest.param(\"Z\", id=\"shortest(upper-Z)\"),\n+ pytest.param(\"Z\" * 64, id=\"longest(upper-Z)\"),\n+ pytest.param(\"a\", id=\"shortest(lower-a)\"),\n+ pytest.param(\"a\" * 64, id=\"longest(lower-a)\"),\n+ pytest.param(\"z\", id=\"shortest(lower-z)\"),\n+ pytest.param(\"z\" * 64, id=\"longest(lower-z)\"),\n+ pytest.param(\"A\" + \"0\" * 63, id=\"longest(trailing 0)\"),\n+ pytest.param(\"A\" + \"9\" * 63, id=\"longest(trailing 9)\"),\n+ pytest.param(\"_\" * 64, id=\"underscore\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"id\": value}\n+\n+ # WHEN\n+ IdentifierModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ [\n+ pytest.param({\"id\": 12}, id=\"not string\"),\n+ pytest.param({\"id\": \"\"}, id=\"too short\"),\n+ pytest.param({\"id\": \"a\" * 65}, id=\"too long\"),\n+ pytest.param({\"id\": \" a\"}, id=\"start space\"),\n+ pytest.param({\"id\": \"a \"}, id=\"end space\"),\n+ pytest.param({\"id\": \"0\"}, id=\"no digit start(0)\"),\n+ pytest.param({\"id\": \"9\"}, id=\"no digit start(9)\"),\n+ pytest.param({\"id\": \"!foo\"}, id=\"starts alpha\"),\n+ pytest.param({\"id\": \"F!\"}, id=\"only alphanum\"),\n+ ]\n+ + [\n+ pytest.param({\"id\": f\"a{letter}\"}, id=f\"'{letter}' not allowed\")\n+ for letter in sorted(\n+ list(\n+ set(string.printable)\n+ - set(string.ascii_letters)\n+ - set(string.digits)\n+ - set(\"_\")\n+ )\n+ )\n+ ],\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ IdentifierModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestDescription:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"A\", id=\"min length\"),\n+ pytest.param(\"A\" * 2048, id=\"max length\"),\n+ # Control character exlusion cases\n+ pytest.param(\"\\u0020\", id=\"start of first printable range\"),\n+ pytest.param(\"\\u007E\", id=\"end of first printable range\"),\n+ pytest.param(\"\\u00A0\", id=\"start of second printable range\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"desc\": value}\n+\n+ # WHEN\n+ DescriptionModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"desc\": 12}, id=\"not string\"),\n+ pytest.param({\"desc\": \"\"}, id=\"too short\"),\n+ pytest.param({\"desc\": \"a\" * 2049}, id=\"too long\"),\n+ pytest.param({\"desc\": \"\\u0000\"}, id=\"start of first control character range\"),\n+ pytest.param({\"desc\": \"\\u001F\"}, id=\"end of first control character range\"),\n+ pytest.param({\"desc\": \"\\u007F\"}, id=\"start of second control character range\"),\n+ pytest.param({\"desc\": \"\\u009F\"}, id=\"end of second control character range\"),\n+ pytest.param({\"desc\": \"a\\n\\u0000\"}, id=\"disallowed after newline\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ DescriptionModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestParameterStringValue:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"\", id=\"min length\"),\n+ pytest.param(\"A\" * 1024, id=\"max length\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"str\": value}\n+\n+ # WHEN\n+ ParameterStringModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"str\": 12}, id=\"not string\"),\n+ pytest.param({\"str\": \"a\" * 1025}, id=\"too long\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ ParameterStringModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestArgString:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"\", id=\"min length\"),\n+ pytest.param(\"A\" * (32 * 1024), id=\"long length\"),\n+ # Control character exlusion cases\n+ pytest.param(\"\\u0020\", id=\"start of first printable range\"),\n+ pytest.param(\"\\u007E\", id=\"end of first printable range\"),\n+ pytest.param(\"\\u00A0\", id=\"start of second printable range\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"arg\": value}\n+\n+ # WHEN\n+ ArgStringModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"arg\": 12}, id=\"not string\"),\n+ pytest.param({\"cmd\": \"\\n\"}, id=\"newline\"),\n+ pytest.param({\"cmd\": \"\\r\"}, id=\"carriage return\"),\n+ pytest.param({\"cmd\": \"\\t\"}, id=\"horizontal tab\"),\n+ pytest.param({\"arg\": \"\\u0000\"}, id=\"start of first control character range\"),\n+ pytest.param({\"arg\": \"\\u001F\"}, id=\"end of first control character range\"),\n+ pytest.param({\"arg\": \"\\u007F\"}, id=\"start of second control character range\"),\n+ pytest.param({\"arg\": \"\\u009F\"}, id=\"end of second control character range\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ ArgStringModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestCommandString:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"A\", id=\"min length\"),\n+ pytest.param(\"A\" * (32 * 1024), id=\"long length\"),\n+ # Control character exlusion cases\n+ pytest.param(\"\\u0020\", id=\"start of first printable range\"),\n+ pytest.param(\"\\u007E\", id=\"end of first printable range\"),\n+ pytest.param(\"\\u00A0\", id=\"start of second printable range\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"cmd\": value}\n+\n+ # WHEN\n+ CommandStringModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"cmd\": 12}, id=\"not string\"),\n+ pytest.param({\"cmd\": \"\"}, id=\"too short\"),\n+ pytest.param({\"cmd\": \"\\n\"}, id=\"newline\"),\n+ pytest.param({\"cmd\": \"\\r\"}, id=\"carriage return\"),\n+ pytest.param({\"cmd\": \"\\t\"}, id=\"horizontal tab\"),\n+ pytest.param({\"cmd\": \"\\u0000\"}, id=\"start of first control character range\"),\n+ pytest.param({\"cmd\": \"\\u001F\"}, id=\"end of first control character range\"),\n+ pytest.param({\"cmd\": \"\\u007F\"}, id=\"start of second control character range\"),\n+ pytest.param({\"cmd\": \"\\u009F\"}, id=\"end of second control character range\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ CommandStringModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestCombinationExpr:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"A\", id=\"shortest\"),\n+ pytest.param(\"a\" * 1280, id=\"longest\"),\n+ pytest.param(string.ascii_letters + string.digits, id=\"allowable identifier chars\"),\n+ pytest.param(\" \", id=\"allowable whitespace\"),\n+ pytest.param(\"*(),\", id=\"allowable operators\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"expr\": value}\n+\n+ # WHEN\n+ CombinationExprModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"expr\": 12}, id=\"not string\"),\n+ pytest.param({\"expr\": \"\"}, id=\"too short\"),\n+ pytest.param({\"expr\": \"a\" * 1281}, id=\"too long\"),\n+ # Disallowed characters that appear in the regex and could be allowed\n+ # if we mess up the regex definition.\n+ pytest.param({\"expr\": \"^\"}, id=\"carat\"),\n+ pytest.param({\"expr\": \"$\"}, id=\"dollar\"),\n+ pytest.param({\"expr\": \"+\"}, id=\"plus\"),\n+ pytest.param({\"expr\": \"[\"}, id=\"square open paren\"),\n+ pytest.param({\"expr\": \"]\"}, id=\"square close paren\"),\n+ pytest.param({\"expr\": \"\\\\\"}, id=\"backslash character\"),\n+ # No multiline strings\n+ pytest.param({\"expr\": \"foo\\n\"}, id=\"no newline\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ CombinationExprModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestTaskParameterStringValueAsJob:\n+ @pytest.mark.parametrize(\n+ \"value\", (pytest.param(\"\", id=\"shortest\"), pytest.param(\"A\" * 1024, id=\"longest\"))\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"str\": value}\n+\n+ # WHEN\n+ TaskParameterStringValueAsJobModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (pytest.param({\"str\": \"A\" * 1025}, id=\"too long\"),),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ TaskParameterStringValueAsJobModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestAmountCapabilityName:\n+ # Note: The string regex is tested in ../test_capabilities.py\n+\n+ @pytest.mark.parametrize(\n+ \"value\", (pytest.param(\"a\", id=\"shortest\"), pytest.param(\"A\" * 100, id=\"longest\"))\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"str\": value}\n+\n+ # WHEN\n+ AmountCapabilityNameModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"str\": 12}, id=\"not string\"),\n+ pytest.param({\"str\": \"A\" * 101}, id=\"too long\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ AmountCapabilityNameModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestAttributeCapabilityName:\n+ # Note: The string regex is tested in ../test_capabilities.py\n+\n+ @pytest.mark.parametrize(\n+ \"value\", (pytest.param(\"a\", id=\"shortest\"), pytest.param(\"A\" * 100, id=\"longest\"))\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"str\": value}\n+\n+ # WHEN\n+ AttributeCapabilityNameModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"str\": 12}, id=\"not string\"),\n+ pytest.param({\"str\": \"A\" * 101}, id=\"too long\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ AttributeCapabilityNameModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestUserInterfaceLabelStringValue:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"a\", id=\"shortest\"),\n+ pytest.param(\"A\" * 64, id=\"longest\"),\n+ pytest.param(\"a0 \\u0103.:/=+-@{}\ud83d\ude00\", id=\"allowable characters\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"str\": value}\n+\n+ # WHEN\n+ UserInterfaceLabelStringValueModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"str\": 12}, id=\"not string\"),\n+ pytest.param({\"str\": \"\"}, id=\"too short\"),\n+ pytest.param({\"str\": \"A\" * 65}, id=\"too long\"),\n+ pytest.param({\"str\": \"\\n\"}, id=\"no newline\"),\n+ # Just testing the boundary points of the allowable characters\n+ pytest.param({\"str\": \"\\u0000\"}, id=\"NULL disallowed\"),\n+ pytest.param({\"str\": \"\\u001F\"}, id=\"1f disallowed\"),\n+ pytest.param({\"str\": \"\\u007F\"}, id=\"DEL disallowed\"),\n+ pytest.param({\"str\": \"\\u009F\"}, id=\"9f disallowed\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ UserInterfaceLabelStringValueModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0\n+\n+\n+class TestFileDialogFilterPatternStringValue:\n+ @pytest.mark.parametrize(\n+ \"value\",\n+ (\n+ pytest.param(\"*\", id=\"shortest, special pattern '*'\"),\n+ pytest.param(\"*.*\", id=\"special pattern '*.*'\"),\n+ pytest.param(\"*.\" + \"A\" * 18, id=\"longest\"),\n+ pytest.param(\"*.a0 \\u0103.+-\ud83d\ude00\", id=\"allowable characters\"),\n+ ),\n+ )\n+ def test_parse_success(self, value: str) -> None:\n+ # GIVEN\n+ data = {\"str\": value}\n+\n+ # WHEN\n+ FileDialogFilterPatternStringValueModel.parse_obj(data)\n+\n+ # THEN\n+ # no exceptions raised\n+\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param({\"str\": 12}, id=\"not string\"),\n+ pytest.param({\"name\": \"\"}, id=\"too short\"),\n+ pytest.param({\"str\": \"*.\" + \"A\" * 19}, id=\"too long\"),\n+ pytest.param({\"str\": \"abc\"}, id=\"need prefix '*.'\"),\n+ pytest.param({\"str\": \".abc\"}, id=\"need prefix '*'\"),\n+ pytest.param({\"name\": \"*.\\n\"}, id=\"no newline\"),\n+ # Just testing the boundary points of the allowable characters\n+ pytest.param({\"name\": \"*.\\u0000\"}, id=\"NULL disallowed\"),\n+ pytest.param({\"name\": \"*.\\u001F\"}, id=\"1f disallowed\"),\n+ pytest.param({\"name\": \"*.\\u007F\"}, id=\"DEL disallowed\"),\n+ pytest.param({\"name\": \"*.\\u009F\"}, id=\"9f disallowed\"),\n+ # The list of characters explicitly disallowed\n+ # b. Path separators \"\\\" and \"/\".\n+ pytest.param({\"name\": \"*.\\\\\"}, id=\"no '\\\\'\"),\n+ pytest.param({\"name\": \"*./\"}, id=\"no '/'\"),\n+ # c. Wildcard characters \"*\", \"?\", \"[\", \"]\".\n+ pytest.param({\"name\": \"*.a*\"}, id=\"no '*' outside special case '*.*'\"),\n+ pytest.param({\"name\": \"*.?\"}, id=\"no '?'\"),\n+ pytest.param({\"name\": \"*.[\"}, id=\"no '['\"),\n+ pytest.param({\"name\": \"*.]\"}, id=\"no ']'\"),\n+ # d. Characters commonly disallowed in paths \"#\", \"%\", \"&\", \"{\", \"}\", \"<\", \">\",\n+ # \"$\", \"!\", \"'\", \"\\\"\", \":\", \"@\", \"`\", \"|\", \"=\".\n+ pytest.param({\"name\": \"*.#\"}, id=\"no '#'\"),\n+ pytest.param({\"name\": \"*.%\"}, id=\"no '%'\"),\n+ pytest.param({\"name\": \"*.&\"}, id=\"no '&'\"),\n+ pytest.param({\"name\": \"*.{\"}, id=\"no '{'\"),\n+ pytest.param({\"name\": \"*.}\"}, id=\"no '}'\"),\n+ pytest.param({\"name\": \"*.<\"}, id=\"no '<'\"),\n+ pytest.param({\"name\": \"*.>\"}, id=\"no '>'\"),\n+ pytest.param({\"name\": \"*.$\"}, id=\"no '$'\"),\n+ pytest.param({\"name\": \"*.!\"}, id=\"no '!'\"),\n+ pytest.param({\"name\": \"*.'\"}, id=\"no '''\"),\n+ pytest.param({\"name\": '*.\"'}, id=\"no '\\\"'\"),\n+ pytest.param({\"name\": \"*.:\"}, id=\"no ':'\"),\n+ pytest.param({\"name\": \"*.@\"}, id=\"no '@'\"),\n+ pytest.param({\"name\": \"*.`\"}, id=\"no '`'\"),\n+ pytest.param({\"name\": \"*.|\"}, id=\"no '|'\"),\n+ pytest.param({\"name\": \"*.=\"}, id=\"no '='\"),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any]) -> None:\n+ # - Constraint tests\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ FileDialogFilterPatternStringValueModel.parse_obj(data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) > 0"}, {"sha": "1f462a7bc02effa63eba978e645a500f7e712a8e", "filename": "test/openjd/model/v2023_09/test_template_variables.py", "status": "added", "additions": 1101, "deletions": 0, "changes": 1101, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_template_variables.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_template_variables.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Fmodel%2Fv2023_09%2Ftest_template_variables.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,1101 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+from typing import Any\n+\n+import pytest\n+from pydantic import ValidationError\n+\n+from openjd.model._parse import _parse_model\n+from openjd.model.v2023_09 import JobTemplate\n+\n+# Some minimal data to reference in tests.\n+ENV_SCRIPT_FOO = {\n+ \"actions\": {\n+ \"onEnter\": {\"command\": \"foo {{Param.Foo}} {{RawParam.Foo}} {{Session.WorkingDirectory}}\"}\n+ }\n+}\n+ENVIRONMENT_FOO = {\"name\": \"FooEnv\", \"script\": ENV_SCRIPT_FOO}\n+STEP_SCRIPT = {\"actions\": {\"onRun\": {\"command\": \"foo\"}}}\n+STEP_TEMPLATE = {\"name\": \"StepName\", \"script\": STEP_SCRIPT}\n+STEP_SCRIPT_FOO = {\n+ \"actions\": {\n+ \"onRun\": {\"command\": \"foo {{Param.Foo}} {{RawParam.Foo}} {{Session.WorkingDirectory}}\"}\n+ }\n+}\n+STEP_TEMPLATE_FOO = {\"name\": \"StepName\", \"script\": STEP_SCRIPT_FOO}\n+FOO_PARAMETER_INT = {\"name\": \"Foo\", \"type\": \"INT\"}\n+FOO_PARAMETER_FLOAT = {\"name\": \"Foo\", \"type\": \"FLOAT\"}\n+FOO_PARAMETER_STRING = {\"name\": \"Foo\", \"type\": \"STRING\"}\n+FOO_PARAMETER_PATH = {\"name\": \"Foo\", \"type\": \"PATH\"}\n+\n+\n+def make_script(env_or_task: str, scriptname: str, scriptdata: str) -> dict:\n+ return {\n+ \"actions\": {\n+ (\"onEnter\" if env_or_task == \"Env\" else \"onRun\"): {\n+ \"command\": (\"{{%s.File.%s}}\" % (env_or_task, scriptname))\n+ }\n+ },\n+ \"embeddedFiles\": [{\"name\": scriptname, \"type\": \"TEXT\", \"data\": scriptdata}],\n+ }\n+\n+\n+class TestJobTemplate:\n+ @pytest.mark.parametrize(\n+ \"data\",\n+ (\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_INT],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ },\n+ id=\"minimum int parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_FLOAT],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ },\n+ id=\"minimum float parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ },\n+ id=\"minimum string parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{RawParam.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_PATH],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ },\n+ id=\"minimum path parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_INT],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ \"description\": \"some text {{Param.NotSubstituted}}\",\n+ },\n+ id=\"with description\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_INT],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ \"jobEnvironments\": [ENVIRONMENT_FOO],\n+ },\n+ id=\"with environments\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_PATH],\n+ \"steps\": [STEP_TEMPLATE],\n+ \"jobEnvironments\": [ENVIRONMENT_FOO],\n+ },\n+ id=\"path in environments\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ STEP_TEMPLATE_FOO,\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\"Task\", \"BarScript\", \"echo {{Param.Foo}}\"),\n+ },\n+ {\n+ \"name\": \"BazStep\",\n+ \"script\": make_script(\n+ \"Task\", \"BazScript\", \"echo {{Param.Foo}} {{Task.File.BazScript}}\"\n+ ),\n+ },\n+ ],\n+ },\n+ id=\"multiple steps\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_INT],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ \"jobEnvironments\": [\n+ ENVIRONMENT_FOO,\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\", \"BarScript\", \"echo {{Param.Foo}} {{Env.File.BarScript}}\"\n+ ),\n+ },\n+ {\n+ \"name\": \"BazEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"BazScript\",\n+ \"echo {{Param.Foo}} {{Session.WorkingDirectory}}\",\n+ ),\n+ },\n+ ],\n+ },\n+ id=\"multiple environments\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Task.Param.Foo}} {{Task.RawParam.Foo}}\",\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"range\": [1, 2]}\n+ ]\n+ },\n+ },\n+ ],\n+ },\n+ id=\"step with parameter space\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_PATH],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\", \"BarScript\", \"echo {{Param.Foo}} {{Task.Param.Foo}}\"\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"range\": [\"blah\", \"{{RawParam.Foo}}\"],\n+ }\n+ ]\n+ },\n+ },\n+ ],\n+ },\n+ id=\"raw path in parameter space\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\", \"BarScript\", \"echo {{Param.Foo}} {{Task.Param.Foo}}\"\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"range\": [1, 2]}\n+ ]\n+ },\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Env.File.BarScript}} {{Session.WorkingDirectory}}\",\n+ ),\n+ }\n+ ],\n+ },\n+ ],\n+ },\n+ id=\"step with parameter space and environment\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Task.Param.Foo}} {{Task.Param.Bar}} {{Task.Param.Baz}}\",\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"range\": [1, 2]},\n+ {\"name\": \"Bar\", \"type\": \"FLOAT\", \"range\": [1, 2]},\n+ {\n+ \"name\": \"Baz\",\n+ \"type\": \"STRING\",\n+ \"range\": [\"{{Param.Foo}}\"],\n+ },\n+ ]\n+ },\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Env.File.BarScript}} {{Session.WorkingDirectory}}\",\n+ ),\n+ }\n+ ],\n+ },\n+ ],\n+ },\n+ id=\"string task param can see the job params\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"BarScript\",\n+ \"echo Hi\",\n+ ),\n+ \"hostRequirements\": {\n+ \"amounts\": [\n+ {\n+ \"name\": \"amount.{{Param.Foo}}\",\n+ \"min\": 3,\n+ },\n+ ],\n+ \"attributes\": [\n+ {\n+ \"name\": \"attr.{{Param.Foo}}\",\n+ \"anyOf\": [\"{{Param.Foo}}\"],\n+ },\n+ {\n+ \"name\": \"attr.allof\",\n+ \"allOf\": [\"{{Param.Foo}}\"],\n+ },\n+ ],\n+ },\n+ },\n+ ],\n+ },\n+ id=\"capabilities can see the job params\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"BarScript\",\n+ \"echo {{Session.WorkingDirectory}} {{Session.HasPathMappingRules}} {{Session.PathMappingRulesFile}}\",\n+ ),\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"BarScript\",\n+ \"echo {{Session.WorkingDirectory}} {{Session.HasPathMappingRules}} {{Session.PathMappingRulesFile}}\",\n+ ),\n+ }\n+ ],\n+ },\n+ ],\n+ },\n+ id=\"Can reference Session values\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": {\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": \"file1\",\n+ \"type\": \"TEXT\",\n+ \"data\": \"{{Task.File.file1}} {{Task.File.file2}}\",\n+ },\n+ {\n+ \"name\": \"file2\",\n+ \"type\": \"TEXT\",\n+ \"data\": \"{{Task.File.file1}} {{Task.File.file2}}\",\n+ },\n+ ],\n+ \"actions\": {\n+ \"onRun\": {\"command\": \"{{Task.File.file1}} {{Task.File.file2}}\"}\n+ },\n+ },\n+ },\n+ ],\n+ },\n+ id=\"embedded stepscript files can reference themself and others.\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"jobEnvironments\": [\n+ {\n+ \"name\": \"JobEnv\",\n+ \"script\": {\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": \"file1\",\n+ \"type\": \"TEXT\",\n+ \"data\": \"{{Env.File.file1}} {{Env.File.file2}} {{Session.WorkingDirectory}}\",\n+ },\n+ {\n+ \"name\": \"file2\",\n+ \"type\": \"TEXT\",\n+ \"data\": \"{{Env.File.file1}} {{Env.File.file2}} {{Session.WorkingDirectory}}\",\n+ },\n+ ],\n+ \"actions\": {\n+ \"onEnter\": {\n+ \"command\": \"{{Env.File.file1}} {{Env.File.file2}} {{Session.WorkingDirectory}}\"\n+ },\n+ \"onExit\": {\n+ \"command\": \"{{Env.File.file1}} {{Env.File.file2}} {{Session.WorkingDirectory}}\"\n+ },\n+ },\n+ },\n+ }\n+ ],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"StepEnv\",\n+ \"script\": {\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": \"fileA\",\n+ \"type\": \"TEXT\",\n+ \"data\": \"{{Env.File.fileA}} {{Env.File.fileB}} {{Session.WorkingDirectory}}\",\n+ },\n+ {\n+ \"name\": \"fileB\",\n+ \"type\": \"TEXT\",\n+ \"data\": \"{{Env.File.fileA}} {{Env.File.fileB}} {{Session.WorkingDirectory}}\",\n+ },\n+ ],\n+ \"actions\": {\n+ \"onEnter\": {\n+ \"command\": \"{{Env.File.fileA}} {{Env.File.fileB}} {{Session.WorkingDirectory}}\"\n+ },\n+ \"onExit\": {\n+ \"command\": \"{{Env.File.fileA}} {{Env.File.fileB}} {{Session.WorkingDirectory}}\"\n+ },\n+ },\n+ },\n+ }\n+ ],\n+ \"script\": {\n+ \"actions\": {\"onRun\": {\"command\": \"foo\"}},\n+ },\n+ },\n+ ],\n+ },\n+ id=\"embedded env script files can reference themself and others.\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ \"jobEnvironments\": [\n+ {\n+ \"name\": \"VariableEnv\",\n+ \"variables\": {\n+ \"VAR_NAME\": \"{{ Param.Foo }}\",\n+ },\n+ }\n+ ],\n+ }\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_INT],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\", \"BarScript\", \"echo {{Param.Foo}} {{Task.Param.Foo}}\"\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"INT\",\n+ \"range\": \"1 - {{Param.Foo}}\",\n+ }\n+ ]\n+ },\n+ },\n+ ],\n+ },\n+ id=\"int range expression can see params\",\n+ ),\n+ ),\n+ )\n+ def test_parse_success(self, data: dict[str, Any]) -> None:\n+ # Parsing tests of valid Open Job Description JobTemplate\n+ # It is sufficient to check that parsing the input does not\n+ # raise an exception. We trust the Pydantic package's testing\n+ # so, if the input parses then our JobTemplate model is correctly\n+ # constructed for valid input.\n+\n+ # WHEN\n+ _parse_model(model=JobTemplate, obj=data)\n+\n+ # THEN\n+ # no exception was raised.\n+\n+ @pytest.mark.parametrize(\n+ \"data,error_count\",\n+ (\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Session.WorkingDirectory}}\",\n+ \"steps\": [STEP_TEMPLATE],\n+ },\n+ 1,\n+ id=\"session working directory not in 'name' scope\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_PATH],\n+ \"steps\": [STEP_TEMPLATE],\n+ },\n+ 1,\n+ id=\"path parameter not in 'name' scope\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ },\n+ 2,\n+ id=\"step missing parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE],\n+ \"jobEnvironments\": [ENVIRONMENT_FOO],\n+ },\n+ 2,\n+ id=\"environment missing parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ \"jobEnvironments\": [ENVIRONMENT_FOO],\n+ },\n+ 4,\n+ id=\"step and environment missing parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_PATH],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\"Task\", \"BarScript\", \"echo\"),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\n+ \"name\": \"Foo\",\n+ \"type\": \"STRING\",\n+ \"range\": [\"blah\", \"{{Param.Foo}}\"],\n+ }\n+ ]\n+ },\n+ },\n+ ],\n+ },\n+ 1,\n+ id=\"parameter space cannot ref path parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ STEP_TEMPLATE_FOO,\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\", \"BarScript\", \"echo {{Task.File.BazScript}}\"\n+ ),\n+ },\n+ {\n+ \"name\": \"BazStep\",\n+ \"script\": make_script(\n+ \"Task\", \"BazScript\", \"echo {{Task.File.BarScript}}\"\n+ ),\n+ },\n+ ],\n+ },\n+ 2,\n+ id=\"multiple steps can't reference other files\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_INT],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ \"jobEnvironments\": [\n+ ENVIRONMENT_FOO,\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\", \"BarScript\", \"echo {{Env.File.BazScript}}\"\n+ ),\n+ },\n+ {\n+ \"name\": \"BazEnv\",\n+ \"script\": make_script(\n+ \"Env\", \"BazScript\", \"echo {{Env.File.BarScript}}\"\n+ ),\n+ },\n+ ],\n+ },\n+ 2,\n+ id=\"multiple environments can't reference other files\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\", \"BarScript\", \"echo {{Param.Foo}} {{Task.Param.Foo}}\"\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"range\": [1, 2]}\n+ ]\n+ },\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Env.File.BarScript}} {{Session.WorkingDirectory}} {{Task.Param.Foo}}\",\n+ ),\n+ }\n+ ],\n+ },\n+ ],\n+ },\n+ 1,\n+ id=\"step environment cannot see task params\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Task.Param.Foo}} {{Env.File.BarScript}}\",\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"range\": [1, 2]}\n+ ]\n+ },\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Env.File.BarScript}} {{Session.WorkingDirectory}}\",\n+ ),\n+ }\n+ ],\n+ },\n+ ],\n+ },\n+ 1,\n+ id=\"step script cannot see environment\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Task.Param.Foo}} {{Task.Param.Bar}} {{Task.Param.Baz}}\",\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"range\": [1, 2]},\n+ {\"name\": \"Bar\", \"type\": \"FLOAT\", \"range\": [1, 2]},\n+ {\n+ \"name\": \"Baz\",\n+ \"type\": \"STRING\",\n+ \"range\": [\n+ \"{{Task.Param.Foo}}\", # Not other task params\n+ \"{{Task.Param.Bar}}\",\n+ \"{{Task.Param.Baz}}\",\n+ \"{{Env.File.BarScript}}\", # Not env scripts\n+ \"{{Session.WorkingDirectory}}\", # Not the session\n+ ],\n+ },\n+ ]\n+ },\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Env.File.BarScript}} {{Session.WorkingDirectory}}\",\n+ ),\n+ }\n+ ],\n+ },\n+ ],\n+ },\n+ 5,\n+ id=\"task params cannot see each other, envs, or the session\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Task.Param.Foo}} {{Task.Param.Bar}} {{Task.Param.Baz}}\",\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"range\": [1, 2]},\n+ {\"name\": \"Bar\", \"type\": \"FLOAT\", \"range\": [1, 2]},\n+ {\n+ \"name\": \"Baz\",\n+ \"type\": \"STRING\",\n+ \"range\": [\n+ \"{{Param.Foo}}\",\n+ \"BazValue\",\n+ ],\n+ },\n+ ]\n+ },\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"BarScript\",\n+ \"echo {{Param.Foo}} {{Env.File.BarScript}} {{Session.WorkingDirectory}}\",\n+ ),\n+ }\n+ ],\n+ },\n+ {\n+ \"name\": \"PubStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"PubScript\",\n+ # errors: Task.Param.Foo, Task.Param.Bar, Task.Param.Baz\n+ \"echo {{Param.Foo}} {{Task.Param.Foo}} {{Task.Param.Bar}} {{Task.Param.Baz}} {{Task.Param.Pub1}} {{Task.Param.Pub2}}\",\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Pub1\", \"type\": \"INT\", \"range\": [1, 2]},\n+ {\"name\": \"Pub2\", \"type\": \"FLOAT\", \"range\": [1, 2]},\n+ {\n+ \"name\": \"Pub3\",\n+ \"type\": \"STRING\",\n+ \"range\": [\n+ # errors: Task.Param.Foo, Task.Param.Pub1\n+ \"{{Task.Param.Foo}}\",\n+ \"{{Task.Param.Pub1}}\",\n+ ],\n+ },\n+ ]\n+ },\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"PubEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"PubScript\",\n+ # errors: Env.File.BarScript\n+ \"echo {{Param.Foo}} {{Env.File.PubScript}} {{Env.File.BarScript}} {{Session.WorkingDirectory}}\",\n+ ),\n+ }\n+ ],\n+ },\n+ ],\n+ },\n+ 6,\n+ id=\"task params cannot be seen across steps\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_INT],\n+ \"jobEnvironments\": [\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\", \"BarScript\", \"echo {{Env.File.BarScript}}\"\n+ ),\n+ },\n+ ],\n+ \"steps\": [\n+ {\n+ \"name\": \"PubStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"PubScript\",\n+ # errors: Env.File.BarScript, Env.File.PubScript\n+ \"echo {{Param.Foo}} {{Task.Param.Pub1}} {{Task.Param.Pub2}} {{Task.File.PubScript}}, {{Env.File.BarScript}} {{Env.File.PubScript}}\",\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Pub1\", \"type\": \"INT\", \"range\": [1, 2]},\n+ {\"name\": \"Pub2\", \"type\": \"FLOAT\", \"range\": [1, 2]},\n+ ]\n+ },\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"PubEnv\",\n+ \"script\": make_script(\n+ \"Env\",\n+ \"PubScript\",\n+ # errors: Env.File.BarScript, Task.File.PubScript\n+ \"echo {{Param.Foo}} {{Env.File.PubScript}} {{Env.File.BarScript}} {{Task.File.PubScript}} {{Session.WorkingDirectory}}\",\n+ ),\n+ }\n+ ],\n+ },\n+ ],\n+ },\n+ 4,\n+ id=\"files from job env cannot be seen in step scripts or step envs\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"BarScript\",\n+ \"echo 'Hi there''\",\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\n+ \"name\": \"Baz\",\n+ \"type\": \"STRING\",\n+ \"range\": [\n+ \"{{Session.WorkingDirectory}}\", # Not the session dir\n+ \"{{Session.HasPathMappingRules}}\", # Not the path mapping reference\n+ \"{{Session.PathMappingRulesFile}}\", # Not the path mapping file reference\n+ ],\n+ },\n+ ]\n+ },\n+ },\n+ ],\n+ },\n+ 3,\n+ id=\"Cannot reference Session values in a Task Parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\",\n+ \"BarScript\",\n+ \"echo 'Hi there''\",\n+ ),\n+ \"hostRequirements\": {\n+ \"amounts\": [\n+ {\n+ \"name\": \"amount.{{Session.PathMappingRulesFile}}\",\n+ \"min\": 3,\n+ },\n+ ],\n+ \"attributes\": [\n+ {\n+ \"name\": \"attr.{{Session.WorkingDirectory}}\",\n+ \"anyOf\": [\"{{Session.HasPathMappingRules}}\"],\n+ },\n+ ],\n+ },\n+ },\n+ ],\n+ },\n+ 3,\n+ id=\"Cannot reference Session values in a Capability\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"StepEnvA\",\n+ \"script\": {\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": \"fileA\",\n+ \"type\": \"TEXT\",\n+ # References the other step env\n+ \"data\": \"{{Env.File.file1}}\",\n+ },\n+ ],\n+ \"actions\": {\n+ # References the other step env\n+ \"onEnter\": {\"command\": \"{{Env.File.file1}}\"},\n+ },\n+ },\n+ },\n+ {\n+ \"name\": \"StepEnv1\",\n+ \"script\": {\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": \"file1\",\n+ \"type\": \"TEXT\",\n+ # References the other step env\n+ \"data\": \"{{Env.File.fileA}}\",\n+ },\n+ ],\n+ \"actions\": {\n+ # References the other step env\n+ \"onEnter\": {\"command\": \"{{Env.File.fileA}}\"},\n+ },\n+ },\n+ },\n+ ],\n+ \"script\": {\n+ \"actions\": {\"onRun\": {\"command\": \"foo\"}},\n+ },\n+ },\n+ ],\n+ },\n+ 4,\n+ id=\"embedded env script files cannot reference other envs\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"jobEnvironments\": [\n+ {\n+ \"name\": \"BarEnv\",\n+ \"script\": make_script(\n+ \"Env\", \"BarScript\", \"echo {{Env.File.BarScript}}\"\n+ ),\n+ },\n+ ],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Pub1\", \"type\": \"INT\", \"range\": [1, 2]},\n+ {\"name\": \"Pub2\", \"type\": \"FLOAT\", \"range\": [1, 2]},\n+ ]\n+ },\n+ \"stepEnvironments\": [\n+ {\n+ \"name\": \"StepEnvA\",\n+ \"script\": {\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": \"fileA\",\n+ \"type\": \"TEXT\",\n+ \"data\": \"filedata\",\n+ },\n+ ],\n+ \"actions\": {\n+ \"onEnter\": {\"command\": \"filedata\"},\n+ },\n+ },\n+ },\n+ {\n+ \"name\": \"StepEnv1\",\n+ \"script\": {\n+ \"actions\": {\n+ \"onEnter\": {\"command\": \"command\"},\n+ },\n+ },\n+ },\n+ ],\n+ \"script\": {\n+ \"actions\": {\"onRun\": {\"command\": \"foo\"}},\n+ \"embeddedFiles\": [\n+ {\n+ \"name\": \"file1\",\n+ \"type\": \"TEXT\",\n+ \"data\": \"filedata\",\n+ },\n+ ],\n+ },\n+ \"hostRequirements\": {\n+ \"amounts\": [\n+ {\n+ # Reference a job environment file\n+ \"name\": \"amount.{{Env.File.BarScript}}\",\n+ \"min\": 3,\n+ },\n+ ],\n+ \"attributes\": [\n+ {\n+ # Reference a step script file\n+ \"name\": \"attr.{{Env.File.file1}}\",\n+ # Reference a step environment file, and two task parameters\n+ \"anyOf\": [\n+ \"{{Env.File.fileA}}\",\n+ \"{{Task.Param.Pub1}} {{Task.Param.Pub2}}\",\n+ ],\n+ },\n+ ],\n+ },\n+ },\n+ ],\n+ },\n+ 5,\n+ id=\"Capabilities cannot reference envs or steps\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_STRING],\n+ \"steps\": [STEP_TEMPLATE_FOO],\n+ \"jobEnvironments\": [\n+ {\n+ \"name\": \"VariableEnv\",\n+ \"variables\": {\n+ \"VAR_NAME\": \"{{ Param.DoNotCreateAParamWithThisName }}\",\n+ },\n+ }\n+ ],\n+ },\n+ 1,\n+ id=\"Environment variable value referencing non-existant parameter\",\n+ ),\n+ pytest.param(\n+ {\n+ \"specificationVersion\": \"jobtemplate-2023-09\",\n+ \"name\": \"Foo {{Param.Foo}}\",\n+ \"parameterDefinitions\": [FOO_PARAMETER_INT],\n+ \"steps\": [\n+ {\n+ \"name\": \"BarStep\",\n+ \"script\": make_script(\n+ \"Task\", \"BarScript\", \"echo {{Param.Foo}} {{Task.Param.Foo}}\"\n+ ),\n+ \"parameterSpace\": {\n+ \"taskParameterDefinitions\": [\n+ {\"name\": \"Foo\", \"type\": \"INT\", \"range\": \"1-{{Fake.Parameter}}\"}\n+ ]\n+ },\n+ },\n+ ],\n+ },\n+ 1,\n+ id=\"int range expression fails on fake format string\",\n+ ),\n+ ),\n+ )\n+ def test_parse_fails(self, data: dict[str, Any], error_count: int) -> None:\n+ # Failure case testing for Open Job Description JobTemplate.\n+\n+ # WHEN\n+ with pytest.raises(ValidationError) as excinfo:\n+ _parse_model(model=JobTemplate, obj=data)\n+\n+ # THEN\n+ assert len(excinfo.value.errors()) == error_count, str(excinfo.value)"}, {"sha": "faa445b546d0585974943b8d458f38439d2f18d1", "filename": "test/openjd/test_copyright_header.py", "status": "added", "additions": 79, "deletions": 0, "changes": 79, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Ftest_copyright_header.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Ftest_copyright_header.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Ftest_copyright_header.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,79 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+import re\n+from pathlib import Path\n+\n+# For distributed open source and proprietary code, we must include a copyright header in source every file:\n+_copyright_header_re = re.compile(\n+ r\"Copyright Amazon\\.com, Inc\\. or its affiliates\\. All Rights Reserved\\.\", re.IGNORECASE\n+)\n+_generated_by_scm = re.compile(r\"# file generated by setuptools_scm\", re.IGNORECASE)\n+\n+\n+def _check_file(filename: Path) -> None:\n+ with open(filename) as infile:\n+ lines_read = 0\n+ for line in infile:\n+ if _copyright_header_re.search(line):\n+ return # success\n+ lines_read += 1\n+ if lines_read > 10:\n+ raise Exception(\n+ f\"Could not find a valid Amazon.com copyright header in the top of {filename}.\"\n+ \" Please add one.\"\n+ )\n+ else:\n+ # __init__.py files are usually empty, this is to catch that.\n+ raise Exception(\n+ f\"Could not find a valid Amazon.com copyright header in the top of {filename}.\"\n+ \" Please add one.\"\n+ )\n+\n+\n+def _is_version_file(filename: Path) -> bool:\n+ if filename.name != \"_version.py\":\n+ return False\n+ with open(filename) as infile:\n+ lines_read = 0\n+ for line in infile:\n+ if _generated_by_scm.search(line):\n+ return True\n+ lines_read += 1\n+ if lines_read > 10:\n+ break\n+ return False\n+\n+\n+def test_copyright_headers():\n+ \"\"\"Verifies every .py file has an Amazon copyright header.\"\"\"\n+ root_project_dir = Path(__file__)\n+ # The root of the project is the directory that contains the test directory.\n+ while not (root_project_dir / \"test\").exists():\n+ root_project_dir = root_project_dir.parent\n+ # Choose only a few top level directories to test.\n+ # That way we don't snag any virtual envs a developer might create, at the risk of missing\n+ # some top level .py files.\n+ # Additionally, ignore any files in the `node_modules` directory that we use in the VS Code\n+ # extension.\n+ top_level_dirs = [\n+ \"src\",\n+ \"test\",\n+ \"scripts\",\n+ \"testing_containers\",\n+ \"openjdvscode!(/node_modules)\",\n+ ]\n+ file_count = 0\n+ for top_level_dir in top_level_dirs:\n+ for glob_pattern in (\"**/*.py\", \"**/*.sh\", \"**/Dockerfile\", \"**/*.ts\"):\n+ for path in Path(root_project_dir / top_level_dir).glob(glob_pattern):\n+ print(path)\n+ if not _is_version_file(path):\n+ _check_file(path)\n+ file_count += 1\n+\n+ print(f\"test_copyright_headers checked {file_count} files successfully.\")\n+ assert file_count > 0, \"Test misconfiguration\"\n+\n+\n+if __name__ == \"__main__\":\n+ test_copyright_headers()"}, {"sha": "f712b3d1de5a18d7aa3a9ff65200c357ecb67eb7", "filename": "test/openjd/test_importable.py", "status": "added", "additions": 5, "deletions": 0, "changes": 5, "blob_url": "https://github.com/OpenJobDescription/openjd-model-for-python/blob/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Ftest_importable.py", "raw_url": "https://github.com/OpenJobDescription/openjd-model-for-python/raw/098d7511816c326a423d36a73a4fd14a95756fdb/test%2Fopenjd%2Ftest_importable.py", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/test%2Fopenjd%2Ftest_importable.py?ref=098d7511816c326a423d36a73a4fd14a95756fdb", "patch": "@@ -0,0 +1,5 @@\n+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n+\n+\n+def test_openjd_importable():\n+ import openjd # noqa: F401"}]}} {"time": "2023-09-01T02:05:25+00:00", "type": "timeline:committed", "payload": {"sha": "098d7511816c326a423d36a73a4fd14a95756fdb", "node_id": "C_kwDOKNhT9doAKDA5OGQ3NTExODE2YzMyNmE0MjNkMzZhNzNhNGZkMTRhOTU3NTZmZGI", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/commits/098d7511816c326a423d36a73a4fd14a95756fdb", "html_url": "https://github.com/OpenJobDescription/openjd-model-for-python/commit/098d7511816c326a423d36a73a4fd14a95756fdb", "author": {"name": "Daniel Neilson", "email": "neilsd@amazon.com", "date": "2023-09-01T02:05:25Z"}, "committer": {"name": "Daniel Neilson", "email": "neilsd@amazon.com", "date": "2023-09-01T18:30:09Z"}, "tree": {"sha": "fce068f2e13f26f2a628c26f9987720ebd0089f9", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/trees/fce068f2e13f26f2a628c26f9987720ebd0089f9"}, "message": "feat!: Import from internal repository\n\nThis is an import of the source code that had been authored on internal\nrepositories.", "parents": [{"sha": "f1d0e490683bb507a3757ab2d640ba52de0d3ee2", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/commits/f1d0e490683bb507a3757ab2d640ba52de0d3ee2", "html_url": "https://github.com/OpenJobDescription/openjd-model-for-python/commit/f1d0e490683bb507a3757ab2d640ba52de0d3ee2"}], "verification": {"verified": false, "reason": "unsigned", "signature": null, "payload": null, "verified_at": null}, "event": "committed"}} {"time": "2023-09-01T02:08:49+00:00", "type": "pr", "payload": {"url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1", "id": 1498130791, "node_id": "PR_kwDOKNhT9c5ZS6ln", "html_url": "https://github.com/OpenJobDescription/openjd-model-for-python/pull/1", "diff_url": "https://github.com/OpenJobDescription/openjd-model-for-python/pull/1.diff", "patch_url": "https://github.com/OpenJobDescription/openjd-model-for-python/pull/1.patch", "issue_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/1", "number": 1, "state": "closed", "locked": false, "title": "feat!: Import from internal repository", "user": {"login": "ddneilson", "id": 53624638, "node_id": "MDQ6VXNlcjUzNjI0NjM4", "avatar_url": "https://avatars.githubusercontent.com/u/53624638?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ddneilson", "html_url": "https://github.com/ddneilson", "followers_url": "https://api.github.com/users/ddneilson/followers", "following_url": "https://api.github.com/users/ddneilson/following{/other_user}", "gists_url": "https://api.github.com/users/ddneilson/gists{/gist_id}", "starred_url": "https://api.github.com/users/ddneilson/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ddneilson/subscriptions", "organizations_url": "https://api.github.com/users/ddneilson/orgs", "repos_url": "https://api.github.com/users/ddneilson/repos", "events_url": "https://api.github.com/users/ddneilson/events{/privacy}", "received_events_url": "https://api.github.com/users/ddneilson/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "This is an import of the source code that had been authored on internal repositories.\r\n\r\n\r\nBy submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.\r\n", "created_at": "2023-09-01T02:08:49Z", "updated_at": "2023-09-05T17:08:31Z", "closed_at": "2023-09-05T17:08:22Z", "merged_at": "2023-09-05T17:08:22Z", "merge_commit_sha": "cb887a16e27352959e2070182c58f3c0610b13fe", "assignees": [], "requested_reviewers": [], "requested_teams": [], "labels": [], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1/commits", "review_comments_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1/comments", "review_comment_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/1/comments", "statuses_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/statuses/098d7511816c326a423d36a73a4fd14a95756fdb", "head": {"label": "OpenJobDescription:ddneilson/initial_commit", "ref": "ddneilson/initial_commit", "sha": "098d7511816c326a423d36a73a4fd14a95756fdb", "user": {"login": "OpenJobDescription", "id": 142452466, "node_id": "O_kgDOCH2m8g", "avatar_url": "https://avatars.githubusercontent.com/u/142452466?v=4", "gravatar_id": "", "url": "https://api.github.com/users/OpenJobDescription", "html_url": "https://github.com/OpenJobDescription", "followers_url": "https://api.github.com/users/OpenJobDescription/followers", "following_url": "https://api.github.com/users/OpenJobDescription/following{/other_user}", "gists_url": "https://api.github.com/users/OpenJobDescription/gists{/gist_id}", "starred_url": "https://api.github.com/users/OpenJobDescription/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/OpenJobDescription/subscriptions", "organizations_url": "https://api.github.com/users/OpenJobDescription/orgs", "repos_url": "https://api.github.com/users/OpenJobDescription/repos", "events_url": "https://api.github.com/users/OpenJobDescription/events{/privacy}", "received_events_url": "https://api.github.com/users/OpenJobDescription/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 685265909, "node_id": "R_kgDOKNhT9Q", "name": "openjd-model-for-python", "full_name": "OpenJobDescription/openjd-model-for-python", "private": false, "owner": {"login": "OpenJobDescription", "id": 142452466, "node_id": "O_kgDOCH2m8g", "avatar_url": "https://avatars.githubusercontent.com/u/142452466?v=4", "gravatar_id": "", "url": "https://api.github.com/users/OpenJobDescription", "html_url": "https://github.com/OpenJobDescription", "followers_url": "https://api.github.com/users/OpenJobDescription/followers", "following_url": "https://api.github.com/users/OpenJobDescription/following{/other_user}", "gists_url": "https://api.github.com/users/OpenJobDescription/gists{/gist_id}", "starred_url": "https://api.github.com/users/OpenJobDescription/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/OpenJobDescription/subscriptions", "organizations_url": "https://api.github.com/users/OpenJobDescription/orgs", "repos_url": "https://api.github.com/users/OpenJobDescription/repos", "events_url": "https://api.github.com/users/OpenJobDescription/events{/privacy}", "received_events_url": "https://api.github.com/users/OpenJobDescription/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/OpenJobDescription/openjd-model-for-python", "description": "Provides a Python implementation of the data model for Open Job Description's template schemas.", "fork": false, "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python", "forks_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/forks", "keys_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/teams", "hooks_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/hooks", "issue_events_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events{/number}", "events_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/events", "assignees_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/assignees{/user}", "branches_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/branches{/branch}", "tags_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/tags", "blobs_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/refs{/sha}", "trees_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/statuses/{sha}", "languages_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/languages", "stargazers_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/stargazers", "contributors_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contributors", "subscribers_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/subscribers", "subscription_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/subscription", "commits_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits{/sha}", "git_commits_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/commits{/sha}", "comments_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/comments{/number}", "issue_comment_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/comments{/number}", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/{+path}", "compare_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/merges", "archive_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/downloads", "issues_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues{/number}", "pulls_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls{/number}", "milestones_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/milestones{/number}", "notifications_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/labels{/name}", "releases_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/releases{/id}", "deployments_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/deployments", "created_at": "2023-08-30T21:28:48Z", "updated_at": "2026-05-19T19:09:34Z", "pushed_at": "2026-05-19T19:09:34Z", "git_url": "git://github.com/OpenJobDescription/openjd-model-for-python.git", "ssh_url": "git@github.com:OpenJobDescription/openjd-model-for-python.git", "clone_url": "https://github.com/OpenJobDescription/openjd-model-for-python.git", "svn_url": "https://github.com/OpenJobDescription/openjd-model-for-python", "homepage": "https://github.com/OpenJobDescription/openjd-specifications/wiki", "size": 488, "stargazers_count": 12, "watchers_count": 12, "language": "Python", "has_issues": true, "has_projects": true, "has_downloads": true, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 20, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 9, "license": {"key": "apache-2.0", "name": "Apache License 2.0", "spdx_id": "Apache-2.0", "url": "https://api.github.com/licenses/apache-2.0", "node_id": "MDc6TGljZW5zZTI="}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 20, "open_issues": 9, "watchers": 12, "default_branch": "mainline"}}, "base": {"label": "OpenJobDescription:mainline", "ref": "mainline", "sha": "f1d0e490683bb507a3757ab2d640ba52de0d3ee2", "user": {"login": "OpenJobDescription", "id": 142452466, "node_id": "O_kgDOCH2m8g", "avatar_url": "https://avatars.githubusercontent.com/u/142452466?v=4", "gravatar_id": "", "url": "https://api.github.com/users/OpenJobDescription", "html_url": "https://github.com/OpenJobDescription", "followers_url": "https://api.github.com/users/OpenJobDescription/followers", "following_url": "https://api.github.com/users/OpenJobDescription/following{/other_user}", "gists_url": "https://api.github.com/users/OpenJobDescription/gists{/gist_id}", "starred_url": "https://api.github.com/users/OpenJobDescription/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/OpenJobDescription/subscriptions", "organizations_url": "https://api.github.com/users/OpenJobDescription/orgs", "repos_url": "https://api.github.com/users/OpenJobDescription/repos", "events_url": "https://api.github.com/users/OpenJobDescription/events{/privacy}", "received_events_url": "https://api.github.com/users/OpenJobDescription/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "repo": {"id": 685265909, "node_id": "R_kgDOKNhT9Q", "name": "openjd-model-for-python", "full_name": "OpenJobDescription/openjd-model-for-python", "private": false, "owner": {"login": "OpenJobDescription", "id": 142452466, "node_id": "O_kgDOCH2m8g", "avatar_url": "https://avatars.githubusercontent.com/u/142452466?v=4", "gravatar_id": "", "url": "https://api.github.com/users/OpenJobDescription", "html_url": "https://github.com/OpenJobDescription", "followers_url": "https://api.github.com/users/OpenJobDescription/followers", "following_url": "https://api.github.com/users/OpenJobDescription/following{/other_user}", "gists_url": "https://api.github.com/users/OpenJobDescription/gists{/gist_id}", "starred_url": "https://api.github.com/users/OpenJobDescription/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/OpenJobDescription/subscriptions", "organizations_url": "https://api.github.com/users/OpenJobDescription/orgs", "repos_url": "https://api.github.com/users/OpenJobDescription/repos", "events_url": "https://api.github.com/users/OpenJobDescription/events{/privacy}", "received_events_url": "https://api.github.com/users/OpenJobDescription/received_events", "type": "Organization", "user_view_type": "public", "site_admin": false}, "html_url": "https://github.com/OpenJobDescription/openjd-model-for-python", "description": "Provides a Python implementation of the data model for Open Job Description's template schemas.", "fork": false, "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python", "forks_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/forks", "keys_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/teams", "hooks_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/hooks", "issue_events_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events{/number}", "events_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/events", "assignees_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/assignees{/user}", "branches_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/branches{/branch}", "tags_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/tags", "blobs_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/refs{/sha}", "trees_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/statuses/{sha}", "languages_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/languages", "stargazers_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/stargazers", "contributors_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contributors", "subscribers_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/subscribers", "subscription_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/subscription", "commits_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits{/sha}", "git_commits_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/git/commits{/sha}", "comments_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/comments{/number}", "issue_comment_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/comments{/number}", "contents_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/contents/{+path}", "compare_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/merges", "archive_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/downloads", "issues_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues{/number}", "pulls_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls{/number}", "milestones_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/milestones{/number}", "notifications_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/labels{/name}", "releases_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/releases{/id}", "deployments_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/deployments", "created_at": "2023-08-30T21:28:48Z", "updated_at": "2026-05-19T19:09:34Z", "pushed_at": "2026-05-19T19:09:34Z", "git_url": "git://github.com/OpenJobDescription/openjd-model-for-python.git", "ssh_url": "git@github.com:OpenJobDescription/openjd-model-for-python.git", "clone_url": "https://github.com/OpenJobDescription/openjd-model-for-python.git", "svn_url": "https://github.com/OpenJobDescription/openjd-model-for-python", "homepage": "https://github.com/OpenJobDescription/openjd-specifications/wiki", "size": 488, "stargazers_count": 12, "watchers_count": 12, "language": "Python", "has_issues": true, "has_projects": true, "has_downloads": true, "has_wiki": false, "has_pages": false, "has_discussions": false, "forks_count": 20, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 9, "license": {"key": "apache-2.0", "name": "Apache License 2.0", "spdx_id": "Apache-2.0", "url": "https://api.github.com/licenses/apache-2.0", "node_id": "MDc6TGljZW5zZTI="}, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "has_pull_requests": true, "pull_request_creation_policy": "all", "topics": [], "visibility": "public", "forks": 20, "open_issues": 9, "watchers": 12, "default_branch": "mainline"}}, "_links": {"self": {"href": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1"}, "html": {"href": "https://github.com/OpenJobDescription/openjd-model-for-python/pull/1"}, "issue": {"href": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/1"}, "comments": {"href": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/1/comments"}, "review_comments": {"href": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1/comments"}, "review_comment": {"href": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/comments{/number}"}, "commits": {"href": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1/commits"}, "statuses": {"href": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/statuses/098d7511816c326a423d36a73a4fd14a95756fdb"}}, "author_association": "CONTRIBUTOR", "auto_merge": null, "assignee": null, "active_lock_reason": null, "merged": true, "mergeable": null, "rebaseable": null, "mergeable_state": "unknown", "merged_by": {"login": "moorec-aws", "id": 122481442, "node_id": "U_kgDOB0zrIg", "avatar_url": "https://avatars.githubusercontent.com/u/122481442?v=4", "gravatar_id": "", "url": "https://api.github.com/users/moorec-aws", "html_url": "https://github.com/moorec-aws", "followers_url": "https://api.github.com/users/moorec-aws/followers", "following_url": "https://api.github.com/users/moorec-aws/following{/other_user}", "gists_url": "https://api.github.com/users/moorec-aws/gists{/gist_id}", "starred_url": "https://api.github.com/users/moorec-aws/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/moorec-aws/subscriptions", "organizations_url": "https://api.github.com/users/moorec-aws/orgs", "repos_url": "https://api.github.com/users/moorec-aws/repos", "events_url": "https://api.github.com/users/moorec-aws/events{/privacy}", "received_events_url": "https://api.github.com/users/moorec-aws/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "comments": 0, "review_comments": 0, "maintainer_can_modify": false, "commits": 1, "additions": 16797, "deletions": 10, "changed_files": 87}} {"time": "2023-09-01T02:35:04+00:00", "type": "timeline:head_ref_force_pushed", "payload": {"id": 10252314370, "node_id": "HRFPE_lADOKNhT9c5v2pGxzwAAAAJjFecC", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events/10252314370", "actor": {"login": "ddneilson", "id": 53624638, "node_id": "MDQ6VXNlcjUzNjI0NjM4", "avatar_url": "https://avatars.githubusercontent.com/u/53624638?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ddneilson", "html_url": "https://github.com/ddneilson", "followers_url": "https://api.github.com/users/ddneilson/followers", "following_url": "https://api.github.com/users/ddneilson/following{/other_user}", "gists_url": "https://api.github.com/users/ddneilson/gists{/gist_id}", "starred_url": "https://api.github.com/users/ddneilson/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ddneilson/subscriptions", "organizations_url": "https://api.github.com/users/ddneilson/orgs", "repos_url": "https://api.github.com/users/ddneilson/repos", "events_url": "https://api.github.com/users/ddneilson/events{/privacy}", "received_events_url": "https://api.github.com/users/ddneilson/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "event": "head_ref_force_pushed", "commit_id": "3c05e6c47b5331358e68a8f88b28bb69fc4f5452", "commit_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits/3c05e6c47b5331358e68a8f88b28bb69fc4f5452", "created_at": "2023-09-01T02:35:04Z", "performed_via_github_app": null}} {"time": "2023-09-01T02:49:54+00:00", "type": "timeline:head_ref_force_pushed", "payload": {"id": 10252372299, "node_id": "HRFPE_lADOKNhT9c5v2pGxzwAAAAJjFslL", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events/10252372299", "actor": {"login": "ddneilson", "id": 53624638, "node_id": "MDQ6VXNlcjUzNjI0NjM4", "avatar_url": "https://avatars.githubusercontent.com/u/53624638?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ddneilson", "html_url": "https://github.com/ddneilson", "followers_url": "https://api.github.com/users/ddneilson/followers", "following_url": "https://api.github.com/users/ddneilson/following{/other_user}", "gists_url": "https://api.github.com/users/ddneilson/gists{/gist_id}", "starred_url": "https://api.github.com/users/ddneilson/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ddneilson/subscriptions", "organizations_url": "https://api.github.com/users/ddneilson/orgs", "repos_url": "https://api.github.com/users/ddneilson/repos", "events_url": "https://api.github.com/users/ddneilson/events{/privacy}", "received_events_url": "https://api.github.com/users/ddneilson/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "event": "head_ref_force_pushed", "commit_id": "2b7d68997eeb468c21977d54af7b392d4e4d3356", "commit_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits/2b7d68997eeb468c21977d54af7b392d4e4d3356", "created_at": "2023-09-01T02:49:54Z", "performed_via_github_app": null}} {"time": "2023-09-01T03:28:42+00:00", "type": "timeline:head_ref_force_pushed", "payload": {"id": 10252562506, "node_id": "HRFPE_lADOKNhT9c5v2pGxzwAAAAJjGbBK", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events/10252562506", "actor": {"login": "ddneilson", "id": 53624638, "node_id": "MDQ6VXNlcjUzNjI0NjM4", "avatar_url": "https://avatars.githubusercontent.com/u/53624638?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ddneilson", "html_url": "https://github.com/ddneilson", "followers_url": "https://api.github.com/users/ddneilson/followers", "following_url": "https://api.github.com/users/ddneilson/following{/other_user}", "gists_url": "https://api.github.com/users/ddneilson/gists{/gist_id}", "starred_url": "https://api.github.com/users/ddneilson/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ddneilson/subscriptions", "organizations_url": "https://api.github.com/users/ddneilson/orgs", "repos_url": "https://api.github.com/users/ddneilson/repos", "events_url": "https://api.github.com/users/ddneilson/events{/privacy}", "received_events_url": "https://api.github.com/users/ddneilson/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "event": "head_ref_force_pushed", "commit_id": "bac47f88771ba2e8e0d5bbd218305c6182fed07d", "commit_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits/bac47f88771ba2e8e0d5bbd218305c6182fed07d", "created_at": "2023-09-01T03:28:42Z", "performed_via_github_app": null}} {"time": "2023-09-01T03:36:36+00:00", "type": "timeline:head_ref_force_pushed", "payload": {"id": 10252601316, "node_id": "HRFPE_lADOKNhT9c5v2pGxzwAAAAJjGkfk", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events/10252601316", "actor": {"login": "ddneilson", "id": 53624638, "node_id": "MDQ6VXNlcjUzNjI0NjM4", "avatar_url": "https://avatars.githubusercontent.com/u/53624638?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ddneilson", "html_url": "https://github.com/ddneilson", "followers_url": "https://api.github.com/users/ddneilson/followers", "following_url": "https://api.github.com/users/ddneilson/following{/other_user}", "gists_url": "https://api.github.com/users/ddneilson/gists{/gist_id}", "starred_url": "https://api.github.com/users/ddneilson/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ddneilson/subscriptions", "organizations_url": "https://api.github.com/users/ddneilson/orgs", "repos_url": "https://api.github.com/users/ddneilson/repos", "events_url": "https://api.github.com/users/ddneilson/events{/privacy}", "received_events_url": "https://api.github.com/users/ddneilson/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "event": "head_ref_force_pushed", "commit_id": "aafe66cf11a0b67e9f187362716f941ad14c9ac2", "commit_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits/aafe66cf11a0b67e9f187362716f941ad14c9ac2", "created_at": "2023-09-01T03:36:36Z", "performed_via_github_app": null}} {"time": "2023-09-01T18:30:17+00:00", "type": "timeline:head_ref_force_pushed", "payload": {"id": 10259993875, "node_id": "HRFPE_lADOKNhT9c5v2pGxzwAAAAJjixUT", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events/10259993875", "actor": {"login": "ddneilson", "id": 53624638, "node_id": "MDQ6VXNlcjUzNjI0NjM4", "avatar_url": "https://avatars.githubusercontent.com/u/53624638?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ddneilson", "html_url": "https://github.com/ddneilson", "followers_url": "https://api.github.com/users/ddneilson/followers", "following_url": "https://api.github.com/users/ddneilson/following{/other_user}", "gists_url": "https://api.github.com/users/ddneilson/gists{/gist_id}", "starred_url": "https://api.github.com/users/ddneilson/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ddneilson/subscriptions", "organizations_url": "https://api.github.com/users/ddneilson/orgs", "repos_url": "https://api.github.com/users/ddneilson/repos", "events_url": "https://api.github.com/users/ddneilson/events{/privacy}", "received_events_url": "https://api.github.com/users/ddneilson/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "event": "head_ref_force_pushed", "commit_id": "098d7511816c326a423d36a73a4fd14a95756fdb", "commit_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits/098d7511816c326a423d36a73a4fd14a95756fdb", "created_at": "2023-09-01T18:30:17Z", "performed_via_github_app": null}} {"time": "2023-09-01T19:13:40+00:00", "type": "timeline:review_requested", "payload": {"id": 10260332333, "node_id": "RRE_lADOKNhT9c5v2pGxzwAAAAJjkD8t", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events/10260332333", "actor": {"login": "moorec-aws", "id": 122481442, "node_id": "U_kgDOB0zrIg", "avatar_url": "https://avatars.githubusercontent.com/u/122481442?v=4", "gravatar_id": "", "url": "https://api.github.com/users/moorec-aws", "html_url": "https://github.com/moorec-aws", "followers_url": "https://api.github.com/users/moorec-aws/followers", "following_url": "https://api.github.com/users/moorec-aws/following{/other_user}", "gists_url": "https://api.github.com/users/moorec-aws/gists{/gist_id}", "starred_url": "https://api.github.com/users/moorec-aws/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/moorec-aws/subscriptions", "organizations_url": "https://api.github.com/users/moorec-aws/orgs", "repos_url": "https://api.github.com/users/moorec-aws/repos", "events_url": "https://api.github.com/users/moorec-aws/events{/privacy}", "received_events_url": "https://api.github.com/users/moorec-aws/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "event": "review_requested", "commit_id": null, "commit_url": null, "created_at": "2023-09-01T19:13:40Z", "review_requester": {"login": "moorec-aws", "id": 122481442, "node_id": "U_kgDOB0zrIg", "avatar_url": "https://avatars.githubusercontent.com/u/122481442?v=4", "gravatar_id": "", "url": "https://api.github.com/users/moorec-aws", "html_url": "https://github.com/moorec-aws", "followers_url": "https://api.github.com/users/moorec-aws/followers", "following_url": "https://api.github.com/users/moorec-aws/following{/other_user}", "gists_url": "https://api.github.com/users/moorec-aws/gists{/gist_id}", "starred_url": "https://api.github.com/users/moorec-aws/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/moorec-aws/subscriptions", "organizations_url": "https://api.github.com/users/moorec-aws/orgs", "repos_url": "https://api.github.com/users/moorec-aws/repos", "events_url": "https://api.github.com/users/moorec-aws/events{/privacy}", "received_events_url": "https://api.github.com/users/moorec-aws/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "requested_reviewer": {"login": "moorec-aws", "id": 122481442, "node_id": "U_kgDOB0zrIg", "avatar_url": "https://avatars.githubusercontent.com/u/122481442?v=4", "gravatar_id": "", "url": "https://api.github.com/users/moorec-aws", "html_url": "https://github.com/moorec-aws", "followers_url": "https://api.github.com/users/moorec-aws/followers", "following_url": "https://api.github.com/users/moorec-aws/following{/other_user}", "gists_url": "https://api.github.com/users/moorec-aws/gists{/gist_id}", "starred_url": "https://api.github.com/users/moorec-aws/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/moorec-aws/subscriptions", "organizations_url": "https://api.github.com/users/moorec-aws/orgs", "repos_url": "https://api.github.com/users/moorec-aws/repos", "events_url": "https://api.github.com/users/moorec-aws/events{/privacy}", "received_events_url": "https://api.github.com/users/moorec-aws/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "performed_via_github_app": null}} {"time": "2023-09-05T17:08:12+00:00", "type": "review", "payload": {"id": 1611558933, "node_id": "PRR_kwDOKNhT9c5gDnAV", "user": {"login": "moorec-aws", "id": 122481442, "node_id": "U_kgDOB0zrIg", "avatar_url": "https://avatars.githubusercontent.com/u/122481442?u=55d045112a37685c157f68dd38f783356f6735d6&v=4", "gravatar_id": "", "url": "https://api.github.com/users/moorec-aws", "html_url": "https://github.com/moorec-aws", "followers_url": "https://api.github.com/users/moorec-aws/followers", "following_url": "https://api.github.com/users/moorec-aws/following{/other_user}", "gists_url": "https://api.github.com/users/moorec-aws/gists{/gist_id}", "starred_url": "https://api.github.com/users/moorec-aws/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/moorec-aws/subscriptions", "organizations_url": "https://api.github.com/users/moorec-aws/orgs", "repos_url": "https://api.github.com/users/moorec-aws/repos", "events_url": "https://api.github.com/users/moorec-aws/events{/privacy}", "received_events_url": "https://api.github.com/users/moorec-aws/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "", "state": "APPROVED", "html_url": "https://github.com/OpenJobDescription/openjd-model-for-python/pull/1#pullrequestreview-1611558933", "pull_request_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1", "author_association": "CONTRIBUTOR", "_links": {"html": {"href": "https://github.com/OpenJobDescription/openjd-model-for-python/pull/1#pullrequestreview-1611558933"}, "pull_request": {"href": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1"}}, "submitted_at": "2023-09-05T17:08:12Z", "commit_id": "098d7511816c326a423d36a73a4fd14a95756fdb"}} {"time": "2023-09-05T17:08:12+00:00", "type": "timeline:reviewed", "payload": {"id": 1611558933, "node_id": "PRR_kwDOKNhT9c5gDnAV", "user": {"login": "moorec-aws", "id": 122481442, "node_id": "U_kgDOB0zrIg", "avatar_url": "https://avatars.githubusercontent.com/u/122481442?v=4", "gravatar_id": "", "url": "https://api.github.com/users/moorec-aws", "html_url": "https://github.com/moorec-aws", "followers_url": "https://api.github.com/users/moorec-aws/followers", "following_url": "https://api.github.com/users/moorec-aws/following{/other_user}", "gists_url": "https://api.github.com/users/moorec-aws/gists{/gist_id}", "starred_url": "https://api.github.com/users/moorec-aws/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/moorec-aws/subscriptions", "organizations_url": "https://api.github.com/users/moorec-aws/orgs", "repos_url": "https://api.github.com/users/moorec-aws/repos", "events_url": "https://api.github.com/users/moorec-aws/events{/privacy}", "received_events_url": "https://api.github.com/users/moorec-aws/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "body": "", "commit_id": "098d7511816c326a423d36a73a4fd14a95756fdb", "state": "approved", "html_url": "https://github.com/OpenJobDescription/openjd-model-for-python/pull/1#pullrequestreview-1611558933", "pull_request_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1", "_links": {"html": {"href": "https://github.com/OpenJobDescription/openjd-model-for-python/pull/1#pullrequestreview-1611558933"}, "pull_request": {"href": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/pulls/1"}}, "submitted_at": "2023-09-05T17:08:12Z", "updated_at": "2023-09-05T17:08:12Z", "author_association": "CONTRIBUTOR", "event": "reviewed"}} {"time": "2023-09-05T17:08:22+00:00", "type": "timeline:merged", "payload": {"id": 10286107846, "node_id": "ME_lADOKNhT9c5v2pGxzwAAAAJlGYzG", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events/10286107846", "actor": {"login": "moorec-aws", "id": 122481442, "node_id": "U_kgDOB0zrIg", "avatar_url": "https://avatars.githubusercontent.com/u/122481442?v=4", "gravatar_id": "", "url": "https://api.github.com/users/moorec-aws", "html_url": "https://github.com/moorec-aws", "followers_url": "https://api.github.com/users/moorec-aws/followers", "following_url": "https://api.github.com/users/moorec-aws/following{/other_user}", "gists_url": "https://api.github.com/users/moorec-aws/gists{/gist_id}", "starred_url": "https://api.github.com/users/moorec-aws/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/moorec-aws/subscriptions", "organizations_url": "https://api.github.com/users/moorec-aws/orgs", "repos_url": "https://api.github.com/users/moorec-aws/repos", "events_url": "https://api.github.com/users/moorec-aws/events{/privacy}", "received_events_url": "https://api.github.com/users/moorec-aws/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "event": "merged", "commit_id": "cb887a16e27352959e2070182c58f3c0610b13fe", "commit_url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/commits/cb887a16e27352959e2070182c58f3c0610b13fe", "created_at": "2023-09-05T17:08:22Z", "performed_via_github_app": null}} {"time": "2023-09-05T17:08:22+00:00", "type": "timeline:closed", "payload": {"id": 10286107866, "node_id": "CE_lADOKNhT9c5v2pGxzwAAAAJlGYza", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events/10286107866", "actor": {"login": "moorec-aws", "id": 122481442, "node_id": "U_kgDOB0zrIg", "avatar_url": "https://avatars.githubusercontent.com/u/122481442?v=4", "gravatar_id": "", "url": "https://api.github.com/users/moorec-aws", "html_url": "https://github.com/moorec-aws", "followers_url": "https://api.github.com/users/moorec-aws/followers", "following_url": "https://api.github.com/users/moorec-aws/following{/other_user}", "gists_url": "https://api.github.com/users/moorec-aws/gists{/gist_id}", "starred_url": "https://api.github.com/users/moorec-aws/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/moorec-aws/subscriptions", "organizations_url": "https://api.github.com/users/moorec-aws/orgs", "repos_url": "https://api.github.com/users/moorec-aws/repos", "events_url": "https://api.github.com/users/moorec-aws/events{/privacy}", "received_events_url": "https://api.github.com/users/moorec-aws/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "event": "closed", "commit_id": null, "commit_url": null, "created_at": "2023-09-05T17:08:22Z", "state_reason": null, "performed_via_github_app": null}} {"time": "2023-09-05T17:08:31+00:00", "type": "timeline:head_ref_deleted", "payload": {"id": 10286109177, "node_id": "HRDE_lADOKNhT9c5v2pGxzwAAAAJlGZH5", "url": "https://api.github.com/repos/OpenJobDescription/openjd-model-for-python/issues/events/10286109177", "actor": {"login": "moorec-aws", "id": 122481442, "node_id": "U_kgDOB0zrIg", "avatar_url": "https://avatars.githubusercontent.com/u/122481442?v=4", "gravatar_id": "", "url": "https://api.github.com/users/moorec-aws", "html_url": "https://github.com/moorec-aws", "followers_url": "https://api.github.com/users/moorec-aws/followers", "following_url": "https://api.github.com/users/moorec-aws/following{/other_user}", "gists_url": "https://api.github.com/users/moorec-aws/gists{/gist_id}", "starred_url": "https://api.github.com/users/moorec-aws/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/moorec-aws/subscriptions", "organizations_url": "https://api.github.com/users/moorec-aws/orgs", "repos_url": "https://api.github.com/users/moorec-aws/repos", "events_url": "https://api.github.com/users/moorec-aws/events{/privacy}", "received_events_url": "https://api.github.com/users/moorec-aws/received_events", "type": "User", "user_view_type": "public", "site_admin": false}, "event": "head_ref_deleted", "commit_id": null, "commit_url": null, "created_at": "2023-09-05T17:08:31Z", "performed_via_github_app": null}}