diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index c484f76bf..000000000 --- a/.editorconfig +++ /dev/null @@ -1,7 +0,0 @@ -# EditorConfig is awesome: https://editorconfig.org/ - -# top-most EditorConfig file -root = true - -[*] -max_line_length = 160 diff --git a/.fossa.yml b/.fossa.yml new file mode 100644 index 000000000..7a283dd20 --- /dev/null +++ b/.fossa.yml @@ -0,0 +1,16 @@ +# Generated by FOSSA CLI (https://github.com/fossas/fossa-cli) +# Visit https://fossa.com to learn more + +version: 2 +cli: + server: https://app.fossa.com + fetcher: custom + project: jira +analyze: + modules: + - name: . + type: pip + target: . + path: . + options: + strategy: requirements diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 20105a190..a12c2cc72 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -26,6 +26,9 @@ A code block with the any trace messages. **Version Information** +Type of Jira instance: +- [ ] Jira Cloud (Hosted by Atlassian) +- [ ] Jira Server or Data Center (Self-hosted) Python Interpreter: jira-python: OS: diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..981f8ad3b --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 +updates: + - package-ecosystem: pip + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 + target-branch: master + labels: + - "dependencies" + - "skip-changelog" diff --git a/.github/workflows/jira_server_ci.yml b/.github/workflows/jira_server_ci.yml new file mode 100644 index 000000000..8e6a97f4b --- /dev/null +++ b/.github/workflows/jira_server_ci.yml @@ -0,0 +1,71 @@ +name: Jira Server CI + +on: + # Trigger the workflow on push or pull request, + # but only for the master branch + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + test: + name: ${{ matrix.os }} / Python ${{ matrix.python-version }} / Jira ${{ matrix.jira-version }} + runs-on: ${{ matrix.os }}-latest + strategy: + matrix: + os: [Ubuntu] + python-version: [3.6, 3.7, 3.8, 3.9] + jira-version: [8.17.1] + + steps: + - uses: actions/checkout@master + - name: Start Jira docker instance + run: docker run -dit -p 2990:2990 --name jira addono/jira-software-standalone --version ${{ matrix.jira-version }} + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Get pip cache dir + id: pip-cache + run: | + echo "::set-output name=dir::$(pip cache dir)" + - name: Setup the Pip cache + uses: actions/cache@v2 + with: + path: ${{ steps.pip-cache.outputs.dir }} + key: >- + ${{ runner.os }}-pip-${{ hashFiles('setup.cfg') }}-${{ + hashFiles('setup.py') }}-${{ hashFiles('tox.ini') }}-${{ + hashFiles('.pre-commit-config.yaml') }} + restore-keys: | + ${{ runner.os }}-pip- + ${{ runner.os }}- + + - name: Install Dependencies + run: | + sudo apt-get update; sudo apt-get install gcc libkrb5-dev + python -m pip install --upgrade pip + python -m pip install --upgrade tox tox-gh-actions + + - name: Lint with tox + run: tox -e lint + + - name: Test with tox + run: tox + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v1.0.15 + with: + file: ./coverage.xml + name: ${{ runner.os }}-${{ matrix.python-version }} + + - name: Run tox pkg + run: tox -e pkg + + - name: Make docs + run: tox -e docs diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 000000000..96c057444 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,87 @@ +name: release + +on: + release: + types: [created, edited] + +jobs: + publish: + environment: publish + if: startsWith(github.ref, 'refs/tags/') # Only release during tags + runs-on: ubuntu-20.04 + + env: + PY_COLORS: 1 + TOXENV: pkg + + steps: + - name: Switch to using Python 3.6 by default + uses: actions/setup-python@v2 + with: + python-version: 3.6 + + - name: Install Dependencies + run: | + sudo apt-get update + sudo apt-get install gcc libkrb5-dev + python3 -m pip install --upgrade pip + python3 -m pip install --upgrade tox + + - name: Check out src from Git + uses: actions/checkout@v2 + with: + # Get shallow Git history (default) for release events + # but have a complete clone for any other workflows. + # Both options fetch tags but since we're going to remove + # one from HEAD in non-create-tag workflows, we need full + # history for them. + fetch-depth: >- + ${{ + ( + ( + github.event_name == 'create' && + github.event.ref_type == 'tag' + ) || + github.event_name == 'release' + ) && + 1 || 0 + }} + + - name: Drop Git tags from HEAD for non-tag-create and non-release events + if: >- + ( + github.event_name != 'create' || + github.event.ref_type != 'tag' + ) && + github.event_name != 'release' + run: >- + git tag --points-at HEAD + | + xargs git tag --delete + + - name: Build dists + run: python3 -m tox + + - name: Publish to test.pypi.org + if: >- + ( + github.event_name == 'push' && + github.ref == format( + 'refs/heads/{0}', github.event.repository.default_branch + ) + ) || + ( + github.event_name == 'create' && + github.event.ref_type == 'tag' + ) + uses: pypa/gh-action-pypi-publish@master + with: + password: ${{ secrets.TESTPYPI_PASSWORD }} + repository_url: https://test.pypi.org/legacy/ + + - name: Publish to pypi.org + if: >- # "create" workflows run separately from "push" & "pull_request" + github.event_name == 'release' + uses: pypa/gh-action-pypi-publish@master + with: + password: ${{ secrets.PYPI_PASSWORD }} diff --git a/.gitignore b/.gitignore index 49840bc00..b44124c28 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,4 @@ -# See https://stackoverflow.com/questions/5533050/gitignore-exclude-folder-but-include-specific-subfolder -# to understand pattern used to include .idea/codeStyleSettings.xml but not the rest of .idea/ -!.idea/ -.idea/* -!.idea/codeStyleSettings.xml +.idea *.bak *.egg *.egg-info/ @@ -23,7 +19,6 @@ reports reports/ setenv.sh settings.py -test-quick tests/settings.py tests/test-reports-*/* **/*.log diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml deleted file mode 100644 index ae83c6768..000000000 --- a/.idea/codeStyleSettings.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4f59ad2b7..21015317a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,12 +1,12 @@ --- repos: - repo: https://github.com/python/black - rev: 19.3b0 + rev: 21.6b0 hooks: - id: black language_version: python3 - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.3.0 + rev: v4.0.1 hooks: - id: end-of-file-fixer - id: trailing-whitespace @@ -19,22 +19,41 @@ repos: - id: debug-statements - id: check-yaml files: .*\.(yaml|yml)$ + - repo: https://github.com/codespell-project/codespell.git + rev: v2.1.0 + hooks: + - id: codespell + name: codespell + description: Checks for common misspellings in text files. + entry: codespell + language: python + types: [text] + args: [] + require_serial: false + additional_dependencies: [] - repo: https://gitlab.com/pycqa/flake8 - rev: 3.7.8 + rev: 3.9.2 hooks: - id: flake8 - additional_dependencies: - - flake8-black + - repo: https://github.com/pycqa/isort + rev: 5.9.1 + hooks: + - id: isort + name: isort - repo: https://github.com/adrienverge/yamllint.git - rev: v1.17.0 + rev: v1.26.1 hooks: - id: yamllint files: \.(yaml|yml)$ - - repo: https://github.com/openstack-dev/bashate.git - rev: 0.6.0 - hooks: - - id: bashate - repo: https://github.com/pre-commit/mirrors-mypy.git - rev: v0.730 + rev: v0.902 hooks: - id: mypy + additional_dependencies: + - types-requests + - types-pkg_resources + - repo: https://github.com/asottile/pyupgrade + rev: v2.26.0 + hooks: + - id: pyupgrade + args: [ --py36-plus ] diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6e90c8aa7..000000000 --- a/.travis.yml +++ /dev/null @@ -1,76 +0,0 @@ ---- -language: python -dist: xenial -# Build only commits on master and release tags for the "Build pushed branches" feature. -# This prevents building twice on PRs originating from our repo ("Build pushed pull requests)". -# See: -# - https://github.com/travis-ci/travis-ci/issues/1147 -# - https://docs.travis-ci.com/user/pull-requests/#double-builds-on-pull-requests -branches: - only: - - master - - /^\d+\.\d+(\.\d+)?(-\S*)?$/ - -cache: - bundler: true - pip: true - directories: - - $HOME/.cache/pre-commit - - $HOME/.pre-commit - - $HOME/.rvm - - $HOME/Library/Caches/Homebrew -os: - - linux -stages: - - maintenance - - test - - deploy -before_install: - - pip install --upgrade tox tox-venv - - rm -rf .tox -notifications: - email: - - pycontribs@googlegroups.com -jobs: - include: - - stage: maintenance - script: - - python -m tox -e maintenance - if: type = cron - - script: - - python -m tox - env: TOXENV="lint,docs,pkg,py37" - python: "3.7" - after_success: - - bash <(curl -s https://codecov.io/bash) -e py37 - - script: python -m tox - python: "3.6" - env: TOXENV=py36 PYTHON='3.6' - after_success: - - bash <(curl -s https://codecov.io/bash) -e TOXENV - - script: python -m tox - python: "3.5" - env: TOXENV=py35 - after_success: - - bash <(curl -s https://codecov.io/bash) -e TOXENV - - stage: deploy - script: - - tox -e upload - if: tag IS present AND type != cron - deploy: - - provider: releases - api_key: - secure: YJGigSNYOzMJqs23gIZLFxiVYRqHdV4WsTZmRVosishD2QIaDlTwJma7k6Y5eMPVNdLpqo7Tq6bt7xkJAz/dcr3UO35T/Y0tiRFFW3sd6IOB6ELwSwPhSeHoyUMvZtKyDTl+9tOfeZusFZuCc+mBLQcG+S2NzEaeyrQ6n5hTT/8FGBP91FOq9l5q2gYbmACZ9MisDIjZkTHNYih36ComnZ9QHC91jHKcSuHmOfWWX3GneDVFtuPhF2vjaLQrz8IFtWGW5Sfe35yDYlVQRH+NFxzSJ2zDuT5j8cRgwXjGout78umtMsqAn+zv1Ws/MUNKMTEtONsACndMpGCkuB6Nifl/KcGj5kD7V4PO/gE0ecr830qAwJxSVB7xk6rl797nMxGbr4w2DWQ/iDdHDTlPAEzbLBMLrMRgPxzKPgg5CNxxjT1cHoBNcFPp6gaf017w4XOVUgp/zxXeCg7iGiNJj7z2t8/m9eYVNNlNRPcodN6BjSjPqkYxC3ZMVCI5KsRXbHmR0zOWbPdcRjrY/IgbiTqX09sHotHw5GThP6YTMbienC4h93cdx6MEfX656W6XMOxpC+MjWtYuV8QlfMEJFlstOnA86MVLcmbl+4A6FHuvlQMdDtP9KsKdKIf/4juGhNEFir32P1rUe8J1abmjwXmDkHVbli0SDqaFtB5gyCc= - file_glob: true - file: - - dist/* - - ChangeLog - skip_cleanup: true - on: - tags: true - repo: pycontribs/jira - branch: master -env: - global: - - secure: "pGQGM5YmHvOgaKihOyzb3k6bdqLQnZQ2OXO9QrfXlXwtop3zvZQi80Q+01l230x2psDWlwvqWTknAjAt1w463fYXPwpoSvKVCsLSSbjrf2l56nrDqnoir+n0CBy288+eIdaGEfzcxDiuULeKjlg08zrqjcjLjW0bDbBrlTXsb5U=" - - PIP_DISABLE_PIP_VERSION_CHECK=1 diff --git a/.yamllint b/.yamllint index 028d683b9..dcb54406e 100644 --- a/.yamllint +++ b/.yamllint @@ -2,15 +2,15 @@ extends: default rules: - braces: {max-spaces-inside: 1, level: error} - brackets: {max-spaces-inside: 1, level: error} - colons: {max-spaces-after: -1, level: error} - commas: {max-spaces-after: -1, level: error} + braces: { max-spaces-inside: 1, level: error } + brackets: { max-spaces-inside: 1, level: error } + colons: { max-spaces-after: -1, level: error } + commas: { max-spaces-after: -1, level: error } comments: disable comments-indentation: disable document-start: disable - empty-lines: {max: 3, level: error} - hyphens: {level: error} + empty-lines: { max: 3, level: error } + hyphens: { level: error } indentation: indent-sequences: consistent # spaces: consistent @@ -23,9 +23,8 @@ rules: allow-non-breakable-words: true allow-non-breakable-inline-mappings: true new-line-at-end-of-file: disable - new-lines: {type: unix} + new-lines: disable trailing-spaces: disable truthy: disable -ignore: - .tox +ignore: .tox diff --git a/MANIFEST.in b/MANIFEST.in index f7afaafa0..bb47213ce 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,14 @@ include LICENSE README.rst + +# Include +include jira/py.typed + +# Exclude what is in these folders prune tests +prune .github + +# Exclude these files +exclude package-lock.json +exclude test-requirements.* +recursive-exclude * *.py[co] +recursive-exclude * __pycache__ diff --git a/Makefile b/Makefile index b21499b7c..969aeb309 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ -all: info clean lint test docs dist upload release -.PHONY: all docs upload info req dist +all: info clean lint test docs dist +.PHONY: all docs info req dist PACKAGE_NAME := $(shell python setup.py --name) PACKAGE_VERSION := $(shell python setup.py --version) @@ -72,10 +72,9 @@ dist: $(PREFIX)python setup.py sdist bdist_wheel prepare: - @pyenv install -s 3.5.7 @pyenv install -s 3.6.9 @pyenv install -s 3.7.4 - @pyenv local 3.5.7 3.6.9 3.7.4 + @pyenv local 3.6.9 3.7.4 @echo "INFO: === Preparing to run for package:$(PACKAGE_NAME) platform:$(PLATFORM) py:$(PYTHON_VERSION) dir:$(DIR) ===" #if [ -f ${HOME}/testspace/testspace ]; then ${HOME}/testspace/testspace config url ${TESTSPACE_TOKEN}@pycontribs.testspace.com/jira/tests ; fi; @@ -107,28 +106,3 @@ tag: bumpversion --feature --no-input git push origin master git push --tags - -release: req -ifeq ($(GIT_BRANCH),master) - tag -else - upload - web - - @echo "INFO: Skipping release on this branch." -endif - -upload: - rm -f dist/* -ifeq ($(GIT_BRANCH),develop) - @echo "INFO: Upload package to testpypi.python.org" - $(PREFIX)python setup.py check --restructuredtext --strict - $(PREFIX)python setup.py sdist bdist_wheel - $(PREFIX)twine upload --repository-url https://test.pypi.org/legacy/ dist/* -endif -ifeq ($(GIT_BRANCH),master) - @echo "INFO: Upload package to pypi.python.org" - $(PREFIX)python setup.py check --restructuredtext --strict - $(PREFIX)python setup.py sdist bdist_wheel - $(PREFIX)twine upload dist/* -endif diff --git a/README.rst b/README.rst index c1aa693cb..737689966 100644 --- a/README.rst +++ b/README.rst @@ -3,41 +3,31 @@ Jira Python Library =================== .. image:: https://img.shields.io/pypi/v/jira.svg - :target: https://pypi.python.org/pypi/jira/ + :target: https://pypi.python.org/pypi/jira/ .. image:: https://img.shields.io/pypi/l/jira.svg - :target: https://pypi.python.org/pypi/jira/ - -.. image:: https://img.shields.io/pypi/wheel/jira.svg - :target: https://pypi.python.org/pypi/jira/ + :target: https://pypi.python.org/pypi/jira/ .. image:: https://img.shields.io/github/issues/pycontribs/jira.svg - :target: https://github.com/pycontribs/jira/issues + :target: https://github.com/pycontribs/jira/issues .. image:: https://img.shields.io/badge/irc-%23pycontribs-blue - :target: irc:///#pycontribs + :target: irc:///#pycontribs ------------ .. image:: https://readthedocs.org/projects/jira/badge/?version=master - :target: https://jira.readthedocs.io/ - -.. image:: https://travis-ci.com/pycontribs/jira.svg?branch=master - :target: https://travis-ci.com/pycontribs/jira - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/python/black - :alt: Python Black Code Style + :target: https://jira.readthedocs.io/ .. image:: https://codecov.io/gh/pycontribs/jira/branch/master/graph/badge.svg - :target: https://codecov.io/gh/pycontribs/jira + :target: https://codecov.io/gh/pycontribs/jira .. image:: https://img.shields.io/bountysource/team/pycontribs/activity.svg - :target: https://www.bountysource.com/teams/pycontribs/issues?tracker_ids=3650997 + :target: https://www.bountysource.com/teams/pycontribs/issues?tracker_ids=3650997 .. image:: https://requires.io/github/pycontribs/jira/requirements.svg?branch=master - :target: https://requires.io/github/pycontribs/jira/requirements/?branch=master - :alt: Requirements Status + :target: https://requires.io/github/pycontribs/jira/requirements/?branch=master + :alt: Requirements Status This library eases the use of the Jira REST API from Python and it has been used in production for years. @@ -54,14 +44,14 @@ Feeling impatient? I like your style. .. code-block:: python - from jira import JIRA + from jira import JIRA - jira = JIRA('https://jira.atlassian.com') + jira = JIRA('https://jira.atlassian.com') - issue = jira.issue('JRA-9') - print(issue.fields.project.key) # 'JRA' - print(issue.fields.issuetype.name) # 'New Feature' - print(issue.fields.reporter.displayName) # 'Mike Cannon-Brookes [Atlassian]' + issue = jira.issue('JRA-9') + print(issue.fields.project.key) # 'JRA' + print(issue.fields.issuetype.name) # 'New Feature' + print(issue.fields.reporter.displayName) # 'Mike Cannon-Brookes [Atlassian]' Installation @@ -95,25 +85,75 @@ Development takes place on GitHub_: * ``master`` - (default branch) contains the primary development stream. Tags will be used to show latest releases. -.. _GitHub: https://github.com/pycontribs/jira Setup ===== * Fork_ repo * Keep it sync_'ed while you are developing * Install pyenv_ -* Install `Atlassian Jira Server`_ for testing - - make install-sdk -* pip install jira[test] -* Start up Jira Server - - atlas-run-standalone -* Test your changes - - make test +* develop and test + * Launch docker jira server + - ``docker run -dit -p 2990:2990 --name jira addono/jira-software-standalone`` + * Lint + - ``tox -e lint`` + * Run tests + - ``tox`` + * Run tests for one env only + - ``tox -e py37`` + * Specify what tests to run with pytest_ + - ``tox -e py39 -- tests/resources/test_attachment.py`` + * Debug tests with breakpoints by disabling the coverage plugin, with the ``--no-cov`` argument. + - Example for VSCode on Windows : + + .. code-block:: java + + { + "name": "Pytest", + "type": "python", + "request": "launch", + "python": ".tox\\py39\\Scripts\\python.exe", + "module": "pytest", + "env": { + "CI_JIRA_URL": "http://localhost:2990/jira", + "CI_JIRA_ADMIN": "admin", + "CI_JIRA_ADMIN_PASSWORD": "admin", + "CI_JIRA_USER": "jira_user", + "CI_JIRA_USER_FULL_NAME": "Newly Created CI User", + "CI_JIRA_USER_PASSWORD": "jira", + "CI_JIRA_ISSUE": "Task", + "PYTEST_TIMEOUT": "0", // Don't timeout + }, + "args": [ + // "-v", + "--no-cov", // running coverage affects breakpoints + "tests/resources/test_attachment.py" + ] + } + + * Build and publish with TWINE + - ``tox -e publish`` .. _Fork: https://help.github.com/articles/fork-a-repo/ .. _sync: https://help.github.com/articles/syncing-a-fork/ .. _pyenv: https://amaral.northwestern.edu/resources/guides/pyenv-tutorial -.. _`Atlassian Jira Server`: https://www.atlassian.com/software/jira/download +.. _pytest: https://docs.pytest.org/en/stable/usage.html#specifying-tests-selecting-tests + + +Jira REST API Reference Links +============================= + +When updating interactions with the Jira REST API please refer to the documentation below. We aim to support both Jira Cloud and Jira Server / Data Center. + +1. `Jira Cloud`_ / `Jira Server`_ (main REST API reference) +2. `Jira Software Cloud`_ / `Jira Software Server`_ (former names include: Jira Agile, Greenhopper) +3. `Jira Service Desk Cloud`_ / `Jira Service Desk Server`_ + +.. _`Jira Cloud`: https://developer.atlassian.com/cloud/jira/platform/rest/v2/ +.. _`Jira Server`: https://docs.atlassian.com/software/jira/docs/api/REST/latest/ +.. _`Jira Software Cloud`: https://developer.atlassian.com/cloud/jira/software/rest/ +.. _`Jira Software Server`: https://docs.atlassian.com/jira-software/REST/latest/ +.. _`Jira Service Desk Cloud`: https://docs.atlassian.com/jira-servicedesk/REST/cloud/ +.. _`Jira Service Desk Server`: https://docs.atlassian.com/jira-servicedesk/REST/server/ Credits @@ -123,15 +163,15 @@ In addition to all the contributors we would like to thank to these companies: * Atlassian_ for developing such a powerful issue tracker and for providing a free on-demand Jira_ instance that we can use for continuous integration testing. * JetBrains_ for providing us with free licenses of PyCharm_ -* Travis_ for hosting our continuous integration +* GitHub_ for hosting our continuous integration and our git repo * Navicat_ for providing us free licenses of their powerful database client GUI tools. .. _Atlassian: https://www.atlassian.com/ .. _Jira: https://pycontribs.atlassian.net .. _JetBrains: https://www.jetbrains.com/ .. _PyCharm: https://www.jetbrains.com/pycharm/ -.. _Travis: https://travis-ci.org/ -.. _navicat: https://www.navicat.com/ +.. _GitHub: https://github.com/pycontribs/jira +.. _Navicat: https://www.navicat.com/ .. image:: https://raw.githubusercontent.com/pycontribs/resources/master/logos/x32/logo-atlassian.png :target: https://www.atlassian.com/ diff --git a/bindep.txt b/bindep.txt new file mode 100644 index 000000000..05c9df6ca --- /dev/null +++ b/bindep.txt @@ -0,0 +1,4 @@ +gcc [platform:rpm] +krb5-devel [platform:rpm] +krb5-workstation [platform:rpm] +python3-devel [platform:rpm] diff --git a/constraints.txt b/constraints.txt new file mode 100644 index 000000000..d95280ccf --- /dev/null +++ b/constraints.txt @@ -0,0 +1,215 @@ +# +# This file is autogenerated by pip-compile with python 3.6 +# To update, run: +# +# pip-compile --extra=async --extra=cli --extra=docs --extra=opt --extra=test --output-file=constraints.txt setup.cfg +# +alabaster==0.7.12 + # via sphinx +appnope==0.1.2 + # via ipython +attrs==21.2.0 + # via pytest +babel==2.9.1 + # via sphinx +backcall==0.2.0 + # via ipython +certifi==2021.5.30 + # via requests +cffi==1.14.6 + # via cryptography +chardet==4.0.0 + # via requests +coverage==5.5 + # via pytest-cov +cryptography==3.4.8 + # via requests-kerberos +decorator==5.1.0 + # via + # ipython + # traitlets +defusedxml==0.7.1 + # via jira (setup.cfg) +docutils==0.16 + # via + # jira (setup.cfg) + # sphinx + # sphinx-rtd-theme +execnet==1.9.0 + # via + # pytest-cache + # pytest-xdist +filemagic==1.6 + # via jira (setup.cfg) +flaky==3.7.0 + # via jira (setup.cfg) +idna==2.10 + # via requests +imagesize==1.2.0 + # via sphinx +importlib-metadata==4.8.1 + # via + # keyring + # pluggy + # pytest +iniconfig==1.1.1 + # via pytest +ipython==7.16.1 + # via jira (setup.cfg) +ipython-genutils==0.2.0 + # via traitlets +jedi==0.18.0 + # via ipython +jinja2==3.0.1 + # via sphinx +keyring==23.2.1 + # via jira (setup.cfg) +markupsafe==2.0.1 + # via + # jinja2 + # jira (setup.cfg) +oauthlib==3.1.1 + # via + # jira (setup.cfg) + # requests-oauthlib +packaging==21.0 + # via + # pytest + # pytest-sugar + # sphinx +parso==0.8.2 + # via jedi +pexpect==4.8.0 + # via ipython +pickleshare==0.7.5 + # via ipython +pluggy==1.0.0 + # via pytest +prompt-toolkit==3.0.20 + # via ipython +ptyprocess==0.7.0 + # via pexpect +py==1.10.0 + # via + # jira (setup.cfg) + # pytest + # pytest-forked +pycparser==2.20 + # via cffi +pygments==2.10.0 + # via + # ipython + # sphinx +pyjwt==2.1.0 + # via + # jira (setup.cfg) + # requests-jwt +pykerberos==1.2.1 + # via requests-kerberos +pyparsing==2.4.7 + # via packaging +pytest==6.2.5 + # via + # jira (setup.cfg) + # pytest-cache + # pytest-cov + # pytest-forked + # pytest-instafail + # pytest-sugar + # pytest-timeout + # pytest-xdist +pytest-cache==1.0 + # via jira (setup.cfg) +pytest-cov==2.12.1 + # via jira (setup.cfg) +pytest-forked==1.3.0 + # via pytest-xdist +pytest-instafail==0.4.2 + # via jira (setup.cfg) +pytest-sugar==0.9.4 + # via jira (setup.cfg) +pytest-timeout==1.4.2 + # via jira (setup.cfg) +pytest-xdist==2.4.0 + # via jira (setup.cfg) +pytz==2021.1 + # via babel +pyyaml==5.4.1 + # via jira (setup.cfg) +requests==2.26.0 + # via + # jira (setup.cfg) + # requests-futures + # requests-jwt + # requests-kerberos + # requests-mock + # requests-oauthlib + # requests-toolbelt + # requires.io + # sphinx +requests-futures==1.0.0 + # via jira (setup.cfg) +requests-jwt==0.5.3 + # via jira (setup.cfg) +requests-kerberos==0.12.0 + # via jira (setup.cfg) +requests-mock==1.9.3 + # via jira (setup.cfg) +requests-oauthlib==1.3.0 + # via jira (setup.cfg) +requests-toolbelt==0.9.1 + # via jira (setup.cfg) +requires.io==0.2.6 + # via jira (setup.cfg) +six==1.16.0 + # via + # requests-mock + # tenacity + # traitlets +snowballstemmer==2.1.0 + # via sphinx +sphinx==4.2.0 + # via + # jira (setup.cfg) + # sphinx-rtd-theme +sphinx-rtd-theme==1.0.0 + # via jira (setup.cfg) +sphinxcontrib-applehelp==1.0.2 + # via sphinx +sphinxcontrib-devhelp==1.0.2 + # via sphinx +sphinxcontrib-htmlhelp==2.0.0 + # via sphinx +sphinxcontrib-jsmath==1.0.1 + # via sphinx +sphinxcontrib-qthelp==1.0.3 + # via sphinx +sphinxcontrib-serializinghtml==1.1.5 + # via sphinx +tenacity==8.0.1 + # via jira (setup.cfg) +termcolor==1.1.0 + # via pytest-sugar +toml==0.10.2 + # via + # pytest + # pytest-cov +traitlets==4.3.3 + # via ipython +typing-extensions==3.10.0.2 + # via importlib-metadata +urllib3==1.26.7 + # via requests +wcwidth==0.2.5 + # via prompt-toolkit +wheel==0.37.0 + # via jira (setup.cfg) +xmlrunner==1.7.7 + # via jira (setup.cfg) +yanc==0.3.3 + # via jira (setup.cfg) +zipp==3.5.0 + # via importlib-metadata + +# The following packages are considered to be unsafe in a requirements file: +# setuptools diff --git a/cspell.json b/cspell.json deleted file mode 100644 index 7bef05387..000000000 --- a/cspell.json +++ /dev/null @@ -1,199 +0,0 @@ -{ - "version": "0.1", - "language": "en", - "words": [ - "addfinalizer", - "appid", - "atexit", - "atlassian", - "atlassians", - "ausername", - "bdist", - "bspeakmon", - "capsys", - "categorised", - "conda", - "cygwin", - "dae", - "Dalko", - "delete", - "deps", - "desk", - "devhelp", - "dgec", - "docutils", - "envars", - "envlist", - "envdir", - "envs", - "envvars", - "epub", - "errno", - "etree", - "favicon", - "favourite", - "favourites", - "fjira", - "fname", - "functools", - "fv", - "gerrit", - "googlicious", - "hashify", - "howto", - "hqi", - "I18NSPHINXOPTS", - "id", - "iDalko", - "ifeq", - "ifndef", - "ifneq", - "igrid", - "imghdr", - "iname", - "incompleted", - "inexistent", - "instafail", - "ipython", - "issueid", - "issuperset", - "itil", - "jira", - "jirapython", - "jirapythondoc", - "jirashell", - "jspa", - "k", - "ky", - "kzh", - "lqqy", - "luk", - "makotemplate", - "mkdir", - "mktemp", - "myfilter", - "myid", - "navicat", - "nclqfp", - "netrc", - "nocheck", - "noqa", - "norecursedirs", - "oauth", - "oauthlib", - "onresolve", - "ornu", - "passenv", - "perc", - "posargs", - "printf", - "procs", - "proja", - "projb", - "project", - "pyargs", - "pycodestyle", - "pycontribs", - "pycrypto", - "pyenv", - "pyinstaller", - "pylint", - "pytest", - "pyyaml", - "qhcp", - "qthelp", - "reindex", - "reindexing", - "repo", - "repos", - "rnd", - "rndpassword", - "rrequirements", - "rsyncdirs", - "rsyncignore", - "rtype", - "sbarnea", - "schemeid", - "sdist", - "seqs", - "serialise", - "serialised", - "service", - "setenv", - "skipif", - "sorin", - "ssbarnea", - "str", - "strftime", - "symlinks", - "test", - "testenv", - "testsd", - "testvercomp", - "tfsds", - "th", - "toctree", - "tolower", - "TOXENV", - "toxinidir", - "toxworkdir", - "transitionid", - "truthy", - "trw", - "twz", - "txcwsb", - "tzinfo", - "ucfirst", - "ul", - "uname", - "undoc", - "unmark", - "unstaged", - "untranslate", - "venv", - "virtualenv", - "virtualenvs", - "websudo", - "woopsydoodle", - "workon", - "xargs", - "xdist", - "xenial", - "xfail", - "xscs", - "xsrf", - "yanc", - "ztravisdeb", - "LGPL" - ], - "flagWords": [], - "allowCompoundWords": true, - "dictionaries": [ - "python", - "html", - "css" - ], - "ignoreRegExpList": [ - "/'s\\b/", - "/\\br'/", - "/\\bu'/", - "/\\b-rrequirements/", - "[^\\s]{20,}", - "/I18NSPHINXOPTS/" - ], - "ignorePaths": [ - "docs/build", - ".tox", - ".eggs" - ], - "ignoreWords": [ - "AACCOUNTID", - "GDPR", - "I18NSPHINXOPTS", - "hdost", - "βρέθηκε", - "PYTHONHTTPSVERIFY", - "ptype", - "mypy" - ] -} diff --git a/docs/_static/css/custom_width.css b/docs/_static/css/custom_width.css new file mode 100644 index 000000000..f9c89c8d2 --- /dev/null +++ b/docs/_static/css/custom_width.css @@ -0,0 +1,5 @@ +@import url("theme.css"); +/* as found in https://stackoverflow.com/a/62338678/2559785 */ +.wy-nav-content { + max-width: 90%; !important +} diff --git a/docs/api.rst b/docs/api.rst index e9259d3bc..dcd5d9ee8 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1,42 +1,90 @@ API Documentation ***************** -.. module:: jira .. contents:: Contents :local: -JIRA -==== +jira package +============ -.. autoclass:: JIRA +jira.client module +------------------ -Issue -======== +.. automodule:: jira.client + :members: + :undoc-members: + :show-inheritance: -.. autoclass:: Issue +jira.config module +------------------ -Priority -======== +.. automodule:: jira.config + :members: + :undoc-members: + :show-inheritance: -.. autoclass:: Priority +jira.exceptions module +---------------------- -Comment -======= +.. automodule:: jira.exceptions + :members: + :undoc-members: + :show-inheritance: -.. autoclass:: Comment +jira.jirashell module +--------------------- -Worklog -======= +.. automodule:: jira.jirashell + :members: + :undoc-members: + :show-inheritance: -.. autoclass:: Worklog +jira.resilientsession module +---------------------------- -Watchers -======== +.. automodule:: jira.resilientsession + :members: + :undoc-members: + :show-inheritance: -.. autoclass:: Watchers +jira.resources module +--------------------- -JIRAError -========= +.. autodata:: jira.client.ResourceType + :annotation: = alias of TypeVar(‘ResourceType’, contravariant=True, bound=jira.resources.Resource) -.. autoclass:: JIRAError +.. automodule:: jira.resources + :members: + :undoc-members: + :show-inheritance: + :private-members: + +.. autoclass:: jira.resources.StatusCategory + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: jira.resources.GreenHopperResource + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: jira.resources.Sprint + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: jira.resources.Board + :members: + :undoc-members: + :show-inheritance: + + +jira.utils module +----------------- + +.. automodule:: jira.utils + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/conf.py b/docs/conf.py index 677fbee18..a35f9ec86 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Jira Python Client documentation build configuration file, created by # sphinx-quickstart on Thu May 3 17:01:50 2012. @@ -12,9 +11,10 @@ # serve to show the default. import os -import sphinx_rtd_theme import sys +import sphinx_rtd_theme + # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. @@ -24,75 +24,50 @@ # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "2.2.0" +needs_sphinx = "4.0.0" # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode", "sphinx.ext.intersphinx"] +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.viewcode", +] intersphinx_mapping = { - "python": ("https://docs.python.org/3.7", None), - # until https://github.com/psf/requests/issues/5212 is addressed - # "requests": ("http://docs.python-requests.org/en/latest/", None), - "requests": ("https://requests.kennethreitz.org/en/master/", None), + "python": ("https://docs.python.org/3.8", None), + "requests": ("https://requests.readthedocs.io/en/latest/", None), "requests-oauthlib": ("https://requests-oauthlib.readthedocs.io/en/latest/", None), "ipython": ("https://ipython.readthedocs.io/en/stable/", None), "pip": ("https://pip.readthedocs.io/en/stable/", None), } autodoc_default_options = { + "member-order": "bysource", "members": True, - "undoc-members": True, "show-inheritance": True, + "special-members": "__init__", + "undoc-members": True, } +autodoc_inherit_docstrings = False + nitpick_ignore = [ - ("py:class", "Any"), - ("py:class", "Attachment"), - ("py:class", "Board"), - ("py:class", "BufferedReader"), - ("py:class", "Component"), - ("py:class", "CustomFieldOption"), - ("py:class", "Customer"), - ("py:class", "Dashboard"), - ("py:class", "Dict"), - ("py:class", "Filter"), - ("py:class", "Issue._IssueFields"), - ("py:class", "IssueLinkType"), - ("py:class", "IssueType"), - ("py:class", "Iterable"), - ("py:class", "List"), - ("py:class", "NoReturn"), - ("py:class", "Optional"), - ("py:class", "Project"), - ("py:class", "Resolution"), - ("py:class", "Resource"), - ("py:class", "Response"), - ("py:class", "ResultList"), - ("py:class", "ServiceDesk"), - ("py:class", "Sprint"), - ("py:class", "Status"), - ("py:class", "StatusCategory"), - ("py:class", "Tuple"), - ("py:class", "Union"), - ("py:class", "User"), - ("py:class", "Version"), - ("py:class", "Votes"), - ("py:class", "diy"), - ("py:class", "integer"), - ("py:class", "jira.client.ResultList"), - ("py:class", "jira.resources.Resource"), - ("py:class", "jira.resources.Sprint"), - ("py:class", "jira.resources.Watchers"), - ("py:class", "kanban"), - ("py:class", "project"), - ("py:class", "scrum"), - ("py:class", "user"), - ("py:meth", "Resource.delete"), - ("py:meth", "Resource.update"), + ("py:class", "JIRA"), # in jira.resources we only import this class if type + ("py:obj", "typing.ResourceType"), # only Py36 has a problem with this reference + ("py:class", "jira.resources.AnyLike"), # Dummy subclass for type checking + # From other packages ("py:mod", "filemagic"), ("py:mod", "ipython"), ("py:mod", "pip"), + ("py:class", "_io.BufferedReader"), + ("py:class", "BufferedReader"), + ("py:class", "Request"), + ("py:class", "requests.models.Response"), + ("py:class", "requests.sessions.Session"), + ("py:class", "requests.structures.CaseInsensitiveDict"), + ("py:class", "Response"), ("py:mod", "requests-kerberos"), ("py:mod", "requests-oauthlib"), ] @@ -110,8 +85,8 @@ master_doc = "index" # General information about the project. -project = u"jira-python" -copyright = u"2012, Atlassian Pty Ltd." +project = "jira-python" +copyright = "2012, Atlassian Pty Ltd." # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -166,7 +141,7 @@ # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -# html_theme_options = {} +html_theme_options = {"body_max_width": "100%"} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] @@ -193,6 +168,8 @@ # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] +html_style = "css/custom_width.css" + # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = "%b %d, %Y" @@ -248,8 +225,8 @@ ( "index", "jirapython.tex", - u"jira-python Documentation", - u"Atlassian Pty Ltd.", + "jira-python Documentation", + "Atlassian Pty Ltd.", "manual", ) ] @@ -280,12 +257,18 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ("index", "jirapython", u"jira-python Documentation", [u"Atlassian Pty Ltd."], 1) + ("index", "jirapython", "jira-python Documentation", ["Atlassian Pty Ltd."], 1) ] # If true, show URL addresses after external links. # man_show_urls = False +# -- Options for Napoleon ----------------------------------------------------- + +napoleon_google_docstring = True +napoleon_numpy_docstring = False # Explicitly prefer Google style docstring +napoleon_use_param = True # for type hint support + # -- Options for Texinfo output ------------------------------------------------ @@ -296,8 +279,8 @@ ( "index", "jirapython", - u"jira-python Documentation", - u"Atlassian Pty Ltd.", + "jira-python Documentation", + "Atlassian Pty Ltd.", "jirapython", "One line description of project.", "Miscellaneous", diff --git a/docs/contributing.rst b/docs/contributing.rst index 1c4e9e635..a07719933 100644 --- a/docs/contributing.rst +++ b/docs/contributing.rst @@ -63,7 +63,7 @@ Issues and Feature Requests * How to recreate the bug. * If relevant, including the versions of your: - * Python interpreter (3.5, etc) + * Python interpreter (3.6, etc) * jira-python * Operating System and Version (Windows 7, OS X 10.10, Ubuntu 14.04, etc.) * IPython if using jirashell diff --git a/docs/examples.rst b/docs/examples.rst index 5b4a1f80b..37014e4d6 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -54,13 +54,35 @@ Pass a tuple of (username, password) to the ``auth`` constructor argument:: Using this method, authentication happens during the initialization of the object. If the authentication is successful, the retrieved session cookie will be used in future requests. Upon cookie expiration, authentication will happen again transparently. +.. warning:: + This way of authentication is not supported anymore on Jira Cloud. You can find the deprecation notice `here `_. + + For Jira Cloud use the basic_auth= :ref:`basic-auth-api-token` authentication + HTTP BASIC ^^^^^^^^^^ +(username, password) +"""""""""""""""""""" + Pass a tuple of (username, password) to the ``basic_auth`` constructor argument:: auth_jira = JIRA(basic_auth=('username', 'password')) +.. warning:: + This way of authentication is not supported anymore on Jira Cloud. You can find the deprecation notice `here `_ + + For Jira Cloud use the basic_auth= :ref:`basic-auth-api-token` authentication + +.. _basic-auth-api-token: + +(username, api_token) +""""""""""""""""""""" + +Or pass a tuple of (email, api_token) to the ``basic_auth`` constructor argument (JIRA cloud):: + + auth_jira = JIRA(basic_auth=('email', 'API token')) + OAuth ^^^^^ @@ -103,6 +125,21 @@ To pass additional options to Kerberos auth use dict ``kerberos_options``, e.g.: .. _jirashell-label: +Headers +------- + +Headers can be provided to the internally used ``requests.Session``. +If the user provides a header that the :py:class:`jira.client.JIRA` also attempts to set, the user provided header will take preference. + +Perhaps you want to use a custom User Agent:: + + from requests_toolbelt import user_agent + + jira = JIRA( + basic_auth=("email", "API token"), + options={"headers": {"User-Agent": user_agent("my_package", "0.0.1")}}, + ) + Issues ------ @@ -251,6 +288,11 @@ Get an individual comment if you know its ID:: comment = jira.comment('JRA-1330', '10234') +Get comment author name and comment creation timestamp if you know its ID:: + + author = jira.comment('JRA-1330', '10234').author.displayName + time = jira.comment('JRA-1330', '10234').created + Adding, editing and deleting comments is similarly straightforward:: comment = jira.add_comment('JRA-1330', 'new comment') # no Issue object required diff --git a/docs/installation.rst b/docs/installation.rst index bd1f1bf61..766998e02 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -28,7 +28,7 @@ Source packages are also available at PyPI: Dependencies ============ -Python 3.5+ is required. +Python >3.5 is required. - :py:mod:`requests` - `python-requests `_ library handles the HTTP business. Usually, the latest version available at time of release is the minimum version required; at this writing, that version is 1.2.0, but any version >= 1.0.0 should work. - :py:mod:`requests-oauthlib` - Used to implement OAuth. The latest version as of this writing is 0.3.3. diff --git a/examples/basic_auth.py b/examples/basic_auth.py index 9587261f6..ccbcdebd5 100644 --- a/examples/basic_auth.py +++ b/examples/basic_auth.py @@ -2,7 +2,11 @@ # username and password over HTTP BASIC authentication. from collections import Counter +from typing import cast + from jira import JIRA +from jira.client import ResultList +from jira.resources import Issue # By default, the client will connect to a Jira instance started from the Atlassian Plugin SDK. # See @@ -15,7 +19,9 @@ props = jira.application_properties() # Find all issues reported by the admin -issues = jira.search_issues("assignee=admin") +# Note: we cast() for mypy's benefit, as search_issues can also return the raw json ! +# This is if the following argument is used: `json_result=True` +issues = cast(ResultList[Issue], jira.search_issues("assignee=admin")) # Find the top three projects containing issues reported by admin top_three = Counter([issue.fields.project.key for issue in issues]).most_common(3) diff --git a/examples/basic_use.py b/examples/basic_use.py index c2f4a4476..a26f98a70 100644 --- a/examples/basic_use.py +++ b/examples/basic_use.py @@ -1,28 +1,26 @@ # This script shows how to use the client in anonymous mode # against jira.atlassian.com. -from jira import JIRA import re +from jira import JIRA + # By default, the client will connect to a Jira instance started from the Atlassian Plugin SDK # (see https://developer.atlassian.com/display/DOCS/Installing+the+Atlassian+Plugin+SDK for details). -# Override this with the options parameter. -options = {"server": "https://jira.atlassian.com"} -jira = JIRA(options) +jira = JIRA(server="https://jira.atlassian.com") # Get all projects viewable by anonymous users. projects = jira.projects() # Sort available project keys, then return the second, third, and fourth keys. -keys = sorted([project.key for project in projects])[2:5] +keys = sorted(project.key for project in projects)[2:5] # Get an issue. issue = jira.issue("JRA-1330") - # Find all comments made by Atlassians on this issue. atl_comments = [ comment for comment in issue.fields.comment.comments - if re.search(r"@atlassian.com$", comment.author.emailAddress) + if re.search(r"@atlassian.com$", comment.author.key) ] # Add a comment to the issue. @@ -41,7 +39,7 @@ # Or modify the List of existing labels. The new label is unicode with no # spaces -issue.fields.labels.append(u"new_text") +issue.fields.labels.append("new_text") issue.update(fields={"labels": issue.fields.labels}) # Send the issue away for good. @@ -50,4 +48,4 @@ # Linking a remote jira issue (needs applinks to be configured to work) issue = jira.issue("JRA-1330") issue2 = jira.issue("XX-23") # could also be another instance -jira.add_remote_link(issue, issue2) +jira.add_remote_link(issue.id, issue2) diff --git a/examples/cookie_auth.py b/examples/cookie_auth.py index cdc4b608f..92f731c4a 100644 --- a/examples/cookie_auth.py +++ b/examples/cookie_auth.py @@ -2,7 +2,11 @@ # username and password over HTTP BASIC authentication. from collections import Counter +from typing import cast + from jira import JIRA +from jira.client import ResultList +from jira.resources import Issue # By default, the client will connect to a Jira instance started from the Atlassian Plugin SDK. # See @@ -15,11 +19,11 @@ props = jira.application_properties() # Find all issues reported by the admin -issues = jira.search_issues("assignee=admin") +issues = cast(ResultList[Issue], jira.search_issues("assignee=admin")) # Find the top three projects containing issues reported by admin top_three = Counter([issue.fields.project.key for issue in issues]).most_common(3) # import time; time.sleep(65) # Fake cookie expiration -issues = jira.search_issues("assignee=admin") +issues = cast(ResultList[Issue], jira.search_issues("assignee=admin")) diff --git a/examples/greenhopper.py b/examples/greenhopper.py index 408c7b378..acb12830d 100644 --- a/examples/greenhopper.py +++ b/examples/greenhopper.py @@ -14,5 +14,5 @@ # Get the sprints in a specific board board_id = 441 -print("GreenHopper board: %s (%s)" % (boards[0].name, board_id)) +print(f"GreenHopper board: {boards[0].name} ({board_id})") sprints = gh.sprints(board_id) diff --git a/examples/maintenance.py b/examples/maintenance.py index 02a2522af..ebef3a012 100755 --- a/examples/maintenance.py +++ b/examples/maintenance.py @@ -1,15 +1,13 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- # # This script will cleanup your jira instance by removing all projects and # it is used to clean the CI/CD Jira server used for testing. # -import os -from jira import Role, Issue, JIRA, JIRAError, Project # noqa -import logging - import json +import logging +import os +from jira import JIRA, Issue, JIRAError, Project, Role # noqa logging.getLogger().setLevel(logging.DEBUG) logging.getLogger("requests").setLevel(logging.INFO) diff --git a/jira/__init__.py b/jira/__init__.py index 90f696495..c719a71f1 100644 --- a/jira/__init__.py +++ b/jira/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """The root of JIRA package namespace.""" try: import pkg_resources @@ -7,9 +6,9 @@ except Exception: __version__ = "unknown" +from jira.client import JIRA # noqa: E402 from jira.client import Comment # noqa: E402 from jira.client import Issue # noqa: E402 -from jira.client import JIRA # noqa: E402 from jira.client import Priority # noqa: E402 from jira.client import Project # noqa: E402 from jira.client import Role # noqa: E402 @@ -19,7 +18,6 @@ from jira.config import get_jira # noqa: E402 from jira.exceptions import JIRAError # noqa: E402 - __all__ = ( "Comment", "__version__", diff --git a/jira/client.py b/jira/client.py index 57b2d1839..ba430c65b 100644 --- a/jira/client.py +++ b/jira/client.py @@ -1,84 +1,93 @@ #!/usr/bin/python -# -*- coding: utf-8 -*- -from requests.auth import AuthBase - """ This module implements a friendly (well, friendlier) interface between the raw JSON responses from Jira and the Resource/dict abstractions provided by this library. Users will construct a JIRA object as described below. Full API documentation can be found at: https://jira.readthedocs.io/en/latest/ """ -from functools import lru_cache -from functools import wraps - -import imghdr -import mimetypes - -from collections.abc import Iterable +import calendar import copy +import datetime +import hashlib +import imghdr import json -import logging +import logging as _logging +import mimetypes import os import re - - -import calendar -import datetime -import hashlib -from numbers import Number -import requests import sys import time import warnings +from collections import OrderedDict +from collections.abc import Iterable +from functools import lru_cache, wraps +from io import BufferedReader +from numbers import Number +from typing import ( + Any, + Callable, + Dict, + Generic, + List, + Optional, + Tuple, + Type, + TypeVar, + Union, + cast, + no_type_check, +) +from urllib.parse import parse_qs, quote, urlparse +import requests +from pkg_resources import parse_version +from requests import Response +from requests.auth import AuthBase +from requests.structures import CaseInsensitiveDict from requests.utils import get_netrc_auth -from urllib.parse import urlparse + +from jira import __version__ # GreenHopper specific resources from jira.exceptions import JIRAError -from jira.resilientsession import raise_on_error -from jira.resilientsession import ResilientSession +from jira.resilientsession import ResilientSession, raise_on_error # Jira-specific resources -from jira.resources import Attachment -from jira.resources import Board -from jira.resources import Comment -from jira.resources import Component -from jira.resources import Customer -from jira.resources import CustomFieldOption -from jira.resources import Dashboard -from jira.resources import Filter -from jira.resources import GreenHopperResource -from jira.resources import Issue -from jira.resources import IssueLink -from jira.resources import IssueLinkType -from jira.resources import IssueType -from jira.resources import Priority -from jira.resources import Project -from jira.resources import RemoteLink -from jira.resources import RequestType -from jira.resources import Resolution -from jira.resources import Resource -from jira.resources import Role -from jira.resources import SecurityLevel -from jira.resources import ServiceDesk -from jira.resources import Sprint -from jira.resources import Status -from jira.resources import StatusCategory -from jira.resources import User -from jira.resources import Group -from jira.resources import Version -from jira.resources import Votes -from jira.resources import Watchers -from jira.resources import Worklog - -from jira import __version__ -from jira.utils import CaseInsensitiveDict -from jira.utils import json_loads -from jira.utils import threaded_requests -from pkg_resources import parse_version - -from collections import OrderedDict +from jira.resources import ( + Attachment, + Board, + Comment, + Component, + Customer, + CustomFieldOption, + Dashboard, + Filter, + GreenHopperResource, + Group, + Issue, + IssueLink, + IssueLinkType, + IssueType, + PermissionScheme, + Priority, + Project, + RemoteLink, + RequestType, + Resolution, + Resource, + Role, + SecurityLevel, + ServiceDesk, + Sprint, + Status, + StatusCategory, + User, + Version, + Votes, + Watchers, + Worklog, +) +from jira.utils import json_loads, threaded_requests try: # noinspection PyUnresolvedReferences @@ -92,19 +101,15 @@ pass -logging.getLogger("jira").addHandler(logging.NullHandler()) +LOG = _logging.getLogger("jira") +LOG.addHandler(_logging.NullHandler()) -def translate_resource_args(func): +def translate_resource_args(func: Callable): """Decorator that converts Issue and Project resources to their keys when used as arguments.""" @wraps(func) - def wrapper(*args, **kwargs): - """ - :type args: *Any - :type kwargs: **Any - :return: Any - """ + def wrapper(*args: Any, **kwargs: Any) -> Any: arg_list = [] for arg in args: if isinstance(arg, (Issue, Project)): @@ -117,27 +122,34 @@ def wrapper(*args, **kwargs): return wrapper -def _field_worker(fields=None, **fieldargs): - """ - :type fields: Optional[Dict[str, Any]] - :type fieldargs: **Any - :return: Union[Dict[str, Dict[str, Any]], Dict[str, Dict[str, str]]] - """ +def _field_worker( + fields: Dict[str, Any] = None, **fieldargs: Any +) -> Union[Dict[str, Dict[str, Any]], Dict[str, Dict[str, str]]]: if fields is not None: return {"fields": fields} return {"fields": fieldargs} -class ResultList(list): +ResourceType = TypeVar("ResourceType", contravariant=True, bound=Resource) + + +class ResultList(list, Generic[ResourceType]): def __init__( - self, iterable=None, _startAt=0, _maxResults=0, _total=0, _isLast=None - ): + self, + iterable: Iterable = None, + _startAt: int = 0, + _maxResults: int = 0, + _total: Optional[int] = None, + _isLast: Optional[bool] = None, + ) -> None: """ - :type iterable: Any - :type _startAt: int - :type _maxResults: int - :type _total: int - :type isLast: Optional[bool] + + Args: + iterable (Iterable): [description]. Defaults to None. + _startAt (int): Start page. Defaults to 0. + _maxResults (int): Max results per page. Defaults to 0. + _total (Optional[int]): Total results from query. Defaults to 0. + _isLast (Optional[bool]): Last Page? Defaults to None. """ if iterable is not None: list.__init__(self, iterable) @@ -148,15 +160,12 @@ def __init__( self.maxResults = _maxResults # Optional parameters: self.isLast = _isLast - self.total = _total + self.total = _total if _total is not None else len(self) - self.iterable = iterable or [] + self.iterable: List = list(iterable) if iterable else [] self.current = self.startAt - def __next__(self): - """ - :return: int - """ + def __next__(self) -> Type[ResourceType]: self.current += 1 if self.current > self.total: raise StopIteration @@ -164,11 +173,15 @@ def __next__(self): return self.iterable[self.current - 1] -class QshGenerator(object): +class QshGenerator: def __init__(self, context_path): self.context_path = context_path def __call__(self, req): + qsh = self._generate_qsh(req) + return hashlib.sha256(qsh.encode("utf-8")).hexdigest() + + def _generate_qsh(self, req): parse_result = urlparse(req.url) path = ( @@ -176,16 +189,21 @@ def __call__(self, req): if len(self.context_path) > 1 else parse_result.path ) - # Per Atlassian docs, use %20 for whitespace when generating qsh for URL - # https://developer.atlassian.com/cloud/jira/platform/understanding-jwt/#qsh - query = "&".join(sorted(parse_result.query.split("&"))).replace("+", "%20") - qsh = "%(method)s&%(path)s&%(query)s" % { - "method": req.method.upper(), - "path": path, - "query": query, + + # create canonical query string according to docs at: + # https://developer.atlassian.com/cloud/jira/platform/understanding-jwt-for-connect-apps/#qsh + params = parse_qs(parse_result.query, keep_blank_values=True) + joined = { + key: ",".join(self._sort_and_quote_values(params[key])) for key in params } + query = "&".join(f"{key}={joined[key]}" for key in sorted(joined.keys())) - return hashlib.sha256(qsh.encode("utf-8")).hexdigest() + qsh = f"{req.method.upper()}&{path}&{query}" + return qsh + + def _sort_and_quote_values(self, values): + ordered_values = sorted(values) + return [quote(value, safe="~") for value in ordered_values] class JiraCookieAuth(AuthBase): @@ -196,7 +214,16 @@ class JiraCookieAuth(AuthBase): """ - def __init__(self, session, _get_session, auth): + def __init__( + self, session: ResilientSession, _get_session: Callable, auth: Tuple[str, str] + ): + """Cookie Based Authentication + + Args: + session (ResilientSession): The Session object to communicate with the API. + _get_session (Callable): The function that returns a :py_class:``User`` + auth (Tuple[str, str]): The username, password tuple + """ self._session = session self._get_session = _get_session self.__auth = auth @@ -237,11 +264,11 @@ def start_session(self): self._get_session(self.__auth) -class JIRA(object): +class JIRA: """User interface to Jira. Clients interact with Jira by constructing an instance of this object and calling its methods. For addressable - resources in Jira -- those with "self" links -- an appropriate subclass of :py:class:`Resource` will be returned + resources in Jira -- those with "self" links -- an appropriate subclass of :py:class:`jira.resources.Resource` will be returned with customized ``update()`` and ``delete()`` methods, along with attribute access to fields. This means that calls of the form ``issue.fields.summary`` will be resolved into the proper lookups to return the JSON value at that mapping. Methods that do not return resources will return a dict constructed from the JSON response or a scalar @@ -258,54 +285,6 @@ class JIRA(object): For quick command line access to a server, see the ``jirashell`` script included with this distribution. The easiest way to instantiate is using ``j = JIRA("https://jira.atlassian.com")`` - - :param options: Specify the server and properties this client will use. Use a dict with any - of the following properties: - - * server -- the server address and context path to use. Defaults to ``http://localhost:2990/jira``. - * rest_path -- the root REST path to use. Defaults to ``api``, where the Jira REST resources live. - * rest_api_version -- the version of the REST resources under rest_path to use. Defaults to ``2``. - * agile_rest_path - the REST path to use for Jira Agile requests. Defaults to ``greenhopper`` (old, private - API). Check `GreenHopperResource` for other supported values. - * verify -- Verify SSL certs. Defaults to ``True``. - * client_cert -- a tuple of (cert,key) for the requests library for client side SSL - * check_update -- Check whether using the newest python-jira library version. - * cookies -- A dict of custom cookies that are sent in all requests to the server. - - :param basic_auth: A tuple of username and password to use when establishing a session via HTTP BASIC - authentication. - :param oauth: A dict of properties for OAuth authentication. The following properties are required: - - * access_token -- OAuth access token for the user - * access_token_secret -- OAuth access token secret to sign with the key - * consumer_key -- key of the OAuth application link defined in Jira - * key_cert -- private key file to sign requests with (should be the pair of the public key supplied to - Jira in the OAuth application link) - - :param kerberos: If true it will enable Kerberos authentication. - :param kerberos_options: A dict of properties for Kerberos authentication. The following properties are possible: - - * mutual_authentication -- string DISABLED or OPTIONAL. - - Example kerberos_options structure: ``{'mutual_authentication': 'DISABLED'}`` - - :param jwt: A dict of properties for JWT authentication supported by Atlassian Connect. The following - properties are required: - - * secret -- shared secret as delivered during 'installed' lifecycle event - (see https://developer.atlassian.com/static/connect/docs/latest/modules/lifecycle.html for details) - * payload -- dict of fields to be inserted in the JWT payload, e.g. 'iss' - - Example jwt structure: ``{'secret': SHARED_SECRET, 'payload': {'iss': PLUGIN_KEY}}`` - - :param validate: If true it will validate your credentials first. Remember that if you are accessing Jira - as anonymous it will fail to instantiate. - :param get_server_info: If true it will fetch server version info first to determine if some API calls - are available. - :param async_: To enable asynchronous requests for those actions where we implemented it, like issue update() or delete(). - :param async_workers: Set the number of worker threads for async operations. - :param timeout: Set a read/connect timeout for the underlying calls to Jira (default: None) - Obviously this means that you cannot rely on the return code when this is enabled. """ DEFAULT_OPTIONS = { @@ -344,22 +323,22 @@ class JIRA(object): def __init__( self, - server=None, - options=None, - basic_auth=None, - oauth=None, - jwt=None, + server: str = None, + options: Dict[str, Union[str, bool, Any]] = None, + basic_auth: Union[None, Tuple[str, str]] = None, + oauth: Dict[str, Any] = None, + jwt: Dict[str, Any] = None, kerberos=False, - kerberos_options=None, + kerberos_options: Dict[str, Any] = None, validate=False, - get_server_info=True, - async_=False, - async_workers=5, - logging=True, - max_retries=3, - proxies=None, - timeout=None, - auth=None, + get_server_info: bool = True, + async_: bool = False, + async_workers: int = 5, + logging: bool = True, + max_retries: int = 3, + proxies: Any = None, + timeout: Optional[Union[Union[float, int], Tuple[float, float]]] = None, + auth: Tuple[str, str] = None, ): """Construct a Jira client instance. @@ -373,78 +352,77 @@ def __init__( For quick command line access to a server, see the ``jirashell`` script included with this distribution. - The easiest way to instantiate is using j = JIRA("https://jira.atlasian.com") - :param server: The server address and context path to use. Defaults to ``http://localhost:2990/jira``. - :type server: Optional[str] - :param options: Specify the server and properties this client will use. Use a dict with any - of the following properties: - * server -- the server address and context path to use. Defaults to ``http://localhost:2990/jira``. - * rest_path -- the root REST path to use. Defaults to ``api``, where the Jira REST resources live. - * rest_api_version -- the version of the REST resources under rest_path to use. Defaults to ``2``. - * agile_rest_path - the REST path to use for Jira Agile requests. Defaults to ``greenhopper`` (old, private - API). Check `GreenHopperResource` for other supported values. - * verify -- Verify SSL certs. Defaults to ``True``. - * client_cert -- a tuple of (cert,key) for the requests library for client side SSL - * check_update -- Check whether using the newest python-jira library version. - :type options: Optional[Dict[str, Any]] - :param basic_auth: A tuple of username and password to use when establishing a session via HTTP BASIC - authentication. - :type basic_auth: Union[Dict, None, Tuple[str, str]] - :param oauth: A dict of properties for OAuth authentication. The following properties are required: - * access_token -- OAuth access token for the user - * access_token_secret -- OAuth access token secret to sign with the key - * consumer_key -- key of the OAuth application link defined in Jira - * key_cert -- private key file to sign requests with (should be the pair of the public key supplied to - Jira in the OAuth application link) - :type oauth: Optional[Any] - :param kerberos: If true it will enable Kerberos authentication. - :type kerberos: bool - :param kerberos_options: A dict of properties for Kerberos authentication. The following properties are possible: - * mutual_authentication -- string DISABLED or OPTIONAL. - Example kerberos_options structure: ``{'mutual_authentication': 'DISABLED'}`` - :type kerberos_options: Optional[Dict[str,str]] - :param jwt: A dict of properties for JWT authentication supported by Atlassian Connect. The following - properties are required: - * secret -- shared secret as delivered during 'installed' lifecycle event - (see https://developer.atlassian.com/static/connect/docs/latest/modules/lifecycle.html for details) - * payload -- dict of fields to be inserted in the JWT payload, e.g. 'iss' - Example jwt structure: ``{'secret': SHARED_SECRET, 'payload': {'iss': PLUGIN_KEY}}`` - :type jwt: Optional[Any] - :param validate: If true it will validate your credentials first. Remember that if you are accessing Jira - as anonymous it will fail to instantiate. - :type validate: bool - :param get_server_info: If true it will fetch server version info first to determine if some API calls - are available. - :type get_server_info: bool - :param async_: To enable async requests for those actions where we implemented it, like issue update() or delete(). - :type async_: bool - :param async_workers: Set the number of worker threads for async operations. - :type async_workers: int - :param timeout: Set a read/connect timeout for the underlying calls to Jira (default: None) - :type timeout: Optional[Any] - Obviously this means that you cannot rely on the return code when this is enabled. - :param max_retries: Sets the amount Retries for the HTTP sessions initiated by the client. (Default: 3) - :type max_retries: int - :param proxies: Sets the proxies for the HTTP session. - :type proxies: Optional[Any] - :param auth: Set a cookie auth token if this is required. - :type auth: Optional[Tuple[str,str]] - :param logging: Determine whether or not logging should be enabled. (Default: True) - :type logging: bool + The easiest way to instantiate is using ``j = JIRA("https://jira.atlasian.com")`` + + Args: + server (Optional[str]): The server address and context path to use. Defaults to ``http://localhost:2990/jira``. + options (Optional[Dict[str, Any]]): Specify the server and properties this client will use. + Use a dict with any of the following properties: + + * server -- the server address and context path to use. Defaults to ``http://localhost:2990/jira``. + * rest_path -- the root REST path to use. Defaults to ``api``, where the Jira REST resources live. + * rest_api_version -- the version of the REST resources under rest_path to use. Defaults to ``2``. + * agile_rest_path - the REST path to use for Jira Agile requests. Defaults to ``greenhopper`` (old, private + API). Check :py:class:`jira.resources.GreenHopperResource` for other supported values. + * verify -- Verify SSL certs. Defaults to ``True``. + * client_cert -- a tuple of (cert,key) for the requests library for client side SSL + * check_update -- Check whether using the newest python-jira library version. + * headers -- a dict to update the default headers the session uses for all API requests. + + basic_auth (Union[None, Tuple[str, str]]): A tuple of username and password to use when + establishing a session via HTTP BASIC authentication. + oauth (Optional[Any]): A dict of properties for OAuth authentication. The following properties are required: + + * access_token -- OAuth access token for the user + * access_token_secret -- OAuth access token secret to sign with the key + * consumer_key -- key of the OAuth application link defined in Jira + * key_cert -- private key file to sign requests with (should be the pair of the public key supplied to + Jira in the OAuth application link) + + kerberos (bool): If true it will enable Kerberos authentication. + kerberos_options (Optional[Dict[str,str]]): A dict of properties for Kerberos authentication. + The following properties are possible: + + * mutual_authentication -- string DISABLED or OPTIONAL. + + Example kerberos_options structure: ``{'mutual_authentication': 'DISABLED'}`` + + jwt (Optional[Any]): A dict of properties for JWT authentication supported by Atlassian Connect. + The following properties are required: + + * secret -- shared secret as delivered during 'installed' lifecycle event + (see https://developer.atlassian.com/static/connect/docs/latest/modules/lifecycle.html for details) + * payload -- dict of fields to be inserted in the JWT payload, e.g. 'iss' + + Example jwt structure: ``{'secret': SHARED_SECRET, 'payload': {'iss': PLUGIN_KEY}}`` + + validate (bool): If true it will validate your credentials first. Remember that if you are accessing Jira + as anonymous it will fail to instantiate. + get_server_info (bool): If true it will fetch server version info first to determine if some API calls + are available. + async_ (bool): To enable async requests for those actions where we implemented it, like issue update() or delete(). + async_workers (int): Set the number of worker threads for async operations. + timeout (Optional[Union[Union[float, int], Tuple[float, float]]]): Set a read/connect timeout for the underlying + calls to Jira (default: None). + Obviously this means that you cannot rely on the return code when this is enabled. + max_retries (int): Sets the amount Retries for the HTTP sessions initiated by the client. (Default: 3) + proxies (Optional[Any]): Sets the proxies for the HTTP session. + auth (Optional[Tuple[str,str]]): Set a cookie auth token if this is required. + logging (bool): Determine whether or not logging should be enabled. (Default: True) """ # force a copy of the tuple to be used in __del__() because # sys.version_info could have already been deleted in __del__() - self.sys_version_info = tuple([i for i in sys.version_info]) + self.sys_version_info = tuple(i for i in sys.version_info) if options is None: options = {} - if server and hasattr(server, "keys"): + if server and isinstance(server, dict): warnings.warn( "Old API usage, use JIRA(url) or JIRA(options={'server': url}, when using dictionary always use named parameters.", DeprecationWarning, ) options = server - server = None + server = "" if server: options["server"] = server @@ -452,24 +430,35 @@ def __init__( options["async"] = async_ options["async_workers"] = async_workers - self.logging = logging + LOG.setLevel(_logging.INFO if logging else _logging.CRITICAL) + self.log = LOG - self._options = copy.copy(JIRA.DEFAULT_OPTIONS) + self._options: Dict[str, Any] = copy.copy(JIRA.DEFAULT_OPTIONS) + + if "headers" in options: + headers = copy.copy(options["headers"]) + del options["headers"] + else: + headers = {} self._options.update(options) + self._options["headers"].update(headers) self._rank = None # Rip off trailing slash since all urls depend on that + assert isinstance(self._options["server"], str) # to help mypy if self._options["server"].endswith("/"): self._options["server"] = self._options["server"][:-1] - context_path = urlparse(self._options["server"]).path + context_path = urlparse(self.server_url).path if len(context_path) > 0: self._options["context_path"] = context_path self._try_magic() + assert isinstance(self._options["headers"], dict) # for mypy benefit + self._session: ResilientSession # for mypy benefit if oauth: self._create_oauth_session(oauth, timeout) elif basic_auth: @@ -481,13 +470,13 @@ def __init__( self._create_kerberos_session(timeout, kerberos_options=kerberos_options) elif auth: self._create_cookie_auth(auth, timeout) - validate = ( - True - ) # always log in for cookie based auth, as we need a first request to be logged in + # always log in for cookie based auth, as we need a first request to be logged in + validate = True else: - verify = self._options["verify"] + verify = bool(self._options["verify"]) self._session = ResilientSession(timeout=timeout) self._session.verify = verify + self._session.headers.update(self._options["headers"]) if "cookies" in self._options: @@ -507,7 +496,7 @@ def __init__( auth_method = ( oauth or basic_auth or jwt or kerberos or auth or "anonymous" ) - raise JIRAError("Can not log in with %s" % str(auth_method)) + raise JIRAError(f"Can not log in with {str(auth_method)}") self.deploymentType = None if get_server_info: @@ -516,7 +505,7 @@ def __init__( try: self._version = tuple(si["versionNumbers"]) except Exception as e: - logging.error("invalid server_info: %s", si) + self.log.error("invalid server_info: %s", si) raise e self.deploymentType = si.get("deploymentType") else: @@ -532,11 +521,26 @@ def __init__( for name in f["clauseNames"]: self._fields[name] = f["id"] - def _create_cookie_auth(self, auth, timeout): + @property + def server_url(self) -> str: + """Return the server url""" + return str(self._options["server"]) + + @property + def _is_cloud(self) -> bool: + """Return whether we are on a Cloud based Jira instance.""" + return self.deploymentType in ("Cloud",) + + def _create_cookie_auth( + self, + auth: Tuple[str, str], + timeout: Optional[Union[Union[float, int], Tuple[float, float]]], + ): self._session = ResilientSession(timeout=timeout) self._session.auth = JiraCookieAuth(self._session, self.session, auth) - self._session.verify = self._options["verify"] - self._session.cert = self._options["client_cert"] + self._session.verify = bool(self._options["verify"]) + client_cert: Tuple[str, str] = self._options["client_cert"] # to help mypy + self._session.cert = client_cert def _check_update_(self): """Check if the current version of the library is outdated.""" @@ -554,7 +558,7 @@ def _check_update_(self): except requests.RequestException: pass except Exception as e: - logging.warning(e) + self.log.warning(e) def __del__(self): """Destructor for JIRA instance.""" @@ -573,12 +577,12 @@ def close(self): pass self._session = None - def _check_for_html_error(self, content): + def _check_for_html_error(self, content: str): # Jira has the bad habit of returning errors in pages with 200 and # embedding the error in a huge webpage. if "" in content: - logging.warning("Got SecurityTokenMissing") - raise JIRAError("SecurityTokenMissing: %s" % content) + self.log.warning("Got SecurityTokenMissing") + raise JIRAError(f"SecurityTokenMissing: {content}") return False return True @@ -593,35 +597,32 @@ def _get_sprint_field_id(self): def _fetch_pages( self, - item_type, - items_key, - request_path, - startAt=0, - maxResults=50, - params=None, - base=JIRA_BASE_URL, - ): - """Fetch pages. - - :param item_type: Type of single item. ResultList of such items will be returned. - :type item_type: type - :param items_key: Path to the items in JSON returned from server. - Set it to None, if response is an array, and not a JSON object. - :type items_key: Optional[str] - :param request_path: path in request URL - :type request_path: str - :param startAt: index of the first record to be fetched. (Default: 0) - :type startAt: int - :param maxResults: Maximum number of items to return. - If maxResults evaluates as False, it will try to get all items in batches. (Default:50) - :type maxResults: int - :param params: Params to be used in all requests. Should not contain startAt and maxResults, - as they will be added for each request created from this function. - :type params: Dict[str, Any] - :param base: base URL - :type base: str - :rtype: ResultList - """ + item_type: Type[ResourceType], + items_key: Optional[str], + request_path: str, + startAt: int = 0, + maxResults: int = 50, + params: Dict[str, Any] = None, + base: str = JIRA_BASE_URL, + ) -> ResultList[ResourceType]: + """Fetch from a paginated end point. + + Args: + item_type (Type[Resource]): Type of single item. ResultList of such items will be returned. + items_key (Optional[str]): Path to the items in JSON returned from server. + Set it to None, if response is an array, and not a JSON object. + request_path (str): path in request URL + startAt (int): index of the first record to be fetched. (Default: 0) + maxResults (int): Maximum number of items to return. + If maxResults evaluates as False, it will try to get all items in batches. (Default:50) + params (Dict[str, Any]): Params to be used in all requests. Should not contain startAt and maxResults, + as they will be added for each request created from this function. + base (str): base URL to use for the requests. + + Returns: + ResultList + """ + async_workers = None async_class = None if self._options["async"]: try: @@ -630,7 +631,7 @@ def _fetch_pages( async_class = FuturesSession except ImportError: pass - async_workers = self._options["async_workers"] + async_workers = self._options.get("async_workers") page_params = params.copy() if params else {} if startAt: page_params["startAt"] = startAt @@ -645,6 +646,7 @@ def _fetch_pages( if isinstance(resource, dict): total = resource.get("total") + total = int(total) if total is not None else total # 'isLast' is the optional key added to responses in Jira Agile 6.7.6. So far not used in basic Jira API. is_last = resource.get("isLast", False) start_at_from_response = resource.get("startAt", 0) @@ -670,7 +672,7 @@ def _fetch_pages( session=self._session, max_workers=async_workers ) for start_index in range(page_start, total, page_size): - page_params = params.copy() + page_params = params.copy() if params else {} page_params["startAt"] = start_index page_params["maxResults"] = page_size url = self._get_url(request_path) @@ -708,22 +710,22 @@ def _fetch_pages( return ResultList( items, start_at_from_response, max_results_from_response, total, is_last ) - else: - # it seams that search_users can return a list() containing a single user! + else: # TODO: unreachable + # it seems that search_users can return a list() containing a single user! return ResultList( [item_type(self._options, self._session, resource)], 0, 1, 1, True ) - def _get_items_from_page(self, item_type, items_key, resource): - """ - :type item_type: type - :type items_key: str - :type resource: Dict[str, Any] - :rtype: Union[List[Dashboard], List[Issue]] - """ + def _get_items_from_page( + self, + item_type: Type[ResourceType], + items_key: Optional[str], + resource: Dict[str, Any], + ) -> List[ResourceType]: try: return [ - item_type(self._options, self._session, raw_issue_json) + # We need to ignore the type here, as 'Resource' is an option + item_type(self._options, self._session, raw_issue_json) # type: ignore for raw_issue_json in (resource[items_key] if items_key else resource) ] except KeyError as e: @@ -732,13 +734,15 @@ def _get_items_from_page(self, item_type, items_key, resource): # Information about this client - def client_info(self): + def client_info(self) -> str: """Get the server this client is connected to.""" - return self._options["server"] + return self.server_url # Universal resource loading - def find(self, resource_format, ids=None): + def find( + self, resource_format: str, ids: Union[Tuple[str, str], int, str] = "" + ) -> Resource: """Find Resource object for any addressable resource on the server. This method is a universal resource locator for any REST-ful resource in Jira. The @@ -753,23 +757,25 @@ def find(self, resource_format, ids=None): reason, it is intended to support resources that are not included in the standard Atlassian REST API. - :param resource_format: the subpath to the resource string - :type resource_format: str - :param ids: values to substitute in the ``resource_format`` string - :type ids: tuple or None - :rtype: Resource + Args: + resource_format (str): the subpath to the resource string + ids (Optional[Tuple]): values to substitute in the ``resource_format`` string + Returns: + Resource """ resource = Resource(resource_format, self._options, self._session) resource.find(ids) return resource - def async_do(self, size=10): + @no_type_check # FIXME: This function fails type checking, probably a bug or two + def async_do(self, size: int = 10): """Execute all asynchronous jobs and wait for them to finish. By default it will run on 10 threads. - :param size: number of threads to run on. + Args: + size (int): number of threads to run on. """ if hasattr(self._session, "_async_jobs"): - logging.info( + self.log.info( "Executing asynchronous %s jobs found in queue by using %s threads..." % (len(self._session._async_jobs), size) ) @@ -778,95 +784,102 @@ def async_do(self, size=10): # Application properties # non-resource - def application_properties(self, key=None): + def application_properties( + self, key: str = None + ) -> Union[Dict[str, str], List[Dict[str, str]]]: """Return the mutable server application properties. - :param key: the single property to return a value for - :type key: Optional[str] - :rtype: Union[Dict[str, str], List[Dict[str, str]]] - + Args: + key (Optional[str]): the single property to return a value for + Returns: + Union[Dict[str, str], List[Dict[str, str]]] """ params = {} if key is not None: params["key"] = key return self._get_json("application-properties", params=params) - def set_application_property(self, key, value): + def set_application_property(self, key: str, value: str): """Set the application property. - :param key: key of the property to set - :type key: str - :param value: value to assign to the property - :type value: str + Args: + key (str): key of the property to set + value (str): value to assign to the property """ - url = self._options["server"] + "/rest/api/latest/application-properties/" + key + url = self._get_latest_url("application-properties/" + key) payload = {"id": key, "value": value} return self._session.put(url, data=json.dumps(payload)) - def applicationlinks(self, cached=True): + def applicationlinks(self, cached: bool = True) -> List: """List of application links. - :return: json + Returns: + List[Dict]: json, or empty list """ + self._applicationlinks: List[Dict] # for mypy benefit # if cached, return the last result if cached and hasattr(self, "_applicationlinks"): return self._applicationlinks # url = self._options['server'] + '/rest/applinks/latest/applicationlink' - url = self._options["server"] + "/rest/applinks/latest/listApplicationlinks" + url = self.server_url + "/rest/applinks/latest/listApplicationlinks" r = self._session.get(url) o = json_loads(r) - if "list" in o: + if "list" in o and isinstance(o, dict): self._applicationlinks = o["list"] else: self._applicationlinks = [] return self._applicationlinks # Attachments - def attachment(self, id): + def attachment(self, id: str) -> Attachment: """Get an attachment Resource from the server for the specified ID. - :param id: The Attachment ID - :type id: str - :rtype: Attachment + Args: + id (str): The Attachment ID + + Returns: + Attachment """ return self._find_for_resource(Attachment, id) # non-resource - def attachment_meta(self): + def attachment_meta(self) -> Dict[str, int]: """Get the attachment metadata. - :rtype: Dict[str, int] + Return: + Dict[str, int] """ return self._get_json("attachment/meta") @translate_resource_args - def add_attachment(self, issue, attachment, filename=None): + def add_attachment( + self, issue: str, attachment: Union[str, BufferedReader], filename: str = None + ) -> Attachment: """Attach an attachment to an issue and returns a Resource for it. The client will *not* attempt to open or validate the attachment; it expects a file-like object to be ready for its use. The user is still responsible for tidying up (e.g., closing the file, killing the socket, etc.) - :param issue: the issue to attach the attachment to - :type issue: str - :param attachment: file-like object to attach to the issue, also works if it is a string with the filename. - :type attachment: BufferedReader - :param filename: optional name for the attached file. If omitted, the file object's ``name`` attribute - is used. If you acquired the file-like object by any other method than ``open()``, make sure - that a name is specified in one way or the other. - :type filename: str - :rtype: Attachment + Args: + issue (str): the issue to attach the attachment to + attachment (Union[str,BufferedReader]): file-like object to attach to the issue, also works if it is a string with the filename. + filename (str): optional name for the attached file. If omitted, the file object's ``name`` attribute + is used. If you acquired the file-like object by any other method than ``open()``, make sure + that a name is specified in one way or the other. + + Returns: + Attachment """ + close_attachment = False if isinstance(attachment, str): - attachment = open(attachment, "rb") - if ( - hasattr(attachment, "read") - and hasattr(attachment, "mode") - and attachment.mode != "rb" - ): - logging.warning( + attachment: BufferedReader = open(attachment, "rb") # type: ignore + attachment = cast(BufferedReader, attachment) + close_attachment = True + elif isinstance(attachment, BufferedReader) and attachment.mode != "rb": + self.log.warning( "%s was not opened in 'rb' mode, attaching file may fail." % attachment.name ) @@ -874,95 +887,105 @@ def add_attachment(self, issue, attachment, filename=None): url = self._get_url("issue/" + str(issue) + "/attachments") fname = filename - if not fname: + if not fname and isinstance(attachment, BufferedReader): fname = os.path.basename(attachment.name) if "MultipartEncoder" not in globals(): method = "old" - r = self._session.post( - url, - files={"file": (fname, attachment, "application/octet-stream")}, - headers=CaseInsensitiveDict( - {"content-type": None, "X-Atlassian-Token": "nocheck"} - ), - ) + try: + r = self._session.post( + url, + files={"file": (fname, attachment, "application/octet-stream")}, + headers=CaseInsensitiveDict( + {"content-type": None, "X-Atlassian-Token": "no-check"} + ), + ) + finally: + if close_attachment: + attachment.close() else: method = "MultipartEncoder" - def file_stream(): - """Returns files stream of attachment. - - :rtype: MultipartEncoder - """ + def file_stream() -> MultipartEncoder: + """Returns files stream of attachment.""" return MultipartEncoder( fields={"file": (fname, attachment, "application/octet-stream")} ) m = file_stream() - r = self._session.post( - url, - data=m, - headers=CaseInsensitiveDict( - {"content-type": m.content_type, "X-Atlassian-Token": "nocheck"} - ), - retry_data=file_stream, - ) + try: + r = self._session.post( + url, + data=m, + headers=CaseInsensitiveDict( + { + "content-type": m.content_type, + "X-Atlassian-Token": "no-check", + } + ), + retry_data=file_stream, + ) + finally: + if close_attachment: + attachment.close() - js = json_loads(r) + js: Union[Dict[str, Any], List[Dict[str, Any]]] = json_loads(r) if not js or not isinstance(js, Iterable): - raise JIRAError("Unable to parse JSON: %s" % js) - attachment = Attachment(self._options, self._session, js[0]) - if attachment.size == 0: + raise JIRAError(f"Unable to parse JSON: {js}") + jira_attachment = Attachment( + self._options, self._session, js[0] if isinstance(js, List) else js + ) + if jira_attachment.size == 0: raise JIRAError( "Added empty attachment via %s method?!: r: %s\nattachment: %s" - % (method, r, attachment) + % (method, r, jira_attachment) ) - return attachment + return jira_attachment - def delete_attachment(self, id): + def delete_attachment(self, id: str) -> Response: """Delete attachment by id. - :param id: ID of the attachment to delete - :type id: str + Args: + id (str): ID of the attachment to delete + + Returns: + Response """ url = self._get_url("attachment/" + str(id)) return self._session.delete(url) # Components - def component(self, id): + def component(self, id: str): """Get a component Resource from the server. - :param id: ID of the component to get - :type id: str + Args: + id (str): ID of the component to get """ return self._find_for_resource(Component, id) @translate_resource_args def create_component( self, - name, - project, + name: str, + project: str, description=None, leadUserName=None, assigneeType=None, isAssigneeTypeValid=False, - ): + ) -> Component: """Create a component inside a project and return a Resource for it. - :param name: name of the component - :type name: str - :param project: key of the project to create the component in - :type project: str - :param description: a description of the component - :type description: str - :param leadUserName: the username of the user responsible for this component - :type leadUserName: Optional[str] - :param assigneeType: see the ComponentBean.AssigneeType class for valid values - :type assigneeType: Optional[str] - :param isAssigneeTypeValid: boolean specifying whether the assignee type is acceptable (Default: False) - :type isAssigneeTypeValid: bool - :rtype: Component + Args: + name (str): name of the component + project (str): key of the project to create the component in + description (str): a description of the component + leadUserName (Optional[str]): the username of the user responsible for this component + assigneeType (Optional[str]): see the ComponentBean.AssigneeType class for valid values + isAssigneeTypeValid (bool): boolean specifying whether the assignee type is acceptable (Default: False) + + Returns: + Component """ data = { "name": name, @@ -982,49 +1005,56 @@ def create_component( component = Component(self._options, self._session, raw=json_loads(r)) return component - def component_count_related_issues(self, id): + def component_count_related_issues(self, id: str): """Get the count of related issues for a component. - :type id: integer - :param id: ID of the component to use + Args: + id (str): ID of the component to use """ - return self._get_json("component/" + id + "/relatedIssueCounts")["issueCount"] + data: Dict[str, Any] = self._get_json( + "component/" + str(id) + "/relatedIssueCounts" + ) + return data["issueCount"] - def delete_component(self, id): + def delete_component(self, id: str) -> Response: """Delete component by id. - :param id: ID of the component to use - :type id: str - :rtype: Response + Args: + id (str): ID of the component to use + + Returns: + Response """ url = self._get_url("component/" + str(id)) return self._session.delete(url) # Custom field options - def custom_field_option(self, id): + def custom_field_option(self, id: str) -> CustomFieldOption: """Get a custom field option Resource from the server. - :param id: ID of the custom field to use - :type id: str - :rtype: CustomFieldOption + Args: + id (str): ID of the custom field to use + + Returns: + CustomFieldOption """ return self._find_for_resource(CustomFieldOption, id) # Dashboards - def dashboards(self, filter=None, startAt=0, maxResults=20): + def dashboards( + self, filter=None, startAt=0, maxResults=20 + ) -> ResultList[Dashboard]: """Return a ResultList of Dashboard resources and a ``total`` count. - :param filter: either "favourite" or "my", the type of dashboards to return - :type filter: Optional[str] - :param startAt: index of the first dashboard to return (Default: 0) - :type startAt: int - :param maxResults: maximum number of dashboards to return. - If maxResults evaluates as False, it will try to get all items in batches. (Default: 20) - :type maxResults: int + Args: + filter (Optional[str]): either "favourite" or "my", the type of dashboards to return + startAt (int): index of the first dashboard to return (Default: 0) + maxResults (int): maximum number of dashboards to return. If maxResults evaluates as False, it will try to get all items in batches. (Default: 20) - :rtype: ResultList + Returns: + ResultList """ params = {} if filter is not None: @@ -1033,63 +1063,74 @@ def dashboards(self, filter=None, startAt=0, maxResults=20): Dashboard, "dashboards", "dashboard", startAt, maxResults, params ) - def dashboard(self, id): + def dashboard(self, id: str) -> Dashboard: """Get a dashboard Resource from the server. - :param id: ID of the dashboard to get. - :type id: str - :rtype: Dashboard + Args: + id (str): ID of the dashboard to get. + + Returns: + Dashboard """ return self._find_for_resource(Dashboard, id) # Fields # non-resource - def fields(self): + def fields(self) -> List[Dict[str, Any]]: """Return a list of all issue fields. - :rtype: List[Dict[str, Any]] + Returns: + List[Dict[str, Any]] """ return self._get_json("field") # Filters - def filter(self, id): + def filter(self, id: str) -> Filter: """Get a filter Resource from the server. - :param id: ID of the filter to get. - :type id: str - :rtype: Filter + Args: + id (str): ID of the filter to get. + + Returns: + Filter """ return self._find_for_resource(Filter, id) - def favourite_filters(self): + def favourite_filters(self) -> List[Filter]: """Get a list of filter Resources which are the favourites of the currently authenticated user. - :rtype: List[Filter] + Returns: + List[Filter] """ - r_json = self._get_json("filter/favourite") + r_json: List[Dict[str, Any]] = self._get_json("filter/favourite") filters = [ Filter(self._options, self._session, raw_filter_json) for raw_filter_json in r_json ] return filters - def create_filter(self, name=None, description=None, jql=None, favourite=None): + def create_filter( + self, + name: str = None, + description: str = None, + jql: str = None, + favourite: bool = None, + ): """Create a new filter and return a filter Resource for it. - :param name: name of the new filter - :type name: str - :param description: useful human readable description of the new filter - :type description: str - :param jql: query string that defines the filter - :type jql: str - :param favourite: whether to add this filter to the current user's favorites - :type favourite: bool - :rtype: Filter + Args: + name (str): name of the new filter + description (str): useful human readable description of the new filter + jql (str): query string that defines the filter + favourite (bool): whether to add this filter to the current user's favorites + + Returns: + Filter """ - data = {} + data: Dict[str, Any] = {} if name is not None: data["name"] = name if description is not None: @@ -1101,22 +1142,24 @@ def create_filter(self, name=None, description=None, jql=None, favourite=None): url = self._get_url("filter") r = self._session.post(url, data=json.dumps(data)) - raw_filter_json = json_loads(r) + raw_filter_json: Dict[str, Any] = json_loads(r) return Filter(self._options, self._session, raw=raw_filter_json) def update_filter( - self, filter_id, name=None, description=None, jql=None, favourite=None + self, + filter_id, + name: str = None, + description: str = None, + jql: str = None, + favourite: bool = None, ): """Update a filter and return a filter Resource for it. - :param name: name of the new filter - :type name: Optional[str] - :param description: useful human readable description of the new filter - :type description: Optional[str] - :param jql: query string that defines the filter - :type jql: Optional[str] - :param favourite: whether to add this filter to the current user's favorites - :type favourite: Optional[bool] + Args: + name (Optional[str]): name of the new filter + description (Optional[str]): useful human readable description of the new filter + jql (Optional[str]): query string that defines the filter + favourite (Optional[bool]): whether to add this filter to the current user's favorites """ filter = self.filter(filter_id) @@ -1126,7 +1169,7 @@ def update_filter( data["jql"] = jql or filter.jql data["favourite"] = favourite or filter.favourite - url = self._get_url("filter/%s" % filter_id) + url = self._get_url(f"filter/{filter_id}") r = self._session.put( url, headers={"content-type": "application/json"}, data=json.dumps(data) ) @@ -1136,15 +1179,15 @@ def update_filter( # Groups - def group(self, id, expand=None): + def group(self, id: str, expand: Any = None) -> Group: """Get a group Resource from the server. - :param id: ID of the group to get - :param id: str - :param expand: Extra information to fetch inside each resource - :type expand: Optional[Any] + Args: + id (str): ID of the group to get + expand (Optional[Any]): Extra information to fetch inside each resource - :rtype: User + Returns: + Group """ group = Group(self._options, self._session) params = {} @@ -1154,19 +1197,23 @@ def group(self, id, expand=None): return group # non-resource - def groups(self, query=None, exclude=None, maxResults=9999): + def groups( + self, + query: Optional[str] = None, + exclude: Optional[Any] = None, + maxResults: int = 9999, + ) -> List[str]: """Return a list of groups matching the specified criteria. - :param query: filter groups by name with this string - :type query: Optional[str] - :param exclude: filter out groups by name with this string - :type exclude: Optional[Any] - :param maxResults: maximum results to return. (Default: 9999) - :type maxResults: int - :rtype: List[str] + Args: + query (Optional[str]): filter groups by name with this string + exclude (Optional[Any]): filter out groups by name with this string + maxResults (int): maximum results to return. (Default: 9999) + Returns: + List[str] """ - params = {} + params: Dict[str, Any] = {} groups = [] if query is not None: params["query"] = query @@ -1178,11 +1225,11 @@ def groups(self, query=None, exclude=None, maxResults=9999): groups.append(group["name"]) return sorted(groups) - def group_members(self, group): + def group_members(self, group: str) -> OrderedDict: """Return a hash or users with their information. Requires Jira 6.0 or will raise NotImplemented. - :param group: Name of the group. - :type group: str + Args: + group (str): Name of the group. """ if self._version < (6, 0, 0): raise NotImplementedError( @@ -1197,7 +1244,7 @@ def group_members(self, group): while end_index < size - 1: params = { "groupname": group, - "expand": "users[%s:%s]" % (end_index + 1, end_index + 50), + "expand": f"users[{end_index + 1}:{end_index + 50}]", } r2 = self._get_json("group", params=params) for user in r2["users"]["items"]: @@ -1207,23 +1254,37 @@ def group_members(self, group): result = {} for user in r["users"]["items"]: - result[user["key"]] = { - "name": user["name"], - "fullname": user["displayName"], + # 'id' is likely available only in older JIRA Server, it's not available on newer JIRA Server. + # 'name' is not available in JIRA Cloud. + hasId = user.get("id") is not None and user.get("id") != "" + hasName = user.get("name") is not None and user.get("name") != "" + result[ + user["id"] + if hasId + else user.get("name") + if hasName + else user.get("accountId") + ] = { + "name": user.get("name"), + "id": user.get("id"), + "accountId": user.get("accountId"), + "fullname": user.get("displayName"), "email": user.get("emailAddress", "hidden"), - "active": user["active"], + "active": user.get("active"), + "timezone": user.get("timezone"), } return OrderedDict(sorted(result.items(), key=lambda t: t[0])) - def add_group(self, groupname): + def add_group(self, groupname: str) -> bool: """Create a new group in Jira. - :param groupname: The name of the group you wish to create. - :type groupname: str - :return: Boolean - True if successful. - :rtype: bool + Args: + groupname (str): The name of the group you wish to create. + + Returns: + bool: True if successful. """ - url = self._options["server"] + "/rest/api/latest/group" + url = self._get_latest_url("group") # implementation based on # https://docs.atlassian.com/jira/REST/ondemand/#d2e5173 @@ -1238,33 +1299,38 @@ def add_group(self, groupname): return True - def remove_group(self, groupname): + def remove_group(self, groupname: str) -> bool: """Delete a group from the Jira instance. - :param groupname: The group to be deleted from the Jira instance. - :type groupname: str - :return: Boolean. Returns True on success. - :rtype: bool + Args: + groupname (str): The group to be deleted from the Jira instance. + + Returns: + bool: Returns True on success. """ # implementation based on # https://docs.atlassian.com/jira/REST/ondemand/#d2e5173 - url = self._options["server"] + "/rest/api/latest/group" + url = self._get_latest_url("group") x = {"groupname": groupname} self._session.delete(url, params=x) return True # Issues - def issue(self, id, fields=None, expand=None): + def issue( + self, + id: Union[Issue, str], + fields: Optional[str] = None, + expand: Optional[str] = None, + ) -> Issue: """Get an issue Resource from the server. - :param id: ID or key of the issue to get - :type id: Union[Issue, str] - :param fields: comma-separated string of issue fields to include in the results - :type fields: Optional[str] - :param expand: extra information to fetch inside each resource - :type expand: Optional[str] - :rtype: Issue + Args: + id (Union[Issue, str]): ID or key of the issue to get + fields (Optional[str]): comma-separated string of issue fields to include in the results + expand (Optional[str]): extra information to fetch inside each resource + Returns: + Issue """ # this allows us to pass Issue objects to issue() if isinstance(id, Issue): @@ -1280,7 +1346,12 @@ def issue(self, id, fields=None, expand=None): issue.find(id, params=params) return issue - def create_issue(self, fields=None, prefetch=True, **fieldargs): + def create_issue( + self, + fields: Optional[Dict[str, Any]] = None, + prefetch: bool = True, + **fieldargs, + ) -> Issue: """Create a new issue and return an issue Resource for it. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value @@ -1294,66 +1365,70 @@ def create_issue(self, fields=None, prefetch=True, **fieldargs): fields in a new issue. This information is available through the 'createmeta' method. Further examples are available here: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue - :param fields: a dict containing field names and the values to use. If present, all other keyword arguments - will be ignored - :type fields: Optional[Dict[str, Any]] - :param prefetch: whether to reload the created issue Resource so that all of its data is present in the value - returned from this method - :type prefetch: bool - :rtype: Issue + Args: + fields (Optional[Dict[str, Any]]): a dict containing field names and the values to use. If present, all other keyword arguments + will be ignored + prefetch (bool): whether to reload the created issue Resource so that all of its data is present in the value + returned from this method + Returns: + Issue """ - data = _field_worker(fields, **fieldargs) + data: Dict[str, Any] = _field_worker(fields, **fieldargs) p = data["fields"]["project"] if isinstance(p, str) or isinstance(p, int): - data["fields"]["project"] = {"id": self.project(p).id} + data["fields"]["project"] = {"id": self.project(str(p)).id} p = data["fields"]["issuetype"] if isinstance(p, int): data["fields"]["issuetype"] = {"id": p} if isinstance(p, str) or isinstance(p, int): - data["fields"]["issuetype"] = {"id": self.issue_type_by_name(p).id} + data["fields"]["issuetype"] = {"id": self.issue_type_by_name(str(p)).id} url = self._get_url("issue") r = self._session.post(url, data=json.dumps(data)) raw_issue_json = json_loads(r) if "key" not in raw_issue_json: - raise JIRAError(r.status_code, response=r, url=url, text=json.dumps(data)) + raise JIRAError( + status_code=r.status_code, response=r, url=url, text=json.dumps(data) + ) if prefetch: return self.issue(raw_issue_json["key"]) else: return Issue(self._options, self._session, raw=raw_issue_json) - def create_issues(self, field_list, prefetch=True): + def create_issues( + self, field_list: List[Dict[str, Any]], prefetch: bool = True + ) -> List[Dict[str, Any]]: """Bulk create new issues and return an issue Resource for each successfully created issue. See `create_issue` documentation for field information. - :param field_list: a list of dicts each containing field names and the values to use. Each dict - is an individual issue to create and is subject to its minimum requirements. - :type field_list: List[Dict[str, Any]] - :param prefetch: whether to reload the created issue Resource for each created issue so that all - of its data is present in the value returned from this method. - :type prefetch: bool - :rtype: List[Dict[str, Any]] + Args: + field_list (List[Dict[str, Any]]): a list of dicts each containing field names and the values to use. Each dict + is an individual issue to create and is subject to its minimum requirements. + prefetch (bool): whether to reload the created issue Resource for each created issue so that all + of its data is present in the value returned from this method. + Returns: + List[Dict[str, Any]] """ - data = {"issueUpdates": []} + data: Dict[str, List] = {"issueUpdates": []} for field_dict in field_list: - issue_data = _field_worker(field_dict) + issue_data: Dict[str, Any] = _field_worker(field_dict) p = issue_data["fields"]["project"] if isinstance(p, str) or isinstance(p, int): - issue_data["fields"]["project"] = {"id": self.project(p).id} + issue_data["fields"]["project"] = {"id": self.project(str(p)).id} p = issue_data["fields"]["issuetype"] if isinstance(p, int): issue_data["fields"]["issuetype"] = {"id": p} - if isinstance(p, str) or isinstance(p, int): + if isinstance(p, str): issue_data["fields"]["issuetype"] = { - "id": self.issue_type_by_name(p).id + "id": self.issue_type_by_name(str(p)).id } data["issueUpdates"].append(issue_data) @@ -1364,7 +1439,7 @@ def create_issues(self, field_list, prefetch=True): raw_issue_json = json_loads(r) # Catching case where none of the issues has been created. See https://github.com/pycontribs/jira/issues/350 except JIRAError as je: - if je.status_code == 400: + if je.status_code == 400 and je.response: raw_issue_json = json.loads(je.response.text) else: raise @@ -1401,9 +1476,10 @@ def create_issues(self, field_list, prefetch=True): def supports_service_desk(self): """Returns whether or not the Jira instance supports service desk. - :rtype: bool + Returns: + bool """ - url = self._options["server"] + "/rest/servicedeskapi/info" + url = self.server_url + "/rest/servicedeskapi/info" headers = {"X-ExperimentalApi": "opt-in"} try: r = self._session.get(url, headers=headers) @@ -1411,17 +1487,17 @@ def supports_service_desk(self): except JIRAError: return False - def create_customer(self, email, displayName): + def create_customer(self, email: str, displayName: str) -> Customer: """Create a new customer and return an issue Resource for it. - :param email: Customer Email - :type email: str - :param displayName: Customer display name - :type displayName: str - :rtype: Customer + Args: + email (str): Customer Email + displayName (str): Customer display name + Returns: + Customer """ - url = self._options["server"] + "/rest/servicedeskapi/customer" + url = self.server_url + "/rest/servicedeskapi/customer" headers = {"X-ExperimentalApi": "opt-in"} r = self._session.post( url, @@ -1432,16 +1508,17 @@ def create_customer(self, email, displayName): raw_customer_json = json_loads(r) if r.status_code != 201: - raise JIRAError(r.status_code, request=r) + raise JIRAError(status_code=r.status_code, request=r) return Customer(self._options, self._session, raw=raw_customer_json) - def service_desks(self): + def service_desks(self) -> List[ServiceDesk]: """Get a list of ServiceDesk Resources from the server visible to the current authenticated user. - :rtype: List[ServiceDesk] + Returns: + List[ServiceDesk] """ - url = self._options["server"] + "/rest/servicedeskapi/servicedesk" + url = self.server_url + "/rest/servicedeskapi/servicedesk" headers = {"X-ExperimentalApi": "opt-in"} r_json = json_loads(self._session.get(url, headers=headers)) print(r_json) @@ -1451,17 +1528,22 @@ def service_desks(self): ] return projects - def service_desk(self, id): + def service_desk(self, id: str) -> ServiceDesk: """Get a Service Desk Resource from the server. - :param id: ID or key of the Service Desk to get - :type id: str - :rtype: ServiceDesk + Args: + id (str): ID or key of the Service Desk to get + + Returns: + ServiceDesk """ return self._find_for_resource(ServiceDesk, id) - def create_customer_request(self, fields=None, prefetch=True, **fieldargs): + @no_type_check # FIXME: This function does not do what it wants to with fieldargs + def create_customer_request( + self, fields: Dict[str, Any] = None, prefetch: bool = True, **fieldargs + ) -> Issue: """Create a new customer request and return an issue Resource for it. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value @@ -1475,13 +1557,13 @@ def create_customer_request(self, fields=None, prefetch=True, **fieldargs): fields in a new issue. This information is available through the 'createmeta' method. Further examples are available here: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue - :param fields: a dict containing field names and the values to use. If present, all other keyword arguments - will be ignored - :type fields: Dict[str, Any] - :param prefetch: whether to reload the created issue Resource so that all of its data is present in the value - returned from this method - :type prefetch: bool - :rtype: Issue + Args: + fields (Dict[str, Any]): a dict containing field names and the values to use. If present, all other keyword arguments + will be ignored + prefetch (bool): whether to reload the created issue Resource so that all of its data is present in the value + returned from this method + Returns: + Issue """ data = fields @@ -1501,13 +1583,13 @@ def create_customer_request(self, fields=None, prefetch=True, **fieldargs): elif isinstance(p, str): data["requestTypeId"] = self.request_type_by_name(service_desk, p).id - url = self._options["server"] + "/rest/servicedeskapi/request" + url = self.server_url + "/rest/servicedeskapi/request" headers = {"X-ExperimentalApi": "opt-in"} r = self._session.post(url, headers=headers, data=json.dumps(data)) raw_issue_json = json_loads(r) if "issueKey" not in raw_issue_json: - raise JIRAError(r.status_code, request=r) + raise JIRAError(status_code=r.status_code, request=r) if prefetch: return self.issue(raw_issue_json["issueKey"]) else: @@ -1515,36 +1597,33 @@ def create_customer_request(self, fields=None, prefetch=True, **fieldargs): def createmeta( self, - projectKeys=None, - projectIds=[], - issuetypeIds=None, - issuetypeNames=None, - expand=None, - ): + projectKeys: Optional[Union[Tuple[str, str], str]] = None, + projectIds: Union[List, Tuple[str, str]] = [], + issuetypeIds: Optional[List[str]] = None, + issuetypeNames: Optional[str] = None, + expand: Optional[str] = None, + ) -> Dict[str, Any]: """Get the metadata required to create issues, optionally filtered by projects and issue types. - :param projectKeys: keys of the projects to filter the results with. - Can be a single value or a comma-delimited string. May be combined - with projectIds. - :type projectKeys: Union[None, Tuple[str, str], str] - :param projectIds: IDs of the projects to filter the results with. Can - be a single value or a comma-delimited string. May be combined with - projectKeys. - :type projectIds: Union[List, Tuple[str, str]] - :param issuetypeIds: IDs of the issue types to filter the results with. - Can be a single value or a comma-delimited string. May be combined - with issuetypeNames. - :type issuetypeIds: Optional[List[str]] - :param issuetypeNames: Names of the issue types to filter the results - with. Can be a single value or a comma-delimited string. May be - combined with issuetypeIds. - :type issuetypeNames: Optional[str] - :param expand: extra information to fetch inside each resource. - :type expand: Optional[str] - :rtype: Dict[str, Any] - - """ - params = {} + Args: + projectKeys (Optional[Union[Tuple[str, str], str]]): keys of the projects to filter the results with. + Can be a single value or a comma-delimited string. May be combined + with projectIds. + projectIds (Union[List, Tuple[str, str]]): IDs of the projects to filter the results with. Can + be a single value or a comma-delimited string. May be combined with + projectKeys. + issuetypeIds (Optional[List[str]]): IDs of the issue types to filter the results with. + Can be a single value or a comma-delimited string. May be combined + with issuetypeNames. + issuetypeNames (Optional[str]): Names of the issue types to filter the results + with. Can be a single value or a comma-delimited string. May be + combined with issuetypeIds. + expand (Optional[str]): extra information to fetch inside each resource. + Returns: + Dict[str, Any] + + """ + params: Dict[str, Any] = {} if projectKeys is not None: params["projectKeys"] = projectKeys if projectIds is not None: @@ -1559,47 +1638,82 @@ def createmeta( params["expand"] = expand return self._get_json("issue/createmeta", params) - def _get_user_accountid(self, user): - """Internal method for translating an user to an accountId.""" + def _get_user_identifier(self, user: User) -> str: + """Get the unique identifier depending on the deployment type. + + - Cloud: 'accountId' + - Self Hosted: 'name' (equivalent to username) + + Args: + user (User): a User object + + Returns: + str: the User's unique identifier. + """ + return user.accountId if self._is_cloud else user.name + + def _get_user_id(self, user: str) -> str: + """Internal method for translating an user search (str) to an id. + + This function uses :py:meth:`JIRA.search_users` to find the user + and then using :py:meth:`JIRA._get_user_identifier` extracts + the relevant identifier property depending on whether + the instance is a Cloud or self-hosted Instance. + + + Args: + user (str): The search term used for finding a user. + + Raises: + JIRAError: If any error occurs. + + Returns: + str: The Jira user's identifier. + """ try: - accountId = self.search_users(user, maxResults=1)[0].accountId + user_obj: User + if self._is_cloud: + user_obj = self.search_users(query=user, maxResults=1)[0] + else: + user_obj = self.search_users(user=user, maxResults=1)[0] except Exception as e: - raise JIRAError(e) - return accountId + raise JIRAError(str(e)) + return self._get_user_identifier(user_obj) # non-resource @translate_resource_args - def assign_issue(self, issue, assignee): + def assign_issue(self, issue: Union[int, str], assignee: str) -> bool: """Assign an issue to a user. None will set it to unassigned. -1 will set it to Automatic. - :param issue: the issue ID or key to assign - :type issue: int or str - :param assignee: the user to assign the issue to - :type assignee: str + Args: + issue (Union[int,str]): the issue ID or key to assign + assignee (str): the user to assign the issue to - :rtype: bool + Returns: + bool """ - url = ( - self._options["server"] - + "/rest/api/latest/issue/" - + str(issue) - + "/assignee" - ) - payload = {"accountId": self._get_user_accountid(assignee)} - # 'key' and 'name' are deprecated in favor of accountId + url = self._get_latest_url(f"issue/{str(issue)}/assignee") + user_id = self._get_user_id(assignee) + payload = {"accountId": user_id} if self._is_cloud else {"name": user_id} r = self._session.put(url, data=json.dumps(payload)) raise_on_error(r) return True @translate_resource_args - def comments(self, issue): + def comments(self, issue: str, expand: Optional[str] = None) -> List[Comment]: """Get a list of comment Resources. :param issue: the issue to get comments from :type issue: str + :param expand: extra information to fetch for each comment + such as renderedBody and properties. + :type expand: str :rtype: List[Comment] """ - r_json = self._get_json("issue/" + str(issue) + "/comment") + params = {} + if expand is not None: + params["expand"] = expand + r_json = self._get_json(f"issue/{str(issue)}/comment", params=params) comments = [ Comment(self._options, self._session, raw_comment_json) @@ -1608,35 +1722,44 @@ def comments(self, issue): return comments @translate_resource_args - def comment(self, issue, comment): + def comment( + self, issue: str, comment: str, expand: Optional[str] = None + ) -> Comment: """Get a comment Resource from the server for the specified ID. :param issue: ID or key of the issue to get the comment from :param comment: ID of the comment to get + :param expand: extra information to fetch for comment + such as renderedBody and properties. """ - return self._find_for_resource(Comment, (issue, comment)) + return self._find_for_resource(Comment, (issue, comment), expand=expand) @translate_resource_args - def add_comment(self, issue, body, visibility=None, is_internal=False): + def add_comment( + self, + issue: str, + body: str, + visibility: Optional[Dict[str, str]] = None, + is_internal: bool = False, + ) -> Comment: """Add a comment from the current authenticated user on the specified issue and return a Resource for it. The issue identifier and comment body are required. - :param issue: ID or key of the issue to add the comment to - :type issue: str - :param body: Text of the comment to add - :type body: str - :param visibility: a dict containing two entries: "type" and "value". - "type" is 'role' (or 'group' if the Jira server has configured - comment visibility for groups) and 'value' is the name of the role - (or group) to which viewing of this comment will be restricted. - :type visibility: Optional[Dict[str, str]] - :param is_internal: Defines whether a comment has to be marked as 'Internal' in Jira Service Desk (Default: False) - :type is_internal: bool - :rtype: Comment + Args: + issue (str): ID or key of the issue to add the comment to + body (str): Text of the comment to add + visibility (Optional[Dict[str, str]]): a dict containing two entries: "type" and "value". + "type" is 'role' (or 'group' if the Jira server has configured + comment visibility for groups) and 'value' is the name of the role + (or group) to which viewing of this comment will be restricted. + is_internal (bool): Defines whether a comment has to be marked as 'Internal' in Jira Service Desk (Default: False) + + Returns: + Comment: the created comment """ - data = {"body": body} + data: Dict[str, Any] = {"body": body} if is_internal: data.update( @@ -1658,20 +1781,24 @@ def add_comment(self, issue, body, visibility=None, is_internal=False): # non-resource @translate_resource_args - def editmeta(self, issue): + def editmeta(self, issue: Union[str, int]): """Get the edit metadata for an issue. - :param issue: the issue to get metadata for - :rtype: Dict[str, Dict[str, Dict[str, Any]]] + Args: + issue (str): the issue to get metadata for + + Returns: + Dict[str, Dict[str, Dict[str, Any]]] """ return self._get_json("issue/" + str(issue) + "/editmeta") @translate_resource_args - def remote_links(self, issue): + def remote_links(self, issue: Union[str, int]) -> List[RemoteLink]: """Get a list of remote link Resources from an issue. - :param issue: the issue to get remote links from + Args: + issue (str): the issue to get remote links from """ r_json = self._get_json("issue/" + str(issue) + "/remotelink") remote_links = [ @@ -1681,35 +1808,45 @@ def remote_links(self, issue): return remote_links @translate_resource_args - def remote_link(self, issue, id): + def remote_link(self, issue: str, id: str) -> RemoteLink: """Get a remote link Resource from the server. - :param issue: the issue holding the remote link - :param id: ID of the remote link + Args: + issue (str): the issue holding the remote link + id (str): ID of the remote link """ return self._find_for_resource(RemoteLink, (issue, id)) # removed the @translate_resource_args because it prevents us from finding # information for building a proper link def add_remote_link( - self, issue, destination, globalId=None, application=None, relationship=None - ): + self, + issue: str, + destination: Union[Issue, Dict[str, Any]], + globalId: Optional[str] = None, + application: Optional[Dict[str, Any]] = None, + relationship: Optional[str] = None, + ) -> RemoteLink: """Add a remote link from an issue to an external application and returns a remote link Resource for it. ``destination`` should be a dict containing at least ``url`` to the linked external URL and ``title`` to display for the link inside Jira. - For definitions of the allowable fields for ``object`` and the keyword arguments ``globalId``, ``application`` + For definitions of the allowable fields for ``destination`` and the keyword arguments ``globalId``, ``application`` and ``relationship``, see https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+for+Remote+Issue+Links. - :param issue: the issue to add the remote link to - :param destination: the link details to add (see the above link for details) - :param globalId: unique ID for the link (see the above link for details) - :param application: application information for the link (see the above link for details) - :param relationship: relationship description for the link (see the above link for details) + Args: + issue (str): the issue to add the remote link to + destination (Union[Issue, Dict[str, Any]]): the link details to add (see the above link for details) + globalId (Optional[str]): unique ID for the link (see the above link for details) + application (Optional[Dict[str,Any]]): application information for the link (see the above link for details) + relationship (Optional[str]): relationship description for the link (see the above link for details) + + Returns: + RemoteLink: the added remote lint """ try: - applicationlinks = self.applicationlinks() + applicationlinks: List[Dict] = self.applicationlinks() except JIRAError as e: applicationlinks = [] # In many (if not most) configurations, non-admin users are @@ -1722,14 +1859,12 @@ def add_remote_link( Warning, ) - data = {} - if isinstance(destination, Issue): - + data: Dict[str, Any] = {} + if isinstance(destination, Issue) and destination.raw: data["object"] = {"title": str(destination), "url": destination.permalink()} - for x in applicationlinks: if x["application"]["displayUrl"] == destination._options["server"]: - data["globalId"] = "appId=%s&issueId=%s" % ( + data["globalId"] = "appId={}&issueId={}".format( x["application"]["id"], destination.raw["id"], ) @@ -1752,17 +1887,18 @@ def add_remote_link( data["relationship"] = relationship # check if the link comes from one of the configured application links - for x in applicationlinks: - if x["application"]["displayUrl"] == self._options["server"]: - data["globalId"] = "appId=%s&issueId=%s" % ( - x["application"]["id"], - destination.raw["id"], - ) - data["application"] = { - "name": x["application"]["name"], - "type": "com.atlassian.jira", - } - break + if isinstance(destination, Issue) and destination.raw: + for x in applicationlinks: + if x["application"]["displayUrl"] == self.server_url: + data["globalId"] = "appId={}&issueId={}".format( + x["application"]["id"], + destination.raw["id"], # .raw only present on Issue + ) + data["application"] = { + "name": x["application"]["name"], + "type": "com.atlassian.jira", + } + break url = self._get_url("issue/" + str(issue) + "/remotelink") r = self._session.post(url, data=json.dumps(data)) @@ -1770,20 +1906,24 @@ def add_remote_link( remote_link = RemoteLink(self._options, self._session, raw=json_loads(r)) return remote_link - def add_simple_link(self, issue, object): + def add_simple_link(self, issue: str, object: Dict[str, Any]): """Add a simple remote link from an issue to web resource. This avoids the admin access problems from add_remote_link by just - using a simple object and presuming all fields are correct and not - requiring more complex ``application`` data. + using a simple object and presuming all fields are correct and not + requiring more complex ``application`` data. ``object`` should be a dict containing at least ``url`` to the - linked external URL and ``title`` to display for the link inside Jira. + linked external URL and ``title`` to display for the link inside Jira. For definitions of the allowable fields for ``object`` , see https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+for+Remote+Issue+Links. - :param issue: the issue to add the remote link to - :param object: the dictionary used to create remotelink data + Args: + issue (str): the issue to add the remote link to + object (Dict[str,Any]): the dictionary used to create remotelink data + + Returns: + RemoteLint """ data = {"object": object} url = self._get_url("issue/" + str(issue) + "/remotelink") @@ -1794,12 +1934,16 @@ def add_simple_link(self, issue, object): # non-resource @translate_resource_args - def transitions(self, issue, id=None, expand=None): + def transitions(self, issue: str, id: Optional[str] = None, expand=None): """Get a list of the transitions available on the specified issue to the current user. - :param issue: ID or key of the issue to get the transitions from - :param id: if present, get only the transition matching this ID - :param expand: extra information to fetch inside each transition + Args: + issue (str): ID or key of the issue to get the transitions from + id (Optional[str]): if present, get only the transition matching this ID + expand (Optional): extra information to fetch inside each transition + + Returns: + Any: json of response """ params = {} if id is not None: @@ -1810,16 +1954,19 @@ def transitions(self, issue, id=None, expand=None): "transitions" ] - def find_transitionid_by_name(self, issue, transition_name): + def find_transitionid_by_name( + self, issue: str, transition_name: str + ) -> Optional[int]: """Get a transitionid available on the specified issue to the current user. Look at https://developer.atlassian.com/static/rest/jira/6.1.html#d2e1074 for json reference - :param issue: ID or key of the issue to get the transitions from - :param trans_name: iname of transition we are looking for + Args: + issue (str): ID or key of the issue to get the transitions from + trans_name (str): iname of transition we are looking for """ transitions_json = self.transitions(issue) - id = None + id: Optional[int] = None for transition in transitions_json: if transition["name"].lower() == transition_name.lower(): @@ -1829,7 +1976,13 @@ def find_transitionid_by_name(self, issue, transition_name): @translate_resource_args def transition_issue( - self, issue, transition, fields=None, comment=None, worklog=None, **fieldargs + self, + issue: str, + transition: str, + fields: Optional[Dict[str, Any]] = None, + comment: Optional[str] = None, + worklog: Optional[str] = None, + **fieldargs, ): """Perform a transition on an issue. @@ -1837,14 +1990,15 @@ def transition_issue( is treated as the intended value for that field -- if the fields argument is used, all other keyword arguments will be ignored. Field values will be set on the issue as part of the transition process. - :param issue: ID or key of the issue to perform the transition on - :param transition: ID or name of the transition to perform - :param comment: *Optional* String to add as comment to the issue when - performing the transition. - :param fields: a dict containing field names and the values to use. - If present, all other keyword arguments will be ignored + Args: + issue (str): ID or key of the issue to perform the transition on + transition (str): ID or name of the transition to perform + fields (Optional[Dict[str,Any]]): a dict containing field names and the values to use. + comment (Optional[str]): String to add as comment to the issue when performing the transition. + workload (Optional[str]): String to add as time spent on the issue when performing the transition. + **fieldargs: If present, all other keyword arguments will be ignored """ - transitionId = None + transitionId: Optional[int] = None try: transitionId = int(transition) @@ -1852,9 +2006,9 @@ def transition_issue( # cannot cast to int, so try to find transitionId by name transitionId = self.find_transitionid_by_name(issue, transition) if transitionId is None: - raise JIRAError("Invalid transition name. %s" % transition) + raise JIRAError(f"Invalid transition name. {transition}") - data = {"transition": {"id": transitionId}} + data: Dict[str, Any] = {"transition": {"id": transitionId}} if comment: data["update"] = {"comment": [{"add": {"body": comment}}]} if worklog: @@ -1872,76 +2026,105 @@ def transition_issue( try: r_json = json_loads(r) except ValueError as e: - logging.error("%s\n%s" % (e, r.text)) + self.log.error(f"{e}\n{r.text}") raise e return r_json @translate_resource_args - def votes(self, issue): + def votes(self, issue: str) -> Votes: """Get a votes Resource from the server. - :param issue: ID or key of the issue to get the votes for - :rtype: Votes + Args: + issue (str): ID or key of the issue to get the votes for + Returns: + Votes """ return self._find_for_resource(Votes, issue) @translate_resource_args - def add_vote(self, issue): + def project_permissionscheme(self, project: str) -> PermissionScheme: + """Get a PermissionScheme Resource from the server. + + + Args: + project (str): ID or key of the project to get the permissionscheme for + + Returns: + PermissionScheme: The permission scheme + """ + return self._find_for_resource(PermissionScheme, project) + + @translate_resource_args + def add_vote(self, issue: str) -> Response: """Register a vote for the current authenticated user on an issue. - :param issue: ID or key of the issue to vote on - :rtype: Response + Args: + issue (str): ID or key of the issue to vote on + + Returns: + Response """ url = self._get_url("issue/" + str(issue) + "/votes") return self._session.post(url) @translate_resource_args - def remove_vote(self, issue): + def remove_vote(self, issue: str): """Remove the current authenticated user's vote from an issue. - :param issue: ID or key of the issue to remove vote on + Args: + issue (str): ID or key of the issue to remove vote on """ url = self._get_url("issue/" + str(issue) + "/votes") self._session.delete(url) @translate_resource_args - def watchers(self, issue): + def watchers(self, issue: str) -> Watchers: """Get a watchers Resource from the server for an issue. - :param issue: ID or key of the issue to get the watchers for - :rtype: Watchers + Args: + issue (str): ID or key of the issue to get the watchers for + Returns: + Watchers """ return self._find_for_resource(Watchers, issue) @translate_resource_args - def add_watcher(self, issue, watcher): + def add_watcher(self, issue: str, watcher: str) -> Response: """Add a user to an issue's watchers list. - :param issue: ID or key of the issue affected - :param watcher: username of the user to add to the watchers list + Args: + issue (str): ID or key of the issue affected + watcher (str): name of the user to add to the watchers list """ url = self._get_url("issue/" + str(issue) + "/watchers") - self._session.post(url, data=json.dumps(watcher)) + return self._session.post(url, data=json.dumps(watcher)) @translate_resource_args - def remove_watcher(self, issue, watcher): + def remove_watcher(self, issue: str, watcher: str) -> Response: """Remove a user from an issue's watch list. - :param issue: ID or key of the issue affected - :param watcher: accountId of the user to remove from the watchers list - :rtype: Response + Args: + issue (str): ID or key of the issue affected + watcher (str): name of the user to remove from the watchers list + + Returns: + Response """ url = self._get_url("issue/" + str(issue) + "/watchers") - params = {"accountId": watcher} - result = self._session.delete(url, params=params) + # https://docs.atlassian.com/software/jira/docs/api/REST/8.13.6/#api/2/issue-removeWatcher + user_id = self._get_user_id(watcher) + payload = {"accountId": user_id} if self._is_cloud else {"username": user_id} + result = self._session.delete(url, params=payload) return result @translate_resource_args - def worklogs(self, issue): + def worklogs(self, issue: str) -> List[Worklog]: """Get a list of worklog Resources from the server for an issue. - :param issue: ID or key of the issue to get worklogs from - :rtype: List[Worklog] + Args: + issue (str): ID or key of the issue to get worklogs from + Returns: + List[Worklog] """ r_json = self._get_json("issue/" + str(issue) + "/worklog") worklogs = [ @@ -1951,12 +2134,14 @@ def worklogs(self, issue): return worklogs @translate_resource_args - def worklog(self, issue, id): + def worklog(self, issue: str, id: str) -> Worklog: """Get a specific worklog Resource from the server. - :param issue: ID or key of the issue to get the worklog from - :param id: ID of the worklog to get - :rtype: Worklog + Args: + issue (str): ID or key of the issue to get the worklog from + id (str): ID of the worklog to get + Returns: + Worklog """ return self._find_for_resource(Worklog, (issue, id)) @@ -1964,26 +2149,30 @@ def worklog(self, issue, id): def add_worklog( self, issue, - timeSpent=None, - timeSpentSeconds=None, - adjustEstimate=None, - newEstimate=None, - reduceBy=None, - comment=None, - started=None, - user=None, - ): + timeSpent: (Optional[str]) = None, + timeSpentSeconds: (Optional[str]) = None, + adjustEstimate: (Optional[str]) = None, + newEstimate: (Optional[str]) = None, + reduceBy: (Optional[str]) = None, + comment: (Optional[str]) = None, + started: (Optional[datetime.datetime]) = None, + user: (Optional[str]) = None, + ) -> Worklog: """Add a new worklog entry on an issue and return a Resource for it. - :param issue: the issue to add the worklog to - :param timeSpent: a worklog entry with this amount of time spent, e.g. "2d" - :param adjustEstimate: (optional) allows the user to provide specific instructions to update the remaining - time estimate of the issue. The value can either be ``new``, ``leave``, ``manual`` or ``auto`` (default). - :param newEstimate: the new value for the remaining estimate field. e.g. "2d" - :param reduceBy: the amount to reduce the remaining estimate by e.g. "2d" - :param started: Moment when the work is logged, if not specified will default to now - :param comment: optional worklog comment - :rtype: Worklog + Args: + issue (str): the issue to add the worklog to + timeSpent (Optional[str]): a worklog entry with this amount of time spent, e.g. "2d" + timeSpentSeconds (Optional[str]): a worklog entry with this amount of time spent in seconds + adjustEstimate (Optional[str]): allows the user to provide specific instructions to update + the remaining time estimate of the issue. The value can either be ``new``, ``leave``, ``manual`` or ``auto`` (default). + newEstimate (Optional[str]): the new value for the remaining estimate field. e.g. "2d" + reduceBy (Optional[str]): the amount to reduce the remaining estimate by e.g. "2d" + comment (Optional[str]): optional worklog comment + started (Optional[datetime.datetime]): Moment when the work is logged, if not specified will default to now + user (Optional[str]): the user ID or name to use for this worklog + Returns: + Worklog """ params = {} if adjustEstimate is not None: @@ -1993,7 +2182,7 @@ def add_worklog( if reduceBy is not None: params["reduceBy"] = reduceBy - data = {} + data: Dict[str, Any] = {} if timeSpent is not None: data["timeSpent"] = timeSpent if timeSpentSeconds is not None: @@ -2020,7 +2209,7 @@ def add_worklog( data["updateAuthor"] = data["author"] # report bug to Atlassian: author and updateAuthor parameters are # ignored. - url = self._get_url("issue/{0}/worklog".format(issue)) + url = self._get_url(f"issue/{issue}/worklog") r = self._session.post(url, params=params, data=json.dumps(data)) return Worklog(self._options, self._session, json_loads(r)) @@ -2028,21 +2217,29 @@ def add_worklog( # Issue links @translate_resource_args - def create_issue_link(self, type, inwardIssue, outwardIssue, comment=None): + def create_issue_link( + self, + type: Union[str, IssueLinkType], + inwardIssue: str, + outwardIssue: str, + comment: Optional[Dict[str, Any]] = None, + ) -> Response: """Create a link between two issues. - :param type: the type of link to create - :param inwardIssue: the issue to link from - :param outwardIssue: the issue to link to - :param comment: a comment to add to the issues with the link. Should be - a dict containing ``body`` and ``visibility`` fields: ``body`` being - the text of the comment and ``visibility`` being a dict containing - two entries: ``type`` and ``value``. ``type`` is ``role`` (or - ``group`` if the Jira server has configured comment visibility for - groups) and ``value`` is the name of the role (or group) to which - viewing of this comment will be restricted. - :type comment: Optional[Dict[str, Any]] - :rtype: Response + Args: + type (Union[str,IssueLinkType]): the type of link to create + inwardIssue: the issue to link from + outwardIssue: the issue to link to + comment (Optional[Dict[str, Any]]): a comment to add to the issues with the link. + Should be a dict containing ``body`` and ``visibility`` fields: ``body`` being + the text of the comment and ``visibility`` being a dict containing + two entries: ``type`` and ``value``. ``type`` is ``role`` (or + ``group`` if the Jira server has configured comment visibility for + groups) and ``value`` is the name of the role (or group) to which + viewing of this comment will be restricted. + + Returns: + Response """ # let's see if we have the right issue link 'type' and fix it if needed issue_link_types = self.issue_link_types() @@ -2068,27 +2265,30 @@ def create_issue_link(self, type, inwardIssue, outwardIssue, comment=None): url = self._get_url("issueLink") return self._session.post(url, data=json.dumps(data)) - def delete_issue_link(self, id): + def delete_issue_link(self, id: str): """Delete a link between two issues. - :param id: ID of the issue link to delete + Args: + id (str): ID of the issue link to delete """ url = self._get_url("issueLink") + "/" + id return self._session.delete(url) - def issue_link(self, id): + def issue_link(self, id: str): """Get an issue link Resource from the server. - :param id: ID of the issue link to get + Args: + id (str): ID of the issue link to get """ return self._find_for_resource(IssueLink, id) # Issue link types - def issue_link_types(self, force=False): + def issue_link_types(self, force: bool = False) -> List[IssueLinkType]: """Get a list of issue link type Resources from the server. - :rtype: List[IssueLinkType] + Returns: + List[IssueLinkType] """ if not hasattr(self, "self._cached_issue_link_types") or force: r_json = self._get_json("issueLinkType") @@ -2098,22 +2298,25 @@ def issue_link_types(self, force=False): ] return self._cached_issue_link_types - def issue_link_type(self, id): + def issue_link_type(self, id: str) -> IssueLinkType: """Get an issue link type Resource from the server. - :param id: ID of the issue link type to get - :type id: str - :rtype: IssueLinkType + Args: + id (str): ID of the issue link type to get + + Returns: + IssueLinkType """ return self._find_for_resource(IssueLinkType, id) # Issue types - def issue_types(self): + def issue_types(self) -> List[IssueType]: """Get a list of issue type Resources from the server. - :rtype: List[IssueType] + Returns: + List[IssueType] """ r_json = self._get_json("issuetype") @@ -2123,38 +2326,47 @@ def issue_types(self): ] return issue_types - def issue_type(self, id): + def issue_type(self, id: str) -> IssueType: """Get an issue type Resource from the server. - :param id: ID of the issue type to get - :rtype: IssueType + Args: + id (str): ID of the issue type to get + + Returns: + IssueType """ return self._find_for_resource(IssueType, id) - def issue_type_by_name(self, name): + def issue_type_by_name(self, name: str) -> IssueType: """ - :param name: Name of the issue type - :type name: str - :rtype: IssueType + Args: + name (str): Name of the issue type + + Returns: + IssueType """ - issue_types = self.issue_types() - try: - issue_type = [it for it in issue_types if it.name == name][0] - except IndexError: - raise KeyError("Issue type '%s' is unknown." % name) - return issue_type + matching_issue_types = [it for it in self.issue_types() if it.name == name] + if len(matching_issue_types) == 1: + return matching_issue_types[0] + elif len(matching_issue_types) == 0: + raise KeyError(f"Issue type '{name}' is unknown.") + else: + raise KeyError(f"Issue type '{name}' appears more than once.") + + def request_types(self, service_desk: ServiceDesk) -> List[RequestType]: + """Returns request types supported by a service desk instance. - def request_types(self, service_desk): - """ Returns request types supported by a service desk instance. - :param service_desk: The service desk instance. - :type service_desk: ServiceDesk - :rtype: List[RequestType] + Args: + service_desk (ServiceDesk): The service desk instance. + + Returns: + List[RequestType] """ if hasattr(service_desk, "id"): service_desk = service_desk.id url = ( - self._options["server"] - + "/rest/servicedeskapi/servicedesk/%s/requesttype" % service_desk + self.server_url + + f"/rest/servicedeskapi/servicedesk/{service_desk}/requesttype" ) headers = {"X-ExperimentalApi": "opt-in"} r_json = json_loads(self._session.get(url, headers=headers)) @@ -2164,31 +2376,34 @@ def request_types(self, service_desk): ] return request_types - def request_type_by_name(self, service_desk, name): + def request_type_by_name(self, service_desk: ServiceDesk, name: str): request_types = self.request_types(service_desk) try: request_type = [rt for rt in request_types if rt.name == name][0] except IndexError: - raise KeyError("Request type '%s' is unknown." % name) + raise KeyError(f"Request type '{name}' is unknown.") return request_type # User permissions # non-resource def my_permissions( - self, projectKey=None, projectId=None, issueKey=None, issueId=None - ): + self, + projectKey: Optional[str] = None, + projectId: Optional[str] = None, + issueKey: Optional[str] = None, + issueId: Optional[str] = None, + ) -> Dict[str, Dict[str, Dict[str, str]]]: """Get a dict of all available permissions on the server. - :param projectKey: limit returned permissions to the specified project - :type projectKey: Optional[str] - :param projectId: limit returned permissions to the specified project - :type projectId: Optional[str] - :param issueKey: limit returned permissions to the specified issue - :type issueKey: Optional[str] - :param issueId: limit returned permissions to the specified issue - :type issueId: Optional[str] - :rtype: Dict[str, Dict[str, Dict[str, str]]] + Args: + projectKey (Optional[str]): limit returned permissions to the specified project + projectId (Optional[str]): limit returned permissions to the specified project + issueKey (Optional[str]): limit returned permissions to the specified issue + issueId (Optional[str]): limit returned permissions to the specified issue + + Returns: + Dict[str, Dict[str, Dict[str, str]]] """ params = {} if projectKey is not None: @@ -2206,7 +2421,8 @@ def my_permissions( def priorities(self): """Get a list of priority Resources from the server. - :rtype: List[Priority] + Returns: + List[Priority] """ r_json = self._get_json("priority") @@ -2216,77 +2432,98 @@ def priorities(self): ] return priorities - def priority(self, id): + def priority(self, id: str) -> Priority: """Get a priority Resource from the server. - :param id: ID of the priority to get - :type id: str - :rtype: Priority + Args: + id (str): ID of the priority to get + + Returns: + Priority """ return self._find_for_resource(Priority, id) # Projects - def projects(self): + def projects(self, expand: Optional[str] = None) -> List[Project]: """Get a list of project Resources from the server visible to the current authenticated user. - :rtype: List[Project] + Args: + expand (Optional[str]): extra information to fetch for each project + such as projectKeys and description. + + Returns: + List[Project] """ - r_json = self._get_json("project") + params = {} + if expand is not None: + params["expand"] = expand + r_json = self._get_json("project", params=params) projects = [ Project(self._options, self._session, raw_project_json) for raw_project_json in r_json ] return projects - def project(self, id): + def project(self, id: str, expand: Optional[str] = None) -> Project: """Get a project Resource from the server. - :param id: ID or key of the project to get - :rtype: Project + Args: + id (str): ID or key of the project to get + expand (Optional[str]): extra information to fetch for the project + such as projectKeys and description. + + Returns: + Project """ - return self._find_for_resource(Project, id) + return self._find_for_resource(Project, id, expand=expand) # non-resource @translate_resource_args - def project_avatars(self, project): + def project_avatars(self, project: str): """Get a dict of all avatars for a project visible to the current authenticated user. - :param project: ID or key of the project to get avatars for + Args: + project (str): ID or key of the project to get avatars for """ return self._get_json("project/" + project + "/avatars") @translate_resource_args def create_temp_project_avatar( - self, project, filename, size, avatar_img, contentType=None, auto_confirm=False + self, + project: str, + filename: str, + size: int, + avatar_img: bytes, + contentType: str = None, + auto_confirm: bool = False, ): """Register an image file as a project avatar. - The avatar created is temporary and must be confirmed before it can - be used. + The avatar created is temporary and must be confirmed before it can be used. Avatar images are specified by a filename, size, and file object. By default, the client will attempt to - autodetect the picture's content type: this mechanism relies on libmagic and will not work out of the box - on Windows systems (see https://filemagic.readthedocs.io/en/latest/guide.html for details on how to install - support). The ``contentType`` argument can be used to explicitly set the value (note that Jira will reject any - type other than the well-known ones for images, e.g. ``image/jpg``, ``image/png``, etc.) + autodetect the picture's content type: this mechanism relies on libmagic and will not work out of the box + on Windows systems (see https://filemagic.readthedocs.io/en/latest/guide.html for details on how to install + support). The ``contentType`` argument can be used to explicitly set the value (note that Jira will reject any + type other than the well-known ones for images, e.g. ``image/jpg``, ``image/png``, etc.) This method returns a dict of properties that can be used to crop a subarea of a larger image for use. This - dict should be saved and passed to :py:meth:`confirm_project_avatar` to finish the avatar creation process. If - you want to cut out the middleman and confirm the avatar with Jira's default cropping, pass the 'auto_confirm' - argument with a truthy value and :py:meth:`confirm_project_avatar` will be called for you before this method - returns. - - :param project: ID or key of the project to create the avatar in - :param filename: name of the avatar file - :param size: size of the avatar file - :param avatar_img: file-like object holding the avatar - :param contentType: explicit specification for the avatar image's content-type - :param auto_confirm: whether to automatically confirm the temporary avatar by calling - :py:meth:`confirm_project_avatar` with the return value of this method. (Default: False) - :type auto_confirm: bool + dict should be saved and passed to :py:meth:`confirm_project_avatar` to finish the avatar creation process. If + you want to cut out the middleman and confirm the avatar with Jira's default cropping, pass the 'auto_confirm' + argument with a truthy value and :py:meth:`confirm_project_avatar` will be called for you before this method + returns. + + Args: + project (str): ID or key of the project to create the avatar in + filename (str): name of the avatar file + size (int): size of the avatar file + avatar_img (bytes): file-like object holding the avatar + contentType (str): explicit specification for the avatar image's content-type + auto_confirm (bool): whether to automatically confirm the temporary avatar by calling + :py:meth:`confirm_project_avatar` with the return value of this method. (Default: False) """ size_from_file = os.path.getsize(filename) if size != size_from_file: @@ -2294,7 +2531,7 @@ def create_temp_project_avatar( params = {"filename": filename, "size": size} - headers = {"X-Atlassian-Token": "no-check"} + headers: Dict[str, Any] = {"X-Atlassian-Token": "no-check"} if contentType is not None: headers["content-type"] = contentType else: @@ -2304,14 +2541,14 @@ def create_temp_project_avatar( url = self._get_url("project/" + project + "/avatar/temporary") r = self._session.post(url, params=params, headers=headers, data=avatar_img) - cropping_properties = json_loads(r) + cropping_properties: Dict[str, Any] = json_loads(r) if auto_confirm: return self.confirm_project_avatar(project, cropping_properties) else: return cropping_properties @translate_resource_args - def confirm_project_avatar(self, project, cropping_properties): + def confirm_project_avatar(self, project: str, cropping_properties: Dict[str, Any]): """Confirm the temporary avatar image previously uploaded with the specified cropping. After a successful registry with :py:meth:`create_temp_project_avatar`, use this method to confirm the avatar @@ -2319,8 +2556,9 @@ def confirm_project_avatar(self, project, cropping_properties): ``cropping_properties``: the return value of :py:meth:`create_temp_project_avatar` should be used for this argument. - :param project: ID or key of the project to confirm the avatar in - :param cropping_properties: a dict of cropping properties from :py:meth:`create_temp_project_avatar` + Args: + project (str): ID or key of the project to confirm the avatar in + cropping_properties (Dict[str,Any]): a dict of cropping properties from :py:meth:`create_temp_project_avatar` """ data = cropping_properties url = self._get_url("project/" + project + "/avatar") @@ -2329,31 +2567,35 @@ def confirm_project_avatar(self, project, cropping_properties): return json_loads(r) @translate_resource_args - def set_project_avatar(self, project, avatar): + def set_project_avatar(self, project: str, avatar: str): """Set a project's avatar. - :param project: ID or key of the project to set the avatar on - :param avatar: ID of the avatar to set + Args: + project (str): ID or key of the project to set the avatar on + avatar (str): ID of the avatar to set """ self._set_avatar(None, self._get_url("project/" + project + "/avatar"), avatar) @translate_resource_args - def delete_project_avatar(self, project, avatar): + def delete_project_avatar(self, project: str, avatar: str) -> Response: """Delete a project's avatar. - :param project: ID or key of the project to delete the avatar from - :param avatar: ID of the avatar to delete + Args: + project (str): ID or key of the project to delete the avatar from + avatar (str): ID of the avatar to delete """ url = self._get_url("project/" + project + "/avatar/" + avatar) return self._session.delete(url) @translate_resource_args - def project_components(self, project): + def project_components(self, project: str) -> List[Component]: """Get a list of component Resources present on a project. - :param project: ID or key of the project to get components from - :type project: str - :rtype: List[Component] + Args: + project (str): ID or key of the project to get components from + + Returns: + List[Component] """ r_json = self._get_json("project/" + project + "/components") components = [ @@ -2363,12 +2605,14 @@ def project_components(self, project): return components @translate_resource_args - def project_versions(self, project): + def project_versions(self, project: str) -> List[Version]: """Get a list of version Resources present on a project. - :param project: ID or key of the project to get versions from - :type project: str - :rtype: List[Version] + Args: + project (str): ID or key of the project to get versions from + + Returns: + List[Version] """ r_json = self._get_json("project/" + project + "/versions") versions = [ @@ -2378,31 +2622,35 @@ def project_versions(self, project): return versions @translate_resource_args - def get_project_version_by_name(self, project, version_name): + def get_project_version_by_name( + self, project: str, version_name: str + ) -> Optional[Version]: """Get a version Resource by its name present on a project. - :param project: ID or key of the project to get versions from - :type project: str - :param version_name: name of the version to search for - :type version_name: str - :rtype: Optional[Version] + Args: + project (str): ID or key of the project to get versions from + version_name (str): name of the version to search for + + Returns: + Optional[Version] """ - versions = self.project_versions(project) + versions: List[Version] = self.project_versions(project) for version in versions: if version.name == version_name: return version + return None @translate_resource_args - def rename_version(self, project, old_name, new_name): + def rename_version(self, project: str, old_name: str, new_name: str) -> None: """Rename a version Resource on a project. - :param project: ID or key of the project to get versions from - :type project: str - :param old_name: old name of the version to rename - :type old_name: str - :param new_name: new name of the version to rename - :type new_name: str - :rtype: None + Args: + project (str): ID or key of the project to get versions from + old_name (str): old name of the version to rename + new_name (str): new name of the version to rename + + Returns: + None """ version = self.get_project_version_by_name(project, old_name) if version: @@ -2410,17 +2658,18 @@ def rename_version(self, project, old_name, new_name): # non-resource @translate_resource_args - def project_roles(self, project): + def project_roles(self, project: str) -> Dict[str, Dict[str, str]]: """Get a dict of role names to resource locations for a project. - :param project: ID or key of the project to get roles from + Args: + project (str): ID or key of the project to get roles from """ path = "project/" + project + "/role" - _rolesdict = self._get_json(path) - rolesdict = {} + _rolesdict: Dict[str, str] = self._get_json(path) + rolesdict: Dict[str, Dict[str, str]] = {} for k, v in _rolesdict.items(): - tmp = {} + tmp: Dict[str, str] = {} tmp["id"] = v.split("/")[-1] tmp["url"] = v rolesdict[k] = tmp @@ -2428,22 +2677,24 @@ def project_roles(self, project): # TODO(ssbarnea): return a list of Roles() @translate_resource_args - def project_role(self, project, id): + def project_role(self, project: str, id: str) -> Role: """Get a role Resource. - :param project: ID or key of the project to get the role from - :param id: ID of the role to get + Args: + project (str): ID or key of the project to get the role from + id (str): ID of the role to get """ if isinstance(id, Number): - id = "%s" % id + id = f"{id}" return self._find_for_resource(Role, (project, id)) # Resolutions - def resolutions(self): + def resolutions(self) -> List[Resolution]: """Get a list of resolution Resources from the server. - :rtype: List[Resolution] + Returns: + List[Resolution] """ r_json = self._get_json("resolution") @@ -2453,12 +2704,14 @@ def resolutions(self): ] return resolutions - def resolution(self, id): + def resolution(self, id: str) -> Resolution: """Get a resolution Resource from the server. - :param id: ID of the resolution to get - :type id: str - :rtype: Resolution + Args: + id (str): ID of the resolution to get + + Returns: + Resolution """ return self._find_for_resource(Resolution, id) @@ -2466,36 +2719,31 @@ def resolution(self, id): def search_issues( self, - jql_str, - startAt=0, - maxResults=50, - validate_query=True, - fields=None, - expand=None, - json_result=None, - ): + jql_str: str, + startAt: int = 0, + maxResults: int = 50, + validate_query: bool = True, + fields: Optional[Union[str, List[str]]] = None, + expand: Optional[str] = None, + json_result: bool = False, + ) -> Union[List[Dict[str, Any]], ResultList[Issue]]: """Get a :class:`~jira.client.ResultList` of issue Resources matching a JQL search string. - :param jql_str: The JQL search string. - :type jql_str: str - :param startAt: Index of the first issue to return. (Default: 0) - :type startAt: int - :param maxResults: Maximum number of issues to return. Total number of results - is available in the ``total`` attribute of the returned :class:`~jira.client.ResultList`. - If maxResults evaluates as False, it will try to get all issues in batches. (Default: 50) - :type maxResults: int - :param validate_query: Whether or not the query should be validated. (Default: True) - :type validate_query: bool - :param fields: comma-separated string or list of issue fields to include in the results. - Default is to include all fields. - :type fields: Optional[str or list] - :param expand: extra information to fetch inside each resource - :type expand: Optional[str] - :param json_result: JSON response will be returned when this parameter is set to True. - Otherwise, :class:`~jira.client.ResultList` will be returned. - :type json_result: bool - - :rtype: dict or :class:`~jira.client.ResultList` + Args: + jql_str (str): The JQL search string. + startAt (int): Index of the first issue to return. (Default: 0) + maxResults (int): Maximum number of issues to return. Total number of results + is available in the ``total`` attribute of the returned :class:`~jira.client.ResultList`. + If maxResults evaluates as False, it will try to get all issues in batches. (Default: 50) + validate_query (bool): Whether or not the query should be validated. (Default: True) + fields (Optional[Union[str, List[str]]]): comma-separated string or list of issue fields to include in the results. + Default is to include all fields. + expand (Optional[str]): extra information to fetch inside each resource + json_result (bool): JSON response will be returned when this parameter is set to True. + Otherwise, :class:`~jira.client.ResultList` will be returned. + + Returns: + Union[Dict,ResultList]: Dict if ``json_result=True`` """ if isinstance(fields, str): @@ -2526,56 +2774,64 @@ def search_issues( "All issues cannot be fetched at once, when json_result parameter is set", Warning, ) - return self._get_json("search", params=search_params) + r_json: List[Dict[str, Any]] = self._get_json( + "search", params=search_params + ) + return r_json issues = self._fetch_pages( Issue, "issues", "search", startAt, maxResults, search_params ) if untranslate: - for i in issues: + iss: Issue + for iss in issues: for k, v in untranslate.items(): - if k in i.raw.get("fields", {}): - i.raw["fields"][v] = i.raw["fields"][k] + if iss.raw: + if k in iss.raw.get("fields", {}): + iss.raw["fields"][v] = iss.raw["fields"][k] return issues # Security levels - def security_level(self, id): + def security_level(self, id: str) -> SecurityLevel: """Get a security level Resource. - :param id: ID of the security level to get + Args: + id (str): ID of the security level to get """ return self._find_for_resource(SecurityLevel, id) # Server info # non-resource - def server_info(self): + def server_info(self) -> Dict[str, Any]: """Get a dict of server information for this Jira instance. - :rtype: Dict[str, Any] + + Returns: + Dict[str, Any] """ retry = 0 j = self._get_json("serverInfo") while not j and retry < 3: - logging.warning( + self.log.warning( "Bug https://jira.atlassian.com/browse/JRA-59676 trying again..." ) retry += 1 j = self._get_json("serverInfo") return j - def myself(self): + def myself(self) -> Dict[str, Any]: """Get a dict of server information for this Jira instance.""" return self._get_json("myself") # Status - def statuses(self): + def statuses(self) -> List[Status]: """Get a list of status Resources from the server. - :rtype: List[Status] - + Returns: + List[Status] """ r_json = self._get_json("status") statuses = [ @@ -2584,20 +2840,24 @@ def statuses(self): ] return statuses - def status(self, id): - # type: (str) -> Status + def status(self, id: str) -> Status: """Get a status Resource from the server. - :param id: ID of the status resource to get + Args: + id (str): ID of the status resource to get + + Returns: + Status """ return self._find_for_resource(Status, id) # Category - def statuscategories(self): + def statuscategories(self) -> List[StatusCategory]: """Get a list of status category Resources from the server. - :rtype: List[StatusCategory] + Returns: + List[StatusCategory] """ r_json = self._get_json("statuscategory") statuscategories = [ @@ -2606,28 +2866,29 @@ def statuscategories(self): ] return statuscategories - def statuscategory(self, id): + def statuscategory(self, id: int) -> StatusCategory: """Get a status category Resource from the server. - :param id: ID of the status category resource to get - :type id: int + Args: + id (int): ID of the status category resource to get - :rtype: StatusCategory + Returns: + StatusCategory """ return self._find_for_resource(StatusCategory, id) # Users - def user(self, id, expand=None): + def user(self, id: str, expand: Optional[Any] = None) -> User: """Get a user Resource from the server. - :param id: ID of the user to get - :param id: str - :param expand: Extra information to fetch inside each resource - :type expand: Optional[Any] + Args: + id (str): ID of the user to get + expand (Optional[Any]): Extra information to fetch inside each resource - :rtype: User + Returns: + User """ user = User(self._options, self._session) params = {} @@ -2637,21 +2898,19 @@ def user(self, id, expand=None): return user def search_assignable_users_for_projects( - self, username, projectKeys, startAt=0, maxResults=50 - ): + self, username: str, projectKeys: str, startAt: int = 0, maxResults: int = 50 + ) -> ResultList: """Get a list of user Resources that match the search string and can be assigned issues for projects. - :param username: A string to match usernames against - :type username: str - :param projectKeys: Comma-separated list of project keys to check for issue assignment permissions - :type projectKeys: str - :param startAt: Index of the first user to return (Default: 0) - :type startAt: int - :param maxResults: Maximum number of users to return. - If maxResults evaluates as False, it will try to get all users in batches. (Default: 50) - :type maxResults: int + Args: + username (str): A string to match usernames against + projectKeys (str): Comma-separated list of project keys to check for issue assignment permissions + startAt (int): Index of the first user to return (Default: 0) + maxResults (int): Maximum number of users to return. + If maxResults evaluates as False, it will try to get all users in batches. (Default: 50) - :rtype: ResultList + Returns: + ResultList """ params = {"username": username, "projectKeys": projectKeys} @@ -2666,56 +2925,74 @@ def search_assignable_users_for_projects( def search_assignable_users_for_issues( self, - username, - project=None, - issueKey=None, - expand=None, - startAt=0, - maxResults=50, + username: Optional[str] = None, + project: Optional[str] = None, + issueKey: Optional[str] = None, + expand: Optional[Any] = None, + startAt: int = 0, + maxResults: int = 50, + query: Optional[str] = None, ): """Get a list of user Resources that match the search string for assigning or creating issues. + "username" query parameter is deprecated in Jira Cloud; the expected parameter now is "query", which can just be + the full email again. But the "user" parameter is kept for backwards compatibility, i.e. Jira Server/Data Center. This method is intended to find users that are eligible to create issues in a project or be assigned to an existing issue. When searching for eligible creators, specify a project. When searching for eligible assignees, specify an issue key. - :param username: A string to match usernames against - :type username: str - :param project: Filter returned users by permission in this project (expected if a result will be used to - create an issue) - :type project: Optional[str] - :param issueKey: Filter returned users by this issue (expected if a result will be used to edit this issue) - :type issueKey: Optional[str] - :param expand: Extra information to fetch inside each resource - :type expand: Optional[Any] - :param startAt: Index of the first user to return (Default: 0) - :type startAt: int - :param maxResults: maximum number of users to return. - If maxResults evaluates as False, it will try to get all items in batches. (Default: 50) - - :rtype: ResultList - """ - params = {"username": username} + Args: + username (Optional[str]): A string to match usernames against + project (Optional[str]): Filter returned users by permission in this project + (expected if a result will be used to create an issue) + issueKey (Optional[str]): Filter returned users by this issue + (expected if a result will be used to edit this issue) + expand (Optional[Any]): Extra information to fetch inside each resource + startAt (int): Index of the first user to return (Default: 0) + maxResults (int): maximum number of users to return. + If maxResults evaluates as False, it will try to get all items in batches. (Default: 50) + query (Optional[str]): Search term. It can just be the email. + + Returns: + ResultList + """ + if username is not None: + params = {"username": username} + if query is not None: + params = {"query": query} if project is not None: params["project"] = project if issueKey is not None: params["issueKey"] = issueKey if expand is not None: params["expand"] = expand + + if not username and not query: + raise ValueError( + "Either 'username' or 'query' arguments must be specified." + ) + return self._fetch_pages( User, None, "user/assignable/search", startAt, maxResults, params ) # non-resource - def user_avatars(self, username): + def user_avatars(self, username: str) -> Dict[str, Any]: """Get a dict of avatars for the specified user. - :param username: the username to get avatars for + Args: + username (str): the username to get avatars for """ return self._get_json("user/avatars", params={"username": username}) def create_temp_user_avatar( - self, user, filename, size, avatar_img, contentType=None, auto_confirm=False + self, + user: str, + filename: str, + size: int, + avatar_img: bytes, + contentType: Any = None, + auto_confirm: bool = False, ): """Register an image file as a user avatar. @@ -2734,21 +3011,15 @@ def create_temp_user_avatar( argument with a truthy value and :py:meth:`confirm_user_avatar` will be called for you before this method returns. - :param user: User to register the avatar for - :type user: str - :param filename: name of the avatar file - :type filename: str - :param size: size of the avatar file - :type size: int - :param avatar_img: file-like object containing the avatar - :type avatar_img: bytes - :param contentType: explicit specification for the avatar image's content-type - :type contentType: Optional[Any] - :param auto_confirm: whether to automatically confirm the temporary avatar by calling - :py:meth:`confirm_user_avatar` with the return value of this method. (Default: False) - :type auto_confirm: bool - - :rtype: NoReturn + Args: + user (str): User to register the avatar for + filename (str): name of the avatar file + size (int): size of the avatar file + avatar_img (bytes): file-like object containing the avatar + contentType (Optional[Any]): explicit specification for the avatar image's content-type + auto_confirm (bool): whether to automatically confirm the temporary avatar by calling + :py:meth:`confirm_user_avatar` with the return value of this method. (Default: False) + """ size_from_file = os.path.getsize(filename) if size != size_from_file: @@ -2759,6 +3030,7 @@ def create_temp_user_avatar( params = {"username": user, "filename": filename, "size": size} + headers: Dict[str, Any] headers = {"X-Atlassian-Token": "no-check"} if contentType is not None: headers["content-type"] = contentType @@ -2769,13 +3041,13 @@ def create_temp_user_avatar( url = self._get_url("user/avatar/temporary") r = self._session.post(url, params=params, headers=headers, data=avatar_img) - cropping_properties = json_loads(r) + cropping_properties: Dict[str, Any] = json_loads(r) if auto_confirm: return self.confirm_user_avatar(user, cropping_properties) else: return cropping_properties - def confirm_user_avatar(self, user, cropping_properties): + def confirm_user_avatar(self, user: str, cropping_properties: Dict[str, Any]): """Confirm the temporary avatar image previously uploaded with the specified cropping. After a successful registry with :py:meth:`create_temp_user_avatar`, use this method to confirm the avatar for @@ -2783,10 +3055,9 @@ def confirm_user_avatar(self, user, cropping_properties): ``cropping_properties``: the return value of :py:meth:`create_temp_user_avatar` should be used for this argument. - :param user: the user to confirm the avatar for - :type user: str - :param cropping_properties: a dict of cropping properties from :py:meth:`create_temp_user_avatar` - :type cropping_properties: Dict[str,Any] + Args: + user (str): the user to confirm the avatar for + cropping_properties (Dict[str,Any]): a dict of cropping properties from :py:meth:`create_temp_user_avatar` """ data = cropping_properties url = self._get_url("user/avatar") @@ -2794,67 +3065,85 @@ def confirm_user_avatar(self, user, cropping_properties): return json_loads(r) - def set_user_avatar(self, username, avatar): + def set_user_avatar(self, username: str, avatar: str) -> Response: """Set a user's avatar. - :param username: the user to set the avatar for - :param avatar: ID of the avatar to set + Args: + username (str): the user to set the avatar for + avatar (str): ID of the avatar to set """ - self._set_avatar({"username": username}, self._get_url("user/avatar"), avatar) + return self._set_avatar( + {"username": username}, self._get_url("user/avatar"), avatar + ) - def delete_user_avatar(self, username, avatar): + def delete_user_avatar(self, username: str, avatar: str): """Delete a user's avatar. - :param username: the user to delete the avatar from - :param avatar: ID of the avatar to remove + Args: + username (str): the user to delete the avatar from + avatar (str): ID of the avatar to remove """ params = {"username": username} url = self._get_url("user/avatar/" + avatar) return self._session.delete(url, params=params) def search_users( - self, user, startAt=0, maxResults=50, includeActive=True, includeInactive=False - ): + self, + user: Optional[str] = None, + startAt: int = 0, + maxResults: int = 50, + includeActive: bool = True, + includeInactive: bool = False, + query: Optional[str] = None, + ) -> ResultList[User]: """Get a list of user Resources that match the specified search string. + "username" query parameter is deprecated in Jira Cloud; the expected parameter now is "query", which can just be the full + email again. But the "user" parameter is kept for backwards compatibility, i.e. Jira Server/Data Center. - :param user: a string to match usernames, name or email against. - :type user: str - :param startAt: index of the first user to return. - :type startAt: int - :param maxResults: maximum number of users to return. - If maxResults evaluates as False, it will try to get all items in batches. - :type maxResults: int - :param includeActive: If true, then active users are included in the results. (Default: True) - :type includeActive: bool - :param includeInactive: If true, then inactive users are included in the results. (Default: False) - :type includeInactive: bool + Args: + user (Optional[str]): a string to match usernames, name or email against. + startAt (int): index of the first user to return. + maxResults (int): maximum number of users to return. + If maxResults evaluates as False, it will try to get all items in batches. + includeActive (bool): If true, then active users are included in the results. (Default: True) + includeInactive (bool): If true, then inactive users are included in the results. (Default: False) + query (Optional[str]): Search term. It can just be the email. - - :rtype: ResultList + Returns: + ResultList[User] """ + if not user and not query: + raise ValueError("Either 'user' or 'query' arguments must be specified.") + params = { "username": user, + "query": query, "includeActive": includeActive, "includeInactive": includeInactive, } + return self._fetch_pages(User, None, "user/search", startAt, maxResults, params) def search_allowed_users_for_issue( - self, user, issueKey=None, projectKey=None, startAt=0, maxResults=50 - ): + self, + user: str, + issueKey: str = None, + projectKey: str = None, + startAt: int = 0, + maxResults: int = 50, + ) -> ResultList: """Get a list of user Resources that match a username string and have browse permission for the issue or project. - :param user: a string to match usernames against. - :type user: str - :param issueKey: find users with browse permission for this issue. - :type issueKey: Optional[str] - :param projectKey: find users with browse permission for this project. - :type projectKey: Optional[str] - :param startAt: index of the first user to return. (Default: 0) - :type startAt: int - :param maxResults: maximum number of users to return. - If maxResults evaluates as False, it will try to get all items in batches. (Default: 50) - :type maxResults: int + Args: + user (str): a string to match usernames against. + issueKey (Optional[str]): find users with browse permission for this issue. + projectKey (Optional[str]): find users with browse permission for this project. + startAt (int): index of the first user to return. (Default: 0) + maxResults (int): maximum number of users to return. + If maxResults evaluates as False, it will try to get all items in batches. (Default: 50) + + Returns: + ResultList """ params = {"username": user} if issueKey is not None: @@ -2870,32 +3159,27 @@ def search_allowed_users_for_issue( @translate_resource_args def create_version( self, - name, - project, - description=None, - releaseDate=None, - startDate=None, - archived=False, - released=False, - ): + name: str, + project: str, + description: str = None, + releaseDate: Any = None, + startDate: Any = None, + archived: bool = False, + released: bool = False, + ) -> Version: """Create a version in a project and return a Resource for it. - :param name: name of the version to create - :type name: str - :param project: key of the project to create the version in - :type project: str - :param description: a description of the version - :type description: str - :param releaseDate: the release date assigned to the version - :type releaseDate: Optional[Any] - :param startDate: The start date for the version - :type startDate: Optional[Any] - :param archived: Denotes whether a version should be archived. (Default: False) - :type archived: bool - :param released: Denotes whether a version is released. (Default: False) - :type released: bool - - :rtype: Version + Args: + name (str): name of the version to create + project (str): key of the project to create the version in + description (str): a description of the version + releaseDate (Optional[Any]): the release date assigned to the version + startDate (Optional[Any]): The start date for the version + archived (bool): Denotes whether a version should be archived. (Default: False) + released (bool): Denotes whether a version is released. (Default: False) + + Returns: + Version """ data = { "name": name, @@ -2917,15 +3201,19 @@ def create_version( version = Version(self._options, self._session, raw=json_loads(r)) return version - def move_version(self, id, after=None, position=None): + def move_version(self, id: str, after: str = None, position: str = None) -> Version: """Move a version within a project's ordered version list and return a new version Resource for it. One, but not both, of ``after`` and ``position`` must be specified. - :param id: ID of the version to move - :param after: the self attribute of a version to place the specified version after (that is, higher in the list) - :param position: the absolute position to move this version to: must be one of ``First``, ``Last``, - ``Earlier``, or ``Later`` + Args: + id (str): ID of the version to move + after (str): the self attribute of a version to place the specified version after (that is, higher in the list) + position (Optional[str]): the absolute position to move this version to: + must be one of ``First``, ``Last``, ``Earlier``, or ``Later`` + + Returns: + Version """ data = {} if after is not None: @@ -2939,15 +3227,15 @@ def move_version(self, id, after=None, position=None): version = Version(self._options, self._session, raw=json_loads(r)) return version - def version(self, id, expand=None): + def version(self, id: str, expand: Any = None) -> Version: """Get a version Resource. - :param id: ID of the version to get - :type id: str - :param expand: extra information to fetch inside each resource - :type expand: Optional[Any] + Args: + id (str): ID of the version to get + expand (Optional[Any]): extra information to fetch inside each resource - :rtype: Version + Returns: + Version """ version = Version(self._options, self._session) params = {} @@ -2956,31 +3244,34 @@ def version(self, id, expand=None): version.find(id, params=params) return version - def version_count_related_issues(self, id): + def version_count_related_issues(self, id: str): """Get a dict of the counts of issues fixed and affected by a version. - :param id: the version to count issues for + Args: + id (str): the version to count issues for """ - r_json = self._get_json("version/" + id + "/relatedIssueCounts") + r_json: Dict[str, Any] = self._get_json("version/" + id + "/relatedIssueCounts") del r_json["self"] # this isn't really an addressable resource return r_json - def version_count_unresolved_issues(self, id): + def version_count_unresolved_issues(self, id: str): """Get the number of unresolved issues for a version. - :param id: ID of the version to count issues for + Args: + id (str): ID of the version to count issues for """ - return self._get_json("version/" + id + "/unresolvedIssueCount")[ - "issuesUnresolvedCount" - ] + r_json: Dict[str, Any] = self._get_json( + "version/" + id + "/unresolvedIssueCount" + ) + return r_json["issuesUnresolvedCount"] # Session authentication - def session(self): + def session(self) -> User: """Get a dict of the current authenticated user's session information. - :rtype: User - + Returns: + User """ url = "{server}{auth_url}".format(**self._options) r = self._session.get(url) @@ -2988,49 +3279,58 @@ def session(self): user = User(self._options, self._session, json_loads(r)) return user - def kill_session(self): + def kill_session(self) -> Response: """Destroy the session of the current authenticated user.""" - url = self._options["server"] + "/rest/auth/latest/session" + url = self.server_url + "/rest/auth/latest/session" return self._session.delete(url) # Websudo - def kill_websudo(self): + def kill_websudo(self) -> Optional[Response]: """Destroy the user's current WebSudo session. Works only for non-cloud deployments, for others does nothing. - :rtype: Optional[Any] + Returns: + Optional[Response] """ - if self.deploymentType != "Cloud": - url = self._options["server"] + "/rest/auth/1/websudo" + if not self._is_cloud: + url = self.server_url + "/rest/auth/1/websudo" return self._session.delete(url) + return None # Utilities - def _create_http_basic_session(self, username, password, timeout=None): - """ Creates a basic http session. + def _create_http_basic_session( + self, + username: str, + password: str, + timeout: Optional[Union[Union[float, int], Tuple[float, float]]] = None, + ): + """Creates a basic http session. - :param username: Username for the session - :type username: str - :param password: Password for the username - :type password: str - :param timeout: If set determines the timeout period for the Session. - :type timeout: Optional[int] + Args: + username (str): Username for the session + password (str): Password for the username + timeout (Optional[int]): If set determines the timeout period for the Session. - :rtype: NoReturn + Returns: + ResilientSession """ - verify = self._options["verify"] + verify = bool(self._options["verify"]) self._session = ResilientSession(timeout=timeout) self._session.verify = verify self._session.auth = (username, password) - self._session.cert = self._options["client_cert"] + client_cert: Tuple[str, str] = self._options["client_cert"] # to help mypy + self._session.cert = client_cert - def _create_oauth_session(self, oauth, timeout): - verify = self._options["verify"] + def _create_oauth_session( + self, oauth, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] + ): + verify = bool(self._options["verify"]) from oauthlib.oauth1 import SIGNATURE_RSA from requests_oauthlib import OAuth1 - oauth = OAuth1( + oauth_instance = OAuth1( oauth["consumer_key"], rsa_key=oauth["key_cert"], signature_method=SIGNATURE_RSA, @@ -3039,16 +3339,18 @@ def _create_oauth_session(self, oauth, timeout): ) self._session = ResilientSession(timeout) self._session.verify = verify - self._session.auth = oauth + self._session.auth = oauth_instance - def _create_kerberos_session(self, timeout, kerberos_options=None): - verify = self._options["verify"] + def _create_kerberos_session( + self, + timeout: Optional[Union[Union[float, int], Tuple[float, float]]], + kerberos_options=None, + ): + verify = bool(self._options["verify"]) if kerberos_options is None: kerberos_options = {} - from requests_kerberos import DISABLED - from requests_kerberos import HTTPKerberosAuth - from requests_kerberos import OPTIONAL + from requests_kerberos import DISABLED, OPTIONAL, HTTPKerberosAuth if kerberos_options.get("mutual_authentication", "OPTIONAL") == "OPTIONAL": mutual_authentication = OPTIONAL @@ -3067,17 +3369,19 @@ def _create_kerberos_session(self, timeout, kerberos_options=None): ) @staticmethod - def _timestamp(dt=None): + def _timestamp(dt: datetime.timedelta = None): t = datetime.datetime.utcnow() if dt is not None: t += dt return calendar.timegm(t.timetuple()) - def _create_jwt_session(self, jwt, timeout): + def _create_jwt_session( + self, jwt, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] + ): try: jwt_auth = JWTAuth(jwt["secret"], alg="HS256") except NameError as e: - logging.error("JWT authentication requires requests_jwt") + self.log.error("JWT authentication requires requests_jwt") raise e jwt_auth.set_header_format("JWT %s") @@ -3089,40 +3393,55 @@ def _create_jwt_session(self, jwt, timeout): for f in jwt["payload"].items(): jwt_auth.add_field(f[0], f[1]) self._session = ResilientSession(timeout=timeout) - self._session.verify = self._options["verify"] + self._session.verify = bool(self._options["verify"]) self._session.auth = jwt_auth def _set_avatar(self, params, url, avatar): data = {"id": avatar} return self._session.put(url, params=params, data=json.dumps(data)) - def _get_url(self, path, base=JIRA_BASE_URL): - """ Returns the full url based on Jira base url and the path provided - - :param path: The subpath desired. - :type path: str - :param base: The base url which should be prepended to the path - :type base: Optional[str] + def _get_url(self, path: str, base: str = JIRA_BASE_URL) -> str: + """Returns the full url based on Jira base url and the path provided. + Using the API version specified during the __init__. - :return Fully qualified URL - :rtype: str + Args: + path (str): The subpath desired. + base (Optional[str]): The base url which should be prepended to the path + Returns: + str: Fully qualified URL """ options = self._options.copy() options.update({"path": path}) return base.format(**options) - def _get_json(self, path, params=None, base=JIRA_BASE_URL): + def _get_latest_url(self, path: str, base: str = JIRA_BASE_URL) -> str: + """Returns the full url based on Jira base url and the path provided. + Using the latest API endpoint. + + Args: + path (str): The subpath desired. + base (Optional[str]): The base url which should be prepended to the path + + Returns: + str: Fully qualified URL + """ + options = self._options.copy() + options.update({"path": path, "rest_api_version": "latest"}) + return base.format(**options) + + def _get_json( + self, path: str, params: Dict[str, Any] = None, base: str = JIRA_BASE_URL + ): """Get the json for a given path and params. - :param path: The subpath required - :type path: str - :param params: Parameters to filter the json query. - :type params: Optional[Dict[str, Any]] - :param base: The Base Jira URL, defaults to the instance base. - :type base: Optional[str] + Args: + path (str): The subpath required + params (Optional[Dict[str, Any]]): Parameters to filter the json query. + base (Optional[str]): The Base Jira URL, defaults to the instance base. - :rtype: Union[Dict[str, Any], List[Dict[str, str]]] + Returns: + Union[Dict[str, Any], List[Dict[str, str]]] """ url = self._get_url(path, base) @@ -3130,24 +3449,41 @@ def _get_json(self, path, params=None, base=JIRA_BASE_URL): try: r_json = json_loads(r) except ValueError as e: - logging.error("%s\n%s" % (e, r.text)) + self.log.error(f"{e}\n{r.text if r else r}") raise e return r_json - def _find_for_resource(self, resource_cls, ids, expand=None): + def _find_for_resource( + self, resource_cls: Any, ids: Union[Tuple[str, str], int, str], expand=None + ) -> Any: + """Uses the find method of the provided Resource class + + Args: + resource_cls (Any): Any instance of :py:class`Resource` + ids (Union[Tuple[str, str], int, str]): The arguments to the Resource's ``find()`` + expand ([type], optional): The value for the expand property in the Resource's + ``find()`` params. Defaults to None. + + Raises: + JIRAError: If the Resource cannot be found + + Returns: + Any: A class of the same type as ``resource_cls`` + """ resource = resource_cls(self._options, self._session) params = {} if expand is not None: params["expand"] = expand resource.find(id=ids, params=params) if not resource: - raise JIRAError("Unable to find resource %s(%s)", resource_cls, ids) + raise JIRAError("Unable to find resource %s(%s)", resource_cls, str(ids)) return resource def _try_magic(self): try: - import magic import weakref + + import magic except ImportError: self._magic = None else: @@ -3164,43 +3500,43 @@ def cleanup(x): except AttributeError: self._magic = None - def _get_mime_type(self, buff): + def _get_mime_type(self, buff: bytes) -> Optional[str]: """Get the MIME type for a given stream of bytes - :param buff: Stream of bytes - :type buff: bytes + Args: + buff (bytes): Stream of bytes - :rtype: str + Returns: + Optional[str]: the MIME type """ if self._magic is not None: return self._magic.id_buffer(buff) else: try: - return mimetypes.guess_type("f." + imghdr.what(0, buff))[0] - except (IOError, TypeError): - logging.warning( + return mimetypes.guess_type("f." + str(imghdr.what(0, buff)))[0] + except (OSError, TypeError): + self.log.warning( "Couldn't detect content type of avatar image" ". Specify the 'contentType' parameter explicitly." ) return None - def rename_user(self, old_user, new_user): + def rename_user(self, old_user: str, new_user: str): """Rename a Jira user. - :param old_user: Old username login - :type old_user: str - :param new_user: New username login - :type new_user: str + Args: + old_user (str): Old username login + new_user (str): New username login """ if self._version > (6, 0, 0): - url = self._options["server"] + "/rest/api/latest/user" + url = self._get_latest_url("user") payload = {"name": new_user} params = {"username": old_user} # raw displayName - logging.debug("renaming %s" % self.user(old_user).emailAddress) + self.log.debug(f"renaming {self.user(old_user).emailAddress}") r = self._session.put(url, params=params, data=json.dumps(payload)) raise_on_error(r) @@ -3209,47 +3545,49 @@ def rename_user(self, old_user, new_user): "Support for renaming users in Jira " "< 6.0.0 has been removed." ) - def delete_user(self, username): + def delete_user(self, username: str) -> bool: """Deletes a Jira User. - :param username: Username to delete - :type username: str + Args: + username (str): Username to delete - :return: Success of user deletion - :rtype: bool + Returns: + bool: Success of user deletion """ - url = self._options["server"] + "/rest/api/latest/user/?username=%s" % username + url = self._get_latest_url(f"user/?username={username}") r = self._session.delete(url) if 200 <= r.status_code <= 299: return True else: - logging.error(r.status_code) + self.log.error(r.status_code) return False - def deactivate_user(self, username): + def deactivate_user(self, username: str) -> Union[str, int]: """Disable/deactivate the user. - :param username: User to be deactivated. - :type username: str + Args: + username (str): User to be deactivated. - :rtype: Union[str, int] + Returns: + Union[str, int] """ - if self.deploymentType == "Cloud": + if self._is_cloud: # Disabling users now needs cookie auth in the Cloud - see https://jira.atlassian.com/browse/ID-6230 if "authCookie" not in vars(self): user = self.session() if user.raw is None: raise JIRAError("Can not log in!") - self.authCookie = "%s=%s" % ( + self.authCookie = "{}={}".format( user.raw["session"]["name"], user.raw["session"]["value"], ) - url = self._options[ - "server" - ] + "/admin/rest/um/1/user/deactivate?username=%s" % (username) + url = ( + self._options["server"] + + f"/admin/rest/um/1/user/deactivate?username={username}" + ) # We can't use our existing session here - this endpoint is fragile and objects to extra headers try: r = requests.post( @@ -3264,16 +3602,15 @@ def deactivate_user(self, username): if r.status_code == 200: return True else: - logging.warning( - "Got response from deactivating %s: %s" - % (username, r.status_code) + self.log.warning( + f"Got response from deactivating {username}: {r.status_code}" ) return r.status_code except Exception as e: - logging.error("Error Deactivating %s: %s" % (username, e)) - raise JIRAError("Error Deactivating %s: %s" % (username, e)) + self.log.error(f"Error Deactivating {username}: {e}") + raise JIRAError(f"Error Deactivating {username}: {e}") else: - url = self._options["server"] + "/secure/admin/user/EditUser.jspa" + url = self.server_url + "/secure/admin/user/EditUser.jspa" self._options["headers"][ "Content-Type" ] = "application/x-www-form-urlencoded; charset=UTF-8" @@ -3293,22 +3630,25 @@ def deactivate_user(self, username): if r.status_code == 200: return True else: - logging.warning( - "Got response from deactivating %s: %s" - % (username, r.status_code) + self.log.warning( + f"Got response from deactivating {username}: {r.status_code}" ) return r.status_code except Exception as e: - logging.error("Error Deactivating %s: %s" % (username, e)) - raise JIRAError("Error Deactivating %s: %s" % (username, e)) + self.log.error(f"Error Deactivating {username}: {e}") + raise JIRAError(f"Error Deactivating {username}: {e}") - def reindex(self, force=False, background=True): + def reindex(self, force: bool = False, background: bool = True) -> bool: """Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False. If you call reindex() without any parameters it will perform a background reindex only if Jira thinks it should do it. - :param force: reindex even if Jira doesn't say this is needed, False by default. - :param background: reindex in background, slower but does not impact the users, defaults to True. + Args: + force (bool): reindex even if Jira doesn't say this is needed, False by default. + background (bool): reindex in background, slower but does not impact the users, defaults to True. + + Returns: + bool: Returns True if reindexing is in progress or not needed, or False. """ # /secure/admin/IndexAdmin.jspa # /secure/admin/jira/IndexProgress.jspa?taskId=1 @@ -3317,12 +3657,12 @@ def reindex(self, force=False, background=True): else: indexingStrategy = "stoptheworld" - url = self._options["server"] + "/secure/admin/jira/IndexReIndex.jspa" + url = self.server_url + "/secure/admin/jira/IndexReIndex.jspa" r = self._session.get(url, headers=self._options["headers"]) if r.status_code == 503: - # logging.warning("Jira returned 503, this could mean that a full reindex is in progress.") - return 503 + # self.log.warning("Jira returned 503, this could mean that a full reindex is in progress.") + return 503 # type: ignore # FIXME: is this a bug? if ( not r.text.find("To perform the re-index now, please go to the") @@ -3331,7 +3671,7 @@ def reindex(self, force=False, background=True): return True if r.text.find("All issues are being re-indexed"): - logging.warning("Jira re-indexing is already running.") + self.log.warning("Jira re-indexing is already running.") return True # still reindexing is considered still a success if r.text.find("To perform the re-index now, please go to the") or force: @@ -3342,28 +3682,29 @@ def reindex(self, force=False, background=True): ) if r.text.find("All issues are being re-indexed") != -1: return True - else: - logging.error("Failed to reindex jira, probably a bug.") - return False - def backup(self, filename="backup.zip", attachments=False): + self.log.error("Failed to reindex jira, probably a bug.") + return False + + def backup(self, filename: str = "backup.zip", attachments: bool = False): """Will call jira export to backup as zipped xml. Returning with success does not mean that the backup process finished.""" - if self.deploymentType == "Cloud": - url = self._options["server"] + "/rest/backup/1/export/runbackup" + payload: Any # _session.post is pretty open + if self._is_cloud: + url = self.server_url + "/rest/backup/1/export/runbackup" payload = json.dumps({"cbAttachments": attachments}) self._options["headers"]["X-Requested-With"] = "XMLHttpRequest" else: - url = self._options["server"] + "/secure/admin/XmlBackup.jspa" + url = self.server_url + "/secure/admin/XmlBackup.jspa" payload = {"filename": filename} try: r = self._session.post(url, headers=self._options["headers"], data=payload) if r.status_code == 200: return True else: - logging.warning("Got %s response from calling backup." % r.status_code) + self.log.warning(f"Got {r.status_code} response from calling backup.") return r.status_code except Exception as e: - logging.error("I see %s", e) + self.log.error("I see %s", e) def backup_progress(self): """Return status of cloud backup as a dict. @@ -3371,12 +3712,10 @@ def backup_progress(self): Is there a way to get progress for Server version? """ epoch_time = int(time.time() * 1000) - if self.deploymentType == "Cloud": - url = ( - self._options["server"] + "/rest/obm/1.0/getprogress?_=%i" % epoch_time - ) + if self._is_cloud: + url = self.server_url + "/rest/obm/1.0/getprogress?_=%i" % epoch_time else: - logging.warning("This functionality is not available in Server version") + self.log.warning("This functionality is not available in Server version") return None r = self._session.get(url, headers=self._options["headers"]) # This is weird. I used to get xml, but now I'm getting json @@ -3389,7 +3728,7 @@ def backup_progress(self): try: root = etree.fromstring(r.text) except etree.ParseError as pe: - logging.warning( + self.log.warning( "Unable to find backup info. You probably need to initiate a new backup. %s" % pe ) @@ -3398,28 +3737,29 @@ def backup_progress(self): progress[k] = root.get(k) return progress - def backup_complete(self): + def backup_complete(self) -> Optional[bool]: """Return boolean based on 'alternativePercentage' and 'size' returned from backup_progress (cloud only).""" - if self.deploymentType != "Cloud": - logging.warning("This functionality is not available in Server version") + if not self._is_cloud: + self.log.warning("This functionality is not available in Server version") return None status = self.backup_progress() + perc_search = re.search(r"\s([0-9]*)\s", status["alternativePercentage"]) perc_complete = int( - re.search(r"\s([0-9]*)\s", status["alternativePercentage"]).group(1) + perc_search.group(1) # type: ignore # ignore that re.search can return None ) file_size = int(status["size"]) return perc_complete >= 100 and file_size > 0 - def backup_download(self, filename=None): + def backup_download(self, filename: str = None): """Download backup file from WebDAV (cloud only).""" - if self.deploymentType != "Cloud": - logging.warning("This functionality is not available in Server version") + if not self._is_cloud: + self.log.warning("This functionality is not available in Server version") return None remote_file = self.backup_progress()["fileName"] local_file = filename or remote_file - url = self._options["server"] + "/webdav/backupmanager/" + remote_file + url = self.server_url + "/webdav/backupmanager/" + remote_file try: - logging.debug("Writing file to %s" % local_file) + self.log.debug(f"Writing file to {local_file}") with open(local_file, "wb") as file: try: resp = self._session.get( @@ -3428,47 +3768,51 @@ def backup_download(self, filename=None): except Exception: raise JIRAError() if not resp.ok: - logging.error("Something went wrong with download: %s" % resp.text) + self.log.error(f"Something went wrong with download: {resp.text}") raise JIRAError(resp.text) for block in resp.iter_content(1024): file.write(block) except JIRAError as je: - logging.error("Unable to access remote backup file: %s" % je) - except IOError as ioe: - logging.error(ioe) + self.log.error(f"Unable to access remote backup file: {je}") + except OSError as ioe: + self.log.error(ioe) return None - def current_user(self, field="key"): + def current_user(self, field: str = "key") -> str: """Returns the username or emailAddress of the current user. For anonymous users it will return a value that evaluates as False. - :rtype: str + Returns: + str """ if not hasattr(self, "_myself"): url = self._get_url("myself") r = self._session.get(url, headers=self._options["headers"]) - r_json = json_loads(r) + r_json: Dict[str, str] = json_loads(r) self._myself = r_json return self._myself[field] - def delete_project(self, pid): + def delete_project(self, pid: Union[str, Project]) -> Optional[bool]: """Delete project from Jira. - :param pid: Jira projectID or Project or slug - :type pid: str - :return: True if project was deleted - :rtype: bool - :raises JIRAError: If project not found or not enough permissions - :raises ValueError: If pid parameter is not Project, slug or ProjectID + Args: + pid (Union[str, Project]): Jira projectID or Project or slug + + Raises: + JIRAError: If project not found or not enough permissions + ValueError: If pid parameter is not Project, slug or ProjectID + + Returns: + bool: True if project was deleted """ # allows us to call it with Project objects - if hasattr(pid, "id"): - pid = pid.id + if isinstance(pid, Project) and hasattr(pid, "id"): + pid = str(pid.id) - url = self._options["server"] + "/rest/api/2/project/%s" % pid + url = self._get_url(f"project/{pid}") r = self._session.delete(url) if r.status_code == 403: raise JIRAError("Not enough permissions to delete project") @@ -3477,7 +3821,7 @@ def delete_project(self, pid): return r.ok def _gain_sudo_session(self, options, destination): - url = self._options["server"] + "/secure/admin/WebSudoAuthenticate.jspa" + url = self.server_url + "/secure/admin/WebSudoAuthenticate.jspa" if not self._session.auth: self._session.auth = get_netrc_auth(url) @@ -3499,12 +3843,12 @@ def _gain_sudo_session(self, options, destination): ) @lru_cache(maxsize=None) - def templates(self): + def templates(self) -> Dict: - url = self._options["server"] + "/rest/project-templates/latest/templates" + url = self.server_url + "/rest/project-templates/latest/templates" r = self._session.get(url) - data = json_loads(r) + data: Dict[str, Any] = json_loads(r) templates = {} if "projectTemplatesGroupedByType" in data: @@ -3517,27 +3861,27 @@ def templates(self): @lru_cache(maxsize=None) def permissionschemes(self): - url = self._options["server"] + "/rest/api/3/permissionscheme" + url = self._get_url("permissionscheme") r = self._session.get(url) - data = json_loads(r)["permissionSchemes"] + data: Dict[str, Any] = json_loads(r) - return data + return data["permissionSchemes"] @lru_cache(maxsize=None) def issuesecurityschemes(self): - url = self._options["server"] + "/rest/api/3/issuesecurityschemes" + url = self._get_url("issuesecurityschemes") r = self._session.get(url) - data = json_loads(r)["issueSecuritySchemes"] + data: Dict[str, Any] = json_loads(r) - return data + return data["issueSecuritySchemes"] @lru_cache(maxsize=None) def projectcategories(self): - url = self._options["server"] + "/rest/api/3/projectCategory" + url = self._get_url("projectCategory") r = self._session.get(url) data = json_loads(r) @@ -3547,35 +3891,35 @@ def projectcategories(self): @lru_cache(maxsize=None) def avatars(self, entity="project"): - url = self._options["server"] + "/rest/api/3/avatar/%s/system" % entity + url = self._get_url(f"avatar/{entity}/system") r = self._session.get(url) - data = json_loads(r)["system"] + data: Dict[str, Any] = json_loads(r) - return data + return data["system"] @lru_cache(maxsize=None) def notificationschemes(self): # TODO(ssbarnea): implement pagination support - url = self._options["server"] + "/rest/api/3/notificationscheme" + url = self._get_url("notificationscheme") r = self._session.get(url) - data = json_loads(r) + data: Dict[str, Any] = json_loads(r) return data["values"] @lru_cache(maxsize=None) def screens(self): # TODO(ssbarnea): implement pagination support - url = self._options["server"] + "/rest/api/3/screens" + url = self._get_url("screens") r = self._session.get(url) - data = json_loads(r) + data: Dict[str, Any] = json_loads(r) return data["values"] @lru_cache(maxsize=None) def workflowscheme(self): # TODO(ssbarnea): implement pagination support - url = self._options["server"] + "/rest/api/3/workflowschemes" + url = self._get_url("workflowschemes") r = self._session.get(url) data = json_loads(r) @@ -3584,15 +3928,15 @@ def workflowscheme(self): @lru_cache(maxsize=None) def workflows(self): # TODO(ssbarnea): implement pagination support - url = self._options["server"] + "/rest/api/3/workflow" + url = self._get_url("workflow") r = self._session.get(url) data = json_loads(r) return data # ['values'] - def delete_screen(self, id): + def delete_screen(self, id: str): - url = self._options["server"] + "/rest/api/3/screens/%s" % id + url = self._get_url(f"screens/{id}") r = self._session.delete(url) data = json_loads(r) @@ -3600,9 +3944,9 @@ def delete_screen(self, id): self.screens.cache_clear() return data - def delete_permissionscheme(self, id): + def delete_permissionscheme(self, id: str): - url = self._options["server"] + "/rest/api/3/permissionscheme/%s" % id + url = self._get_url(f"permissionscheme/{id}") r = self._session.delete(url) data = json_loads(r) @@ -3612,44 +3956,42 @@ def delete_permissionscheme(self, id): def create_project( self, - key, - name=None, - assignee=None, - ptype="software", - template_name=None, + key: str, + name: str = None, + assignee: str = None, + ptype: str = "software", + template_name: str = None, avatarId=None, issueSecurityScheme=None, permissionScheme=None, projectCategory=None, notificationScheme=10000, categoryId=None, - url="", + url: str = "", ): """Create a project with the specified parameters. - :param key: Mandatory. Must match Jira project key requirements, usually only 2-10 uppercase characters. - :type: str - :param name: If not specified it will use the key value. - :type name: Optional[str] - :param assignee: accountId of the lead, if not specified it will use current user. - :type assignee: Optional[str] - :param type: Determines the type of project should be created. - :type ptype: Optional[str] - :param template_name: is used to create a project based on one of the existing project templates. - If `template_name` is not specified, then it should use one of the default values. - :type template_name: Optional[str] + Args: + key (str): Mandatory. Must match Jira project key requirements, usually only 2-10 uppercase characters. + name (Optional[str]): If not specified it will use the key value. + assignee (Optional[str]): key of the lead, if not specified it will use current user. + ptype (Optional[str]): Determines the type of project should be created. + template_name (Optional[str]): is used to create a project based on one of the existing project templates. + If `template_name` is not specified, then it should use one of the default values. - :return: Should evaluate to False if it fails otherwise it will be the new project id. - :rtype: Union[bool,int] + Returns: + Union[bool,int]: Should evaluate to False if it fails otherwise it will be the new project id. """ template_key = None if assignee is None: - assignee = self.current_user("accountId") + assignee = self.current_user() if name is None: name = key + ps_list: List[Dict[str, Any]] + if not permissionScheme: ps_list = self.permissionschemes() for sec in ps_list: @@ -3682,8 +4024,12 @@ def create_project( # https://jira.atlassian.com/browse/JRASERVER-59658 # preference list for picking a default template if not template_name: - template_key = "com.pyxis.greenhopper.jira:gh-simplified-basic" + # https://confluence.atlassian.com/jirakb/creating-projects-via-rest-api-in-jira-963651978.html + template_key = ( + "com.pyxis.greenhopper.jira:basic-software-development-template" + ) + # https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-projects/#api-rest-api-2-project-get # template_keys = [ # "com.pyxis.greenhopper.jira:gh-simplified-agility-kanban", # "com.pyxis.greenhopper.jira:gh-simplified-agility-scrum", @@ -3743,7 +4089,8 @@ def create_project( "key": key, "projectTypeKey": ptype, "projectTemplateKey": template_key, - "leadAccountId": assignee, + "lead": assignee, + # "leadAccountId": assignee, "assigneeType": "PROJECT_LEAD", "description": "", # "avatarId": 13946, @@ -3756,7 +4103,7 @@ def create_project( if projectCategory: payload["categoryId"] = int(projectCategory) - url = self._options["server"] + "/rest/api/3/project" + url = self._get_url("project") r = self._session.post(url, data=json.dumps(payload)) r.raise_for_status() @@ -3765,52 +4112,46 @@ def create_project( def add_user( self, - username, - email, - directoryId=1, - password=None, - fullname=None, - notify=False, - active=True, - ignore_existing=False, - application_keys=None, + username: str, + email: str, + directoryId: int = 1, + password: str = None, + fullname: str = None, + notify: bool = False, + active: bool = True, + ignore_existing: bool = False, + application_keys: Optional[List] = None, ): """Create a new Jira user. - :param username: the username of the new user - :type username: str - :param email: email address of the new user - :type email: str - :param directoryId: The directory ID the new user should be a part of (Default: 1) - :type directoryId: int - :param password: Optional, the password for the new user - :type password: Optional[str] - :param fullname: Optional, the full name of the new user - :type fullname: Optional[str] - :param notify: Whether or not to send a notification to the new user. (Default: False) - :type notify: bool - :param active: Whether or not to make the new user active upon creation. (Default: True) - :type active: bool - :param ignore_existing: Whether or not to ignore and existing user. (Default: False) - :type ignore_existing: bool - :param applicationKeys: Keys of products user should have access to - :type applicationKeys: Optional[list] - - :return: Whether or not the user creation was successful. - :rtype: bool - - :raises JIRAError: If username already exists and `ignore_existing` has not been set to `True`. + Args: + username (str): the username of the new user + email (str): email address of the new user + directoryId (int): The directory ID the new user should be a part of (Default: 1) + password (Optional[str]): Optional, the password for the new user + fullname (Optional[str]): Optional, the full name of the new user + notify (bool): Whether or not to send a notification to the new user. (Default: False) + active (bool): Whether or not to make the new user active upon creation. (Default: True) + ignore_existing (bool): Whether or not to ignore and existing user. (Default: False) + applicationKeys (Optional[list]): Keys of products user should have access to + + Raises: + JIRAError: If username already exists and `ignore_existing` has not been set to `True`. + + Returns: + bool: Whether or not the user creation was successful. + """ if not fullname: fullname = username # TODO(ssbarnea): default the directoryID to the first directory in jira instead # of 1 which is the internal one. - url = self._options["server"] + "/rest/api/latest/user" + url = self._get_latest_url("user") # implementation based on # https://docs.atlassian.com/jira/REST/ondemand/#d2e5173 - x = OrderedDict() + x: Dict[str, Any] = OrderedDict() x["displayName"] = fullname x["emailAddress"] = email @@ -3826,73 +4167,77 @@ def add_user( try: self._session.post(url, data=payload) except JIRAError as e: - err = e.response.json()["errors"] - if ( - "username" in err - and err["username"] == "A user with that username already exists." - and ignore_existing - ): - return True + if e.response: + err = e.response.json()["errors"] + if ( + "username" in err + and err["username"] == "A user with that username already exists." + and ignore_existing + ): + return True raise e return True - def add_user_to_group(self, username, group): + def add_user_to_group( + self, username: str, group: str + ) -> Union[bool, Dict[str, Any]]: """Add a user to an existing group. - :param username: Username that will be added to specified group. - :type username: str - :param group: Group that the user will be added to. - :type group: str + Args: + username (str): Username that will be added to specified group. + group (str): Group that the user will be added to. - :return: json response from Jira server for success or a value that evaluates as False in case of failure. - :rtype: Union[bool,Dict[str,Any]] + Returns: + Union[bool,Dict[str,Any]]: json response from Jira server for success or a value that evaluates as False in case of failure. """ - url = self._options["server"] + "/rest/api/latest/group/user" + url = self._get_latest_url("group/user") x = {"groupname": group} y = {"name": username} payload = json.dumps(y) - r = json_loads(self._session.post(url, params=x, data=payload)) + r: Dict[str, Any] = json_loads(self._session.post(url, params=x, data=payload)) if "name" not in r or r["name"] != group: return False else: return r - def remove_user_from_group(self, username, groupname): + def remove_user_from_group(self, username: str, groupname: str): """Remove a user from a group. - :param username: The user to remove from the group. - :param groupname: The group that the user will be removed from. + Args: + username (str): The user to remove from the group. + groupname (str): The group that the user will be removed from. """ - url = self._options["server"] + "/rest/api/latest/group/user" + url = self._get_latest_url("group/user") x = {"groupname": groupname, "username": username} self._session.delete(url, params=x) return True - def role(self): + def role(self) -> List[Dict[str, Any]]: """Return Jira role information. - :return: List of current user roles - :rtype: Iterable + Returns: + List[Dict[str,Any]]: List of current user roles """ # https://developer.atlassian.com/cloud/jira/platform/rest/v3/?utm_source=%2Fcloud%2Fjira%2Fplatform%2Frest%2F&utm_medium=302#api-rest-api-3-role-get - url = self._options["server"] + "/rest/api/latest/role" + url = self._get_latest_url("role") r = self._session.get(url) - return json_loads(r) + data: List[Dict[str, Any]] = json_loads(r) + return data # Experimental # Experimental support for iDalko Grid, expect API to change as it's using private APIs currently # https://support.idalko.com/browse/IGRID-1017 - def get_igrid(self, issueid, customfield, schemeid): - url = self._options["server"] + "/rest/idalko-igrid/1.0/datagrid/data" + def get_igrid(self, issueid: str, customfield: str, schemeid: str): + url = self.server_url + "/rest/idalko-igrid/1.0/datagrid/data" if str(customfield).isdigit(): - customfield = "customfield_%s" % customfield + customfield = f"customfield_{customfield}" params = { "_issueId": issueid, "_fieldId": customfield, @@ -3908,16 +4253,24 @@ def get_igrid(self, issueid, customfield, schemeid): @translate_resource_args def boards( - self, startAt=0, maxResults=50, type=None, name=None, projectKeyOrID=None - ): + self, + startAt: int = 0, + maxResults: int = 50, + type: str = None, + name: str = None, + projectKeyOrID=None, + ) -> ResultList[Board]: """Get a list of board resources. - :param startAt: The starting index of the returned boards. Base index: 0. - :param maxResults: The maximum number of boards to return per page. Default: 50 - :param type: Filters results to boards of the specified type. Valid values: scrum, kanban. - :param name: Filters results to boards that match or partially match the specified name. - :param projectKeyOrID: Filters results to boards that match the specified project key or ID. - :rtype: ResultList[Board] + Args: + startAt: The starting index of the returned boards. Base index: 0. + maxResults: The maximum number of boards to return per page. Default: 50 + type: Filters results to boards of the specified type. Valid values: scrum, kanban. + name: Filters results to boards that match or partially match the specified name. + projectKeyOrID: Filters results to boards that match the specified project key or ID. + + Returns: + ResultList[Board] When old GreenHopper private API is used, paging is not enabled and all parameters are ignored. """ @@ -3941,7 +4294,9 @@ def boards( Warning, ) - r_json = self._get_json("rapidviews/list", base=self.AGILE_BASE_URL) + r_json: Dict[str, Any] = self._get_json( + "rapidviews/list", base=self.AGILE_BASE_URL + ) boards = [ Board(self._options, self._session, raw_boards_json) for raw_boards_json in r_json["views"] @@ -3959,26 +4314,28 @@ def boards( ) @translate_resource_args - def sprints(self, board_id, extended=False, startAt=0, maxResults=50, state=None): + def sprints( + self, + board_id: int, + extended: bool = False, + startAt: int = 0, + maxResults: int = 50, + state: str = None, + ) -> ResultList[Sprint]: """Get a list of sprint GreenHopperResources. - :param board_id: the board to get sprints from - :param extended: Used only by old GreenHopper API to fetch additional information like - startDate, endDate, completeDate, much slower because it requires an additional requests for each sprint. - New Jira Agile API always returns this information without a need for additional requests. - :param startAt: the index of the first sprint to return (0 based) - :param maxResults: the maximum number of sprints to return - :param state: Filters results to sprints in specified states. Valid values: `future`, `active`, `closed`. - You can define multiple states separated by commas - - :type board_id: int - :type extended: bool - :type startAt: int - :type maxResults: int - :type state: str - - :rtype: list of :class:`~jira.resources.Sprint` - :return: (content depends on API version, but always contains id, name, state, startDate and endDate) + Args: + board_id (int): the board to get sprints from + extended (bool): Used only by old GreenHopper API to fetch additional information like + startDate, endDate, completeDate, much slower because it requires an additional requests for each sprint. + New Jira Agile API always returns this information without a need for additional requests. + startAt (int): the index of the first sprint to return (0 based) + maxResults (int): the maximum number of sprints to return + state (str): Filters results to sprints in specified states. Valid values: `future`, `active`, `closed`. + You can define multiple states separated by commas + + Returns: + ResultList[Sprint]: (content depends on API version, but always contains id, name, state, startDate and endDate) When old GreenHopper private API is used, paging is not enabled, and `startAt`, `maxResults` and `state` parameters are ignored. """ @@ -3990,7 +4347,7 @@ def sprints(self, board_id, extended=False, startAt=0, maxResults=50, state=None self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): - r_json = self._get_json( + r_json: Dict[str, Any] = self._get_json( "sprintquery/%s?includeHistoricSprints=true&includeFutureSprints=true" % board_id, base=self.AGILE_BASE_URL, @@ -4008,7 +4365,7 @@ def sprints(self, board_id, extended=False, startAt=0, maxResults=50, state=None Sprint( self._options, self._session, - self.sprint_info(None, raw_sprints_json["id"]), + self.sprint_info("", raw_sprints_json["id"]), ) for raw_sprints_json in r_json["sprints"] ] @@ -4023,7 +4380,7 @@ def sprints(self, board_id, extended=False, startAt=0, maxResults=50, state=None return self._fetch_pages( Sprint, "values", - "board/%s/sprint" % board_id, + f"board/{board_id}/sprint", startAt, maxResults, params, @@ -4057,24 +4414,23 @@ def update_sprint(self, id, name=None, startDate=None, endDate=None, state=None) ) payload["state"] = state - url = self._get_url("sprint/%s" % id, base=self.AGILE_BASE_URL) + url = self._get_url(f"sprint/{id}", base=self.AGILE_BASE_URL) r = self._session.put(url, data=json.dumps(payload)) return json_loads(r) - def incompletedIssuesEstimateSum(self, board_id, sprint_id): + def incompletedIssuesEstimateSum(self, board_id: str, sprint_id: str): """Return the total incompleted points this sprint.""" - return self._get_json( - "rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s" - % (board_id, sprint_id), + data: Dict[str, Any] = self._get_json( + f"rapid/charts/sprintreport?rapidViewId={board_id}&sprintId={sprint_id}", base=self.AGILE_BASE_URL, - )["contents"]["incompletedIssuesEstimateSum"]["value"] + ) + return data["contents"]["incompletedIssuesEstimateSum"]["value"] - def removed_issues(self, board_id, sprint_id): + def removed_issues(self, board_id: str, sprint_id: str): """Return the completed issues for the sprint.""" - r_json = self._get_json( - "rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s" - % (board_id, sprint_id), + r_json: Dict[str, Any] = self._get_json( + f"rapid/charts/sprintreport?rapidViewId={board_id}&sprintId={sprint_id}", base=self.AGILE_BASE_URL, ) issues = [ @@ -4084,33 +4440,34 @@ def removed_issues(self, board_id, sprint_id): return issues - def removedIssuesEstimateSum(self, board_id, sprint_id): + def removedIssuesEstimateSum(self, board_id: str, sprint_id: str): """Return the total incompleted points this sprint.""" - return self._get_json( - "rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s" - % (board_id, sprint_id), + data: Dict[str, Any] = self._get_json( + f"rapid/charts/sprintreport?rapidViewId={board_id}&sprintId={sprint_id}", base=self.AGILE_BASE_URL, - )["contents"]["puntedIssuesEstimateSum"]["value"] + ) + return data["contents"]["puntedIssuesEstimateSum"]["value"] # TODO(ssbarnea): remove sprint_info() method, sprint() method suit the convention more - def sprint_info(self, board_id, sprint_id): + def sprint_info(self, board_id: str, sprint_id: str) -> Optional[Dict[str, Any]]: """Return the information about a sprint. - :param board_id: the board retrieving issues from. Deprecated and ignored. - :param sprint_id: the sprint retrieving issues from + Args: + board_id (str): the board retrieving issues from. Deprecated and ignored. + sprint_id (str): the sprint retrieving issues from """ sprint = Sprint(self._options, self._session) sprint.find(sprint_id) return sprint.raw - def sprint(self, id): + def sprint(self, id: int) -> Sprint: """Return the information about a sprint. - :param sprint_id: the sprint retrieving issues from - - :type sprint_id: int + Args: + sprint_id (int): the sprint retrieving issues from - :rtype: :class:`~jira.resources.Sprint` + Returns: + Sprint """ sprint = Sprint(self._options, self._session) sprint.find(id) @@ -4123,24 +4480,25 @@ def delete_board(self, id): board.delete() def create_board( - self, name, project_ids, preset="scrum", location_type="user", location_id=None - ): + self, + name: str, + project_ids: Union[str, List[str]], + preset: str = "scrum", + location_type: str = "user", + location_id: Optional[str] = None, + ) -> Board: """Create a new board for the ``project_ids``. - :param name: name of the board - :type name: str - :param project_ids: the projects to create the board in - :type project_ids: str - :param preset: What preset to use for this board. (Default: scrum) - :type preset: kanban, scrum, diy - :param location_type: the location type. Available in cloud. (Default: user) - :type location_type: user, project - :param location_id: the id of project that the board should be - located under. Omit this for a 'user' location_type. Available in cloud. - :type location_id: Optional[str] - - :return: The newly created board - :rtype: Board + Args: + name (str): name of the board + project_ids (str): the projects to create the board in + preset (str): What preset to use for this board, options: kanban, scrum, diy. (Default: scrum) + location_type (str): the location type. Available in cloud. (Default: user) + location_id (Optional[str]): the id of project that the board should be located under. + Omit this for a 'user' location_type. Available in cloud. + + Returns: + Board: The newly created board """ if ( self._options["agile_rest_path"] @@ -4150,7 +4508,7 @@ def create_board( "Jira Agile Public API does not support this request" ) - payload = {} + payload: Dict[str, Any] = {} if isinstance(project_ids, str): ids = [] for p in project_ids.split(","): @@ -4160,10 +4518,10 @@ def create_board( location_id = self.project(location_id).id payload["name"] = name if isinstance(project_ids, str): - project_ids = project_ids.split(",") + project_ids = project_ids.split(",") # type: ignore # re-use of variable payload["projectIds"] = project_ids payload["preset"] = preset - if self.deploymentType == "Cloud": + if self._is_cloud: payload["locationType"] = location_type payload["locationId"] = location_id url = self._get_url("rapidview/create/presets", base=self.AGILE_BASE_URL) @@ -4172,32 +4530,36 @@ def create_board( raw_issue_json = json_loads(r) return Board(self._options, self._session, raw=raw_issue_json) - def create_sprint(self, name, board_id, startDate=None, endDate=None): + def create_sprint( + self, + name: str, + board_id: int, + startDate: Optional[Any] = None, + endDate: Optional[Any] = None, + ) -> Sprint: """Create a new sprint for the ``board_id``. - :param name: Name of the sprint - :type name: str - :param board_id: Which board the sprint should be assigned. - :type board_id: int - :param startDate: Start date for the sprint. - :type startDate: Optional[Any] - :param endDate: End date for the sprint. - :type endDate: Optional[Any] + Args: + name (str): Name of the sprint + board_id (int): Which board the sprint should be assigned. + startDate (Optional[Any]): Start date for the sprint. + endDate (Optional[Any]): End date for the sprint. - :return: The newly created Sprint - :rtype: Sprint + Returns: + Sprint: The newly created Sprint """ - payload = {"name": name} + payload: Dict[str, Any] = {"name": name} if startDate: payload["startDate"] = startDate if endDate: payload["endDate"] = endDate + raw_issue_json: Dict[str, Any] if ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): - url = self._get_url("sprint/%s" % board_id, base=self.AGILE_BASE_URL) + url = self._get_url(f"sprint/{board_id}", base=self.AGILE_BASE_URL) r = self._session.post(url) raw_issue_json = json_loads(r) """ now r contains something like: @@ -4213,7 +4575,7 @@ def create_sprint(self, name, board_id, startDate=None, endDate=None): }""" url = self._get_url( - "sprint/%s" % raw_issue_json["id"], base=self.AGILE_BASE_URL + f"sprint/{raw_issue_json['id']}", base=self.AGILE_BASE_URL ) r = self._session.put(url, data=json.dumps(payload)) raw_issue_json = json_loads(r) @@ -4225,7 +4587,7 @@ def create_sprint(self, name, board_id, startDate=None, endDate=None): return Sprint(self._options, self._session, raw=raw_issue_json) - def add_issues_to_sprint(self, sprint_id, issue_keys): + def add_issues_to_sprint(self, sprint_id: int, issue_keys: List[str]) -> Response: """Add the issues in ``issue_keys`` to the ``sprint_id``. The sprint must be started but not completed. @@ -4238,18 +4600,18 @@ def add_issues_to_sprint(self, sprint_id, issue_keys): If a sprint was not started, then have to edit the marker and copy the rank of each issue too. - :param sprint_id: the sprint to add issues to - :type sprint_id: int - :param issue_keys: the issues to add to the sprint - :type issue_keys: List[str] + Args: + sprint_id (int): the sprint to add issues to + issue_keys (List[str]): the issues to add to the sprint - :rtype: Response + Returns: + Response """ if self._options["agile_rest_path"] == GreenHopperResource.AGILE_BASE_REST_PATH: - url = self._get_url("sprint/%s/issue" % sprint_id, base=self.AGILE_BASE_URL) + url = self._get_url(f"sprint/{sprint_id}/issue", base=self.AGILE_BASE_URL) payload = {"issues": issue_keys} try: - self._session.post(url, data=json.dumps(payload)) + return self._session.post(url, data=json.dumps(payload)) except JIRAError as e: if e.status_code == 404: warnings.warn( @@ -4281,15 +4643,15 @@ def add_issues_to_sprint(self, sprint_id, issue_keys): % self._options["agile_rest_path"] ) - def add_issues_to_epic(self, epic_id, issue_keys, ignore_epics=True): + def add_issues_to_epic( + self, epic_id: str, issue_keys: str, ignore_epics: bool = True + ) -> Response: """Add the issues in ``issue_keys`` to the ``epic_id``. - :param epic_id: The ID for the epic where issues should be added. - :type epic_id: int - :param issue_keys: The issues to add to the epic - :type issue_keys: str - :param ignore_epics: ignore any issues listed in ``issue_keys`` that are epics. (Default: True) - :type ignore_epics: bool + Args: + epic_id (str): The ID for the epic where issues should be added. + issue_keys (str): The issues to add to the epic + ignore_epics (bool): ignore any issues listed in ``issue_keys`` that are epics. (Default: True) """ if ( @@ -4301,18 +4663,19 @@ def add_issues_to_epic(self, epic_id, issue_keys, ignore_epics=True): "Jira Agile Public API does not support this request" ) - data = {} + data: Dict[str, Any] = {} data["issueKeys"] = issue_keys data["ignoreEpics"] = ignore_epics - url = self._get_url("epics/%s/add" % epic_id, base=self.AGILE_BASE_URL) + url = self._get_url(f"epics/{epic_id}/add", base=self.AGILE_BASE_URL) return self._session.put(url, data=json.dumps(data)) # TODO(ssbarnea): Both GreenHopper and new Jira Agile API support moving more than one issue. - def rank(self, issue, next_issue): + def rank(self, issue: str, next_issue: str) -> Response: """Rank an issue before another using the default Ranking field, the one named 'Rank'. - :param issue: issue key of the issue to be ranked before the second one. - :param next_issue: issue key of the second issue. + Args: + issue (str): issue key of the issue to be ranked before the second one. + next_issue (str): issue key of the second issue. """ if not self._rank: for field in self.fields(): @@ -4363,19 +4726,20 @@ def rank(self, issue, next_issue): % self._options["agile_rest_path"] ) - def move_to_backlog(self, issue_keys): + def move_to_backlog(self, issue_keys: str) -> Response: """Move issues in ``issue_keys`` to the backlog, removing them from all sprints that have not been completed. - :param issue_keys: the issues to move to the backlog - :param issue_keys: str + Args: + issue_keys (str): the issues to move to the backlog - :raises JIRAError: If moving issues to backlog fails + Raises: + JIRAError: If moving issues to backlog fails """ if self._options["agile_rest_path"] == GreenHopperResource.AGILE_BASE_REST_PATH: url = self._get_url("backlog/issue", base=self.AGILE_BASE_URL) payload = {"issues": issue_keys} try: - self._session.post(url, data=json.dumps(payload)) + return self._session.post(url, data=json.dumps(payload)) except JIRAError as e: if e.status_code == 404: warnings.warn( diff --git a/jira/config.py b/jira/config.py index 6d8624d7c..a01fbcab2 100644 --- a/jira/config.py +++ b/jira/config.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- """ This module allows people to keep their jira server credentials outside their script, in a configuration file that is not saved in the source control. @@ -10,28 +9,36 @@ import logging import os import sys +from typing import Optional from jira.client import JIRA def get_jira( - profile=None, - url="http://localhost:2990", - username="admin", - password="admin", + profile: Optional[str] = None, + url: str = "http://localhost:2990", + username: str = "admin", + password: str = "admin", appid=None, autofix=False, - verify=True, + verify: bool = True, ): """Return a JIRA object by loading the connection details from the `config.ini` file. - :param profile: The name of the section from config.ini file that stores server config url/username/password - :param url: URL of the Jira server - :param username: username to use for authentication - :param password: password to use for authentication - :param verify: boolean indicating whether SSL certificates should be verified - :return: JIRA -- an instance to a JIRA object. - :raises: EnvironmentError + Args: + profile (Optional[str]): The name of the section from config.ini file that stores server config url/username/password + url (str): URL of the Jira server + username (str): username to use for authentication + password (str): password to use for authentication + appid: appid + autofix: autofix + verify (bool): boolean indicating whether SSL certificates should be verified + + Returns: + JIRA: an instance to a JIRA object. + + Raises: + EnvironmentError Usage: @@ -79,7 +86,7 @@ def findfile(path): config_file = findfile("config.ini") if config_file: - logging.debug("Found %s config file" % config_file) + logging.debug(f"Found {config_file} config file") if not profile: if config_file: @@ -100,7 +107,7 @@ def findfile(path): verify = config.getboolean(profile, "verify") else: - raise EnvironmentError( + raise OSError( "%s was not able to locate the config.ini file in current directory, user home directory or PYTHONPATH." % __name__ ) diff --git a/jira/exceptions.py b/jira/exceptions.py index 6e1b4ee77..d6d355dc2 100644 --- a/jira/exceptions.py +++ b/jira/exceptions.py @@ -1,37 +1,30 @@ -# -*- coding: utf-8 -*- import os import tempfile +from requests import Response + class JIRAError(Exception): """General error raised for all problems in operation of the client.""" - log_to_tempfile = True - if "TRAVIS" in os.environ: - log_to_tempfile = False # Travis is keeping only the console log. - def __init__( self, - status_code=None, - text=None, - url=None, - request=None, - response=None, - **kwargs + text: str = None, + status_code: int = None, + url: str = None, + request: Response = None, + response: Response = None, + **kwargs, ): - """ Creates a JIRAError. + """Creates a JIRAError. - :param status_code: Status code for the error. - :type status_code: Optional[int] - :param text: Message for the error. - :type text: Optional[str] - :param url: Url related to the error. - :type url: Optional[str] - :param request: Request made related to the error. - :type request: Optional[Any] - :param response: Response received related to the error. - :type response: Optional[Response] - :type kwargs: **Any + Args: + text (Optional[str]): Message for the error. + status_code (Optional[int]): Status code for the error. + url (Optional[str]): Url related to the error. + request (Optional[requests.Response]): Request made related to the error. + response (Optional[requests.Response]): Response received related to the error. + **kwargs: Will be used to get request headers. """ self.status_code = status_code self.text = text @@ -39,50 +32,38 @@ def __init__( self.request = request self.response = response self.headers = kwargs.get("headers", None) - self.log_to_tempfile = False - self.travis = False - if "PYJIRA_LOG_TO_TEMPFILE" in os.environ: - self.log_to_tempfile = True - if "TRAVIS" in os.environ: - self.travis = True - - def __str__(self): - """Return a string representation of the error. + self.log_to_tempfile = "PYJIRA_LOG_TO_TEMPFILE" in os.environ + self.ci_run = "GITHUB_ACTION" in os.environ - :rtype: str - """ - t = "JiraError HTTP %s" % self.status_code + def __str__(self) -> str: + t = f"JiraError HTTP {self.status_code}" if self.url: - t += " url: %s" % self.url + t += f" url: {self.url}" details = "" - if self.request is not None and hasattr(self.request, "headers"): - details += "\n\trequest headers = %s" % self.request.headers - - if self.request is not None and hasattr(self.request, "text"): - details += "\n\trequest text = %s" % self.request.text + if self.request is not None: + if hasattr(self.request, "headers"): + details += f"\n\trequest headers = {self.request.headers}" - if self.response is not None and hasattr(self.response, "headers"): - details += "\n\tresponse headers = %s" % self.response.headers + if hasattr(self.request, "text"): + details += f"\n\trequest text = {self.request.text}" + if self.response is not None: + if hasattr(self.response, "headers"): + details += f"\n\tresponse headers = {self.response.headers}" - if self.response is not None and hasattr(self.response, "text"): - details += "\n\tresponse text = %s" % self.response.text + if hasattr(self.response, "text"): + details += f"\n\tresponse text = {self.response.text}" - # separate logging for Travis makes sense. - if self.travis: - if self.text: - t += "\n\ttext: %s" % self.text - t += details - # Only log to tempfile if the option is set. - elif self.log_to_tempfile: - fd, file_name = tempfile.mkstemp(suffix=".tmp", prefix="jiraerror-") + if self.log_to_tempfile: + # Only log to tempfile if the option is set. + _, file_name = tempfile.mkstemp(suffix=".tmp", prefix="jiraerror-") with open(file_name, "w") as f: - t += " details: %s" % file_name + t += f" details: {file_name}" f.write(details) - # Otherwise, just return the error as usual else: + # Otherwise, just return the error as usual if self.text: - t += "\n\ttext: %s" % self.text - t += "\n\t" + details + t += f"\n\ttext: {self.text}" + t += f"\n\t{details}" return t diff --git a/jira/jirashell.py b/jira/jirashell.py index dc413581e..6783bfa11 100644 --- a/jira/jirashell.py +++ b/jira/jirashell.py @@ -7,23 +7,22 @@ """ import argparse +import configparser import os import sys import webbrowser from getpass import getpass +from urllib.parse import parse_qsl import keyring import requests from oauthlib.oauth1 import SIGNATURE_RSA from requests_oauthlib import OAuth1 -from urllib.parse import parse_qsl from jira import JIRA, __version__ -import configparser - - CONFIG_PATH = os.path.join(os.path.expanduser("~"), ".jira-python", "jirashell.ini") +SENTINEL = object() def oauth_dance(server, consumer_key, key_cert_data, print_tokens=False, verify=None): @@ -36,23 +35,25 @@ def oauth_dance(server, consumer_key, key_cert_data, print_tokens=False, verify= server + "/plugins/servlet/oauth/request-token", verify=verify, auth=oauth ) request = dict(parse_qsl(r.text)) - request_token = request["oauth_token"] - request_token_secret = request["oauth_token_secret"] + request_token = request.get("oauth_token", SENTINEL) + request_token_secret = request.get("oauth_token_secret", SENTINEL) + if request_token is SENTINEL or request_token_secret is SENTINEL: + problem = request.get("oauth_problem") + if problem is not None: + message = f"OAuth error: {problem}" + else: + message = " ".join(f"{key}:{value}" for key, value in request.items()) + exit(message) + if print_tokens: print("Request tokens received.") - print(" Request token: {}".format(request_token)) - print(" Request token secret: {}".format(request_token_secret)) + print(f" Request token: {request_token}") + print(f" Request token secret: {request_token_secret}") # step 2: prompt user to validate - auth_url = "{}/plugins/servlet/oauth/authorize?oauth_token={}".format( - server, request_token - ) + auth_url = f"{server}/plugins/servlet/oauth/authorize?oauth_token={request_token}" if print_tokens: - print( - "Please visit this URL to authorize the OAuth request:\n\t{}".format( - auth_url - ) - ) + print(f"Please visit this URL to authorize the OAuth request:\n\t{auth_url}") else: webbrowser.open_new(auth_url) print( @@ -60,9 +61,7 @@ def oauth_dance(server, consumer_key, key_cert_data, print_tokens=False, verify= ) approved = input( - "Have you authorized this program to connect on your behalf to {}? (y/n)".format( - server - ) + f"Have you authorized this program to connect on your behalf to {server}? (y/n)" ) if approved.lower() != "y": @@ -85,8 +84,8 @@ def oauth_dance(server, consumer_key, key_cert_data, print_tokens=False, verify= if print_tokens: print("Access tokens received.") - print(" Access token: {}".format(access["oauth_token"])) - print(" Access token secret: {}".format(access["oauth_token_secret"])) + print(f" Access token: {access['oauth_token']}") + print(f" Access token secret: {access['oauth_token_secret']}") return { "access_token": access["oauth_token"], @@ -104,7 +103,7 @@ def process_config(): try: parser.read(CONFIG_PATH) except configparser.ParsingError as err: - print("Couldn't read config file at path: {}\n{}".format(CONFIG_PATH, err)) + print(f"Couldn't read config file at path: {CONFIG_PATH}\n{err}") raise if parser.has_section("options"): @@ -251,7 +250,7 @@ def process_command_line(): key_cert_data = None if args.key_cert: - with open(args.key_cert, "r") as key_cert_file: + with open(args.key_cert) as key_cert_file: key_cert_data = key_cert_file.read() oauth = {} @@ -306,7 +305,7 @@ def handle_basic_auth(auth, server): print("Getting password from keyring...") password = keyring.get_password(server, auth["username"]) assert password, "No password provided!" - return (auth["username"], password) + return auth["username"], password def main(): @@ -362,9 +361,9 @@ def main(): from IPython.frontend.terminal.embed import InteractiveShellEmbed ip_shell = InteractiveShellEmbed( - banner1="" + banner1="" ) - ip_shell("*** Jira shell active; client is in 'jira'." " Press Ctrl-D to exit.") + ip_shell("*** Jira shell active; client is in 'jira'. Press Ctrl-D to exit.") except Exception as e: print(e, file=sys.stderr) return 2 diff --git a/jira/py.typed b/jira/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/jira/resilientsession.py b/jira/resilientsession.py index 3ee851bcc..450b860d9 100644 --- a/jira/resilientsession.py +++ b/jira/resilientsession.py @@ -1,19 +1,29 @@ -# -*- coding: utf-8 -*- import json import logging - - import random -from requests.exceptions import ConnectionError -from requests import Session import time +from typing import Callable, Optional, Union, cast + +from requests import Response, Session +from requests.exceptions import ConnectionError from jira.exceptions import JIRAError logging.getLogger("jira").addHandler(logging.NullHandler()) -def raise_on_error(r, verb="???", **kwargs): +def raise_on_error(r: Optional[Response], verb="???", **kwargs): + """Handle errors from a Jira Request + + Args: + r (Optional[Response]): Response from Jira request + verb (Optional[str]): Request type, e.g. POST. Defaults to "???". + + Raises: + JIRAError: If Response is None + JIRAError: for unhandled 400 status codes. + JIRAError: for unhandled 200 status codes. + """ request = kwargs.get("request", None) # headers = kwargs.get('headers', None) @@ -52,12 +62,19 @@ def raise_on_error(r, verb="???", **kwargs): except ValueError: error = r.text raise JIRAError( - r.status_code, error, r.url, request=request, response=r, **kwargs + error, + status_code=r.status_code, + url=r.url, + request=request, + response=r, + **kwargs, ) # for debugging weird errors on CI if r.status_code not in [200, 201, 202, 204]: - raise JIRAError(r.status_code, request=request, response=r, **kwargs) - # testing for the WTH bug exposed on + raise JIRAError( + status_code=r.status_code, request=request, response=r, **kwargs + ) + # testing for the bug exposed on # https://answers.atlassian.com/questions/11457054/answers/11975162 if ( r.status_code == 200 @@ -76,30 +93,29 @@ class ResilientSession(Session): def __init__(self, timeout=None): self.max_retries = 3 + self.max_retry_delay = 60 self.timeout = timeout - super(ResilientSession, self).__init__() + super().__init__() # Indicate our preference for JSON to avoid https://bitbucket.org/bspeakmon/jira-python/issue/46 and https://jira.atlassian.com/browse/JRA-38551 self.headers.update({"Accept": "application/json,*.*;q=0.9"}) - def __recoverable(self, response, url, request, counter=1): - msg = response + def __recoverable( + self, + response: Optional[Union[ConnectionError, Response]], + url: str, + request, + counter: int = 1, + ): + msg = str(response) if isinstance(response, ConnectionError): logging.warning( - "Got ConnectionError [%s] errno:%s on %s %s\n%s\n%s" - % ( - response, - response.errno, - request, - url, - vars(response), - response.__dict__, - ) + f"Got ConnectionError [{response}] errno:{response.errno} on {request} {url}\n{vars(response)}\n{response.__dict__}" ) - if hasattr(response, "status_code"): + if isinstance(response, Response): if response.status_code in [502, 503, 504, 401]: # 401 UNAUTHORIZED still randomly returned by Atlassian Cloud as of 2017-01-16 - msg = "%s %s" % (response.status_code, response.reason) + msg = f"{response.status_code} {response.reason}" # 2019-07-25: Disabled recovery for codes above^ return False elif not ( @@ -113,17 +129,20 @@ def __recoverable(self, response, url, request, counter=1): msg = "Atlassian's bug https://jira.atlassian.com/browse/JRA-41559" # Exponential backoff with full jitter. - delay = min(60, 10 * 2 ** counter) * random.random() + delay = min(self.max_retry_delay, 10 * 2 ** counter) * random.random() logging.warning( "Got recoverable error from %s %s, will retry [%s/%s] in %ss. Err: %s" % (request, url, counter, self.max_retries, delay, msg) ) - logging.debug("response.headers: %s", response.headers) - logging.debug("response.body: %s", response.content) + if isinstance(response, Response): + logging.debug("response.headers: %s", response.headers) + logging.debug("response.body: %s", response.content) time.sleep(delay) return True - def __verb(self, verb, url, retry_data=None, **kwargs): + def __verb( + self, verb: str, url: str, retry_data: Callable = None, **kwargs + ) -> Response: d = self.headers.copy() d.update(kwargs.get("headers", {})) @@ -136,18 +155,19 @@ def __verb(self, verb, url, retry_data=None, **kwargs): data = json.dumps(data) retry_number = 0 + exception = None + response = None while retry_number <= self.max_retries: response = None exception = None try: - method = getattr(super(ResilientSession, self), verb.lower()) + method = getattr(super(), verb.lower()) response = method(url, timeout=self.timeout, **kwargs) if response.status_code >= 200 and response.status_code <= 299: return response except ConnectionError as e: - logging.warning( - "%s while doing %s %s [%s]" % (e, verb.upper(), url, kwargs) - ) + logging.warning(f"{e} while doing {verb.upper()} {url}") + exception = e retry_number += 1 @@ -167,25 +187,27 @@ def __verb(self, verb, url, retry_data=None, **kwargs): if exception is not None: raise exception raise_on_error(response, verb=verb, **kwargs) + # after raise_on_error, only Response objects are allowed through + response = cast(Response, response) # tell mypy only Response-like are here return response - def get(self, url, **kwargs): - return self.__verb("GET", url, **kwargs) + def get(self, url: Union[str, bytes], **kwargs) -> Response: # type: ignore + return self.__verb("GET", str(url), **kwargs) - def post(self, url, **kwargs): - return self.__verb("POST", url, **kwargs) + def post(self, url: Union[str, bytes], data=None, json=None, **kwargs) -> Response: # type: ignore + return self.__verb("POST", str(url), data=data, json=json, **kwargs) - def put(self, url, **kwargs): - return self.__verb("PUT", url, **kwargs) + def put(self, url: Union[str, bytes], data=None, **kwargs) -> Response: # type: ignore + return self.__verb("PUT", str(url), data=data, **kwargs) - def delete(self, url, **kwargs): - return self.__verb("DELETE", url, **kwargs) + def delete(self, url: Union[str, bytes], **kwargs) -> Response: # type: ignore + return self.__verb("DELETE", str(url), **kwargs) - def head(self, url, **kwargs): - return self.__verb("HEAD", url, **kwargs) + def head(self, url: Union[str, bytes], **kwargs) -> Response: # type: ignore + return self.__verb("HEAD", str(url), **kwargs) - def patch(self, url, **kwargs): - return self.__verb("PATCH", url, **kwargs) + def patch(self, url: Union[str, bytes], data=None, **kwargs) -> Response: # type: ignore + return self.__verb("PATCH", str(url), data=data, **kwargs) - def options(self, url, **kwargs): - return self.__verb("OPTIONS", url, **kwargs) + def options(self, url: Union[str, bytes], **kwargs) -> Response: # type: ignore + return self.__verb("OPTIONS", str(url), **kwargs) diff --git a/jira/resources.py b/jira/resources.py index 6464dd449..da87c9cf0 100644 --- a/jira/resources.py +++ b/jira/resources.py @@ -1,18 +1,31 @@ -# -*- coding: utf-8 -*- """ This module implements the Resource classes that translate JSON from Jira REST resources into usable objects. """ +import json import logging import re import time +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union, cast -import json +from requests import Response +from requests.structures import CaseInsensitiveDict + +from jira.resilientsession import ResilientSession +from jira.utils import json_loads, threaded_requests + +if TYPE_CHECKING: + from jira.client import JIRA + + AnyLike = Any +else: + + class AnyLike: + """Dummy subclass of base object class for when type checker is not running.""" + + pass -from jira.utils import CaseInsensitiveDict -from jira.utils import json_loads -from jira.utils import threaded_requests __all__ = ( "Resource", @@ -24,6 +37,7 @@ "Dashboard", "Filter", "Votes", + "PermissionScheme", "Watchers", "Worklog", "IssueLink", @@ -42,19 +56,20 @@ "Customer", "ServiceDesk", "RequestType", + "resource_class_map", ) logging.getLogger("jira").addHandler(logging.NullHandler()) -def get_error_list(r): +def get_error_list(r: Response) -> List[str]: error_list = [] if r.status_code >= 400: if r.status_code == 403 and "x-authentication-denied-reason" in r.headers: error_list = [r.headers["x-authentication-denied-reason"]] elif r.text: try: - response = json_loads(r) + response: Dict[str, Any] = json_loads(r) if "message" in response: # Jira 5.1 errors error_list = [response["message"]] @@ -63,7 +78,7 @@ def get_error_list(r): # Sometimes this is present but empty errorMessages = response["errorMessages"] if isinstance(errorMessages, (list, tuple)): - error_list = errorMessages + error_list = list(errorMessages) else: error_list = [errorMessages] elif "errors" in response and len(response["errors"]) > 0: @@ -76,7 +91,7 @@ def get_error_list(r): return error_list -class Resource(object): +class Resource: """Models a URL-addressable resource in the Jira REST API. All Resource objects provide the following: @@ -118,16 +133,30 @@ class Resource(object): "closed", ) - def __init__(self, resource, options, session, base_url=JIRA_BASE_URL): + # A list of properties that should uniquely identify a Resource object + # Each of these properties should be hashable, usually strings + _HASH_IDS = ( + "self", + "type", + "key", + "id", + "name", + ) + + def __init__( + self, + resource: str, + options: Dict[str, Any], + session: ResilientSession, + base_url: str = JIRA_BASE_URL, + ): """Initializes a generic resource. - :param resource: The name of the resource. - :type resource: str - :param options: Options for the new resource - :type options: Dict[str,str] - :param session: Session used for the resource. - :type session: ResilientSession - :param base_url: The Base Jira url. - :type base_url: Optional[str] + + Args: + resource (str): The name of the resource. + options (Dict[str,str]): Options for the new resource + session (ResilientSession): Session used for the resource. + base_url (Optional[str]): The Base Jira url. """ self._resource = resource @@ -137,12 +166,13 @@ def __init__(self, resource, options, session, base_url=JIRA_BASE_URL): # Explicitly define as None so we know when a resource has actually # been loaded - self.raw = None + self.raw: Optional[Dict[str, Any]] = None - def __str__(self): + def __str__(self) -> str: """Return the first value we find that is likely to be human readable. - :rtype: str + Returns: + str """ if self.raw: for name in self._READABLE_IDS: @@ -156,71 +186,94 @@ def __str__(self): # If all else fails, use repr to make sure we get something. return repr(self) - def __repr__(self): + def __repr__(self) -> str: """Identify the class and include any and all relevant values. - :rtype: str + Returns: + str """ - names = [] + names: List[str] = [] if self.raw: for name in self._READABLE_IDS: if name in self.raw: names.append(name + "=" + repr(self.raw[name])) if not names: - return "" % (self.__class__.__name__, id(self)) - return "" % (self.__class__.__name__, ", ".join(names)) + return f"" + return f"" - def __getattr__(self, item): + def __getattr__(self, item: str) -> Any: """Allow access of attributes via names. - :param item: Attribute name - :type item: str + Args: + item (str): Attribute Name - :rtype: Any - - :raises KeyError: When the attribute does not exist. - :raises AttributeError: When attribute does not exist. + Raises: + AttributeError: When attribute does not exist. + Returns: + Any: Attribute value. """ try: - return self[item] + return self[item] # type: ignore except Exception as e: - # Make sure pickling doesn't break - # *MORE INFO*: This conditional wouldn't be necessary if __getattr__ wasn't used. But - # since it is in use (no worries), we need to give the pickle.dump* - # methods what they expect back. They expect to either get a KeyError - # exception or a tuple of args to be passed to the __new__ method upon - # unpickling (i.e. pickle.load* methods). - # *NOTE*: if the __new__ method were to be implemented in this class, this may have - # to be removed or changed. - if item == "__getnewargs__": - raise KeyError(item) - - if hasattr(self, "raw") and item in self.raw: + if hasattr(self, "raw") and self.raw is not None and item in self.raw: return self.raw[item] else: raise AttributeError( - "%r object has no attribute %r (%s)" % (self.__class__, item, e) + f"{self.__class__!r} object has no attribute {item!r} ({e})" ) - # def __getstate__(self): - # """ - # Pickling the resource; using the raw dict - # """ - # return self.raw - # - # def __setstate__(self, raw_pickled): - # """ - # Unpickling of the resource - # """ - # self._parse_raw(raw_pickled) - # + def __getstate__(self) -> Dict[str, Any]: + """Pickling the resource.""" + return vars(self) - def find(self, id, params=None): + def __setstate__(self, raw_pickled: Dict[str, Any]): + """Unpickling of the resource""" + # https://stackoverflow.com/a/50888571/7724187 + vars(self).update(raw_pickled) + + def __hash__(self) -> int: + """Hash calculation. + + We try to find unique identifier like properties + to form our hash object. + Technically 'self', if present, is the unique URL to the object, + and should be sufficient to generate a unique hash. + """ + hash_list = [] + for a in self._HASH_IDS: + if hasattr(self, a): + hash_list.append(getattr(self, a)) + + if hash_list: + return hash(tuple(hash_list)) + else: + raise TypeError(f"'{self.__class__}' is not hashable") + + def __eq__(self, other: Any) -> bool: + """Default equality test. + + Checks the types look about right and that the relevant + attributes that uniquely identify a resource are equal. + """ + return isinstance(other, self.__class__) and all( + [ + getattr(self, a) == getattr(other, a) + for a in self._HASH_IDS + if hasattr(self, a) + ] + ) + + def find( + self, + id: Union[Tuple[str, str], int, str], + params: Optional[Dict[str, str]] = None, + ): """Finds a resource based on the input parameters. - :type id: Union[Tuple[str, str], int, str] - :type params: Optional[Dict[str, str]] + Args: + id (Union[Tuple[str, str], int, str]): id + params (Optional[Dict[str, str]]): params """ @@ -234,51 +287,54 @@ def find(self, id, params=None): url = self._get_url(path) self._load(url, params=params) - def _get_url(self, path): - """ Gets the url for the specified path. + def _get_url(self, path: str) -> str: + """Gets the url for the specified path. - :type path: str - - :rtype: str + Args: + path (str): str + Returns: + str """ options = self._options.copy() options.update({"path": path}) return self._base_url.format(**options) - def update(self, fields=None, async_=None, jira=None, notify=True, **kwargs): + def update( + self, + fields: Optional[Dict[str, Any]] = None, + async_: Optional[bool] = None, + jira: "JIRA" = None, + notify: bool = True, + **kwargs: Any, + ): """Update this resource on the server. Keyword arguments are marshalled into a dict before being sent. If this resource doesn't support ``PUT``, a :py:exc:`.JIRAError` will be raised; subclasses that specialize this method will only raise errors in case of user error. - :param fields: Fields which should be updated for the object. - :type fields: Optional[Dict[str, Any]] - :param async_: If true the request will be added to the queue so it can be executed later using async_run() - :type async_: bool - :param jira: Instance of Jira Client - :type jira: jira.JIRA - :param notify: Whether or not to notify users about the update. (Default: True) - :type notify: bool - :type kwargs: **Any + Args: + fields (Optional[Dict[str, Any]]): Fields which should be updated for the object. + async_ (bool): If true the request will be added to the queue so it can be executed later using async_run() + jira (jira.client.JIRA): Instance of Jira Client + notify (bool): Whether or not to notify users about the update. (Default: True) + kwargs (Any): extra arguments to the PUT request. """ if async_ is None: - async_ = self._options["async"] + async_: bool = self._options["async"] # type: ignore # redefinition data = {} if fields is not None: data.update(fields) data.update(kwargs) - data = json.dumps(data) - if not notify: querystring = "?notifyUsers=false" else: querystring = "" - r = self._session.put(self.self + querystring, data=data) + r = self._session.put(self.self + querystring, data=json.dumps(data)) if "autofix" in self._options and r.status_code == 400: user = None error_list = get_error_list(r) @@ -333,7 +389,7 @@ def update(self, fields=None, async_=None, jira=None, notify=True, **kwargs): else: raise NotImplementedError() - if user: + if user and jira: logging.warning( "Trying to add missing orphan user '%s' in order to complete the previous failed operation." % user @@ -343,11 +399,13 @@ def update(self, fields=None, async_=None, jira=None, notify=True, **kwargs): # logging.warning("autofix: setting assignee to '%s' and retrying the update." % self._options['autofix']) # data['fields']['assignee'] = {'name': self._options['autofix']} # EXPERIMENTAL ---> - if async_: + if async_: # FIXME: no async if not hasattr(self._session, "_async_jobs"): - self._session._async_jobs = set() - self._session._async_jobs.add( - threaded_requests.put(self.self, data=json.dumps(data)) + self._session._async_jobs = set() # type: ignore + self._session._async_jobs.add( # type: ignore + threaded_requests.put( # type: ignore + self.self, data=json.dumps(data) + ) ) else: r = self._session.put(self.self, data=json.dumps(data)) @@ -355,54 +413,67 @@ def update(self, fields=None, async_=None, jira=None, notify=True, **kwargs): time.sleep(self._options["delay_reload"]) self._load(self.self) - def delete(self, params=None): + def delete(self, params: Optional[Dict[str, Any]] = None) -> Optional[Response]: """Delete this resource from the server, passing the specified query parameters. If this resource doesn't support ``DELETE``, a :py:exc:`.JIRAError` will be raised; subclasses that specialize this method will only raise errors in case of user error. - :param params: Parameters for the delete request. - :type params: Optional[Dict[str, Any]] + Args: + params: Parameters for the delete request. - :rtype: Response + Returns: + Optional[Response]: Returns None if async """ if self._options["async"]: + # FIXME: mypy doesn't think this should work if not hasattr(self._session, "_async_jobs"): - self._session._async_jobs = set() - self._session._async_jobs.add( - threaded_requests.delete(url=self.self, params=params) + self._session._async_jobs = set() # type: ignore + self._session._async_jobs.add( # type: ignore + threaded_requests.delete(url=self.self, params=params) # type: ignore ) + return None else: return self._session.delete(url=self.self, params=params) - def _load(self, url, headers=CaseInsensitiveDict(), params=None, path=None): - """ Load a resource. + def _load( + self, + url: str, + headers=CaseInsensitiveDict(), + params: Optional[Dict[str, str]] = None, + path: Optional[str] = None, + ): + """Load a resource. - :type url: str - :type headers: CaseInsensitiveDict - :type params: Optional[Dict[str,str]] - :type path: Optional[str] + Args: + url (str): url + headers (Optional[CaseInsensitiveDict]): headers. Defaults to CaseInsensitiveDict(). + params (Optional[Dict[str,str]]): params to get request. Defaults to None. + path (Optional[str]): field to get. Defaults to None. + Raises: + ValueError: If json cannot be loaded """ r = self._session.get(url, headers=headers, params=params) try: j = json_loads(r) except ValueError as e: - logging.error("%s:\n%s" % (e, r.text)) + logging.error(f"{e}:\n{r.text}") raise e if path: j = j[path] self._parse_raw(j) - def _parse_raw(self, raw): + def _parse_raw(self, raw: Dict[str, Any]): """Parse a raw dictionary to create a resource. - :type raw: Dict[str, Any] + Args: + raw (Dict[str, Any]) """ self.raw = raw if not raw: - raise NotImplementedError("We cannot instantiate empty resources: %s" % raw) + raise NotImplementedError(f"We cannot instantiate empty resources: {raw}") dict2resource(raw, self, self._options, self._session) def _default_headers(self, user_headers): @@ -416,10 +487,16 @@ def _default_headers(self, user_headers): class Attachment(Resource): """An issue attachment.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "attachment/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) def get(self): """Return the file content as a string.""" @@ -435,82 +512,134 @@ def iter_content(self, chunk_size=1024): class Component(Resource): """A project component.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "component/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) - def delete(self, moveIssuesTo=None): + def delete(self, moveIssuesTo: Optional[str] = None): # type: ignore[override] """Delete this component from the server. - :param moveIssuesTo: the name of the component to which to move any issues this component is applied + Args: + moveIssuesTo: the name of the component to which to move any issues this component is applied """ params = {} if moveIssuesTo is not None: params["moveIssuesTo"] = moveIssuesTo - super(Component, self).delete(params) + super().delete(params) class CustomFieldOption(Resource): """An existing option for a custom issue field.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "customFieldOption/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Dashboard(Resource): """A Jira dashboard.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "dashboard/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Filter(Resource): """An issue navigator filter.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "filter/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Issue(Resource): """A Jira issue.""" - class _IssueFields(object): - def __init__(self): - self.attachment = None - """ :type : list[Attachment] """ - self.description = None - """ :type : str """ - self.project = None - """ :type : Project """ - self.comment = None - """ :type : list[Comment] """ - self.issuelinks = None - """ :type : list[IssueLink] """ - self.worklog = None - """ :type : list[Worklog] """ + class _IssueFields(AnyLike): + class _Comment: + def __init__(self) -> None: + self.comments: List[Comment] = [] - def __init__(self, options, session, raw=None): + class _Worklog: + def __init__(self) -> None: + self.worklogs: List[Worklog] = [] + + def __init__(self): + self.assignee: Optional[UnknownResource] = None + self.attachment: List[Attachment] = [] + self.comment = self._Comment() + self.created: str + self.description: Optional[str] = None + self.duedate: Optional[str] = None + self.issuelinks: List[IssueLink] = [] + self.issuetype: IssueType + self.labels: List[str] = [] + self.priority: Priority + self.project: Project + self.reporter: UnknownResource + self.resolution: Optional[Resolution] = None + self.security: Optional[SecurityLevel] = None + self.status: Status + self.statuscategorychangedate: Optional[str] = None + self.summary: str + self.timetracking: TimeTracking + self.versions: List[Version] = [] + self.votes: Votes + self.watchers: Watchers + self.worklog = self._Worklog() + + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issue/{0}", options, session) - self.fields = None - """ :type: :class:`~Issue._IssueFields` """ - self.id = None - """ :type: int """ - self.key = None - """ :type: str """ + self.fields: Issue._IssueFields + self.id: str + self.key: str if raw: self._parse_raw(raw) - - def update( - self, fields=None, update=None, async_=None, jira=None, notify=True, **fieldargs + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) + + def update( # type: ignore[override] # incompatible supertype ignored + self, + fields: Dict[str, Any] = None, + update: Dict[str, Any] = None, + async_: bool = None, + jira: "JIRA" = None, + notify: bool = True, + **fieldargs, ): """Update this issue on the server. @@ -522,15 +651,14 @@ def update( fields in an issue. This information is available through the :py:meth:`.JIRA.editmeta` method. Further examples are available here: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Edit+issues - :param fields: a dict containing field names and the values to use - :param update: a dict containing update operations to apply - :param notify: query parameter notifyUsers. If true send the email with notification that the issue was updated - to users that watch it. Admin or project admin permissions are required to disable the notification. - :param fieldargs: keyword arguments will generally be merged into fields, except lists, - which will be merged into updates - - :type fields: dict - :type update: dict + Args: + fields (Dict[str,Any]): a dict containing field names and the values to use + update (Dict[str,Any]): a dict containing update operations to apply + notify (bool): query parameter notifyUsers. If true send the email with notification that the issue was updated + to users that watch it. Admin or project admin permissions are required to disable the notification. + jira (Optional[jira.client.JIRA]): JIRA instance. + fieldargs (dict): keyword arguments will generally be merged into fields, except lists, + which will be merged into updates """ data = {} @@ -549,7 +677,7 @@ def update( # apply some heuristics to make certain changes easier if isinstance(value, str): if field == "assignee" or field == "reporter": - fields_dict["assignee"] = {"name": value} + fields_dict[field] = {"name": value} elif field == "comment": if "comment" not in update_dict: update_dict["comment"] = [] @@ -563,50 +691,51 @@ def update( else: fields_dict[field] = value - super(Issue, self).update(async_=async_, jira=jira, notify=notify, fields=data) + super().update(async_=async_, jira=jira, notify=notify, fields=data) - def add_field_value(self, field, value): + def add_field_value(self, field: str, value: str): """Add a value to a field that supports multiple values, without resetting the existing values. This should work with: labels, multiple checkbox lists, multiple select - :param field: The field name - :param value: The field's value + Args: + field (str): The field name + value (str): The field's value - :type field: str """ - super(Issue, self).update(fields={"update": {field: [{"add": value}]}}) + super().update(fields={"update": {field: [{"add": value}]}}) def delete(self, deleteSubtasks=False): """Delete this issue from the server. - :param deleteSubtasks: if the issue has subtasks, this argument must be set to true for the call to succeed. + Args: + deleteSubtasks (bool): if the issue has subtasks, this argument must be set to true for the call to succeed. - :type deleteSubtasks: bool """ - super(Issue, self).delete(params={"deleteSubtasks": deleteSubtasks}) + super().delete(params={"deleteSubtasks": deleteSubtasks}) def permalink(self): """Get the URL of the issue, the browsable one not the REST one. - :return: URL of the issue - - :rtype: str + Returns: + str: URL of the issue """ - return "%s/browse/%s" % (self._options["server"], self.key) - - def __eq__(self, other): - """Comparison method.""" - return other is not None and self.id == other.id + return f"{self._options['server']}/browse/{self.key}" class Comment(Resource): """An issue comment.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issue/{0}/comment/{1}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) def update(self, fields=None, async_=None, jira=None, body="", visibility=None): """Update a comment""" @@ -615,16 +744,22 @@ def update(self, fields=None, async_=None, jira=None, body="", visibility=None): data["body"] = body if visibility: data["visibility"] = visibility - super(Comment, self).update(data) + super().update(data) class RemoteLink(Resource): """A link to a remote application from an issue.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issue/{0}/remotelink/{1}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) def update(self, object, globalId=None, application=None, relationship=None): """Update a RemoteLink. 'object' is required. @@ -632,10 +767,11 @@ def update(self, object, globalId=None, application=None, relationship=None): For definitions of the allowable fields for 'object' and the keyword arguments 'globalId', 'application' and 'relationship', see https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+for+Remote+Issue+Links. - :param object: the link details to add (see the above link for details) - :param globalId: unique ID for the link (see the above link for details) - :param application: application information for the link (see the above link for details) - :param relationship: relationship description for the link (see the above link for details) + Args: + object: the link details to add (see the above link for details) + globalId: unique ID for the link (see the above link for details) + application: application information for the link (see the above link for details) + relationship: relationship description for the link (see the above link for details) """ data = {"object": object} if globalId is not None: @@ -645,55 +781,94 @@ def update(self, object, globalId=None, application=None, relationship=None): if relationship is not None: data["relationship"] = relationship - super(RemoteLink, self).update(**data) + super().update(**data) class Votes(Resource): """Vote information on an issue.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issue/{0}/votes", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) + + +class PermissionScheme(Resource): + """Permissionscheme information on an project.""" + + def __init__(self, options, session, raw=None): + Resource.__init__( + self, "project/{0}/permissionscheme?expand=user", options, session + ) + if raw: + self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Watchers(Resource): """Watcher information on an issue.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issue/{0}/watchers", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) def delete(self, username): """Remove the specified user from the watchers list.""" - super(Watchers, self).delete(params={"username": username}) + super().delete(params={"username": username}) class TimeTracking(Resource): - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issue/{0}/worklog/{1}", options, session) self.remainingEstimate = None if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Worklog(Resource): """Worklog on an issue.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issue/{0}/worklog/{1}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) - def delete(self, adjustEstimate=None, newEstimate=None, increaseBy=None): + def delete( # type: ignore[override] + self, adjustEstimate: Optional[str] = None, newEstimate=None, increaseBy=None + ): """Delete this worklog entry from its associated issue. - :param adjustEstimate: one of ``new``, ``leave``, ``manual`` or ``auto``. - ``auto`` is the default and adjusts the estimate automatically. - ``leave`` leaves the estimate unchanged by this deletion. - :param newEstimate: combined with ``adjustEstimate=new``, set the estimate to this value - :param increaseBy: combined with ``adjustEstimate=manual``, increase the remaining estimate by this amount + Args: + adjustEstimate: one of ``new``, ``leave``, ``manual`` or ``auto``. + ``auto`` is the default and adjusts the estimate automatically. + ``leave`` leaves the estimate unchanged by this deletion. + newEstimate: combined with ``adjustEstimate=new``, set the estimate to this value + increaseBy: combined with ``adjustEstimate=manual``, increase the remaining estimate by this amount """ params = {} if adjustEstimate is not None: @@ -703,69 +878,108 @@ def delete(self, adjustEstimate=None, newEstimate=None, increaseBy=None): if increaseBy is not None: params["increaseBy"] = increaseBy - super(Worklog, self).delete(params) + super().delete(params) class IssueLink(Resource): """Link between two issues.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issueLink/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class IssueLinkType(Resource): """Type of link between two issues.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issueLinkType/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class IssueType(Resource): """Type of an issue.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "issuetype/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Priority(Resource): """Priority that can be set on an issue.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "priority/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Project(Resource): """A Jira project.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "project/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Role(Resource): """A role inside a project.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "project/{0}/role/{1}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) - def update(self, users=None, groups=None): + def update( # type: ignore[override] + self, + users: Union[str, List, Tuple] = None, + groups: Union[str, List, Tuple] = None, + ): """Add the specified users or groups to this project role. One of ``users`` or ``groups`` must be specified. - :param users: a user or users to add to the role - :type users: string, list or tuple - :param groups: a group or groups to add to the role - :type groups: string, list or tuple + Args: + users (Optional[Union[str,List,Tuple]]): a user or users to add to the role + groups (Optional[Union[str,List,Tuple]]): a group or groups to add to the role """ if users is not None and isinstance(users, str): @@ -781,17 +995,20 @@ def update(self, users=None, groups=None): }, } - super(Role, self).update(**data) + super().update(**data) - def add_user(self, users=None, groups=None): + def add_user( + self, + users: Union[str, List, Tuple] = None, + groups: Union[str, List, Tuple] = None, + ): """Add the specified users or groups to this project role. One of ``users`` or ``groups`` must be specified. - :param users: a user or users to add to the role - :type users: string, list or tuple - :param groups: a group or groups to add to the role - :type groups: string, list or tuple + Args: + users (Optional[Union[str,List,Tuple]]): a user or users to add to the role + groups (Optional[Union[str,List,Tuple]]): a group or groups to add to the role """ if users is not None and isinstance(users, str): @@ -799,98 +1016,126 @@ def add_user(self, users=None, groups=None): if groups is not None and isinstance(groups, str): groups = (groups,) - data = {"user": users} + data = {"user": users, "group": groups} self._session.post(self.self, data=json.dumps(data)) class Resolution(Resource): """A resolution for an issue.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "resolution/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class SecurityLevel(Resource): """A security level for an issue or project.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "securitylevel/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Status(Resource): """Status for an issue.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "status/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class StatusCategory(Resource): """StatusCategory for an issue.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "statuscategory/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class User(Resource): """A Jira user.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "user?username={0}", options, session) if raw: self._parse_raw(raw) - - def __hash__(self): - """Hash calculation.""" - return hash(str(self.name)) - - def __eq__(self, other): - """Comparison.""" - return str(self.name) == str(other.name) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Group(Resource): """A Jira user group.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "group?groupname={0}", options, session) if raw: self._parse_raw(raw) - - def __hash__(self): - """Hash calculation.""" - return hash(str(self.name)) - - def __eq__(self, other): - """Equality by name.""" - return str(self.name) == str(other.name) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Version(Resource): """A version of a project.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "version/{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) def delete(self, moveFixIssuesTo=None, moveAffectedIssuesTo=None): - """Delete this project version from the server. + """ + Delete this project version from the server. - If neither of the arguments are specified, the version is - removed from all issues it is attached to. + If neither of the arguments are specified, the version is removed from all + issues it is attached to. - :param moveFixIssuesTo: in issues for which this version is a fix - version, add this argument version to the fix version list - :param moveAffectedIssuesTo: in issues for which this version is an - affected version, add this argument version to the affected version list + Args: + moveFixIssuesTo: in issues for which this version is a fix + version, add this argument version to the fix version list + moveAffectedIssuesTo: in issues for which this version is an + affected version, add this argument version to the affected version list """ params = {} @@ -899,19 +1144,36 @@ def delete(self, moveFixIssuesTo=None, moveAffectedIssuesTo=None): if moveAffectedIssuesTo is not None: params["moveAffectedIssuesTo"] = moveAffectedIssuesTo - return super(Version, self).delete(params) + return super().delete(params) - def update(self, **args): - """Update this project version from the server. It is prior used to archive versions.""" - data = {} - for field in args: - data[field] = args[field] + def update(self, **kwargs): + """ + Update this project version from the server. It is prior used to archive versions. - super(Version, self).update(**data) + Refer to Atlassian REST API `documentation`_. - def __eq__(self, other): - """Comparison.""" - return self.id == other.id and self.name == other.name + .. _documentation: https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-project-versions/#api-rest-api-2-version-id-put + + :Example: + + .. code-block:: python + + >> version_id = "10543" + >> version = JIRA("https://atlassian.org").version(version_id) + >> print(version.name) + "some_version_name" + >> version.update(name="another_name") + >> print(version.name) + "another_name" + >> version.update(archived=True) + >> print(version.archived) + True + """ + data = {} + for field in kwargs: + data[field] = kwargs[field] + + super().update(**data) # GreenHopper @@ -929,7 +1191,13 @@ class GreenHopperResource(Resource): AGILE_BASE_REST_PATH = "agile" """ Public API introduced in Jira Agile 6.7.7. """ - def __init__(self, path, options, session, raw): + def __init__( + self, + path: str, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): self.self = None Resource.__init__(self, path, options, session, self.AGILE_BASE_URL) @@ -938,12 +1206,18 @@ def __init__(self, path, options, session, raw): # Old GreenHopper API did not contain self - create it for backward compatibility. if not self.self: self.self = self._get_url(path.format(raw["id"])) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class Sprint(GreenHopperResource): """A GreenHopper sprint.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): GreenHopperResource.__init__(self, "sprint/{0}", options, session, raw) def find(self, id, params=None): @@ -954,14 +1228,19 @@ def find(self, id, params=None): Resource.find(self, id, params) else: # Old, private GreenHopper API had non-standard way of loading Sprint - url = self._get_url("sprint/%s/edit/model" % id) + url = self._get_url(f"sprint/{id}/edit/model") self._load(url, params=params, path="sprint") class Board(GreenHopperResource): """A GreenHopper board.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): path = ( "rapidview/{0}" if options["agile_rest_path"] == self.GREENHOPPER_REST_PATH @@ -987,18 +1266,29 @@ def delete(self, params=None): class Customer(Resource): """A Service Desk customer.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__( self, "customer", options, session, "{server}/rest/servicedeskapi/{path}" ) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class ServiceDesk(Resource): """A Service Desk.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__( self, "servicedesk/{0}", @@ -1008,15 +1298,18 @@ def __init__(self, options, session, raw=None): ) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) class RequestType(Resource): """A Service Desk Request Type.""" - def __init__(self, options, session, raw=None): - if raw: - self._parse_raw(raw) - + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__( self, "servicedesk/{0}/requesttype", @@ -1025,11 +1318,17 @@ def __init__(self, options, session, raw=None): "{server}/rest/servicedeskapi/{path}", ) + if raw: + self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) + # Utilities -def dict2resource(raw, top=None, options=None, session=None): +def dict2resource( + raw: Dict[str, Any], top=None, options=None, session=None +) -> Union["PropertyHolder", Type[Resource]]: """Convert a dictionary into a Jira Resource object. Recursively walks a dict structure, transforming the properties into attributes @@ -1043,19 +1342,36 @@ def dict2resource(raw, top=None, options=None, session=None): for i, j in raw.items(): if isinstance(j, dict): if "self" in j: - resource = cls_for_resource(j["self"])(options, session, j) + # to try and help mypy know that cls_for_resource can never be 'Resource' + resource_class = cast(Type[Resource], cls_for_resource(j["self"])) + resource = cast( + Type[Resource], + resource_class( # type: ignore + options=options, session=session, raw=j # type: ignore + ), + ) setattr(top, i, resource) elif i == "timetracking": setattr(top, "timetracking", TimeTracking(options, session, j)) else: setattr(top, i, dict2resource(j, options=options, session=session)) elif isinstance(j, seqs): - seq_list = [] + j = cast(List[Dict[str, Any]], j) # help mypy + seq_list: List[Any] = [] for seq_elem in j: if isinstance(seq_elem, dict): if "self" in seq_elem: - resource = cls_for_resource(seq_elem["self"])( - options, session, seq_elem + # to try and help mypy know that cls_for_resource can never be 'Resource' + resource_class = cast( + Type[Resource], cls_for_resource(seq_elem["self"]) + ) + resource = cast( + Type[Resource], + resource_class( # type: ignore + options=options, + session=session, + raw=seq_elem, # type: ignore + ), ) seq_list.append(resource) else: @@ -1070,7 +1386,7 @@ def dict2resource(raw, top=None, options=None, session=None): return top -resource_class_map = { +resource_class_map: Dict[str, Type[Resource]] = { # Jira-specific resources r"attachment/[^/]+$": Attachment, r"component/[^/]+$": Component, @@ -1088,11 +1404,12 @@ def dict2resource(raw, top=None, options=None, session=None): r"priority/[^/]+$": Priority, r"project/[^/]+$": Project, r"project/[^/]+/role/[^/]+$": Role, + r"project/[^/]+/permissionscheme[^/]+$": PermissionScheme, r"resolution/[^/]+$": Resolution, r"securitylevel/[^/]+$": SecurityLevel, r"status/[^/]+$": Status, r"statuscategory/[^/]+$": StatusCategory, - r"user\?(username|accountId).+$": User, + r"user\?(username|key).+$": User, r"group\?groupname.+$": Group, r"version/[^/]+$": Version, # GreenHopper specific resources @@ -1104,13 +1421,19 @@ def dict2resource(raw, top=None, options=None, session=None): class UnknownResource(Resource): """A Resource from Jira that is not (yet) supported.""" - def __init__(self, options, session, raw=None): + def __init__( + self, + options: Dict[str, str], + session: ResilientSession, + raw: Dict[str, Any] = None, + ): Resource.__init__(self, "unknown{0}", options, session) if raw: self._parse_raw(raw) + self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) -def cls_for_resource(resource_literal): +def cls_for_resource(resource_literal: str) -> Type[Resource]: for resource in resource_class_map: if re.search(resource, resource_literal): return resource_class_map[resource] @@ -1119,6 +1442,6 @@ def cls_for_resource(resource_literal): return UnknownResource -class PropertyHolder(object): +class PropertyHolder: def __init__(self, raw): __bases__ = raw # noqa diff --git a/jira/utils/__init__.py b/jira/utils/__init__.py index c339b3ba5..2c0e5a266 100644 --- a/jira/utils/__init__.py +++ b/jira/utils/__init__.py @@ -1,13 +1,19 @@ -# -*- coding: utf-8 -*- """Jira utils used internally.""" import threading +import warnings +from typing import Any, Optional, cast + +from requests import Response +from requests.structures import CaseInsensitiveDict as _CaseInsensitiveDict from jira.resilientsession import raise_on_error -class CaseInsensitiveDict(dict): +class CaseInsensitiveDict(_CaseInsensitiveDict): """A case-insensitive ``dict``-like object. + DEPRECATED: use requests.structures.CaseInsensitiveDict directly. + Implements all methods and operations of ``collections.MutableMapping`` as well as dict's ``copy``. Also provides ``lower_items``. @@ -28,37 +34,16 @@ class CaseInsensitiveDict(dict): of how the header name was originally stored. If the constructor, ``.update``, or equality comparison - operations are given keys that have equal ``.lower()``s, the + operations are given keys that have equal ``.lower()`` s, the behavior is undefined. """ - def __init__(self, *args, **kw): - super(CaseInsensitiveDict, self).__init__(*args, **kw) - - self.itemlist = {} - for key, value in super(CaseInsensitiveDict, self).copy().items(): - if key != key.lower(): - self[key.lower()] = value - self.pop(key, None) - - # self.itemlist[key.lower()] = value - - def __setitem__(self, key, value): - """Overwrite [] implementation.""" - super(CaseInsensitiveDict, self).__setitem__(key.lower(), value) - - # def __iter__(self): - # return iter(self.itemlist) - - # def keys(self): - # return self.itemlist - - # def values(self): - # return [self[key] for key in self] - - # def itervalues(self): - # return (self[key] for key in self) + def __init__(self, *args, **kwargs) -> None: + warnings.warn( + "Use requests.structures.CaseInsensitiveDict directly", DeprecationWarning + ) + super().__init__(*args, **kwargs) def threaded_requests(requests): @@ -71,8 +56,20 @@ def threaded_requests(requests): th.join() -def json_loads(r): - raise_on_error(r) +def json_loads(r: Optional[Response]) -> Any: + """Attempts to load json the result of a response + + Args: + r (Optional[Response]): The Response object + + Raises: + JIRAError: via :py:func:`jira.resilientsession.raise_on_error` + + Returns: + Union[List[Dict[str, Any]], Dict[str, Any]]: the json + """ + raise_on_error(r) # if 'r' is None, will raise an error here + r = cast(Response, r) # tell mypy only Response-like are here try: return r.json() except ValueError: diff --git a/make_local_jira_user.py b/make_local_jira_user.py new file mode 100644 index 000000000..45c8d8f91 --- /dev/null +++ b/make_local_jira_user.py @@ -0,0 +1,50 @@ +"""Attempts to create a test user, +as the empty JIRA instance isn't provisioned with one. +""" +import time +from os import environ + +import requests + +from jira import JIRA + +CI_JIRA_URL = environ["CI_JIRA_URL"] + + +def add_user_to_jira(): + try: + JIRA( + CI_JIRA_URL, + basic_auth=(environ["CI_JIRA_ADMIN"], environ["CI_JIRA_ADMIN_PASSWORD"]), + ).add_user( + username=environ["CI_JIRA_USER"], + email="user@example.com", + fullname=environ["CI_JIRA_USER_FULL_NAME"], + password=environ["CI_JIRA_USER_PASSWORD"], + ) + print("user", environ["CI_JIRA_USER"]) + except Exception as e: + if "username already exists" not in str(e): + raise e + + +if __name__ == "__main__": + start_time = time.time() + timeout_mins = 15 + print( + "waiting for instance of jira to be running, to add a user for CI system:\n" + f" timeout = {timeout_mins} mins" + ) + while True: + try: + requests.get(CI_JIRA_URL + "rest/api/2/permissions") + print("JIRA IS REACHABLE") + add_user_to_jira() + break + except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as ex: + print(f"encountered {ex} while waiting for the JiraServer docker") + time.sleep(20) + if start_time + 60 * timeout_mins < time.time(): + raise TimeoutError( + f"Jira server wasn't reachable within timeout {timeout_mins}" + ) diff --git a/package.json b/package.json deleted file mode 100644 index 070c353cd..000000000 --- a/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "python-jira", - "version": "0.0.1", - "license": "SEE LICENSE IN LICENSE", - "scripts": { - "spell": "npm -s run spell-files && npm -s run spell-commit", - "spell-commit": "git log -1 --pretty=%B > .git/commit.msg && cspell .git/commit.msg", - "spell-files": "git ls-files | xargs cspell --unique" - }, - "repository": { - "type": "git", - "url": "https://github.com/pycontribs/jira.git" - }, - "dependencies": { - "cspell": "^4.0.23", - "npm": "^6.10.0" - } -} diff --git a/pyproject.toml b/pyproject.toml index ba41bc7f5..3b9e229bd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,5 +5,5 @@ requires = [ "setuptools_scm_git_archive >= 1.0", "wheel", ] -requires-python = ">=3.5" +requires-python = ">3.5" build-backend = "setuptools.build_meta" diff --git a/setup.cfg b/setup.cfg index 545190166..600285b78 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,24 +1,24 @@ [metadata] name = jira author = Ben Speakmon -author-email = ben.speakmon@gmail.com +author_email = ben.speakmon@gmail.com maintainer = Sorin Sbarnea -maintainer-email = sorin.sbarnea@gmail.com -summary = Python library for interacting with Jira via REST APIs. -long-description = file: README.rst +maintainer_email = sorin.sbarnea@gmail.com +summary = Python library for interacting with JIRA via REST APIs. +long_description = file: README.rst # Do not include ChangeLog in description-file due to multiple reasons: # - Unicode chars, see https://github.com/pycontribs/jira/issues/512 # - Breaks ability to perform `python setup.py install` -long-description-content-type = text/x-rst; charset=UTF-8 -home-page = https://github.com/pycontribs/jira -project-urls = +long_description_content_type = text/x-rst; charset=UTF-8 +url = https://github.com/pycontribs/jira +project_urls = Bug Tracker = https://github.com/pycontribs/jira/issues Release Management = https://github.com/pycontribs/jira/projects - CI: Travis = https://travis-ci.com/pycontribs/jira + CI: GitHub Actions = https://github.com/pycontribs/jira/actions Source Code = https://github.com/pycontribs/jira.git Documentation = https://jira.readthedocs.io/en/master/ Forum = https://community.atlassian.com/t5/tag/jira-python/tg-p?sort=recent -requires-python = >=3.5 +requires_python = >=3.6 platforms = any license = BSD classifiers = @@ -31,9 +31,10 @@ classifiers = Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3 :: Only - Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 Topic :: Software Development :: Libraries :: Python Modules Topic :: Internet :: WWW/HTTP keywords = api, atlassian, jira, rest, web @@ -44,7 +45,7 @@ packages = [options] use_scm_version = True -python_requires = >=3.5 +python_requires = >=3.6 packages = find: include_package_data = True zip_safe = False @@ -77,17 +78,15 @@ test = docutils>=0.12 flaky MarkupSafe>=0.23 - mypy oauthlib - pre-commit # MIT py >= 1.4 pytest-cache pytest-cov pytest-instafail pytest-sugar pytest-timeout>=1.3.1 - pytest-xdist>=1.14 - pytest>=5.0.0,<6.0 # MIT + pytest-xdist>=2.2 + pytest>=6.0.0,<7.0 # MIT PyYAML>=5.1 # MIT requests_mock # Apache-2 requires.io # UNKNOWN!!! @@ -100,6 +99,9 @@ test = console_scripts = jirashell = jira.jirashell:main +[options.package_data] +jira = jira/py.typed + [egg_info] egg_base = . @@ -127,6 +129,19 @@ ignore = E741,W503,W504,H,E501,E203 # 88 is official black default: max-line-length = 88 +[isort] +# start - black compatible settings +multi_line_output = 3 +include_trailing_comma = True +force_grid_wrap = 0 +use_parentheses = True +ensure_newline_before_comments = True +line_length = 88 +# end - black compatible settings +known_first_party = + jira + tests + [tool:pytest] norecursedirs = . jira _build tmp* lib/third lib *.egg bin distutils build docs demo python_files = *.py @@ -146,4 +161,4 @@ filterwarnings = ignore::pytest.PytestWarning [mypy] -python_version = 3.5 +python_version = 3.6 diff --git a/setup.py b/setup.py index 140dc8d4d..a5bf1b484 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,5 @@ # !/usr/bin/env python import setuptools - if __name__ == "__main__": setuptools.setup(use_scm_version=True) diff --git a/test.local b/test.local deleted file mode 100755 index ebd061bbc..000000000 --- a/test.local +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash - -# Settings for using the Vagrant VM from atlassian -# (see https://developer.atlassian.com/static/connect/docs/latest/developing/developing-locally.html) -# a user "jira_user" with password "jira" needs to be created manually -export CI_JIRA_URL="http://localhost:2990/jira" -export CI_JIRA_ADMIN="admin" -export CI_JIRA_ADMIN_PASSWORD="admin" -export CI_JIRA_USER=jira_user -export CI_JIRA_USER_PASSWORD=jira -export CI_JIRA_ISSUE=Task - -if [ "$1" = "--tox" ] ; then - shift - exec tox "$@" -else - exec python -m pytest --cov-report xml --cov jira --pyargs jira "$@" -fi diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..16c21845a --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,7 @@ +"""All the tests for the jira package. + +Refer to conftest.py for shared helper methods. + +resources/test_* : For tests related to resources +test_* : For other tests of the non-resource elements of the jira package. +""" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..bc81c0a9d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,353 @@ +import getpass +import hashlib +import logging +import os +import random +import re +import string +import sys +import unittest +from time import sleep +from typing import Any, Dict + +import pytest +from flaky import flaky + +from jira import JIRA + +TEST_ROOT = os.path.dirname(__file__) +TEST_ICON_PATH = os.path.join(TEST_ROOT, "icon.png") +TEST_ATTACH_PATH = os.path.join(TEST_ROOT, "tests.py") + +LOGGER = logging.getLogger(__name__) + +OAUTH = False +CONSUMER_KEY = "oauth-consumer" +KEY_CERT_FILE = "/home/bspeakmon/src/atlassian-oauth-examples/rsa.pem" +KEY_CERT_DATA = None +try: + with open(KEY_CERT_FILE) as cert: + KEY_CERT_DATA = cert.read() + OAUTH = True +except Exception: + OAUTH = False + + +ON_CUSTOM_JIRA = "CI_JIRA_URL" in os.environ + + +not_on_custom_jira_instance = pytest.mark.skipif( + ON_CUSTOM_JIRA, reason="Not applicable for custom Jira instance" +) +if ON_CUSTOM_JIRA: + LOGGER.info("Picked up custom Jira engine.") + + +broken_test = pytest.mark.xfail + + +@flaky # all have default flaki-ness +class JiraTestCase(unittest.TestCase): + """Test case for all Jira tests. + + This is the base class for all Jira tests that require access to the + Jira instance. + + It calls JiraTestManager() in the setUp() method. + setUp() is the method that is called **before** each test is run. + + Where possible follow the: + + * GIVEN - where you set up any pre-requisites e.g. the expected result + * WHEN - where you perform the action and obtain the result + * THEN - where you assert the expectation vs the result + + format for tests. + """ + + jira: JIRA # admin authenticated + jira_normal: JIRA # non-admin authenticated + + def setUp(self) -> None: + """ + This is called before each test. If you want to add more for your tests, + Run `JiraTestCase.setUp(self) in your custom setUp() to obtain these. + """ + self.test_manager = JiraTestManager() + self.jira = self.test_manager.jira_admin + self.jira_normal = self.test_manager.jira_normal + self.user_admin = self.test_manager.user_admin + self.user_normal = self.test_manager.user_normal # use this user where possible + self.project_b = self.test_manager.project_b + self.project_a = self.test_manager.project_a + + +def rndstr(): + return "".join(random.sample(string.ascii_lowercase, 6)) + + +def rndpassword(): + # generates a password of length 14 + s = ( + "".join(random.sample(string.ascii_uppercase, 5)) + + "".join(random.sample(string.ascii_lowercase, 5)) + + "".join(random.sample(string.digits, 2)) + + "".join(random.sample("~`!@#$%^&*()_+-=[]\\{}|;':<>?,./", 2)) + ) + return "".join(random.sample(s, len(s))) + + +def hashify(some_string, max_len=8): + return hashlib.sha256(some_string.encode("utf-8")).hexdigest()[:8].upper() + + +def get_unique_project_name(): + user = re.sub("[^A-Z_]", "", getpass.getuser().upper()) + if "GITHUB_ACTION" in os.environ and "GITHUB_RUN_NUMBER" in os.environ: + # please note that user underline (_) is not supported by + # Jira even if it is documented as supported. + return "GH" + hashify(user + os.environ["GITHUB_RUN_NUMBER"]) + identifier = ( + user + chr(ord("A") + sys.version_info[0]) + chr(ord("A") + sys.version_info[1]) + ) + return "Z" + hashify(identifier) + + +class JiraTestManager: + """Instantiate and populate the JIRA instance with data for tests. + + Attributes: + CI_JIRA_ADMIN (str): Admin user account name. + CI_JIRA_USER (str): Limited user account name. + max_retries (int): number of retries to perform for recoverable HTTP errors. + """ + + __shared_state: Dict[Any, Any] = {} + + def __init__(self, jira_hosted_type="Server"): + """Instantiate and populate the JIRA instance""" + self.__dict__ = self.__shared_state + + if not self.__dict__: + self.initialized = False + self.max_retries = 5 + + if jira_hosted_type and jira_hosted_type == "Cloud": + self.set_jira_cloud_details() + else: + self.set_jira_server_details() + + jira_class_kwargs = { + "server": self.CI_JIRA_URL, + "logging": False, + "validate": True, + "max_retries": self.max_retries, + } + if OAUTH: + self.set_oauth_logins() + else: + self.set_basic_auth_logins(**jira_class_kwargs) + + if not self.jira_admin.current_user(): + self.initialized = True + sys.exit(3) + + # now we need to create some data to start with for the tests + self.create_some_data() + + if not hasattr(self, "jira_normal") or not hasattr(self, "jira_admin"): + pytest.exit("FATAL: WTF!?") + + self.user_admin = self.jira_admin.search_users(self.CI_JIRA_ADMIN)[0] + self.user_normal = self.jira_admin.search_users(self.CI_JIRA_USER)[0] + self.initialized = True + + def set_jira_cloud_details(self): + self.CI_JIRA_URL = "https://pycontribs.atlassian.net" + self.CI_JIRA_ADMIN = "ci-admin" + self.CI_JIRA_ADMIN_PASSWORD = "sd4s3dgec5fhg4tfsds3434" + self.CI_JIRA_USER = "ci-user" + self.CI_JIRA_USER_PASSWORD = "sd4s3dgec5fhg4tfsds3434" + + def set_jira_server_details(self): + self.CI_JIRA_URL = os.environ["CI_JIRA_URL"] + self.CI_JIRA_ADMIN = os.environ["CI_JIRA_ADMIN"] + self.CI_JIRA_ADMIN_PASSWORD = os.environ["CI_JIRA_ADMIN_PASSWORD"] + self.CI_JIRA_USER = os.environ["CI_JIRA_USER"] + self.CI_JIRA_USER_PASSWORD = os.environ["CI_JIRA_USER_PASSWORD"] + self.CI_JIRA_ISSUE = os.environ.get("CI_JIRA_ISSUE", "Bug") + + def set_oauth_logins(self): + self.jira_admin = JIRA( + oauth={ + "access_token": "hTxcwsbUQiFuFALf7KZHDaeAJIo3tLUK", + "access_token_secret": "aNCLQFP3ORNU6WY7HQISbqbhf0UudDAf", + "consumer_key": CONSUMER_KEY, + "key_cert": KEY_CERT_DATA, + } + ) + self.jira_sysadmin = JIRA( + oauth={ + "access_token": "4ul1ETSFo7ybbIxAxzyRal39cTrwEGFv", + "access_token_secret": "K83jBZnjnuVRcfjBflrKyThJa0KSjSs2", + "consumer_key": CONSUMER_KEY, + "key_cert": KEY_CERT_DATA, + }, + logging=False, + max_retries=self.max_retries, + ) + self.jira_normal = JIRA( + oauth={ + "access_token": "ZVDgYDyIQqJY8IFlQ446jZaURIz5ECiB", + "access_token_secret": "5WbLBybPDg1lqqyFjyXSCsCtAWTwz1eD", + "consumer_key": CONSUMER_KEY, + "key_cert": KEY_CERT_DATA, + } + ) + + def set_basic_auth_logins(self, **jira_class_kwargs): + if self.CI_JIRA_ADMIN: + self.jira_admin = JIRA( + basic_auth=(self.CI_JIRA_ADMIN, self.CI_JIRA_ADMIN_PASSWORD), + **jira_class_kwargs, + ) + self.jira_sysadmin = JIRA( + basic_auth=(self.CI_JIRA_ADMIN, self.CI_JIRA_ADMIN_PASSWORD), + **jira_class_kwargs, + ) + self.jira_normal = JIRA( + basic_auth=(self.CI_JIRA_USER, self.CI_JIRA_USER_PASSWORD), + **jira_class_kwargs, + ) + else: + # Setup some un-authenticated users + self.jira_admin = JIRA(self.CI_JIRA_URL, **jira_class_kwargs) + self.jira_sysadmin = JIRA(self.CI_JIRA_URL, **jira_class_kwargs) + self.jira_normal = JIRA(self.CI_JIRA_URL, **jira_class_kwargs) + + def create_some_data(self): + """Create some data for the tests""" + + # jira project key is max 10 chars, no letter. + # [0] always "Z" + # [1-6] username running the tests (hope we will not collide) + # [7-8] python version A=0, B=1,.. + # [9] A,B -- we may need more than one project + + """ `jid` is important for avoiding concurrency problems when + executing tests in parallel as we have only one test instance. + + jid length must be less than 9 characters because we may append + another one and the Jira Project key length limit is 10. + """ + + self.jid = get_unique_project_name() + + self.project_a = self.jid + "A" # old XSS + self.project_a_name = "Test user={} key={} A".format( + getpass.getuser(), + self.project_a, + ) + self.project_b = self.jid + "B" # old BULK + self.project_b_name = "Test user={} key={} B".format( + getpass.getuser(), + self.project_b, + ) + self.project_sd = self.jid + "C" + self.project_sd_name = "Test user={} key={} C".format( + getpass.getuser(), + self.project_sd, + ) + + # TODO(ssbarnea): find a way to prevent SecurityTokenMissing for On Demand + # https://jira.atlassian.com/browse/JRA-39153 + try: + self.jira_admin.project(self.project_a) + except Exception as e: + LOGGER.warning(e) + else: + try: + self.jira_admin.delete_project(self.project_a) + except Exception as e: + LOGGER.warning("Failed to delete %s\n%s", self.project_a, e) + + try: + self.jira_admin.project(self.project_b) + except Exception as e: + LOGGER.warning(e) + else: + try: + self.jira_admin.delete_project(self.project_b) + except Exception as e: + LOGGER.warning("Failed to delete %s\n%s", self.project_b, e) + + # wait for the project to be deleted + for _ in range(1, 20): + try: + self.jira_admin.project(self.project_b) + except Exception: + break + print("Warning: Project not deleted yet....") + sleep(2) + + for _ in range(6): + try: + if self.jira_admin.create_project(self.project_a, self.project_a_name): + break + except Exception as e: + if "A project with that name already exists" not in str(e): + raise e + self.project_a_id = self.jira_admin.project(self.project_a).id + self.jira_admin.create_project(self.project_b, self.project_b_name) + + try: + self.jira_admin.create_project(self.project_b, self.project_b_name) + except Exception: + # we care only for the project to exist + pass + sleep(1) # keep it here as often Jira will report the + # project as missing even after is created + self.project_b_issue1_obj = self.jira_admin.create_issue( + project=self.project_b, + summary="issue 1 from %s" % self.project_b, + issuetype=self.CI_JIRA_ISSUE, + ) + self.project_b_issue1 = self.project_b_issue1_obj.key + + self.project_b_issue2_obj = self.jira_admin.create_issue( + project=self.project_b, + summary="issue 2 from %s" % self.project_b, + issuetype={"name": self.CI_JIRA_ISSUE}, + ) + self.project_b_issue2 = self.project_b_issue2_obj.key + + self.project_b_issue3_obj = self.jira_admin.create_issue( + project=self.project_b, + summary="issue 3 from %s" % self.project_b, + issuetype={"name": self.CI_JIRA_ISSUE}, + ) + self.project_b_issue3 = self.project_b_issue3_obj.key + + +def find_by_key(seq, key): + for seq_item in seq: + if seq_item["key"] == key: + return seq_item + + +def find_by_key_value(seq, key): + for seq_item in seq: + if seq_item.key == key: + return seq_item + + +def find_by_id(seq, id): + for seq_item in seq: + if seq_item.id == id: + return seq_item + + +def find_by_name(seq, name): + for seq_item in seq: + if seq_item["name"] == name: + return seq_item diff --git a/tests/resources/__init__.py b/tests/resources/__init__.py new file mode 100644 index 000000000..845fcce77 --- /dev/null +++ b/tests/resources/__init__.py @@ -0,0 +1,5 @@ +"""Tests grouped by Resource type + +The resources/ folder contains tests grouped per +jira.resource.Resource with files for each of its subclasses. +""" diff --git a/tests/resources/test_attachment.py b/tests/resources/test_attachment.py new file mode 100644 index 000000000..71dbb86a3 --- /dev/null +++ b/tests/resources/test_attachment.py @@ -0,0 +1,43 @@ +import os + +from tests.conftest import TEST_ATTACH_PATH, JiraTestCase + + +class AttachmentTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue_1 = self.test_manager.project_b_issue1 + self.attachment = None + + def test_0_attachment_meta(self): + meta = self.jira.attachment_meta() + self.assertTrue(meta["enabled"]) + # we have no control over server side upload limit + self.assertIn("uploadLimit", meta) + + def test_1_add_remove_attachment_using_filestream(self): + issue = self.jira.issue(self.issue_1) + with open(TEST_ATTACH_PATH, "rb") as f: + attachment = self.jira.add_attachment(issue, f, "new test attachment") + new_attachment = self.jira.attachment(attachment.id) + msg = f"attachment {new_attachment.__dict__} of issue {issue}" + self.assertEqual(new_attachment.filename, "new test attachment", msg=msg) + self.assertEqual( + new_attachment.size, os.path.getsize(TEST_ATTACH_PATH), msg=msg + ) + # JIRA returns a HTTP 204 upon successful deletion + self.assertEqual(attachment.delete().status_code, 204) + + def test_2_add_remove_attachment_using_filename(self): + issue = self.jira.issue(self.issue_1) + attachment = self.jira.add_attachment( + issue, TEST_ATTACH_PATH, "new test attachment" + ) + new_attachment = self.jira.attachment(attachment.id) + msg = f"attachment {new_attachment.__dict__} of issue {issue}" + self.assertEqual(new_attachment.filename, "new test attachment", msg=msg) + self.assertEqual( + new_attachment.size, os.path.getsize(TEST_ATTACH_PATH), msg=msg + ) + # JIRA returns a HTTP 204 upon successful deletion + self.assertEqual(attachment.delete().status_code, 204) diff --git a/tests/resources/test_board.py b/tests/resources/test_board.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/resources/test_comment.py b/tests/resources/test_comment.py new file mode 100644 index 000000000..950ec4571 --- /dev/null +++ b/tests/resources/test_comment.py @@ -0,0 +1,69 @@ +from tests.conftest import JiraTestCase + + +class CommentTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue_1 = self.test_manager.project_b_issue1 + self.issue_2 = self.test_manager.project_b_issue2 + self.issue_3 = self.test_manager.project_b_issue3 + + def test_comments(self): + for issue in [self.issue_1, self.jira.issue(self.issue_2)]: + self.jira.issue(issue) + comment1 = self.jira.add_comment(issue, "First comment") + comment2 = self.jira.add_comment(issue, "Second comment") + comments = self.jira.comments(issue) + assert comments[0].body == "First comment" + assert comments[1].body == "Second comment" + comment1.delete() + comment2.delete() + comments = self.jira.comments(issue) + assert len(comments) == 0 + + def test_expanded_comments(self): + comment1 = self.jira.add_comment(self.issue_1, "First comment") + comment2 = self.jira.add_comment(self.issue_1, "Second comment") + comments = self.jira.comments(self.issue_1, expand="renderedBody") + self.assertTrue(hasattr(comments[0], "renderedBody")) + ret_comment1 = self.jira.comment( + self.issue_1, comment1.id, expand="renderedBody" + ) + ret_comment2 = self.jira.comment(self.issue_1, comment2.id) + comment1.delete() + comment2.delete() + self.assertTrue(hasattr(ret_comment1, "renderedBody")) + self.assertFalse(hasattr(ret_comment2, "renderedBody")) + comments = self.jira.comments(self.issue_1) + assert len(comments) == 0 + + def test_add_comment(self): + comment = self.jira.add_comment( + self.issue_3, + "a test comment!", + visibility={"type": "role", "value": "Administrators"}, + ) + self.assertEqual(comment.body, "a test comment!") + self.assertEqual(comment.visibility.type, "role") + self.assertEqual(comment.visibility.value, "Administrators") + comment.delete() + + def test_add_comment_with_issue_obj(self): + issue = self.jira.issue(self.issue_3) + comment = self.jira.add_comment( + issue, + "a new test comment!", + visibility={"type": "role", "value": "Administrators"}, + ) + self.assertEqual(comment.body, "a new test comment!") + self.assertEqual(comment.visibility.type, "role") + self.assertEqual(comment.visibility.value, "Administrators") + comment.delete() + + def test_update_comment(self): + comment = self.jira.add_comment(self.issue_3, "updating soon!") + comment.update(body="updated!") + self.assertEqual(comment.body, "updated!") + # self.assertEqual(comment.visibility.type, 'role') + # self.assertEqual(comment.visibility.value, 'Administrators') + comment.delete() diff --git a/tests/resources/test_component.py b/tests/resources/test_component.py new file mode 100644 index 000000000..95099a6ea --- /dev/null +++ b/tests/resources/test_component.py @@ -0,0 +1,82 @@ +from jira.exceptions import JIRAError +from tests.conftest import JiraTestCase, rndstr + + +class ComponentTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue_1 = self.test_manager.project_b_issue1 + self.issue_2 = self.test_manager.project_b_issue2 + + def test_2_create_component(self): + proj = self.jira.project(self.project_b) + name = f"project-{proj}-component-{rndstr()}" + component = self.jira.create_component( + name, + proj, + description="test!!", + assigneeType="COMPONENT_LEAD", + isAssigneeTypeValid=False, + ) + self.assertEqual(component.name, name) + self.assertEqual(component.description, "test!!") + self.assertEqual(component.assigneeType, "COMPONENT_LEAD") + self.assertFalse(component.isAssigneeTypeValid) + component.delete() + + # Components field can't be modified from issue.update + # def test_component_count_related_issues(self): + # component = self.jira.create_component('PROJECT_B_TEST',self.project_b, description='test!!', + # assigneeType='COMPONENT_LEAD', isAssigneeTypeValid=False) + # issue1 = self.jira.issue(self.issue_1) + # issue2 = self.jira.issue(self.issue_2) + # (issue1.update ({'components': ['PROJECT_B_TEST']})) + # (issue2.update (components = ['PROJECT_B_TEST'])) + # issue_count = self.jira.component_count_related_issues(component.id) + # self.assertEqual(issue_count, 2) + # component.delete() + + def test_3_update(self): + try: + components = self.jira.project_components(self.project_b) + for component in components: + if component.name == "To be updated": + component.delete() + break + except Exception: + # We ignore errors as this code intends only to prepare for + # component creation + raise + + name = "component-" + rndstr() + + component = self.jira.create_component( + name, + self.project_b, + description="stand by!", + leadUserName=self.jira.current_user(), + ) + name = "renamed-" + name + component.update( + name=name, description="It is done.", leadUserName=self.jira.current_user() + ) + self.assertEqual(component.name, name) + self.assertEqual(component.description, "It is done.") + self.assertEqual(component.lead.name, self.jira.current_user()) + component.delete() + + def test_4_delete(self): + component = self.jira.create_component( + "To be deleted", self.project_b, description="not long for this world" + ) + myid = component.id + component.delete() + self.assertRaises(JIRAError, self.jira.component, myid) + + def test_delete_component_by_id(self): + component = self.jira.create_component( + "To be deleted", self.project_b, description="not long for this world" + ) + myid = component.id + self.jira.delete_component(myid) + self.assertRaises(JIRAError, self.jira.component, myid) diff --git a/tests/resources/test_custom_field_option.py b/tests/resources/test_custom_field_option.py new file mode 100644 index 000000000..273da848a --- /dev/null +++ b/tests/resources/test_custom_field_option.py @@ -0,0 +1,7 @@ +from tests.conftest import JiraTestCase + + +class CustomFieldOptionTests(JiraTestCase): + def test_custom_field_option(self): + option = self.jira.custom_field_option("10000") + self.assertEqual(option.value, "To Do") diff --git a/tests/resources/test_customer.py b/tests/resources/test_customer.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/resources/test_dashboard.py b/tests/resources/test_dashboard.py new file mode 100644 index 000000000..7a0b0af79 --- /dev/null +++ b/tests/resources/test_dashboard.py @@ -0,0 +1,29 @@ +from tests.conftest import JiraTestCase, broken_test + + +class DashboardTests(JiraTestCase): + def test_dashboards(self): + dashboards = self.jira.dashboards() + self.assertGreaterEqual(len(dashboards), 1) + + @broken_test( + reason="standalone jira docker image has only 1 system dashboard by default" + ) + def test_dashboards_filter(self): + dashboards = self.jira.dashboards(filter="my") + self.assertEqual(len(dashboards), 2) + self.assertEqual(dashboards[0].id, "10101") + + def test_dashboards_startat(self): + dashboards = self.jira.dashboards(startAt=0, maxResults=1) + self.assertEqual(len(dashboards), 1) + + def test_dashboards_maxresults(self): + dashboards = self.jira.dashboards(maxResults=1) + self.assertEqual(len(dashboards), 1) + + def test_dashboard(self): + expected_ds = self.jira.dashboards()[0] + dashboard = self.jira.dashboard(expected_ds.id) + self.assertEqual(dashboard.id, expected_ds.id) + self.assertEqual(dashboard.name, expected_ds.name) diff --git a/tests/resources/test_filter.py b/tests/resources/test_filter.py new file mode 100644 index 000000000..43d2b705e --- /dev/null +++ b/tests/resources/test_filter.py @@ -0,0 +1,30 @@ +from tests.conftest import JiraTestCase, rndstr + + +class FilterTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue_1 = self.test_manager.project_b_issue1 + self.issue_2 = self.test_manager.project_b_issue2 + + def test_filter(self): + jql = "project = %s and component is not empty" % self.project_b + name = "same filter " + rndstr() + myfilter = self.jira.create_filter( + name=name, description="just some new test filter", jql=jql, favourite=False + ) + self.assertEqual(myfilter.name, name) + self.assertEqual(myfilter.owner.name, self.test_manager.user_admin.name) + myfilter.delete() + + def test_favourite_filters(self): + # filters = self.jira.favourite_filters() + jql = "project = %s and component is not empty" % self.project_b + name = "filter-to-fav-" + rndstr() + myfilter = self.jira.create_filter( + name=name, description="just some new test filter", jql=jql, favourite=True + ) + new_filters = self.jira.favourite_filters() + + assert name in [f.name for f in new_filters] + myfilter.delete() diff --git a/tests/resources/test_generic_resource.py b/tests/resources/test_generic_resource.py new file mode 100644 index 000000000..16030b5c6 --- /dev/null +++ b/tests/resources/test_generic_resource.py @@ -0,0 +1,55 @@ +import unittest + +from flaky import flaky + +from jira.resources import ( + Group, + Issue, + Project, + Role, + UnknownResource, + cls_for_resource, +) + + +@flaky +class ResourceTests(unittest.TestCase): + def setUp(self): + pass + + def test_cls_for_resource(self): + self.assertEqual( + cls_for_resource( + "https://jira.atlassian.com/rest/\ + api/latest/issue/JRA-1330" + ), + Issue, + ) + self.assertEqual( + cls_for_resource( + "http://localhost:2990/jira/rest/\ + api/latest/project/BULK" + ), + Project, + ) + self.assertEqual( + cls_for_resource( + "http://imaginary-jira.com/rest/\ + api/latest/project/IMG/role/10002" + ), + Role, + ) + self.assertEqual( + cls_for_resource( + "http://customized-jira.com/rest/\ + plugin-resource/4.5/json/getMyObject" + ), + UnknownResource, + ) + self.assertEqual( + cls_for_resource( + "http://customized-jira.com/rest/\ + group?groupname=bla" + ), + Group, + ) diff --git a/tests/resources/test_group.py b/tests/resources/test_group.py new file mode 100644 index 000000000..8be77dd2a --- /dev/null +++ b/tests/resources/test_group.py @@ -0,0 +1,15 @@ +from tests.conftest import JiraTestCase + + +class GroupsTest(JiraTestCase): + def test_group(self): + group = self.jira.group("jira-administrators") + self.assertEqual(group.name, "jira-administrators") + + def test_groups(self): + groups = self.jira.groups() + self.assertGreater(len(groups), 0) + + def test_groups_for_users(self): + groups = self.jira.groups("jira-administrators") + self.assertGreater(len(groups), 0) diff --git a/tests/resources/test_issue.py b/tests/resources/test_issue.py new file mode 100644 index 000000000..ca7bcbcd0 --- /dev/null +++ b/tests/resources/test_issue.py @@ -0,0 +1,497 @@ +import logging +import re +from time import sleep + +from jira.exceptions import JIRAError +from tests.conftest import ( + JiraTestCase, + broken_test, + find_by_key, + find_by_key_value, + rndstr, +) + +LOGGER = logging.getLogger(__name__) + + +class IssueTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue_1 = self.test_manager.project_b_issue1 + self.issue_2 = self.test_manager.project_b_issue2 + self.issue_3 = self.test_manager.project_b_issue3 + + def test_issue(self): + issue = self.jira.issue(self.issue_1) + self.assertEqual(issue.key, self.issue_1) + self.assertEqual(issue.fields.summary, "issue 1 from %s" % self.project_b) + + def test_issue_field_limiting(self): + issue = self.jira.issue(self.issue_2, fields="summary,comment") + self.assertEqual(issue.fields.summary, "issue 2 from %s" % self.project_b) + comment1 = self.jira.add_comment(issue, "First comment") + comment2 = self.jira.add_comment(issue, "Second comment") + comment3 = self.jira.add_comment(issue, "Third comment") + self.jira.issue(self.issue_2, fields="summary,comment") + LOGGER.warning(issue.raw["fields"]) + self.assertFalse(hasattr(issue.fields, "reporter")) + self.assertFalse(hasattr(issue.fields, "progress")) + comment1.delete() + comment2.delete() + comment3.delete() + + def test_issue_equal(self): + issue1 = self.jira.issue(self.issue_1) + issue2 = self.jira.issue(self.issue_2) + issues = self.jira.search_issues("key=%s" % self.issue_1) + self.assertTrue(issue1 is not None) + self.assertTrue(issue1 == issues[0]) + self.assertFalse(issue2 == issues[0]) + + def test_issue_expand(self): + issue = self.jira.issue(self.issue_1, expand="editmeta,schema") + self.assertTrue(hasattr(issue, "editmeta")) + self.assertTrue(hasattr(issue, "schema")) + # testing for changelog is not reliable because it may exist or not based on test order + # self.assertFalse(hasattr(issue, 'changelog')) + + def test_create_issue_with_fieldargs(self): + issue = self.jira.create_issue( + summary="Test issue created", + project=self.project_b, + issuetype={"name": "Bug"}, + description="foo description", + ) # customfield_10022='XSS' + self.assertEqual(issue.fields.summary, "Test issue created") + self.assertEqual(issue.fields.description, "foo description") + self.assertEqual(issue.fields.issuetype.name, "Bug") + self.assertEqual(issue.fields.project.key, self.project_b) + # self.assertEqual(issue.fields.customfield_10022, 'XSS') + issue.delete() + + def test_create_issue_with_fielddict(self): + fields = { + "summary": "Issue created from field dict", + "project": {"key": self.project_b}, + "issuetype": {"name": "Bug"}, + "description": "Some new issue for test", + # 'customfield_10022': 'XSS', + "priority": {"name": "High"}, + } + issue = self.jira.create_issue(fields=fields) + self.assertEqual(issue.fields.summary, "Issue created from field dict") + self.assertEqual(issue.fields.description, "Some new issue for test") + self.assertEqual(issue.fields.issuetype.name, "Bug") + self.assertEqual(issue.fields.project.key, self.project_b) + # self.assertEqual(issue.fields.customfield_10022, 'XSS') + self.assertEqual(issue.fields.priority.name, "High") + issue.delete() + + def test_create_issue_without_prefetch(self): + issue = self.jira.create_issue( + summary="Test issue created", + project=self.project_b, + issuetype={"name": "Bug"}, + description="some details", + prefetch=False, + ) # customfield_10022='XSS' + + assert hasattr(issue, "self") + assert hasattr(issue, "raw") + assert "fields" not in issue.raw + issue.delete() + + def test_create_issues(self): + field_list = [ + { + "summary": "Issue created via bulk create #1", + "project": {"key": self.project_b}, + "issuetype": {"name": "Bug"}, + "description": "Some new issue for test", + # 'customfield_10022': 'XSS', + "priority": {"name": "High"}, + }, + { + "summary": "Issue created via bulk create #2", + "project": {"key": self.project_a}, + "issuetype": {"name": "Bug"}, + "description": "Another new issue for bulk test", + "priority": {"name": "High"}, + }, + ] + issues = self.jira.create_issues(field_list=field_list) + self.assertEqual(len(issues), 2) + self.assertIsNotNone(issues[0]["issue"], "the first issue has not been created") + self.assertEqual( + issues[0]["issue"].fields.summary, "Issue created via bulk create #1" + ) + self.assertEqual( + issues[0]["issue"].fields.description, "Some new issue for test" + ) + self.assertEqual(issues[0]["issue"].fields.issuetype.name, "Bug") + self.assertEqual(issues[0]["issue"].fields.project.key, self.project_b) + self.assertEqual(issues[0]["issue"].fields.priority.name, "High") + self.assertIsNotNone( + issues[1]["issue"], "the second issue has not been created" + ) + self.assertEqual( + issues[1]["issue"].fields.summary, "Issue created via bulk create #2" + ) + self.assertEqual( + issues[1]["issue"].fields.description, "Another new issue for bulk test" + ) + self.assertEqual(issues[1]["issue"].fields.issuetype.name, "Bug") + self.assertEqual(issues[1]["issue"].fields.project.key, self.project_a) + self.assertEqual(issues[1]["issue"].fields.priority.name, "High") + for issue in issues: + issue["issue"].delete() + + def test_create_issues_one_failure(self): + field_list = [ + { + "summary": "Issue created via bulk create #1", + "project": {"key": self.project_b}, + "issuetype": {"name": "Bug"}, + "description": "Some new issue for test", + # 'customfield_10022': 'XSS', + "priority": {"name": "High"}, + }, + { + "summary": "This issue will not succeed", + "project": {"key": self.project_a}, + "issuetype": {"name": "InvalidIssueType"}, + "description": "Should not be seen.", + "priority": {"name": "High"}, + }, + { + "summary": "However, this one will.", + "project": {"key": self.project_a}, + "issuetype": {"name": "Bug"}, + "description": "Should be seen.", + "priority": {"name": "High"}, + }, + ] + issues = self.jira.create_issues(field_list=field_list) + self.assertEqual( + issues[0]["issue"].fields.summary, "Issue created via bulk create #1" + ) + self.assertEqual( + issues[0]["issue"].fields.description, "Some new issue for test" + ) + self.assertEqual(issues[0]["issue"].fields.issuetype.name, "Bug") + self.assertEqual(issues[0]["issue"].fields.project.key, self.project_b) + self.assertEqual(issues[0]["issue"].fields.priority.name, "High") + self.assertEqual(issues[0]["error"], None) + self.assertEqual(issues[1]["issue"], None) + self.assertEqual(issues[1]["error"], {"issuetype": "issue type is required"}) + self.assertEqual(issues[1]["input_fields"], field_list[1]) + self.assertEqual(issues[2]["issue"].fields.summary, "However, this one will.") + self.assertEqual(issues[2]["issue"].fields.description, "Should be seen.") + self.assertEqual(issues[2]["issue"].fields.issuetype.name, "Bug") + self.assertEqual(issues[2]["issue"].fields.project.key, self.project_a) + self.assertEqual(issues[2]["issue"].fields.priority.name, "High") + self.assertEqual(issues[2]["error"], None) + self.assertEqual(len(issues), 3) + for issue in issues: + if issue["issue"] is not None: + issue["issue"].delete() + + def test_create_issues_without_prefetch(self): + field_list = [ + dict( + summary="Test issue #1 created with dicts without prefetch", + project=self.project_b, + issuetype={"name": "Bug"}, + description="some details", + ), + dict( + summary="Test issue #2 created with dicts without prefetch", + project=self.project_a, + issuetype={"name": "Bug"}, + description="foo description", + ), + ] + issues = self.jira.create_issues(field_list, prefetch=False) + + assert hasattr(issues[0]["issue"], "self") + assert hasattr(issues[0]["issue"], "raw") + assert hasattr(issues[1]["issue"], "self") + assert hasattr(issues[1]["issue"], "raw") + assert "fields" not in issues[0]["issue"].raw + assert "fields" not in issues[1]["issue"].raw + for issue in issues: + issue["issue"].delete() + + def test_update_with_fieldargs(self): + issue = self.jira.create_issue( + summary="Test issue for updating with fieldargs", + project=self.project_b, + issuetype={"name": "Bug"}, + description="Will be updated shortly", + ) + # customfield_10022='XSS') + issue.update( + summary="Updated summary", + description="Now updated", + issuetype={"name": "Task"}, + ) + self.assertEqual(issue.fields.summary, "Updated summary") + self.assertEqual(issue.fields.description, "Now updated") + self.assertEqual(issue.fields.issuetype.name, "Task") + # self.assertEqual(issue.fields.customfield_10022, 'XSS') + self.assertEqual(issue.fields.project.key, self.project_b) + issue.delete() + + def test_update_with_fielddict(self): + issue = self.jira.create_issue( + summary="Test issue for updating with fielddict", + project=self.project_b, + description="Will be updated shortly", + issuetype={"name": "Bug"}, + ) + fields = { + "summary": "Issue is updated", + "description": "it sure is", + "issuetype": {"name": "Task"}, + # 'customfield_10022': 'DOC', + "priority": {"name": "High"}, + } + issue.update(fields=fields) + self.assertEqual(issue.fields.summary, "Issue is updated") + self.assertEqual(issue.fields.description, "it sure is") + self.assertEqual(issue.fields.issuetype.name, "Task") + # self.assertEqual(issue.fields.customfield_10022, 'DOC') + self.assertEqual(issue.fields.priority.name, "High") + issue.delete() + + def test_update_with_label(self): + issue = self.jira.create_issue( + summary="Test issue for updating labels", + project=self.project_b, + description="Label testing", + issuetype=self.test_manager.CI_JIRA_ISSUE, + ) + + labelarray = ["testLabel"] + fields = {"labels": labelarray} + + issue.update(fields=fields) + self.assertEqual(issue.fields.labels, ["testLabel"]) + + def test_update_with_bad_label(self): + issue = self.jira.create_issue( + summary="Test issue for updating bad labels", + project=self.project_b, + description="Label testing", + issuetype=self.test_manager.CI_JIRA_ISSUE, + ) + + issue.fields.labels.append("this should not work") + + fields = {"labels": issue.fields.labels} + + self.assertRaises(JIRAError, issue.update, fields=fields) + + def test_update_with_notify_false(self): + issue = self.jira.create_issue( + summary="Test issue for updating wiith notify false", + project=self.project_b, + description="Will be updated shortly", + issuetype={"name": "Bug"}, + ) + issue.update(notify=False, description="Now updated, but silently") + self.assertEqual(issue.fields.description, "Now updated, but silently") + issue.delete() + + def test_delete(self): + issue = self.jira.create_issue( + summary="Test issue created", + project=self.project_b, + description="Not long for this world", + issuetype=self.test_manager.CI_JIRA_ISSUE, + ) + key = issue.key + issue.delete() + self.assertRaises(JIRAError, self.jira.issue, key) + + def test_createmeta(self): + meta = self.jira.createmeta() + proj = find_by_key(meta["projects"], self.project_b) + # we assume that this project should allow at least one issue type + self.assertGreaterEqual(len(proj["issuetypes"]), 1) + + def test_createmeta_filter_by_projectkey_and_name(self): + meta = self.jira.createmeta(projectKeys=self.project_b, issuetypeNames="Bug") + self.assertEqual(len(meta["projects"]), 1) + self.assertEqual(len(meta["projects"][0]["issuetypes"]), 1) + + def test_createmeta_filter_by_projectkeys_and_name(self): + meta = self.jira.createmeta( + projectKeys=(self.project_a, self.project_b), issuetypeNames="Task" + ) + self.assertEqual(len(meta["projects"]), 2) + for project in meta["projects"]: + self.assertEqual(len(project["issuetypes"]), 1) + + def test_createmeta_filter_by_id(self): + projects = self.jira.projects() + proja = find_by_key_value(projects, self.project_a) + projb = find_by_key_value(projects, self.project_b) + issue_type_ids = dict() + full_meta = self.jira.createmeta(projectIds=(proja.id, projb.id)) + for project in full_meta["projects"]: + for issue_t in project["issuetypes"]: + issue_t_id = issue_t["id"] + val = issue_type_ids.get(issue_t_id) + if val is None: + issue_type_ids[issue_t_id] = [] + issue_type_ids[issue_t_id].append([project["id"]]) + common_issue_ids = [] + for key, val in issue_type_ids.items(): + if len(val) == 2: + common_issue_ids.append(key) + self.assertNotEqual(len(common_issue_ids), 0) + for_lookup_common_issue_ids = common_issue_ids + if len(common_issue_ids) > 2: + for_lookup_common_issue_ids = common_issue_ids[:-1] + meta = self.jira.createmeta( + projectIds=(proja.id, projb.id), issuetypeIds=for_lookup_common_issue_ids + ) + self.assertEqual(len(meta["projects"]), 2) + for project in meta["projects"]: + self.assertEqual( + len(project["issuetypes"]), len(for_lookup_common_issue_ids) + ) + + def test_createmeta_expand(self): + # limit to SCR project so the call returns promptly + meta = self.jira.createmeta( + projectKeys=self.project_b, expand="projects.issuetypes.fields" + ) + self.assertTrue("fields" in meta["projects"][0]["issuetypes"][0]) + + def test_assign_issue(self): + self.assertTrue(self.jira.assign_issue(self.issue_1, self.user_normal.name)) + self.assertEqual( + self.jira.issue(self.issue_1).fields.assignee.name, self.user_normal.name + ) + + def test_assign_issue_with_issue_obj(self): + issue = self.jira.issue(self.issue_1) + x = self.jira.assign_issue(issue, self.user_normal.name) + self.assertTrue(x) + self.assertEqual( + self.jira.issue(self.issue_1).fields.assignee.name, self.user_normal.name + ) + + def test_assign_to_bad_issue_raises(self): + self.assertRaises(JIRAError, self.jira.assign_issue, "NOPE-1", "notauser") + + def test_editmeta(self): + expected_fields = { + "assignee", + "attachment", + "comment", + "components", + "description", + "fixVersions", + "issuelinks", + "labels", + "summary", + } + for i in (self.issue_1, self.issue_2): + meta = self.jira.editmeta(i) + meta_field_set = set(meta["fields"].keys()) + self.assertEqual( + meta_field_set.intersection(expected_fields), expected_fields + ) + + def test_transitioning(self): + # we check with both issue-as-string or issue-as-object + transitions = [] + for issue in [self.issue_2, self.jira.issue(self.issue_2)]: + transitions = self.jira.transitions(issue) + self.assertTrue(transitions) + self.assertTrue("id" in transitions[0]) + self.assertTrue("name" in transitions[0]) + + self.assertTrue(transitions, msg="Expecting at least one transition") + # we test getting a single transition + transition = self.jira.transitions(self.issue_2, transitions[0]["id"])[0] + self.assertDictEqual(transition, transitions[0]) + + # we test the expand of fields + transition = self.jira.transitions( + self.issue_2, transitions[0]["id"], expand="transitions.fields" + )[0] + self.assertTrue("fields" in transition) + + # Testing of transition with field assignment is disabled now because default workflows do not have it. + + # self.jira.transition_issue(issue, transitions[0]['id'], assignee={'name': self.test_manager.CI_JIRA_ADMIN}) + # issue = self.jira.issue(issue.key) + # self.assertEqual(issue.fields.assignee.name, self.test_manager.CI_JIRA_ADMIN) + # + # fields = { + # 'assignee': { + # 'name': self.test_manager.CI_JIRA_USER + # } + # } + # transitions = self.jira.transitions(issue.key) + # self.assertTrue(transitions) # any issue should have at least one transition available to it + # transition_id = transitions[0]['id'] + # + # self.jira.transition_issue(issue.key, transition_id, fields=fields) + # issue = self.jira.issue(issue.key) + # self.assertEqual(issue.fields.assignee.name, self.test_manager.CI_JIRA_USER) + # self.assertEqual(issue.fields.status.id, transition_id) + + @broken_test( + reason="Greenhopper API doesn't work on standalone docker image with JIRA Server 8.9.0" + ) + def test_agile(self): + uniq = rndstr() + board_name = "board-" + uniq + sprint_name = "sprint-" + uniq + filter_name = "filter-" + uniq + + filter = self.jira.create_filter( + filter_name, "description", f"project={self.project_b}", True + ) + + b = self.jira.create_board(board_name, filter.id) + assert isinstance(b.id, int) + + s = self.jira.create_sprint(sprint_name, b.id) + assert isinstance(s.id, int) + assert s.name == sprint_name + assert s.state.upper() == "FUTURE" + + self.jira.add_issues_to_sprint(s.id, [self.issue_1]) + + sprint_field_name = "Sprint" + sprint_field_id = [ + f["schema"]["customId"] + for f in self.jira.fields() + if f["name"] == sprint_field_name + ][0] + sprint_customfield = "customfield_" + str(sprint_field_id) + + updated_issue_1 = self.jira.issue(self.issue_1) + serialised_sprint = getattr(updated_issue_1.fields, sprint_customfield)[0] + + # Too hard to serialise the sprint object. Performing simple regex match instead. + assert re.search(r"\[id=" + str(s.id) + ",", serialised_sprint) + + # self.jira.add_issues_to_sprint(s.id, self.issue_2) + + # self.jira.rank(self.issue_2, self.issue_1) + + sleep(2) # avoid https://travis-ci.org/pycontribs/jira/jobs/176561534#L516 + s.delete() + + sleep(2) + b.delete() + # self.jira.delete_board(b.id) + + filter.delete() # must delete this filter AFTER deleting board referencing the filter diff --git a/tests/resources/test_issue_link.py b/tests/resources/test_issue_link.py new file mode 100644 index 000000000..82aee6799 --- /dev/null +++ b/tests/resources/test_issue_link.py @@ -0,0 +1,41 @@ +from tests.conftest import JiraTestCase + + +class IssueLinkTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.link_types = self.test_manager.jira_admin.issue_link_types() + + def test_issue_link(self): + self.link = self.test_manager.jira_admin.issue_link_type(self.link_types[0].id) + link = self.link # Duplicate outward + self.assertEqual(link.id, self.link_types[0].id) + + def test_create_issue_link(self): + self.test_manager.jira_admin.create_issue_link( + self.link_types[0].outward, + self.test_manager.project_b_issue1, + self.test_manager.project_b_issue2, + ) + + def test_create_issue_link_with_issue_obj(self): + inwardissue = self.test_manager.jira_admin.issue( + self.test_manager.project_b_issue1 + ) + self.assertIsNotNone(inwardissue) + outwardissue = self.test_manager.jira_admin.issue( + self.test_manager.project_b_issue2 + ) + self.assertIsNotNone(outwardissue) + self.test_manager.jira_admin.create_issue_link( + self.link_types[0].outward, inwardissue, outwardissue + ) + + # @unittest.skip("Creating an issue link doesn't return its ID, so can't easily test delete") + # def test_delete_issue_link(self): + # pass + + def test_issue_link_type(self): + link_type = self.test_manager.jira_admin.issue_link_type(self.link_types[0].id) + self.assertEqual(link_type.id, self.link_types[0].id) + self.assertEqual(link_type.name, self.link_types[0].name) diff --git a/tests/resources/test_issue_link_type.py b/tests/resources/test_issue_link_type.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/resources/test_priority.py b/tests/resources/test_priority.py new file mode 100644 index 000000000..639d05ec7 --- /dev/null +++ b/tests/resources/test_priority.py @@ -0,0 +1,12 @@ +from tests.conftest import JiraTestCase + + +class PrioritiesTests(JiraTestCase): + def test_priorities(self): + priorities = self.jira.priorities() + self.assertEqual(len(priorities), 5) + + def test_priority(self): + priority = self.jira.priority("2") + self.assertEqual(priority.id, "2") + self.assertEqual(priority.name, "High") diff --git a/tests/resources/test_project.py b/tests/resources/test_project.py new file mode 100644 index 000000000..386d9a44e --- /dev/null +++ b/tests/resources/test_project.py @@ -0,0 +1,206 @@ +from tests.conftest import JiraTestCase, find_by_id, rndstr + + +class ProjectTests(JiraTestCase): + def test_projects(self): + projects = self.jira.projects() + self.assertGreaterEqual(len(projects), 2) + + def test_project(self): + project = self.jira.project(self.project_b) + self.assertEqual(project.key, self.project_b) + + def test_project_expand(self): + project = self.jira.project(self.project_b) + self.assertFalse(hasattr(project, "projectKeys")) + project = self.jira.project(self.project_b, expand="projectKeys") + self.assertTrue(hasattr(project, "projectKeys")) + + def test_projects_expand(self): + projects = self.jira.projects() + for project in projects: + self.assertFalse(hasattr(project, "projectKeys")) + projects = self.jira.projects(expand="projectKeys") + for project in projects: + self.assertTrue(hasattr(project, "projectKeys")) + + # I have no idea what avatars['custom'] is and I get different results every time + # def test_project_avatars(self): + # avatars = self.jira.project_avatars(self.project_b) + # self.assertEqual(len(avatars['custom']), 3) + # self.assertEqual(len(avatars['system']), 16) + # + # def test_project_avatars_with_project_obj(self): + # project = self.jira.project(self.project_b) + # avatars = self.jira.project_avatars(project) + # self.assertEqual(len(avatars['custom']), 3) + # self.assertEqual(len(avatars['system']), 16) + + # def test_create_project_avatar(self): + # Tests the end-to-end project avatar creation process: upload as temporary, confirm after cropping, + # and selection. + # project = self.jira.project(self.project_b) + # size = os.path.getsize(TEST_ICON_PATH) + # filename = os.path.basename(TEST_ICON_PATH) + # with open(TEST_ICON_PATH, "rb") as icon: + # props = self.jira.create_temp_project_avatar(project, filename, size, icon.read()) + # self.assertIn('cropperOffsetX', props) + # self.assertIn('cropperOffsetY', props) + # self.assertIn('cropperWidth', props) + # self.assertTrue(props['needsCropping']) + # + # props['needsCropping'] = False + # avatar_props = self.jira.confirm_project_avatar(project, props) + # self.assertIn('id', avatar_props) + # + # self.jira.set_project_avatar(self.project_b, avatar_props['id']) + # + # def test_delete_project_avatar(self): + # size = os.path.getsize(TEST_ICON_PATH) + # filename = os.path.basename(TEST_ICON_PATH) + # with open(TEST_ICON_PATH, "rb") as icon: + # props = self.jira.create_temp_project_avatar(self.project_b, filename, size, icon.read(), auto_confirm=True) + # self.jira.delete_project_avatar(self.project_b, props['id']) + # + # def test_delete_project_avatar_with_project_obj(self): + # project = self.jira.project(self.project_b) + # size = os.path.getsize(TEST_ICON_PATH) + # filename = os.path.basename(TEST_ICON_PATH) + # with open(TEST_ICON_PATH, "rb") as icon: + # props = self.jira.create_temp_project_avatar(project, filename, size, icon.read(), auto_confirm=True) + # self.jira.delete_project_avatar(project, props['id']) + + # @pytest.mark.xfail(reason="Jira may return 500") + # def test_set_project_avatar(self): + # def find_selected_avatar(avatars): + # for avatar in avatars['system']: + # if avatar['isSelected']: + # return avatar + # else: + # raise Exception + # + # self.jira.set_project_avatar(self.project_b, '10001') + # avatars = self.jira.project_avatars(self.project_b) + # self.assertEqual(find_selected_avatar(avatars)['id'], '10001') + # + # project = self.jira.project(self.project_b) + # self.jira.set_project_avatar(project, '10208') + # avatars = self.jira.project_avatars(project) + # self.assertEqual(find_selected_avatar(avatars)['id'], '10208') + + def test_project_components(self): + proj = self.jira.project(self.project_b) + name = f"component-{proj} from project {rndstr()}" + component = self.jira.create_component( + name, + proj, + description="test!!", + assigneeType="COMPONENT_LEAD", + isAssigneeTypeValid=False, + ) + components = self.jira.project_components(self.project_b) + self.assertGreaterEqual(len(components), 1) + sample = find_by_id(components, component.id) + self.assertEqual(sample.id, component.id) + self.assertEqual(sample.name, name) + component.delete() + + def test_project_versions(self): + name = "version-%s" % rndstr() + version = self.jira.create_version(name, self.project_b, "will be deleted soon") + versions = self.jira.project_versions(self.project_b) + self.assertGreaterEqual(len(versions), 1) + test = find_by_id(versions, version.id) + self.assertEqual(test.id, version.id) + self.assertEqual(test.name, name) + + i = self.jira.issue(self.test_manager.project_b_issue1) + i.update(fields={"fixVersions": [{"id": version.id}]}) + version.delete() + + def test_update_project_version(self): + # given + name = "version-%s" % rndstr() + version = self.jira.create_version(name, self.project_b, "will be deleted soon") + updated_name = "version-%s" % rndstr() + # when + version.update(name=updated_name) + # then + self.assertEqual(updated_name, version.name) + version.delete() + + def test_get_project_version_by_name(self): + name = "version-%s" % rndstr() + version = self.jira.create_version(name, self.project_b, "will be deleted soon") + + found_version = self.jira.get_project_version_by_name(self.project_b, name) + self.assertEqual(found_version.id, version.id) + self.assertEqual(found_version.name, name) + + not_found_version = self.jira.get_project_version_by_name( + self.project_b, "non-existent" + ) + self.assertEqual(not_found_version, None) + + i = self.jira.issue(self.test_manager.project_b_issue1) + i.update(fields={"fixVersions": [{"id": version.id}]}) + version.delete() + + def test_rename_version(self): + old_name = "version-%s" % rndstr() + version = self.jira.create_version( + old_name, self.project_b, "will be deleted soon" + ) + + new_name = old_name + "-renamed" + self.jira.rename_version(self.project_b, old_name, new_name) + + found_version = self.jira.get_project_version_by_name(self.project_b, new_name) + self.assertEqual(found_version.id, version.id) + self.assertEqual(found_version.name, new_name) + + not_found_version = self.jira.get_project_version_by_name( + self.project_b, old_name + ) + self.assertEqual(not_found_version, None) + + i = self.jira.issue(self.test_manager.project_b_issue1) + i.update(fields={"fixVersions": [{"id": version.id}]}) + version.delete() + + def test_project_versions_with_project_obj(self): + name = "version-%s" % rndstr() + version = self.jira.create_version(name, self.project_b, "will be deleted soon") + project = self.jira.project(self.project_b) + versions = self.jira.project_versions(project) + self.assertGreaterEqual(len(versions), 1) + test = find_by_id(versions, version.id) + self.assertEqual(test.id, version.id) + self.assertEqual(test.name, name) + version.delete() + + def test_project_roles(self): + role_name = "Administrators" + admin = None + roles = self.jira.project_roles(self.project_b) + self.assertGreaterEqual(len(roles), 1) + self.assertIn(role_name, roles) + admin = roles[role_name] + self.assertTrue(admin) + role = self.jira.project_role(self.project_b, admin["id"]) + self.assertEqual(role.id, int(admin["id"])) + + actornames = {actor.name: actor for actor in role.actors} + actor_admin = "jira-administrators" + self.assertIn(actor_admin, actornames) + members = self.jira.group_members(actor_admin) + user = self.user_admin + self.assertIn(user.name, members.keys()) + role.update(users=user.name, groups=actor_admin) + role = self.jira.project_role(self.project_b, int(admin["id"])) + self.assertIn(user.name, [a.name for a in role.actors]) + self.assertIn(actor_admin, [a.name for a in role.actors]) + + def test_project_permissionscheme(self): + permissionscheme = self.jira.project_permissionscheme(self.project_b) + self.assertEqual(permissionscheme.name, "Default Permission Scheme") diff --git a/tests/resources/test_remote_link.py b/tests/resources/test_remote_link.py new file mode 100644 index 000000000..bb9c28b60 --- /dev/null +++ b/tests/resources/test_remote_link.py @@ -0,0 +1,145 @@ +from jira.exceptions import JIRAError +from tests.conftest import JiraTestCase + +DEFAULT_NEW_REMOTE_LINK_OBJECT = {"url": "http://google.com", "title": "googlicious!"} + + +class RemoteLinkTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue_1 = self.test_manager.project_b_issue1 + self.issue_2 = self.test_manager.project_b_issue2 + self.issue_3 = self.test_manager.project_b_issue3 + self.project_b_issue1_obj = self.test_manager.project_b_issue1_obj + + def test_remote_links(self): + self.jira.add_remote_link( + self.issue_1, + destination=DEFAULT_NEW_REMOTE_LINK_OBJECT, + ) + links = self.jira.remote_links(self.issue_1) + self.assertEqual(len(links), 1) + self.jira.remote_link(self.issue_1, links[0].id).delete() + links = self.jira.remote_links(self.issue_2) + self.assertEqual(len(links), 0) + + def test_remote_links_with_issue_obj(self): + self.jira.add_remote_link( + self.issue_1, + destination=DEFAULT_NEW_REMOTE_LINK_OBJECT, + ) + links = self.jira.remote_links(self.project_b_issue1_obj) + self.assertEqual(len(links), 1) + self.jira.remote_link(self.issue_1, links[0].id).delete() + links = self.jira.remote_links(self.project_b_issue1_obj) + self.assertEqual(len(links), 0) + + def test_remote_link(self): + added_link = self.jira.add_remote_link( + self.issue_1, + destination=DEFAULT_NEW_REMOTE_LINK_OBJECT, + globalId="python-test:story.of.horse.riding", + application={"name": "far too silly", "type": "sketch"}, + relationship="mousebending", + ) + link = self.jira.remote_link(self.issue_1, added_link.id) + self.assertEqual(link.id, added_link.id) + self.assertTrue(hasattr(link, "globalId")) + self.assertTrue(hasattr(link, "relationship")) + self.assertTrue(hasattr(link, "application")) + self.assertTrue(hasattr(link, "object")) + + link.delete() + + def test_remote_link_with_issue_obj(self): + added_link = self.jira.add_remote_link( + self.issue_1, + destination=DEFAULT_NEW_REMOTE_LINK_OBJECT, + globalId="python-test:story.of.horse.riding", + application={"name": "far too silly", "type": "sketch"}, + relationship="mousebending", + ) + link = self.jira.remote_link(self.project_b_issue1_obj, added_link.id) + self.assertEqual(link.id, added_link.id) + self.assertTrue(hasattr(link, "globalId")) + self.assertTrue(hasattr(link, "relationship")) + self.assertTrue(hasattr(link, "application")) + self.assertTrue(hasattr(link, "object")) + + link.delete() + + def test_add_remote_link(self): + link = self.jira.add_remote_link( + self.issue_1, + destination=DEFAULT_NEW_REMOTE_LINK_OBJECT, + globalId="python-test:story.of.horse.riding", + application={"name": "far too silly", "type": "sketch"}, + relationship="mousebending", + ) + # creation response doesn't include full remote link info, + # so we fetch it again using the new internal ID + link = self.jira.remote_link(self.issue_1, link.id) + self.assertEqual(link.application.name, "far too silly") + self.assertEqual(link.application.type, "sketch") + self.assertEqual(link.object.url, DEFAULT_NEW_REMOTE_LINK_OBJECT["url"]) + self.assertEqual(link.object.title, DEFAULT_NEW_REMOTE_LINK_OBJECT["title"]) + self.assertEqual(link.relationship, "mousebending") + self.assertEqual(link.globalId, "python-test:story.of.horse.riding") + + link.delete() + + def test_add_remote_link_with_issue_obj(self): + link = self.jira.add_remote_link( + self.project_b_issue1_obj, + destination=DEFAULT_NEW_REMOTE_LINK_OBJECT, + globalId="python-test:story.of.horse.riding", + application={"name": "far too silly", "type": "sketch"}, + relationship="mousebending", + ) + # creation response doesn't include full remote link info, + # so we fetch it again using the new internal ID + link = self.jira.remote_link(self.project_b_issue1_obj, link.id) + self.assertEqual(link.application.name, "far too silly") + self.assertEqual(link.application.type, "sketch") + self.assertEqual(link.object.url, DEFAULT_NEW_REMOTE_LINK_OBJECT["url"]) + self.assertEqual(link.object.title, DEFAULT_NEW_REMOTE_LINK_OBJECT["title"]) + self.assertEqual(link.relationship, "mousebending") + self.assertEqual(link.globalId, "python-test:story.of.horse.riding") + + link.delete() + + def test_update_remote_link(self): + link = self.jira.add_remote_link( + self.issue_1, + destination=DEFAULT_NEW_REMOTE_LINK_OBJECT, + globalId="python-test:story.of.horse.riding", + application={"name": "far too silly", "type": "sketch"}, + relationship="mousebending", + ) + # creation response doesn't include full remote link info, + # so we fetch it again using the new internal ID + link = self.jira.remote_link(self.issue_1, link.id) + new_link = {"url": "http://yahoo.com", "title": "yahoo stuff"} + link.update( + object=new_link, + globalId="python-test:updated.id", + relationship="cheesing", + ) + self.assertEqual(link.globalId, "python-test:updated.id") + self.assertEqual(link.relationship, "cheesing") + self.assertEqual(link.object.url, new_link["url"]) + self.assertEqual(link.object.title, new_link["title"]) + link.delete() + + def test_delete_remote_link(self): + link = self.jira.add_remote_link( + self.issue_1, + destination=DEFAULT_NEW_REMOTE_LINK_OBJECT, + globalId="python-test:story.of.horse.riding", + application={"name": "far too silly", "type": "sketch"}, + relationship="mousebending", + ) + _id = link.id + link = self.jira.remote_link(self.issue_1, link.id) + link.delete() + self.assertRaises(JIRAError, self.jira.remote_link, self.issue_1, _id) diff --git a/tests/resources/test_request_type.py b/tests/resources/test_request_type.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/resources/test_resolution.py b/tests/resources/test_resolution.py new file mode 100644 index 000000000..c14d34570 --- /dev/null +++ b/tests/resources/test_resolution.py @@ -0,0 +1,12 @@ +from tests.conftest import JiraTestCase + + +class ResolutionTests(JiraTestCase): + def test_resolutions(self): + resolutions = self.jira.resolutions() + self.assertGreaterEqual(len(resolutions), 1) + + def test_resolution(self): + resolution = self.jira.resolution("10002") + self.assertEqual(resolution.id, "10002") + self.assertEqual(resolution.name, "Duplicate") diff --git a/tests/resources/test_role.py b/tests/resources/test_role.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/resources/test_security_level.py b/tests/resources/test_security_level.py new file mode 100644 index 000000000..d366d86ed --- /dev/null +++ b/tests/resources/test_security_level.py @@ -0,0 +1,11 @@ +from tests.conftest import JiraTestCase, broken_test + + +@broken_test( + reason="Skipped due to standalone jira docker image has no security schema created by default" +) +class SecurityLevelTests(JiraTestCase): + def test_security_level(self): + # This is hardcoded due to Atlassian bug: https://jira.atlassian.com/browse/JRA-59619 + sec_level = self.jira.security_level("10000") + self.assertEqual(sec_level.id, "10000") diff --git a/tests/resources/test_service_desk.py b/tests/resources/test_service_desk.py new file mode 100644 index 000000000..b1d407f13 --- /dev/null +++ b/tests/resources/test_service_desk.py @@ -0,0 +1,60 @@ +import logging +from time import sleep + +import pytest + +from tests.conftest import JiraTestCase, broken_test + +LOGGER = logging.getLogger(__name__) + + +class JiraServiceDeskTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + if not self.jira.supports_service_desk(): + pytest.skip("Skipping Service Desk not enabled") + + try: + self.jira.delete_project(self.test_manager.project_sd) + except Exception: + LOGGER.warning("Failed to delete %s", self.test_manager.project_sd) + + @broken_test(reason="Broken needs fixing") + def test_create_customer_request(self): + + self.jira.create_project( + key=self.test_manager.project_sd, + name=self.test_manager.project_sd_name, + ptype="service_desk", + template_name="IT Service Desk", + ) + service_desks = [] + for _ in range(3): + service_desks = self.jira.service_desks() + if service_desks: + break + logging.warning("Service desk not reported...") + sleep(2) + self.assertTrue(service_desks, "No service desks were found!") + service_desk = service_desks[0] + + for _ in range(3): + request_types = self.jira.request_types(service_desk) + if request_types: + logging.warning("Service desk request_types not reported...") + break + sleep(2) + self.assertTrue(request_types, "No request_types for service desk found!") + + request = self.jira.create_customer_request( + dict( + serviceDeskId=service_desk.id, + requestTypeId=int(request_types[0].id), + requestFieldValues=dict( + summary="Ticket title here", description="Ticket body here" + ), + ) + ) + + self.assertEqual(request.fields.summary, "Ticket title here") + self.assertEqual(request.fields.description, "Ticket body here") diff --git a/tests/resources/test_sprint.py b/tests/resources/test_sprint.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/resources/test_status.py b/tests/resources/test_status.py new file mode 100644 index 000000000..e497ace96 --- /dev/null +++ b/tests/resources/test_status.py @@ -0,0 +1,16 @@ +from tests.conftest import JiraTestCase + + +class StatusTests(JiraTestCase): + def test_statuses(self): + found = False + statuses = self.jira.statuses() + for status in statuses: + if status.name == "Done": + found = True + # find status + s = self.jira.status(status.id) + self.assertEqual(s.id, status.id) + break + self.assertTrue(found, "Status Done not found. [%s]" % statuses) + self.assertGreater(len(statuses), 0) diff --git a/tests/resources/test_status_category.py b/tests/resources/test_status_category.py new file mode 100644 index 000000000..3eaadc615 --- /dev/null +++ b/tests/resources/test_status_category.py @@ -0,0 +1,20 @@ +from tests.conftest import JiraTestCase + + +class StatusCategoryTests(JiraTestCase): + def test_statuscategories(self): + found = False + statuscategories = self.jira.statuscategories() + for statuscategory in statuscategories: + if statuscategory.id == 1 and statuscategory.name == "No Category": + found = True + break + self.assertTrue( + found, "StatusCategory with id=1 not found. [%s]" % statuscategories + ) + self.assertGreater(len(statuscategories), 0) + + def test_statuscategory(self): + statuscategory = self.jira.statuscategory(1) + self.assertEqual(statuscategory.id, 1) + self.assertEqual(statuscategory.name, "No Category") diff --git a/tests/resources/test_user.py b/tests/resources/test_user.py new file mode 100644 index 000000000..354f54052 --- /dev/null +++ b/tests/resources/test_user.py @@ -0,0 +1,185 @@ +import os + +from tests.conftest import TEST_ICON_PATH, JiraTestCase + + +class UserTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue = self.test_manager.project_b_issue3 + + def test_user(self): + user = self.jira.user(self.test_manager.user_admin.name) + self.assertTrue(user.name) + self.assertRegex( + user.emailAddress, r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" + ) + + def test_search_assignable_users_for_projects(self): + users = self.jira.search_assignable_users_for_projects( + self.test_manager.CI_JIRA_ADMIN, + f"{self.project_a},{self.project_b}", + ) + self.assertGreaterEqual(len(users), 1) + usernames = map(lambda user: user.name, users) + self.assertIn(self.test_manager.CI_JIRA_ADMIN, usernames) + + def test_search_assignable_users_for_projects_maxresults(self): + users = self.jira.search_assignable_users_for_projects( + self.test_manager.CI_JIRA_ADMIN, + f"{self.project_a},{self.project_b}", + maxResults=1, + ) + self.assertLessEqual(len(users), 1) + + def test_search_assignable_users_for_projects_startat(self): + users = self.jira.search_assignable_users_for_projects( + self.test_manager.CI_JIRA_ADMIN, + f"{self.project_a},{self.project_b}", + startAt=1, + ) + self.assertGreaterEqual(len(users), 0) + + def test_search_assignable_users_for_issues_by_project(self): + users = self.jira.search_assignable_users_for_issues( + self.test_manager.CI_JIRA_ADMIN, project=self.project_b + ) + self.assertEqual(len(users), 1) + usernames = map(lambda user: user.name, users) + self.assertIn(self.test_manager.CI_JIRA_ADMIN, usernames) + + def test_search_assignable_users_for_issues_by_project_maxresults(self): + users = self.jira.search_assignable_users_for_issues( + self.test_manager.CI_JIRA_USER, project=self.project_b, maxResults=1 + ) + self.assertLessEqual(len(users), 1) + + def test_search_assignable_users_for_issues_by_project_startat(self): + users = self.jira.search_assignable_users_for_issues( + self.test_manager.CI_JIRA_USER, project=self.project_a, startAt=1 + ) + self.assertGreaterEqual(len(users), 0) + + def test_search_assignable_users_for_issues_by_issue(self): + users = self.jira.search_assignable_users_for_issues( + self.test_manager.CI_JIRA_ADMIN, issueKey=self.issue + ) + self.assertEqual(len(users), 1) + usernames = map(lambda user: user.name, users) + self.assertIn(self.test_manager.CI_JIRA_ADMIN, usernames) + + def test_search_assignable_users_for_issues_by_issue_maxresults(self): + users = self.jira.search_assignable_users_for_issues( + self.test_manager.CI_JIRA_ADMIN, issueKey=self.issue, maxResults=2 + ) + self.assertLessEqual(len(users), 2) + + def test_search_assignable_users_for_issues_by_issue_startat(self): + users = self.jira.search_assignable_users_for_issues( + self.test_manager.CI_JIRA_ADMIN, issueKey=self.issue, startAt=2 + ) + self.assertGreaterEqual(len(users), 0) + + def test_user_avatars(self): + # Tests the end-to-end user avatar creation process: upload as temporary, confirm after cropping, + # and selection. + size = os.path.getsize(TEST_ICON_PATH) + # filename = os.path.basename(TEST_ICON_PATH) + with open(TEST_ICON_PATH, "rb") as icon: + props = self.jira.create_temp_user_avatar( + self.test_manager.CI_JIRA_ADMIN, TEST_ICON_PATH, size, icon.read() + ) + self.assertIn("cropperOffsetX", props) + self.assertIn("cropperOffsetY", props) + self.assertIn("cropperWidth", props) + self.assertTrue(props["needsCropping"]) + + props["needsCropping"] = False + avatar_props = self.jira.confirm_user_avatar( + self.test_manager.CI_JIRA_ADMIN, props + ) + self.assertIn("id", avatar_props) + self.assertEqual(avatar_props["owner"], self.test_manager.CI_JIRA_ADMIN) + + self.jira.set_user_avatar(self.test_manager.CI_JIRA_ADMIN, avatar_props["id"]) + + avatars = self.jira.user_avatars(self.test_manager.CI_JIRA_ADMIN) + self.assertGreaterEqual( + len(avatars["system"]), 20 + ) # observed values between 20-24 so far + self.assertGreaterEqual(len(avatars["custom"]), 1) + + def test_set_user_avatar(self): + def find_selected_avatar(avatars): + for avatar in avatars["system"]: + if avatar["isSelected"]: + return avatar + # else: + # raise Exception as e + # print(e) + + avatars = self.jira.user_avatars(self.test_manager.CI_JIRA_ADMIN) + + self.jira.set_user_avatar( + self.test_manager.CI_JIRA_ADMIN, avatars["system"][0]["id"] + ) + avatars = self.jira.user_avatars(self.test_manager.CI_JIRA_ADMIN) + self.assertEqual( + find_selected_avatar(avatars)["id"], avatars["system"][0]["id"] + ) + + self.jira.set_user_avatar( + self.test_manager.CI_JIRA_ADMIN, avatars["system"][1]["id"] + ) + avatars = self.jira.user_avatars(self.test_manager.CI_JIRA_ADMIN) + self.assertEqual( + find_selected_avatar(avatars)["id"], avatars["system"][1]["id"] + ) + + def test_delete_user_avatar(self): + size = os.path.getsize(TEST_ICON_PATH) + with open(TEST_ICON_PATH, "rb") as icon: + props = self.jira.create_temp_user_avatar( + self.test_manager.CI_JIRA_ADMIN, + TEST_ICON_PATH, + size, + icon.read(), + auto_confirm=True, + ) + self.jira.delete_user_avatar(self.test_manager.CI_JIRA_ADMIN, props["id"]) + + def test_search_users(self): + users = self.jira.search_users(self.test_manager.CI_JIRA_ADMIN) + self.assertGreaterEqual(len(users), 1) + usernames = map(lambda user: user.name, users) + self.assertIn(self.test_manager.user_admin.name, usernames) + + def test_search_users_maxresults(self): + users = self.jira.search_users(self.test_manager.CI_JIRA_USER, maxResults=1) + self.assertGreaterEqual(1, len(users)) + + def test_search_allowed_users_for_issue_by_project(self): + users = self.jira.search_allowed_users_for_issue( + self.test_manager.CI_JIRA_USER, projectKey=self.project_a + ) + self.assertGreaterEqual(len(users), 1) + + def test_search_allowed_users_for_issue_by_issue(self): + users = self.jira.search_allowed_users_for_issue("a", issueKey=self.issue) + self.assertGreaterEqual(len(users), 1) + + def test_search_allowed_users_for_issue_maxresults(self): + users = self.jira.search_allowed_users_for_issue( + "a", projectKey=self.project_b, maxResults=2 + ) + self.assertLessEqual(len(users), 2) + + def test_search_allowed_users_for_issue_startat(self): + users = self.jira.search_allowed_users_for_issue( + "c", projectKey=self.project_b, startAt=1 + ) + self.assertGreaterEqual(len(users), 0) + + def test_add_users_to_set(self): + users_set = {self.test_manager.user_admin, self.test_manager.user_admin} + self.assertEqual(len(users_set), 1) diff --git a/tests/resources/test_version.py b/tests/resources/test_version.py new file mode 100644 index 000000000..b4af6b388 --- /dev/null +++ b/tests/resources/test_version.py @@ -0,0 +1,58 @@ +from jira.exceptions import JIRAError +from tests.conftest import JiraTestCase + + +class VersionTests(JiraTestCase): + def test_create_version(self): + name = "new version " + self.project_b + desc = "test version of " + self.project_b + release_date = "2015-03-11" + version = self.jira.create_version( + name, self.project_b, releaseDate=release_date, description=desc + ) + self.assertEqual(version.name, name) + self.assertEqual(version.description, desc) + self.assertEqual(version.releaseDate, release_date) + version.delete() + + def test_create_version_with_project_obj(self): + project = self.jira.project(self.project_b) + version = self.jira.create_version( + "new version 2", + project, + releaseDate="2015-03-11", + description="test version!", + ) + self.assertEqual(version.name, "new version 2") + self.assertEqual(version.description, "test version!") + self.assertEqual(version.releaseDate, "2015-03-11") + version.delete() + + def test_update_version(self): + + version = self.jira.create_version( + "new updated version 1", + self.project_b, + releaseDate="2015-03-11", + description="new to be updated!", + ) + version.update(name="new updated version name 1", description="new updated!") + self.assertEqual(version.name, "new updated version name 1") + self.assertEqual(version.description, "new updated!") + + v = self.jira.version(version.id) + self.assertEqual(v, version) + self.assertEqual(v.id, version.id) + + version.delete() + + def test_delete_version(self): + version_str = "test_delete_version:" + self.test_manager.jid + version = self.jira.create_version( + version_str, + self.project_b, + releaseDate="2015-03-11", + description="not long for this world", + ) + version.delete() + self.assertRaises(JIRAError, self.jira.version, version.id) diff --git a/tests/resources/test_vote.py b/tests/resources/test_vote.py new file mode 100644 index 000000000..d3d6451ef --- /dev/null +++ b/tests/resources/test_vote.py @@ -0,0 +1,36 @@ +from tests.conftest import JiraTestCase + + +class VoteTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue_1 = self.test_manager.project_b_issue1 + + def test_votes(self): + self.jira_normal.remove_vote(self.issue_1) + # not checking the result on this + votes = self.jira.votes(self.issue_1) + self.assertEqual(votes.votes, 0) + + self.jira_normal.add_vote(self.issue_1) + new_votes = self.jira.votes(self.issue_1) + assert votes.votes + 1 == new_votes.votes + + self.jira_normal.remove_vote(self.issue_1) + new_votes = self.jira.votes(self.issue_1) + assert votes.votes == new_votes.votes + + def test_votes_with_issue_obj(self): + issue = self.jira_normal.issue(self.issue_1) + self.jira_normal.remove_vote(issue) + # not checking the result on this + votes = self.jira.votes(issue) + self.assertEqual(votes.votes, 0) + + self.jira_normal.add_vote(issue) + new_votes = self.jira.votes(issue) + assert votes.votes + 1 == new_votes.votes + + self.jira_normal.remove_vote(issue) + new_votes = self.jira.votes(issue) + assert votes.votes == new_votes.votes diff --git a/tests/resources/test_watchers.py b/tests/resources/test_watchers.py new file mode 100644 index 000000000..a8137adbf --- /dev/null +++ b/tests/resources/test_watchers.py @@ -0,0 +1,22 @@ +from tests.conftest import JiraTestCase + + +class WatchersTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue_1 = self.test_manager.project_b_issue1 + + def test_add_remove_watcher(self): + + # removing it in case it exists, so we know its state + self.jira.remove_watcher(self.issue_1, self.test_manager.user_normal.name) + init_watchers = self.jira.watchers(self.issue_1).watchCount + + # adding a new watcher + self.jira.add_watcher(self.issue_1, self.test_manager.user_normal.name) + self.assertEqual(self.jira.watchers(self.issue_1).watchCount, init_watchers + 1) + + # now we verify that remove does indeed remove watchers + self.jira.remove_watcher(self.issue_1, self.test_manager.user_normal.name) + new_watchers = self.jira.watchers(self.issue_1).watchCount + self.assertEqual(init_watchers, new_watchers) diff --git a/tests/resources/test_worklog.py b/tests/resources/test_worklog.py new file mode 100644 index 000000000..642539094 --- /dev/null +++ b/tests/resources/test_worklog.py @@ -0,0 +1,65 @@ +from tests.conftest import JiraTestCase + + +class WorklogTests(JiraTestCase): + def setUp(self): + JiraTestCase.setUp(self) + self.issue_1 = self.test_manager.project_b_issue1 + self.issue_2 = self.test_manager.project_b_issue2 + self.issue_3 = self.test_manager.project_b_issue3 + + def test_worklogs(self): + worklog = self.jira.add_worklog(self.issue_1, "2h") + worklogs = self.jira.worklogs(self.issue_1) + self.assertEqual(len(worklogs), 1) + worklog.delete() + + def test_worklogs_with_issue_obj(self): + issue = self.jira.issue(self.issue_1) + worklog = self.jira.add_worklog(issue, "2h") + worklogs = self.jira.worklogs(issue) + self.assertEqual(len(worklogs), 1) + worklog.delete() + + def test_worklog(self): + worklog = self.jira.add_worklog(self.issue_1, "1d 2h") + new_worklog = self.jira.worklog(self.issue_1, str(worklog)) + self.assertEqual(new_worklog.author.name, self.test_manager.user_admin.name) + self.assertEqual(new_worklog.timeSpent, "1d 2h") + worklog.delete() + + def test_worklog_with_issue_obj(self): + issue = self.jira.issue(self.issue_1) + worklog = self.jira.add_worklog(issue, "1d 2h") + new_worklog = self.jira.worklog(issue, str(worklog)) + self.assertEqual(new_worklog.author.name, self.test_manager.user_admin.name) + self.assertEqual(new_worklog.timeSpent, "1d 2h") + worklog.delete() + + def test_add_worklog(self): + worklog_count = len(self.jira.worklogs(self.issue_2)) + worklog = self.jira.add_worklog(self.issue_2, "2h") + self.assertIsNotNone(worklog) + self.assertEqual(len(self.jira.worklogs(self.issue_2)), worklog_count + 1) + worklog.delete() + + def test_add_worklog_with_issue_obj(self): + issue = self.jira.issue(self.issue_2) + worklog_count = len(self.jira.worklogs(issue)) + worklog = self.jira.add_worklog(issue, "2h") + self.assertIsNotNone(worklog) + self.assertEqual(len(self.jira.worklogs(issue)), worklog_count + 1) + worklog.delete() + + def test_update_and_delete_worklog(self): + worklog = self.jira.add_worklog(self.issue_3, "3h") + issue = self.jira.issue(self.issue_3, fields="worklog,timetracking") + worklog.update(comment="Updated!", timeSpent="2h") + self.assertEqual(worklog.comment, "Updated!") + # rem_estimate = issue.fields.timetracking.remainingEstimate + self.assertEqual(worklog.timeSpent, "2h") + issue = self.jira.issue(self.issue_3, fields="worklog,timetracking") + self.assertEqual(issue.fields.timetracking.remainingEstimate, "1h") + worklog.delete() + issue = self.jira.issue(self.issue_3, fields="worklog,timetracking") + self.assertEqual(issue.fields.timetracking.remainingEstimate, "3h") diff --git a/tests/test_client.py b/tests/test_client.py index 1c49fdbc6..3b8909e15 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,14 +1,13 @@ -# -*- coding: utf-8 -*- import getpass + import pytest +import jira.client +from jira.exceptions import JIRAError +from tests.conftest import JiraTestManager, get_unique_project_name + # from tenacity import retry # from tenacity import wait_incrementing -from tests import get_unique_project_name -from tests import JiraTestManager - -from jira import Role, Issue, JIRA, JIRAError, Project # noqa -import jira.client @pytest.fixture() @@ -42,7 +41,7 @@ def remove_by_slug(): slug = get_unique_project_name() - project_name = "Test user=%s key=%s A" % (getpass.getuser(), slug) + project_name = f"Test user={getpass.getuser()} key={slug} A" try: proj = cl_admin.project(slug) @@ -55,6 +54,16 @@ def remove_by_slug(): return slug +@pytest.fixture() +def no_fields(monkeypatch): + """When we want to test the __init__ method of the jira.client.JIRA + we don't need any external calls to get the fields. + + We don't need the features of a MagicMock, hence we don't use it here. + """ + monkeypatch.setattr(jira.client.JIRA, "fields", lambda *args, **kwargs: []) + + def test_delete_project(cl_admin, cl_normal, slug): assert cl_admin.delete_project(slug) @@ -73,24 +82,15 @@ def test_delete_inexistent_project(cl_admin): def test_templates(cl_admin): - templates = cl_admin.templates() + templates = set(cl_admin.templates()) expected_templates = set( filter( None, """ -Agility -Basic -Bug tracking -Content Management -Customer service -Document Approval -IT Service Desk +Basic software development Kanban software development -Lead Tracking Process management -Procurement Project management -Recruitment Scrum software development Task management """.split( @@ -99,8 +99,7 @@ def test_templates(cl_admin): ) ) - for t in expected_templates: - assert t in templates + assert templates == expected_templates def test_result_list(): @@ -129,3 +128,69 @@ def test_result_list_if_empty(): with pytest.raises(StopIteration): next(results) + + +@pytest.mark.parametrize( + "options_arg", + [ + {"headers": {"Content-Type": "application/json;charset=UTF-8"}}, + {"headers": {"random-header": "nice random"}}, + ], + ids=["overwrite", "new"], +) +def test_headers_unclobbered_update(options_arg, no_fields): + + assert "headers" in options_arg, "test case options must contain headers" + + # GIVEN: the headers and the expected value + header_to_check: str = list(options_arg["headers"].keys())[0] + expected_header_value: str = options_arg["headers"][header_to_check] + + invariant_header_name: str = "X-Atlassian-Token" + invariant_header_value: str = jira.client.JIRA.DEFAULT_OPTIONS["headers"][ + invariant_header_name + ] + + # We arbitrarily chose a header to check it remains unchanged/unclobbered + # so should not be overwritten by a test case + assert ( + invariant_header_name not in options_arg["headers"] + ), f"{invariant_header_name} is checked as not being overwritten in this test" + + # WHEN: we initialise the JIRA class and get the headers + jira_client = jira.client.JIRA( + server="https://jira.atlasian.com", + get_server_info=False, + validate=False, + options=options_arg, + ) + + session_headers = jira_client._session.headers + + # THEN: we have set the right headers and not affect the other headers' defaults + assert session_headers[header_to_check] == expected_header_value + assert session_headers[invariant_header_name] == invariant_header_value + + +def test_headers_unclobbered_update_with_no_provided_headers(no_fields): + + options_arg = {} # a dict with "headers" not set + + # GIVEN:the headers and the expected value + invariant_header_name: str = "X-Atlassian-Token" + invariant_header_value: str = jira.client.JIRA.DEFAULT_OPTIONS["headers"][ + invariant_header_name + ] + + # WHEN: we initialise the JIRA class with no provided headers and get the headers + jira_client = jira.client.JIRA( + server="https://jira.atlasian.com", + get_server_info=False, + validate=False, + options=options_arg, + ) + + session_headers = jira_client._session.headers + + # THEN: we have not affected the other headers' defaults + assert session_headers[invariant_header_name] == invariant_header_value diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py new file mode 100644 index 000000000..d531c24f5 --- /dev/null +++ b/tests/test_exceptions.py @@ -0,0 +1,147 @@ +import unittest +from pathlib import Path +from unittest.mock import mock_open, patch + +from requests import Response +from requests.structures import CaseInsensitiveDict + +from jira.exceptions import JIRAError + +DUMMY_HEADERS = {"h": "nice headers"} +DUMMY_TEXT = "nice text" +DUMMY_URL = "https://nice.jira.tests" +DUMMY_STATUS_CODE = 200 + +PATCH_BASE = "jira.exceptions" + + +class ExceptionsTests(unittest.TestCase): + class MockResponse(Response): + def __init__( + self, + headers: dict = None, + text: str = "", + status_code: int = DUMMY_STATUS_CODE, + url: str = DUMMY_URL, + ): + """Sub optimal but we create a mock response like this.""" + self.headers = CaseInsensitiveDict(headers if headers else {}) + self._text = text + self.status_code = status_code + self.url = url + + @property + def text(self): + return self._text + + @text.setter + def text(self, new_text): + self._text = new_text + + class MalformedMockResponse: + def __init__( + self, + headers: dict = None, + text: str = "", + status_code: int = DUMMY_STATUS_CODE, + url: str = DUMMY_URL, + ): + if headers: + self.headers = headers + if text: + self.text = text + self.url = url + self.status_code = status_code + + def test_jira_error_response_added(self): + + err = JIRAError( + response=self.MockResponse(headers=DUMMY_HEADERS, text=DUMMY_TEXT) + ) + err_str = str(err) + + assert f"headers = {DUMMY_HEADERS}" in err_str + assert f"text = {DUMMY_TEXT}" in err_str + + def test_jira_error_malformed_response(self): + # GIVEN: a malformed Response object, without headers or text set + bad_repsonse = self.MalformedMockResponse() + # WHEN: The JiraError's __str__ method is called + err = JIRAError(response=bad_repsonse) + err_str = str(err) + # THEN: there are no errors and neither headers nor text are in the result + assert "headers = " not in err_str + assert "text = " not in err_str + + def test_jira_error_request_added(self): + + err = JIRAError( + request=self.MockResponse(headers=DUMMY_HEADERS, text=DUMMY_TEXT) + ) + err_str = str(err) + + assert f"headers = {DUMMY_HEADERS}" in err_str + assert f"text = {DUMMY_TEXT}" in err_str + + def test_jira_error_malformed_request(self): + # GIVEN: a malformed Response object, without headers or text set + bad_repsonse = self.MalformedMockResponse() + # WHEN: The JiraError's __str__ method is called + err = JIRAError(request=bad_repsonse) + err_str = str(err) + # THEN: there are no errors and neither headers nor text are in the result + assert "headers = " not in err_str + assert "text = " not in err_str + + def test_jira_error_url_added(self): + assert f"url: {DUMMY_URL}" in str(JIRAError(url=DUMMY_URL)) + + def test_jira_error_status_code_added(self): + assert f"JiraError HTTP {DUMMY_STATUS_CODE}" in str( + JIRAError(status_code=DUMMY_STATUS_CODE) + ) + + def test_jira_error_text_added(self): + dummy_text = "wow\tthis\nis\nso cool" + assert f"text: {dummy_text}" in str(JIRAError(text=dummy_text)) + + def test_jira_error_log_to_tempfile_if_env_var_set(self): + # GIVEN: the right env vars are set and the tempfile's filename + env_vars = {"PYJIRA_LOG_TO_TEMPFILE": "so true"} + test_jira_error_filename = ( + Path(__file__).parent / "test_jira_error_log_to_tempfile.bak" + ) + # https://docs.python.org/3/library/unittest.mock.html#mock-open + mocked_open = mock_open() + + # WHEN: a JIRAError's __str__ method is called and + # log details are expected to be sent to the tempfile + with patch.dict("os.environ", env_vars), patch( + f"{PATCH_BASE}.tempfile.mkstemp", autospec=True + ) as mock_mkstemp, patch(f"{PATCH_BASE}.open", mocked_open): + mock_mkstemp.return_value = 0, str(test_jira_error_filename) + str(JIRAError(response=self.MockResponse(text=DUMMY_TEXT))) + + # THEN: the known filename is opened and contains the exception details + mocked_open.assert_called_once_with(str(test_jira_error_filename), "w") + mock_file_stream = mocked_open() + assert f"text = {DUMMY_TEXT}" in mock_file_stream.write.call_args[0][0] + + def test_jira_error_log_to_tempfile_not_used_if_env_var_not_set(self): + # GIVEN: no env vars are set and the tempfile's filename + env_vars = {} + test_jira_error_filename = ( + Path(__file__).parent / "test_jira_error_log_to_tempfile.bak" + ) + # https://docs.python.org/3/library/unittest.mock.html#mock-open + mocked_open = mock_open() + + # WHEN: a JIRAError's __str__ method is called + with patch.dict("os.environ", env_vars), patch( + f"{PATCH_BASE}.tempfile.mkstemp", autospec=True + ) as mock_mkstemp, patch(f"{PATCH_BASE}.open", mocked_open): + mock_mkstemp.return_value = 0, str(test_jira_error_filename) + str(JIRAError(response=self.MockResponse(text=DUMMY_TEXT))) + + # THEN: no files are opened + mocked_open.assert_not_called() diff --git a/tests/test_qsh.py b/tests/test_qsh.py new file mode 100644 index 000000000..7641f8aea --- /dev/null +++ b/tests/test_qsh.py @@ -0,0 +1,47 @@ +import pytest + +from jira.client import QshGenerator + + +class MockRequest: + def __init__(self, method, url): + self.method = method + self.url = url + + +@pytest.mark.parametrize( + "method,url,expected", + [ + ("GET", "http://example.com", "GET&&"), + # empty parameter + ("GET", "http://example.com?key=&key2=A", "GET&&key=&key2=A"), + # whitespace + ("GET", "http://example.com?key=A+B", "GET&&key=A%20B"), + # tilde + ("GET", "http://example.com?key=A~B", "GET&&key=A~B"), + # repeated parameters + ( + "GET", + "http://example.com?key2=Z&key1=X&key3=Y&key1=A", + "GET&&key1=A,X&key2=Z&key3=Y", + ), + # repeated parameters with whitespace + ( + "GET", + "http://example.com?key2=Z+A&key1=X+B&key3=Y&key1=A+B", + "GET&&key1=A%20B,X%20B&key2=Z%20A&key3=Y", + ), + ], + ids=[ + "no parameters", + "empty parameter", + "whitespace", + "tilde", + "repeated parameters", + "repeated parameters with whitespace", + ], +) +def test_qsh(method, url, expected): + gen = QshGenerator("http://example.com") + req = MockRequest(method, url) + assert gen._generate_qsh(req) == expected diff --git a/tests/test_resilientsession.py b/tests/test_resilientsession.py new file mode 100644 index 000000000..831321cb0 --- /dev/null +++ b/tests/test_resilientsession.py @@ -0,0 +1,55 @@ +import logging + +import jira.resilientsession +from tests.conftest import JiraTestCase + + +class ListLoggingHandler(logging.Handler): + """A logging handler that records all events in a list.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.records = [] + + def emit(self, record): + self.records.append(record) + + def reset(self): + self.records = [] + + +class ResilientSessionLoggingConfidentialityTests(JiraTestCase): + """No sensitive data shall be written to the log.""" + + def setUp(self): + self.loggingHandler = ListLoggingHandler() + jira.resilientsession.logging.getLogger().addHandler(self.loggingHandler) + + def test_logging_with_connection_error(self): + """No sensitive data shall be written to the log in case of a connection error.""" + witness = "etwhpxbhfniqnbbjoqvw" # random string; hopefully unique + for max_retries in (0, 1): + for verb in ("get", "post", "put", "delete", "head", "patch", "options"): + with self.subTest(max_retries=max_retries, verb=verb): + with jira.resilientsession.ResilientSession() as session: + session.max_retries = max_retries + session.max_retry_delay = 0 + try: + getattr(session, verb)( + "http://127.0.0.1:9", + headers={"sensitive_header": witness}, + data={"sensitive_data": witness}, + ) + except jira.resilientsession.ConnectionError: + pass + # check that `witness` does not appear in log + for record in self.loggingHandler.records: + self.assertNotIn(witness, record.msg) + for arg in record.args: + self.assertNotIn(witness, str(arg)) + self.assertNotIn(witness, str(record)) + self.loggingHandler.reset() + + def tearDown(self): + jira.resilientsession.logging.getLogger().removeHandler(self.loggingHandler) + del self.loggingHandler diff --git a/tests/test_shell.py b/tests/test_shell.py index 719b0aa18..aec6490ff 100644 --- a/tests/test_shell.py +++ b/tests/test_shell.py @@ -1,13 +1,12 @@ -# -*- coding: utf-8 -*- -import pytest # noqa import io -import requests # noqa import sys -from unittest.mock import patch, MagicMock +from unittest.mock import MagicMock, patch +import pytest # noqa +import requests # noqa -from jira import Role, Issue, JIRA, JIRAError, Project # noqa import jira.jirashell as jirashell +from jira import JIRA, Issue, JIRAError, Project, Role # noqa @pytest.fixture diff --git a/tests/tests.py b/tests/tests.py index 32f1d6758..20ef9a5bf 100755 --- a/tests/tests.py +++ b/tests/tests.py @@ -1,370 +1,32 @@ #!/usr/bin/env python -import getpass -import hashlib +"""This file contains tests that do not fit into any specific file yet. + +Feel free to make your own test file if appropriate. + +Refer to conftest.py for shared helper methods. + +resources/test_* : For tests related to resources +test_* : For other tests of the non-resource elements of the jira package. +""" import logging import os import pickle -import random -import re -import string -import sys from time import sleep +from typing import cast +from unittest import mock -from flaky import flaky -import py import pytest import requests -from typing import Any, Dict -import unittest +from jira import JIRA, Issue, JIRAError +from jira.client import ResultList +from jira.resources import cls_for_resource +from tests.conftest import JiraTestCase, rndpassword -from unittest import mock - - -import jira # noqa -from jira import Role, Issue, JIRA, JIRAError, Project # noqa -from jira.resources import Resource, cls_for_resource, Group, UnknownResource # noqa - -TEST_ROOT = os.path.dirname(__file__) -TEST_ICON_PATH = os.path.join(TEST_ROOT, "icon.png") -TEST_ATTACH_PATH = os.path.join(TEST_ROOT, "tests.py") - -OAUTH = False -CONSUMER_KEY = "oauth-consumer" -KEY_CERT_FILE = "/home/bspeakmon/src/atlassian-oauth-examples/rsa.pem" -KEY_CERT_DATA = None -try: - with open(KEY_CERT_FILE, "r") as cert: - KEY_CERT_DATA = cert.read() - OAUTH = True -except Exception: - pass - -if "CI_JIRA_URL" in os.environ: - not_on_custom_jira_instance = pytest.mark.skipif( - True, reason="Not applicable for custom Jira instance" - ) - logging.info("Picked up custom Jira engine.") -else: - - def noop(arg): - return arg - - not_on_custom_jira_instance = noop - - -def rndstr(): - return "".join(random.sample(string.ascii_lowercase, 6)) - - -def rndpassword(): - # generates a password of length 14 - s = ( - "".join(random.sample(string.ascii_uppercase, 5)) - + "".join(random.sample(string.ascii_lowercase, 5)) - + "".join(random.sample(string.digits, 2)) - + "".join(random.sample("~`!@#$%^&*()_+-=[]\\{}|;':<>?,./", 2)) - ) - return "".join(random.sample(s, len(s))) - - -def hashify(some_string, max_len=8): - return hashlib.md5(some_string.encode("utf-8")).hexdigest()[:8].upper() - - -def get_unique_project_name(): - jid = "" - user = re.sub("[^A-Z_]", "", getpass.getuser().upper()) - if user == "TRAVIS" and "TRAVIS_JOB_NUMBER" in os.environ: - # please note that user underline (_) is not supported by - # Jira even if it is documented as supported. - jid = "T" + hashify(user + os.environ["TRAVIS_JOB_NUMBER"]) - else: - identifier = ( - user - + chr(ord("A") + sys.version_info[0]) - + chr(ord("A") + sys.version_info[1]) - ) - jid = "Z" + hashify(identifier) - return jid - - -class JiraTestManager(object): - """Used to instantiate and populate the JIRA instance with data used by the unit tests. - - Attributes: - CI_JIRA_ADMIN (str): Admin user account name. - CI_JIRA_USER (str): Limited user account name. - max_retries (int): number of retries to perform for recoverable HTTP errors. - """ - - __shared_state = {} # type: Dict[Any, Any] - - def __init__(self): - self.__dict__ = self.__shared_state - - if not self.__dict__: - self.initialized = 0 - - if "CI_JIRA_URL" in os.environ: - self.CI_JIRA_URL = os.environ["CI_JIRA_URL"] - self.max_retries = 5 - else: - self.CI_JIRA_URL = "https://pycontribs.atlassian.net" - self.max_retries = 5 - - if "CI_JIRA_ADMIN" in os.environ: - self.CI_JIRA_ADMIN = os.environ["CI_JIRA_ADMIN"] - else: - self.CI_JIRA_ADMIN = "ci-admin" - - if "CI_JIRA_ADMIN_PASSWORD" in os.environ: - self.CI_JIRA_ADMIN_PASSWORD = os.environ["CI_JIRA_ADMIN_PASSWORD"] - else: - self.CI_JIRA_ADMIN_PASSWORD = "sd4s3dgec5fhg4tfsds3434" - - if "CI_JIRA_USER" in os.environ: - self.CI_JIRA_USER = os.environ["CI_JIRA_USER"] - else: - self.CI_JIRA_USER = "ci-user" - - if "CI_JIRA_USER_PASSWORD" in os.environ: - self.CI_JIRA_USER_PASSWORD = os.environ["CI_JIRA_USER_PASSWORD"] - else: - self.CI_JIRA_USER_PASSWORD = "sd4s3dgec5fhg4tfsds3434" - - self.CI_JIRA_ISSUE = os.environ.get("CI_JIRA_ISSUE", "Bug") - - if OAUTH: - self.jira_admin = JIRA( - oauth={ - "access_token": "hTxcwsbUQiFuFALf7KZHDaeAJIo3tLUK", - "access_token_secret": "aNCLQFP3ORNU6WY7HQISbqbhf0UudDAf", - "consumer_key": CONSUMER_KEY, - "key_cert": KEY_CERT_DATA, - } - ) - else: - if self.CI_JIRA_ADMIN: - self.jira_admin = JIRA( - self.CI_JIRA_URL, - basic_auth=(self.CI_JIRA_ADMIN, self.CI_JIRA_ADMIN_PASSWORD), - logging=False, - validate=True, - max_retries=self.max_retries, - ) - else: - self.jira_admin = JIRA( - self.CI_JIRA_URL, - validate=True, - logging=False, - max_retries=self.max_retries, - ) - if not self.jira_admin.current_user(): - self.initialized = 1 - sys.exit(3) - - if OAUTH: - self.jira_sysadmin = JIRA( - oauth={ - "access_token": "4ul1ETSFo7ybbIxAxzyRal39cTrwEGFv", - "access_token_secret": "K83jBZnjnuVRcfjBflrKyThJa0KSjSs2", - "consumer_key": CONSUMER_KEY, - "key_cert": KEY_CERT_DATA, - }, - logging=False, - max_retries=self.max_retries, - ) - else: - if self.CI_JIRA_ADMIN: - self.jira_sysadmin = JIRA( - self.CI_JIRA_URL, - basic_auth=(self.CI_JIRA_ADMIN, self.CI_JIRA_ADMIN_PASSWORD), - logging=False, - validate=True, - max_retries=self.max_retries, - ) - else: - self.jira_sysadmin = JIRA( - self.CI_JIRA_URL, logging=False, max_retries=self.max_retries - ) - - if OAUTH: - self.jira_normal = JIRA( - oauth={ - "access_token": "ZVDgYDyIQqJY8IFlQ446jZaURIz5ECiB", - "access_token_secret": "5WbLBybPDg1lqqyFjyXSCsCtAWTwz1eD", - "consumer_key": CONSUMER_KEY, - "key_cert": KEY_CERT_DATA, - } - ) - else: - if self.CI_JIRA_ADMIN: - self.jira_normal = JIRA( - self.CI_JIRA_URL, - basic_auth=(self.CI_JIRA_USER, self.CI_JIRA_USER_PASSWORD), - validate=True, - logging=False, - max_retries=self.max_retries, - ) - else: - self.jira_normal = JIRA( - self.CI_JIRA_URL, - validate=True, - logging=False, - max_retries=self.max_retries, - ) - - # now we need some data to start with for the tests - - # jira project key is max 10 chars, no letter. - # [0] always "Z" - # [1-6] username running the tests (hope we will not collide) - # [7-8] python version A=0, B=1,.. - # [9] A,B -- we may need more than one project - - """ `jid` is important for avoiding concurency problems when - executing tests in parallel as we have only one test instance. - - jid length must be less than 9 characters because we may append - another one and the Jira Project key length limit is 10. - - Tests run in parallel: - * git branches master or developer, git pr or developers running - tests outside Travis - * Travis is using "Travis" username - - https://docs.travis-ci.com/user/environment-variables/ - """ - - self.jid = get_unique_project_name() - - self.project_a = self.jid + "A" # old XSS - self.project_a_name = "Test user=%s key=%s A" % ( - getpass.getuser(), - self.project_a, - ) - self.project_b = self.jid + "B" # old BULK - self.project_b_name = "Test user=%s key=%s B" % ( - getpass.getuser(), - self.project_b, - ) - self.project_sd = self.jid + "C" - self.project_sd_name = "Test user=%s key=%s C" % ( - getpass.getuser(), - self.project_b, - ) - - # TODO(ssbarnea): find a way to prevent SecurityTokenMissing for On Demand - # https://jira.atlassian.com/browse/JRA-39153 - try: - self.jira_admin.project(self.project_a) - except Exception as e: - logging.warning(e) - pass - else: - try: - self.jira_admin.delete_project(self.project_a) - except Exception as e: # noqa - pass - - try: - self.jira_admin.project(self.project_b) - except Exception as e: - logging.warning(e) - pass - else: - try: - self.jira_admin.delete_project(self.project_b) - except Exception as e: # noqa - pass - - # wait for the project to be deleted - for i in range(1, 20): - try: - self.jira_admin.project(self.project_b) - except Exception: - break - print("Warning: Project not deleted yet....") - sleep(2) - - for i in range(6): - try: - if self.jira_admin.create_project( - self.project_a, self.project_a_name - ): - break - except Exception as e: - if "A project with that name already exists" not in e.text: - raise e - self.project_a_id = self.jira_admin.project(self.project_a).id - self.jira_admin.create_project(self.project_b, self.project_b_name) - - try: - self.jira_admin.create_project(self.project_b, self.project_b_name) - except Exception: - # we care only for the project to exist - pass - sleep(1) # keep it here as often Jira will report the - # project as missing even after is created - self.project_b_issue1_obj = self.jira_admin.create_issue( - project=self.project_b, - summary="issue 1 from %s" % self.project_b, - issuetype=self.CI_JIRA_ISSUE, - ) - self.project_b_issue1 = self.project_b_issue1_obj.key - - self.project_b_issue2_obj = self.jira_admin.create_issue( - project=self.project_b, - summary="issue 2 from %s" % self.project_b, - issuetype={"name": self.CI_JIRA_ISSUE}, - ) - self.project_b_issue2 = self.project_b_issue2_obj.key - - self.project_b_issue3_obj = self.jira_admin.create_issue( - project=self.project_b, - summary="issue 3 from %s" % self.project_b, - issuetype={"name": self.CI_JIRA_ISSUE}, - ) - self.project_b_issue3 = self.project_b_issue3_obj.key +LOGGER = logging.getLogger(__name__) - if not hasattr(self, "jira_normal") or not hasattr(self, "jira_admin"): - py.test.exit("FATAL: WTF!?") - - self.user_admin = self.jira_admin.search_users(self.CI_JIRA_ADMIN)[0] - self.initialized = 1 - - -def find_by_key(seq, key): - for seq_item in seq: - if seq_item["key"] == key: - return seq_item - - -def find_by_key_value(seq, key): - for seq_item in seq: - if seq_item.key == key: - return seq_item - - -def find_by_id(seq, id): - for seq_item in seq: - if seq_item.id == id: - return seq_item - - -def find_by_name(seq, name): - for seq_item in seq: - if seq_item["name"] == name: - return seq_item - - -@flaky -class UniversalResourceTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - self.test_manager = JiraTestManager() +class UniversalResourceTests(JiraTestCase): def test_universal_find_existing_resource(self): resource = self.jira.find("issue/{0}", self.test_manager.project_b_issue1) issue = self.jira.issue(self.test_manager.project_b_issue1) @@ -390,70 +52,81 @@ def test_pickling_resource(self): self.jira._options, self.jira._session, raw=pickle.loads(pickled) ) self.assertEqual(resource.key, unpickled_instance.key) - self.assertTrue(resource == unpickled_instance) + # Class types are no longer equal, cls_for_resource() returns an Issue type + # find() returns a Resource type. So we compare the raw json + self.assertEqual(resource.raw, unpickled_instance.raw) + def test_pickling_resource_class(self): + resource = self.jira.find("issue/{0}", self.test_manager.project_b_issue1) -@flaky -class ResourceTests(unittest.TestCase): - def setUp(self): - pass + pickled = pickle.dumps(resource) + unpickled = pickle.loads(pickled) - def test_cls_for_resource(self): - self.assertEqual( - cls_for_resource( - "https://jira.atlassian.com/rest/\ - api/latest/issue/JRA-1330" - ), - Issue, - ) - self.assertEqual( - cls_for_resource( - "http://localhost:2990/jira/rest/\ - api/latest/project/BULK" - ), - Project, - ) - self.assertEqual( - cls_for_resource( - "http://imaginary-jira.com/rest/\ - api/latest/project/IMG/role/10002" - ), - Role, - ) - self.assertEqual( - cls_for_resource( - "http://customized-jira.com/rest/\ - plugin-resource/4.5/json/getMyObject" - ), - UnknownResource, - ) - self.assertEqual( - cls_for_resource( - "http://customized-jira.com/rest/\ - group?groupname=bla" - ), - Group, - ) + self.assertEqual(resource.key, unpickled.key) + self.assertEqual(resource, unpickled) + def test_pickling_issue_class(self): + resource = self.test_manager.project_b_issue1_obj -@flaky -class ApplicationPropertiesTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin + pickled = pickle.dumps(resource) + unpickled = pickle.loads(pickled) + + self.assertEqual(resource.key, unpickled.key) + self.assertEqual(resource, unpickled) + + def test_bad_attribute(self): + resource = self.jira.find("issue/{0}", self.test_manager.project_b_issue1) + + with self.assertRaises(AttributeError): + getattr(resource, "bogus123") + + def test_hashable(self): + resource = self.jira.find("issue/{0}", self.test_manager.project_b_issue1) + resource2 = self.jira.find("issue/{0}", self.test_manager.project_b_issue2) + + r1_hash = hash(resource) + r2_hash = hash(resource2) + + assert r1_hash != r2_hash + + dict_of_resource = {resource: "hey", resource2: "peekaboo"} + dict_of_resource.update({resource: "hey ho"}) + + assert len(dict_of_resource.keys()) == 2 + assert {resource, resource2} == set(dict_of_resource.keys()) + assert dict_of_resource[resource] == "hey ho" + + def test_hashable_issue_object(self): + resource = self.test_manager.project_b_issue1_obj + resource2 = self.test_manager.project_b_issue2_obj + + r1_hash = hash(resource) + r2_hash = hash(resource2) + + assert r1_hash != r2_hash + dict_of_resource = {resource: "hey", resource2: "peekaboo"} + dict_of_resource.update({resource: "hey ho"}) + + assert len(dict_of_resource.keys()) == 2 + assert {resource, resource2} == set(dict_of_resource.keys()) + assert dict_of_resource[resource] == "hey ho" + + +class ApplicationPropertiesTests(JiraTestCase): def test_application_properties(self): props = self.jira.application_properties() for p in props: self.assertIsInstance(p, dict) self.assertTrue( - set(p.keys()).issuperset(set(["type", "name", "value", "key", "id"])) + set(p.keys()).issuperset({"type", "name", "value", "key", "id"}) ) def test_application_property(self): clone_prefix = self.jira.application_properties( key="jira.lf.text.headingcolour" ) - self.assertEqual(clone_prefix["value"], "#292929") + self.assertEqual(clone_prefix["value"], "#172b4d") def test_set_application_property(self): prop = "jira.lf.favicon.hires.url" @@ -474,988 +147,15 @@ def test_setting_bad_property_raises(self): self.assertRaises(JIRAError, self.jira.set_application_property, prop, "666") -@flaky -class AttachmentTests(unittest.TestCase): - def setUp(self): - self.test_manager = JiraTestManager() - self.jira = JiraTestManager().jira_admin - self.project_b = self.test_manager.project_b - self.issue_1 = self.test_manager.project_b_issue1 - self.attachment = None - - def test_0_attachment_meta(self): - meta = self.jira.attachment_meta() - self.assertTrue(meta["enabled"]) - # we have no control over server side upload limit - self.assertIn("uploadLimit", meta) - - def test_1_add_remove_attachment(self): - issue = self.jira.issue(self.issue_1) - with open(TEST_ATTACH_PATH, "rb") as f: - attachment = self.jira.add_attachment(issue, f, "new test attachment") - new_attachment = self.jira.attachment(attachment.id) - msg = "attachment %s of issue %s" % (new_attachment.__dict__, issue) - self.assertEqual(new_attachment.filename, "new test attachment", msg=msg) - self.assertEqual( - new_attachment.size, os.path.getsize(TEST_ATTACH_PATH), msg=msg - ) - # JIRA returns a HTTP 204 upon successful deletion - self.assertEqual(attachment.delete().status_code, 204) - - -@flaky -class ComponentTests(unittest.TestCase): - def setUp(self): - self.test_manager = JiraTestManager() - self.jira = JiraTestManager().jira_admin - self.project_b = self.test_manager.project_b - self.issue_1 = self.test_manager.project_b_issue1 - self.issue_2 = self.test_manager.project_b_issue2 - - def test_2_create_component(self): - proj = self.jira.project(self.project_b) - name = "project-%s-component-%s" % (proj, rndstr()) - component = self.jira.create_component( - name, - proj, - description="test!!", - assigneeType="COMPONENT_LEAD", - isAssigneeTypeValid=False, - ) - self.assertEqual(component.name, name) - self.assertEqual(component.description, "test!!") - self.assertEqual(component.assigneeType, "COMPONENT_LEAD") - self.assertFalse(component.isAssigneeTypeValid) - component.delete() - - # Components field can't be modified from issue.update - # def test_component_count_related_issues(self): - # component = self.jira.create_component('PROJECT_B_TEST',self.project_b, description='test!!', - # assigneeType='COMPONENT_LEAD', isAssigneeTypeValid=False) - # issue1 = self.jira.issue(self.issue_1) - # issue2 = self.jira.issue(self.issue_2) - # (issue1.update ({'components': ['PROJECT_B_TEST']})) - # (issue2.update (components = ['PROJECT_B_TEST'])) - # issue_count = self.jira.component_count_related_issues(component.id) - # self.assertEqual(issue_count, 2) - # component.delete() - - def test_3_update(self): - try: - components = self.jira.project_components(self.project_b) - for component in components: - if component.name == "To be updated": - component.delete() - break - except Exception: - # We ignore errors as this code intends only to prepare for - # component creation - raise - - name = "component-" + rndstr() - - component = self.jira.create_component( - name, - self.project_b, - description="stand by!", - leadUserName=self.jira.current_user(), - ) - name = "renamed-" + name - component.update( - name=name, description="It is done.", leadUserName=self.jira.current_user() - ) - self.assertEqual(component.name, name) - self.assertEqual(component.description, "It is done.") - self.assertEqual(component.lead.name, self.jira.current_user()) - component.delete() - - def test_4_delete(self): - component = self.jira.create_component( - "To be deleted", self.project_b, description="not long for this world" - ) - myid = component.id - component.delete() - self.assertRaises(JIRAError, self.jira.component, myid) - - def test_delete_component_by_id(self): - component = self.jira.create_component( - "To be deleted", self.project_b, description="not long for this world" - ) - myid = component.id - self.jira.delete_component(myid) - self.assertRaises(JIRAError, self.jira.component, myid) - - -@flaky -class CustomFieldOptionTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - - @not_on_custom_jira_instance - def test_custom_field_option(self): - option = self.jira.custom_field_option("10001") - self.assertEqual(option.value, "To Do") - - -@not_on_custom_jira_instance -@flaky -class DashboardTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - - def test_dashboards(self): - dashboards = self.jira.dashboards() - self.assertEqual(len(dashboards), 3) - - def test_dashboards_filter(self): - dashboards = self.jira.dashboards(filter="my") - self.assertEqual(len(dashboards), 2) - self.assertEqual(dashboards[0].id, "10101") - - def test_dashboards_startat(self): - dashboards = self.jira.dashboards(startAt=1, maxResults=1) - self.assertEqual(len(dashboards), 1) - - def test_dashboards_maxresults(self): - dashboards = self.jira.dashboards(maxResults=1) - self.assertEqual(len(dashboards), 1) - - def test_dashboard(self): - dashboard = self.jira.dashboard("10101") - self.assertEqual(dashboard.id, "10101") - self.assertEqual(dashboard.name, "Another test dashboard") - - -@not_on_custom_jira_instance -@flaky -class FieldsTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - +class FieldsTests(JiraTestCase): def test_fields(self): fields = self.jira.fields() self.assertGreater(len(fields), 10) -@flaky -class FilterTests(unittest.TestCase): - def setUp(self): - self.test_manager = JiraTestManager() - self.jira = JiraTestManager().jira_admin - self.project_b = self.test_manager.project_b - self.issue_1 = self.test_manager.project_b_issue1 - self.issue_2 = self.test_manager.project_b_issue2 - - def test_filter(self): - jql = "project = %s and component is not empty" % self.project_b - name = "same filter " + rndstr() - myfilter = self.jira.create_filter( - name=name, description="just some new test filter", jql=jql, favourite=False - ) - self.assertEqual(myfilter.name, name) - self.assertEqual(myfilter.owner.name, self.test_manager.user_admin.name) - myfilter.delete() - - def test_favourite_filters(self): - # filters = self.jira.favourite_filters() - jql = "project = %s and component is not empty" % self.project_b - name = "filter-to-fav-" + rndstr() - myfilter = self.jira.create_filter( - name=name, description="just some new test filter", jql=jql, favourite=True - ) - new_filters = self.jira.favourite_filters() - - assert name in [f.name for f in new_filters] - myfilter.delete() - - -@not_on_custom_jira_instance -@flaky -class GroupsTest(unittest.TestCase): - def setUp(self): - self.test_manager = JiraTestManager() - self.jira = self.test_manager.jira_admin - - def test_group(self): - group = self.jira.group("jira-users") - self.assertEqual(group.name, "jira-users") - - def test_groups(self): - groups = self.jira.groups() - self.assertGreater(len(groups), 0) - - def test_groups_for_users(self): - groups = self.jira.groups("jira-users") - self.assertGreater(len(groups), 0) - - -@flaky -class IssueTests(unittest.TestCase): - def setUp(self): - self.test_manager = JiraTestManager() - self.jira = JiraTestManager().jira_admin - self.jira_normal = JiraTestManager().jira_normal - self.user_admin = self.jira.search_users(self.test_manager.CI_JIRA_ADMIN)[0] - self.project_b = self.test_manager.project_b - self.project_a = self.test_manager.project_a - self.issue_1 = self.test_manager.project_b_issue1 - self.issue_2 = self.test_manager.project_b_issue2 - self.issue_3 = self.test_manager.project_b_issue3 - - def test_issue(self): - issue = self.jira.issue(self.issue_1) - self.assertEqual(issue.key, self.issue_1) - self.assertEqual(issue.fields.summary, "issue 1 from %s" % self.project_b) - - @unittest.skip("disabled as it seems to be ignored by jira, returning all") - def test_issue_field_limiting(self): - issue = self.jira.issue(self.issue_2, fields="summary,comment") - self.assertEqual(issue.fields.summary, "issue 2 from %s" % self.project_b) - comment1 = self.jira.add_comment(issue, "First comment") - comment2 = self.jira.add_comment(issue, "Second comment") - comment3 = self.jira.add_comment(issue, "Third comment") - self.jira.issue(self.issue_2, fields="summary,comment") - logging.warning(issue.raw["fields"]) - self.assertFalse(hasattr(issue.fields, "reporter")) - self.assertFalse(hasattr(issue.fields, "progress")) - comment1.delete() - comment2.delete() - comment3.delete() - - def test_issue_equal(self): - issue1 = self.jira.issue(self.issue_1) - issue2 = self.jira.issue(self.issue_2) - issues = self.jira.search_issues("key=%s" % self.issue_1) - self.assertTrue(issue1 is not None) - self.assertTrue(issue1 == issues[0]) - self.assertFalse(issue2 == issues[0]) - - def test_issue_expand(self): - issue = self.jira.issue(self.issue_1, expand="editmeta,schema") - self.assertTrue(hasattr(issue, "editmeta")) - self.assertTrue(hasattr(issue, "schema")) - # testing for changelog is not reliable because it may exist or not based on test order - # self.assertFalse(hasattr(issue, 'changelog')) - - @not_on_custom_jira_instance - def test_create_issue_with_fieldargs(self): - issue = self.jira.create_issue( - project=self.project_b, - summary="Test issue created", - description="foo description", - issuetype={"name": "Bug"}, - ) # customfield_10022='XSS' - self.assertEqual(issue.fields.summary, "Test issue created") - self.assertEqual(issue.fields.description, "foo description") - self.assertEqual(issue.fields.issuetype.name, "Bug") - self.assertEqual(issue.fields.project.key, self.project_b) - # self.assertEqual(issue.fields.customfield_10022, 'XSS') - issue.delete() - - @not_on_custom_jira_instance - def test_create_issue_with_fielddict(self): - fields = { - "project": {"key": self.project_b}, - "summary": "Issue created from field dict", - "description": "Some new issue for test", - "issuetype": {"name": "Bug"}, - # 'customfield_10022': 'XSS', - "priority": {"name": "Major"}, - } - issue = self.jira.create_issue(fields=fields) - self.assertEqual(issue.fields.summary, "Issue created from field dict") - self.assertEqual(issue.fields.description, "Some new issue for test") - self.assertEqual(issue.fields.issuetype.name, "Bug") - self.assertEqual(issue.fields.project.key, self.project_b) - # self.assertEqual(issue.fields.customfield_10022, 'XSS') - self.assertEqual(issue.fields.priority.name, "Major") - issue.delete() - - @not_on_custom_jira_instance - def test_create_issue_without_prefetch(self): - issue = self.jira.create_issue( - prefetch=False, - project=self.project_b, - summary="Test issue created", - description="some details", - issuetype={"name": "Bug"}, - ) # customfield_10022='XSS' - - assert hasattr(issue, "self") - assert hasattr(issue, "raw") - assert "fields" not in issue.raw - issue.delete() - - @not_on_custom_jira_instance - def test_create_issues(self): - field_list = [ - { - "project": {"key": self.project_b}, - "summary": "Issue created via bulk create #1", - "description": "Some new issue for test", - "issuetype": {"name": "Bug"}, - # 'customfield_10022': 'XSS', - "priority": {"name": "Major"}, - }, - { - "project": {"key": self.project_a}, - "issuetype": {"name": "Bug"}, - "summary": "Issue created via bulk create #2", - "description": "Another new issue for bulk test", - "priority": {"name": "Major"}, - }, - ] - issues = self.jira.create_issues(field_list=field_list) - self.assertEqual(len(issues), 2) - self.assertIsNotNone(issues[0]["issue"], "the first issue has not been created") - self.assertEqual( - issues[0]["issue"].fields.summary, "Issue created via bulk create #1" - ) - self.assertEqual( - issues[0]["issue"].fields.description, "Some new issue for test" - ) - self.assertEqual(issues[0]["issue"].fields.issuetype.name, "Bug") - self.assertEqual(issues[0]["issue"].fields.project.key, self.project_b) - self.assertEqual(issues[0]["issue"].fields.priority.name, "Major") - self.assertIsNotNone( - issues[1]["issue"], "the second issue has not been created" - ) - self.assertEqual( - issues[1]["issue"].fields.summary, "Issue created via bulk create #2" - ) - self.assertEqual( - issues[1]["issue"].fields.description, "Another new issue for bulk test" - ) - self.assertEqual(issues[1]["issue"].fields.issuetype.name, "Bug") - self.assertEqual(issues[1]["issue"].fields.project.key, self.project_a) - self.assertEqual(issues[1]["issue"].fields.priority.name, "Major") - for issue in issues: - issue["issue"].delete() - - @not_on_custom_jira_instance - def test_create_issues_one_failure(self): - field_list = [ - { - "project": {"key": self.project_b}, - "summary": "Issue created via bulk create #1", - "description": "Some new issue for test", - "issuetype": {"name": "Bug"}, - # 'customfield_10022': 'XSS', - "priority": {"name": "Major"}, - }, - { - "project": {"key": self.project_a}, - "issuetype": {"name": "InvalidIssueType"}, - "summary": "This issue will not succeed", - "description": "Should not be seen.", - "priority": {"name": "Blah"}, - }, - { - "project": {"key": self.project_a}, - "issuetype": {"name": "Bug"}, - "summary": "However, this one will.", - "description": "Should be seen.", - "priority": {"name": "Major"}, - }, - ] - issues = self.jira.create_issues(field_list=field_list) - self.assertEqual( - issues[0]["issue"].fields.summary, "Issue created via bulk create #1" - ) - self.assertEqual( - issues[0]["issue"].fields.description, "Some new issue for test" - ) - self.assertEqual(issues[0]["issue"].fields.issuetype.name, "Bug") - self.assertEqual(issues[0]["issue"].fields.project.key, self.project_b) - self.assertEqual(issues[0]["issue"].fields.priority.name, "Major") - self.assertEqual(issues[0]["error"], None) - self.assertEqual(issues[1]["issue"], None) - self.assertEqual(issues[1]["error"], {"issuetype": "issue type is required"}) - self.assertEqual(issues[1]["input_fields"], field_list[1]) - self.assertEqual(issues[2]["issue"].fields.summary, "However, this one will.") - self.assertEqual(issues[2]["issue"].fields.description, "Should be seen.") - self.assertEqual(issues[2]["issue"].fields.issuetype.name, "Bug") - self.assertEqual(issues[2]["issue"].fields.project.key, self.project_a) - self.assertEqual(issues[2]["issue"].fields.priority.name, "Major") - self.assertEqual(issues[2]["error"], None) - self.assertEqual(len(issues), 3) - for issue in issues: - if issue["issue"] is not None: - issue["issue"].delete() - - @not_on_custom_jira_instance - def test_create_issues_without_prefetch(self): - field_list = [ - dict( - project=self.project_b, - summary="Test issue created", - description="some details", - issuetype={"name": "Bug"}, - ), - dict( - project=self.project_a, - summary="Test issue #2", - description="foo description", - issuetype={"name": "Bug"}, - ), - ] - issues = self.jira.create_issues(field_list, prefetch=False) - - assert hasattr(issues[0]["issue"], "self") - assert hasattr(issues[0]["issue"], "raw") - assert hasattr(issues[1]["issue"], "self") - assert hasattr(issues[1]["issue"], "raw") - assert "fields" not in issues[0]["issue"].raw - assert "fields" not in issues[1]["issue"].raw - for issue in issues: - issue["issue"].delete() - - @not_on_custom_jira_instance - def test_update_with_fieldargs(self): - issue = self.jira.create_issue( - project=self.project_b, - summary="Test issue for updating", - description="Will be updated shortly", - issuetype={"name": "Bug"}, - ) - # customfield_10022='XSS') - issue.update( - summary="Updated summary", - description="Now updated", - issuetype={"name": "Story"}, - ) - self.assertEqual(issue.fields.summary, "Updated summary") - self.assertEqual(issue.fields.description, "Now updated") - self.assertEqual(issue.fields.issuetype.name, "Story") - # self.assertEqual(issue.fields.customfield_10022, 'XSS') - self.assertEqual(issue.fields.project.key, self.project_b) - issue.delete() - - @not_on_custom_jira_instance - def test_update_with_fielddict(self): - issue = self.jira.create_issue( - project=self.project_b, - summary="Test issue for updating", - description="Will be updated shortly", - issuetype={"name": "Bug"}, - ) - fields = { - "summary": "Issue is updated", - "description": "it sure is", - "issuetype": {"name": "Story"}, - # 'customfield_10022': 'DOC', - "priority": {"name": "Major"}, - } - issue.update(fields=fields) - self.assertEqual(issue.fields.summary, "Issue is updated") - self.assertEqual(issue.fields.description, "it sure is") - self.assertEqual(issue.fields.issuetype.name, "Story") - # self.assertEqual(issue.fields.customfield_10022, 'DOC') - self.assertEqual(issue.fields.priority.name, "Major") - issue.delete() - - def test_update_with_label(self): - issue = self.jira.create_issue( - project=self.project_b, - summary="Test issue for updating labels", - description="Label testing", - issuetype=self.test_manager.CI_JIRA_ISSUE, - ) - - labelarray = ["testLabel"] - fields = {"labels": labelarray} - - issue.update(fields=fields) - self.assertEqual(issue.fields.labels, ["testLabel"]) - - def test_update_with_bad_label(self): - issue = self.jira.create_issue( - project=self.project_b, - summary="Test issue for updating labels", - description="Label testing", - issuetype=self.test_manager.CI_JIRA_ISSUE, - ) - - issue.fields.labels.append("this should not work") - - fields = {"labels": issue.fields.labels} - - self.assertRaises(JIRAError, issue.update, fields=fields) - - @not_on_custom_jira_instance - def test_update_with_notify_false(self): - issue = self.jira.create_issue( - project=self.project_b, - summary="Test issue for updating", - description="Will be updated shortly", - issuetype={"name": "Bug"}, - ) - issue.update(notify=False, description="Now updated, but silently") - self.assertEqual(issue.fields.description, "Now updated, but silently") - issue.delete() - - def test_delete(self): - issue = self.jira.create_issue( - project=self.project_b, - summary="Test issue created", - description="Not long for this world", - issuetype=self.test_manager.CI_JIRA_ISSUE, - ) - key = issue.key - issue.delete() - self.assertRaises(JIRAError, self.jira.issue, key) - - @not_on_custom_jira_instance - def test_createmeta(self): - meta = self.jira.createmeta() - proj = find_by_key(meta["projects"], self.project_b) - # we assume that this project should allow at least one issue type - self.assertGreaterEqual(len(proj["issuetypes"]), 1) - - @not_on_custom_jira_instance - def test_createmeta_filter_by_projectkey_and_name(self): - meta = self.jira.createmeta(projectKeys=self.project_b, issuetypeNames="Bug") - self.assertEqual(len(meta["projects"]), 1) - self.assertEqual(len(meta["projects"][0]["issuetypes"]), 1) - - @not_on_custom_jira_instance - def test_createmeta_filter_by_projectkeys_and_name(self): - meta = self.jira.createmeta( - projectKeys=(self.project_a, self.project_b), issuetypeNames="Story" - ) - self.assertEqual(len(meta["projects"]), 2) - for project in meta["projects"]: - self.assertEqual(len(project["issuetypes"]), 1) - - @not_on_custom_jira_instance - def test_createmeta_filter_by_id(self): - projects = self.jira.projects() - proja = find_by_key_value(projects, self.project_a) - projb = find_by_key_value(projects, self.project_b) - issue_type_ids = dict() - full_meta = self.jira.createmeta(projectIds=(proja.id, projb.id)) - for project in full_meta["projects"]: - for issue_t in project["issuetypes"]: - issue_t_id = issue_t["id"] - val = issue_type_ids.get(issue_t_id) - if val is None: - issue_type_ids[issue_t_id] = [] - issue_type_ids[issue_t_id].append([project["id"]]) - common_issue_ids = [] - for key, val in issue_type_ids.items(): - if len(val) == 2: - common_issue_ids.append(key) - self.assertNotEqual(len(common_issue_ids), 0) - for_lookup_common_issue_ids = common_issue_ids - if len(common_issue_ids) > 2: - for_lookup_common_issue_ids = common_issue_ids[:-1] - meta = self.jira.createmeta( - projectIds=(proja.id, projb.id), issuetypeIds=for_lookup_common_issue_ids - ) - self.assertEqual(len(meta["projects"]), 2) - for project in meta["projects"]: - self.assertEqual( - len(project["issuetypes"]), len(for_lookup_common_issue_ids) - ) - - def test_createmeta_expand(self): - # limit to SCR project so the call returns promptly - meta = self.jira.createmeta( - projectKeys=self.project_b, expand="projects.issuetypes.fields" - ) - self.assertTrue("fields" in meta["projects"][0]["issuetypes"][0]) - - def test_assign_issue(self): - self.assertTrue(self.jira.assign_issue(self.issue_1, self.user_admin.name)) - self.assertEqual( - self.jira.issue(self.issue_1).fields.assignee.name, self.user_admin.name - ) - - def test_assign_issue_with_issue_obj(self): - issue = self.jira.issue(self.issue_1) - x = self.jira.assign_issue(issue, self.user_admin.name) - self.assertTrue(x) - self.assertEqual( - self.jira.issue(self.issue_1).fields.assignee.name, self.user_admin.name - ) - - def test_assign_to_bad_issue_raises(self): - self.assertRaises(JIRAError, self.jira.assign_issue, "NOPE-1", "notauser") - - def test_comments(self): - for issue in [self.issue_1, self.jira.issue(self.issue_2)]: - self.jira.issue(issue) - comment1 = self.jira.add_comment(issue, "First comment") - comment2 = self.jira.add_comment(issue, "Second comment") - comments = self.jira.comments(issue) - assert comments[0].body == "First comment" - assert comments[1].body == "Second comment" - comment1.delete() - comment2.delete() - comments = self.jira.comments(issue) - assert len(comments) == 0 - - def test_add_comment(self): - comment = self.jira.add_comment( - self.issue_3, - "a test comment!", - visibility={"type": "role", "value": "Administrators"}, - ) - self.assertEqual(comment.body, "a test comment!") - self.assertEqual(comment.visibility.type, "role") - self.assertEqual(comment.visibility.value, "Administrators") - comment.delete() - - def test_add_comment_with_issue_obj(self): - issue = self.jira.issue(self.issue_3) - comment = self.jira.add_comment( - issue, - "a new test comment!", - visibility={"type": "role", "value": "Administrators"}, - ) - self.assertEqual(comment.body, "a new test comment!") - self.assertEqual(comment.visibility.type, "role") - self.assertEqual(comment.visibility.value, "Administrators") - comment.delete() - - def test_update_comment(self): - comment = self.jira.add_comment(self.issue_3, "updating soon!") - comment.update(body="updated!") - self.assertEqual(comment.body, "updated!") - # self.assertEqual(comment.visibility.type, 'role') - # self.assertEqual(comment.visibility.value, 'Administrators') - comment.delete() - - def test_editmeta(self): - expected_fields = { - "assignee", - "attachment", - "comment", - "components", - "description", - "environment", - "fixVersions", - "issuelinks", - "labels", - "summary", - "versions", - } - for i in (self.issue_1, self.issue_2): - meta = self.jira.editmeta(i) - meta_field_set = set(meta["fields"].keys()) - self.assertEqual( - meta_field_set.intersection(expected_fields), expected_fields - ) - - # Nothing from remote link works - # def test_remote_links(self): - # self.jira.add_remote_link ('ZTRAVISDEB-3', globalId='python-test:story.of.horse.riding', - # links = self.jira.remote_links('QA-44') - # self.assertEqual(len(links), 1) - # links = self.jira.remote_links('BULK-1') - # self.assertEqual(len(links), 0) - # - # @unittest.skip("temporary disabled") - # def test_remote_links_with_issue_obj(self): - # issue = self.jira.issue('QA-44') - # links = self.jira.remote_links(issue) - # self.assertEqual(len(links), 1) - # issue = self.jira.issue('BULK-1') - # links = self.jira.remote_links(issue) - # self.assertEqual(len(links), 0) - # - # @unittest.skip("temporary disabled") - # def test_remote_link(self): - # link = self.jira.remote_link('QA-44', '10000') - # self.assertEqual(link.id, 10000) - # self.assertTrue(hasattr(link, 'globalId')) - # self.assertTrue(hasattr(link, 'relationship')) - # - # @unittest.skip("temporary disabled") - # def test_remote_link_with_issue_obj(self): - # issue = self.jira.issue('QA-44') - # link = self.jira.remote_link(issue, '10000') - # self.assertEqual(link.id, 10000) - # self.assertTrue(hasattr(link, 'globalId')) - # self.assertTrue(hasattr(link, 'relationship')) - # - # @unittest.skip("temporary disabled") - # def test_add_remote_link(self): - # link = self.jira.add_remote_link('BULK-3', globalId='python-test:story.of.horse.riding', - # object={'url': 'http://google.com', 'title': 'googlicious!'}, - # application={'name': 'far too silly', 'type': 'sketch'}, relationship='mousebending') - # creation response doesn't include full remote link info, so we fetch it again using the new internal ID - # link = self.jira.remote_link('BULK-3', link.id) - # self.assertEqual(link.application.name, 'far too silly') - # self.assertEqual(link.application.type, 'sketch') - # self.assertEqual(link.object.url, 'http://google.com') - # self.assertEqual(link.object.title, 'googlicious!') - # self.assertEqual(link.relationship, 'mousebending') - # self.assertEqual(link.globalId, 'python-test:story.of.horse.riding') - # - # @unittest.skip("temporary disabled") - # def test_add_remote_link_with_issue_obj(self): - # issue = self.jira.issue('BULK-3') - # link = self.jira.add_remote_link(issue, globalId='python-test:story.of.horse.riding', - # object={'url': 'http://google.com', 'title': 'googlicious!'}, - # application={'name': 'far too silly', 'type': 'sketch'}, relationship='mousebending') - # creation response doesn't include full remote link info, so we fetch it again using the new internal ID - # link = self.jira.remote_link(issue, link.id) - # self.assertEqual(link.application.name, 'far too silly') - # self.assertEqual(link.application.type, 'sketch') - # self.assertEqual(link.object.url, 'http://google.com') - # self.assertEqual(link.object.title, 'googlicious!') - # self.assertEqual(link.relationship, 'mousebending') - # self.assertEqual(link.globalId, 'python-test:story.of.horse.riding') - # - # @unittest.skip("temporary disabled") - # def test_update_remote_link(self): - # link = self.jira.add_remote_link('BULK-3', globalId='python-test:story.of.horse.riding', - # object={'url': 'http://google.com', 'title': 'googlicious!'}, - # application={'name': 'far too silly', 'type': 'sketch'}, relationship='mousebending') - # creation response doesn't include full remote link info, so we fetch it again using the new internal ID - # link = self.jira.remote_link('BULK-3', link.id) - # link.update(object={'url': 'http://yahoo.com', 'title': 'yahoo stuff'}, globalId='python-test:updated.id', - # relationship='cheesing') - # self.assertEqual(link.globalId, 'python-test:updated.id') - # self.assertEqual(link.relationship, 'cheesing') - # self.assertEqual(link.object.url, 'http://yahoo.com') - # self.assertEqual(link.object.title, 'yahoo stuff') - # link.delete() - # - # @unittest.skip("temporary disabled") - # def test_delete_remove_link(self): - # link = self.jira.add_remote_link('BULK-3', globalId='python-test:story.of.horse.riding', - # object={'url': 'http://google.com', 'title': 'googlicious!'}, - # application={'name': 'far too silly', 'type': 'sketch'}, relationship='mousebending') - # _id = link.id - # link.delete() - # self.assertRaises(JIRAError, self.jira.remote_link, 'BULK-3', _id) - - def test_transitioning(self): - # we check with both issue-as-string or issue-as-object - transitions = [] - for issue in [self.issue_2, self.jira.issue(self.issue_2)]: - transitions = self.jira.transitions(issue) - self.assertTrue(transitions) - self.assertTrue("id" in transitions[0]) - self.assertTrue("name" in transitions[0]) - - self.assertTrue(transitions, msg="Expecting at least one transition") - # we test getting a single transition - transition = self.jira.transitions(self.issue_2, transitions[0]["id"])[0] - self.assertDictEqual(transition, transitions[0]) - - # we test the expand of fields - transition = self.jira.transitions( - self.issue_2, transitions[0]["id"], expand="transitions.fields" - )[0] - self.assertTrue("fields" in transition) - - # Testing of transition with field assignment is disabled now because default workflows do not have it. - - # self.jira.transition_issue(issue, transitions[0]['id'], assignee={'name': self.test_manager.CI_JIRA_ADMIN}) - # issue = self.jira.issue(issue.key) - # self.assertEqual(issue.fields.assignee.name, self.test_manager.CI_JIRA_ADMIN) - # - # fields = { - # 'assignee': { - # 'name': self.test_manager.CI_JIRA_USER - # } - # } - # transitions = self.jira.transitions(issue.key) - # self.assertTrue(transitions) # any issue should have at least one transition available to it - # transition_id = transitions[0]['id'] - # - # self.jira.transition_issue(issue.key, transition_id, fields=fields) - # issue = self.jira.issue(issue.key) - # self.assertEqual(issue.fields.assignee.name, self.test_manager.CI_JIRA_USER) - # self.assertEqual(issue.fields.status.id, transition_id) - - def test_votes(self): - self.jira_normal.remove_vote(self.issue_1) - # not checking the result on this - votes = self.jira.votes(self.issue_1) - self.assertEqual(votes.votes, 0) - - self.jira_normal.add_vote(self.issue_1) - new_votes = self.jira.votes(self.issue_1) - assert votes.votes + 1 == new_votes.votes - - self.jira_normal.remove_vote(self.issue_1) - new_votes = self.jira.votes(self.issue_1) - assert votes.votes == new_votes.votes - - def test_votes_with_issue_obj(self): - issue = self.jira_normal.issue(self.issue_1) - self.jira_normal.remove_vote(issue) - # not checking the result on this - votes = self.jira.votes(issue) - self.assertEqual(votes.votes, 0) - - self.jira_normal.add_vote(issue) - new_votes = self.jira.votes(issue) - assert votes.votes + 1 == new_votes.votes - - self.jira_normal.remove_vote(issue) - new_votes = self.jira.votes(issue) - assert votes.votes == new_votes.votes - - def test_add_remove_watcher(self): - - # removing it in case it exists, so we know its state - self.jira.remove_watcher(self.issue_1, self.test_manager.user_admin.accountId) - init_watchers = self.jira.watchers(self.issue_1).watchCount - - # adding a new watcher - self.jira.add_watcher(self.issue_1, self.test_manager.user_admin.accountId) - self.assertEqual(self.jira.watchers(self.issue_1).watchCount, init_watchers + 1) - - # now we verify that remove does indeed remove watchers - self.jira.remove_watcher(self.issue_1, self.test_manager.user_admin.accountId) - new_watchers = self.jira.watchers(self.issue_1).watchCount - self.assertEqual(init_watchers, new_watchers) - - @not_on_custom_jira_instance - def test_agile(self): - uniq = rndstr() - board_name = "board-" + uniq - sprint_name = "sprint-" + uniq - - b = self.jira.create_board(board_name, self.project_a) - assert isinstance(b.id, int) - - s = self.jira.create_sprint(sprint_name, b.id) - assert isinstance(s.id, int) - assert s.name == sprint_name - assert s.state == "FUTURE" - - self.jira.add_issues_to_sprint(s.id, [self.issue_1]) - - sprint_field_name = "Sprint" - sprint_field_id = [ - f["schema"]["customId"] - for f in self.jira.fields() - if f["name"] == sprint_field_name - ][0] - sprint_customfield = "customfield_" + str(sprint_field_id) - - updated_issue_1 = self.jira.issue(self.issue_1) - serialised_sprint = getattr(updated_issue_1.fields, sprint_customfield)[0] - - # Too hard to serialise the sprint object. Performing simple regex match instead. - assert re.search(r"\[id=" + str(s.id) + ",", serialised_sprint) - - # self.jira.add_issues_to_sprint(s.id, self.issue_2) - - # self.jira.rank(self.issue_2, self.issue_1) - - sleep(2) # avoid https://travis-ci.org/pycontribs/jira/jobs/176561534#L516 - s.delete() - - sleep(2) - b.delete() - # self.jira.delete_board(b.id) - - def test_worklogs(self): - worklog = self.jira.add_worklog(self.issue_1, "2h") - worklogs = self.jira.worklogs(self.issue_1) - self.assertEqual(len(worklogs), 1) - worklog.delete() - - def test_worklogs_with_issue_obj(self): - issue = self.jira.issue(self.issue_1) - worklog = self.jira.add_worklog(issue, "2h") - worklogs = self.jira.worklogs(issue) - self.assertEqual(len(worklogs), 1) - worklog.delete() - - def test_worklog(self): - worklog = self.jira.add_worklog(self.issue_1, "1d 2h") - new_worklog = self.jira.worklog(self.issue_1, str(worklog)) - self.assertEqual(new_worklog.author.name, self.test_manager.user_admin.name) - self.assertEqual(new_worklog.timeSpent, "1d 2h") - worklog.delete() - - def test_worklog_with_issue_obj(self): - issue = self.jira.issue(self.issue_1) - worklog = self.jira.add_worklog(issue, "1d 2h") - new_worklog = self.jira.worklog(issue, str(worklog)) - self.assertEqual(new_worklog.author.name, self.test_manager.user_admin.name) - self.assertEqual(new_worklog.timeSpent, "1d 2h") - worklog.delete() - - def test_add_worklog(self): - worklog_count = len(self.jira.worklogs(self.issue_2)) - worklog = self.jira.add_worklog(self.issue_2, "2h") - self.assertIsNotNone(worklog) - self.assertEqual(len(self.jira.worklogs(self.issue_2)), worklog_count + 1) - worklog.delete() - - def test_add_worklog_with_issue_obj(self): - issue = self.jira.issue(self.issue_2) - worklog_count = len(self.jira.worklogs(issue)) - worklog = self.jira.add_worklog(issue, "2h") - self.assertIsNotNone(worklog) - self.assertEqual(len(self.jira.worklogs(issue)), worklog_count + 1) - worklog.delete() - - def test_update_and_delete_worklog(self): - worklog = self.jira.add_worklog(self.issue_3, "3h") - issue = self.jira.issue(self.issue_3, fields="worklog,timetracking") - worklog.update(comment="Updated!", timeSpent="2h") - self.assertEqual(worklog.comment, "Updated!") - # rem_estimate = issue.fields.timetracking.remainingEstimate - self.assertEqual(worklog.timeSpent, "2h") - issue = self.jira.issue(self.issue_3, fields="worklog,timetracking") - self.assertEqual(issue.fields.timetracking.remainingEstimate, "1h") - worklog.delete() - issue = self.jira.issue(self.issue_3, fields="worklog,timetracking") - self.assertEqual(issue.fields.timetracking.remainingEstimate, "3h") - - -@flaky -class IssueLinkTests(unittest.TestCase): - def setUp(self): - self.manager = JiraTestManager() - self.link_types = self.manager.jira_admin.issue_link_types() - - def test_issue_link(self): - self.link = self.manager.jira_admin.issue_link_type(self.link_types[0].id) - link = self.link # Duplicate outward - self.assertEqual(link.id, self.link_types[0].id) - - def test_create_issue_link(self): - self.manager.jira_admin.create_issue_link( - self.link_types[0].outward, - JiraTestManager().project_b_issue1, - JiraTestManager().project_b_issue2, - ) - - def test_create_issue_link_with_issue_obj(self): - inwardissue = self.manager.jira_admin.issue(JiraTestManager().project_b_issue1) - self.assertIsNotNone(inwardissue) - outwardissue = self.manager.jira_admin.issue(JiraTestManager().project_b_issue2) - self.assertIsNotNone(outwardissue) - self.manager.jira_admin.create_issue_link( - self.link_types[0].outward, inwardissue, outwardissue - ) - - # @unittest.skip("Creating an issue link doesn't return its ID, so can't easily test delete") - # def test_delete_issue_link(self): - # pass - - def test_issue_link_type(self): - link_type = self.manager.jira_admin.issue_link_type(self.link_types[0].id) - self.assertEqual(link_type.id, self.link_types[0].id) - self.assertEqual(link_type.name, self.link_types[0].name) - - -@flaky -class MyPermissionsTests(unittest.TestCase): +class MyPermissionsTests(JiraTestCase): def setUp(self): - self.test_manager = JiraTestManager() - self.jira = JiraTestManager().jira_normal + JiraTestCase.setUp(self) self.issue_1 = self.test_manager.project_b_issue1 def test_my_permissions(self): @@ -1468,256 +168,23 @@ def test_my_permissions_by_project(self): perms = self.jira.my_permissions(projectId=self.test_manager.project_a_id) self.assertGreaterEqual(len(perms["permissions"]), 10) - @unittest.skip("broken") def test_my_permissions_by_issue(self): - perms = self.jira.my_permissions(issueKey="ZTRAVISDEB-7") + perms = self.jira.my_permissions(issueKey=self.issue_1) self.assertGreaterEqual(len(perms["permissions"]), 10) - perms = self.jira.my_permissions(issueId="11021") - self.assertGreaterEqual(len(perms["permissions"]), 10) - - -@flaky -class PrioritiesTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - - def test_priorities(self): - priorities = self.jira.priorities() - self.assertEqual(len(priorities), 5) - - @not_on_custom_jira_instance - def test_priority(self): - priority = self.jira.priority("2") - self.assertEqual(priority.id, "2") - self.assertEqual(priority.name, "Critical") - - -@flaky -class ProjectTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - self.project_b = JiraTestManager().project_b - self.test_manager = JiraTestManager() - - def test_projects(self): - projects = self.jira.projects() - self.assertGreaterEqual(len(projects), 2) - - def test_project(self): - project = self.jira.project(self.project_b) - self.assertEqual(project.key, self.project_b) - - # I have no idea what avatars['custom'] is and I get different results every time - # def test_project_avatars(self): - # avatars = self.jira.project_avatars(self.project_b) - # self.assertEqual(len(avatars['custom']), 3) - # self.assertEqual(len(avatars['system']), 16) - # - # def test_project_avatars_with_project_obj(self): - # project = self.jira.project(self.project_b) - # avatars = self.jira.project_avatars(project) - # self.assertEqual(len(avatars['custom']), 3) - # self.assertEqual(len(avatars['system']), 16) - - # def test_create_project_avatar(self): - # Tests the end-to-end project avatar creation process: upload as temporary, confirm after cropping, - # and selection. - # project = self.jira.project(self.project_b) - # size = os.path.getsize(TEST_ICON_PATH) - # filename = os.path.basename(TEST_ICON_PATH) - # with open(TEST_ICON_PATH, "rb") as icon: - # props = self.jira.create_temp_project_avatar(project, filename, size, icon.read()) - # self.assertIn('cropperOffsetX', props) - # self.assertIn('cropperOffsetY', props) - # self.assertIn('cropperWidth', props) - # self.assertTrue(props['needsCropping']) - # - # props['needsCropping'] = False - # avatar_props = self.jira.confirm_project_avatar(project, props) - # self.assertIn('id', avatar_props) - # - # self.jira.set_project_avatar(self.project_b, avatar_props['id']) - # - # def test_delete_project_avatar(self): - # size = os.path.getsize(TEST_ICON_PATH) - # filename = os.path.basename(TEST_ICON_PATH) - # with open(TEST_ICON_PATH, "rb") as icon: - # props = self.jira.create_temp_project_avatar(self.project_b, filename, size, icon.read(), auto_confirm=True) - # self.jira.delete_project_avatar(self.project_b, props['id']) - # - # def test_delete_project_avatar_with_project_obj(self): - # project = self.jira.project(self.project_b) - # size = os.path.getsize(TEST_ICON_PATH) - # filename = os.path.basename(TEST_ICON_PATH) - # with open(TEST_ICON_PATH, "rb") as icon: - # props = self.jira.create_temp_project_avatar(project, filename, size, icon.read(), auto_confirm=True) - # self.jira.delete_project_avatar(project, props['id']) - - # @pytest.mark.xfail(reason="Jira may return 500") - # def test_set_project_avatar(self): - # def find_selected_avatar(avatars): - # for avatar in avatars['system']: - # if avatar['isSelected']: - # return avatar - # else: - # raise Exception - # - # self.jira.set_project_avatar(self.project_b, '10001') - # avatars = self.jira.project_avatars(self.project_b) - # self.assertEqual(find_selected_avatar(avatars)['id'], '10001') - # - # project = self.jira.project(self.project_b) - # self.jira.set_project_avatar(project, '10208') - # avatars = self.jira.project_avatars(project) - # self.assertEqual(find_selected_avatar(avatars)['id'], '10208') - - def test_project_components(self): - proj = self.jira.project(self.project_b) - name = "component-%s from project %s" % (proj, rndstr()) - component = self.jira.create_component( - name, - proj, - description="test!!", - assigneeType="COMPONENT_LEAD", - isAssigneeTypeValid=False, - ) - components = self.jira.project_components(self.project_b) - self.assertGreaterEqual(len(components), 1) - sample = find_by_id(components, component.id) - self.assertEqual(sample.id, component.id) - self.assertEqual(sample.name, name) - component.delete() - - def test_project_versions(self): - name = "version-%s" % rndstr() - version = self.jira.create_version(name, self.project_b, "will be deleted soon") - versions = self.jira.project_versions(self.project_b) - self.assertGreaterEqual(len(versions), 1) - test = find_by_id(versions, version.id) - self.assertEqual(test.id, version.id) - self.assertEqual(test.name, name) - - i = self.jira.issue(JiraTestManager().project_b_issue1) - i.update( - fields={ - "versions": [{"id": version.id}], - "fixVersions": [{"id": version.id}], - } - ) - version.delete() - - def test_get_project_version_by_name(self): - name = "version-%s" % rndstr() - version = self.jira.create_version(name, self.project_b, "will be deleted soon") - - found_version = self.jira.get_project_version_by_name(self.project_b, name) - self.assertEqual(found_version.id, version.id) - self.assertEqual(found_version.name, name) - - not_found_version = self.jira.get_project_version_by_name( - self.project_b, "non-existent" - ) - self.assertEqual(not_found_version, None) - - i = self.jira.issue(JiraTestManager().project_b_issue1) - i.update( - fields={ - "versions": [{"id": version.id}], - "fixVersions": [{"id": version.id}], - } - ) - version.delete() - - def test_rename_version(self): - old_name = "version-%s" % rndstr() - version = self.jira.create_version( - old_name, self.project_b, "will be deleted soon" - ) - - new_name = old_name + "-renamed" - self.jira.rename_version(self.project_b, old_name, new_name) - - found_version = self.jira.get_project_version_by_name(self.project_b, new_name) - self.assertEqual(found_version.id, version.id) - self.assertEqual(found_version.name, new_name) - - not_found_version = self.jira.get_project_version_by_name( - self.project_b, old_name - ) - self.assertEqual(not_found_version, None) - - i = self.jira.issue(JiraTestManager().project_b_issue1) - i.update( - fields={ - "versions": [{"id": version.id}], - "fixVersions": [{"id": version.id}], - } + perms = self.jira.my_permissions( + issueId=self.test_manager.project_b_issue1_obj.id ) - version.delete() - - def test_project_versions_with_project_obj(self): - name = "version-%s" % rndstr() - version = self.jira.create_version(name, self.project_b, "will be deleted soon") - project = self.jira.project(self.project_b) - versions = self.jira.project_versions(project) - self.assertGreaterEqual(len(versions), 1) - test = find_by_id(versions, version.id) - self.assertEqual(test.id, version.id) - self.assertEqual(test.name, name) - version.delete() - - @unittest.skip( - "temporary disabled because roles() return a dictionary of role_name:role_url and we have no call to convert it to proper Role()" - ) - def test_project_roles(self): - project = self.jira.project(self.project_b) - role_name = "Developers" - dev = None - for roles in [ - self.jira.project_roles(self.project_b), - self.jira.project_roles(project), - ]: - self.assertGreaterEqual(len(roles), 5) - self.assertIn("Users", roles) - self.assertIn(role_name, roles) - dev = roles[role_name] - self.assertTrue(dev) - role = self.jira.project_role(self.project_b, dev.id) - self.assertEqual(role.id, dev.id) - self.assertEqual(role.name, dev.name) - user = self.test_manager.jira_admin - self.assertNotIn(user, role.actors) - role.update(users=user, groups=["jira-developers", "jira-users"]) - role = self.jira.project_role(self.project_b, dev.id) - self.assertIn(user, role.actors) - - -@not_on_custom_jira_instance -@flaky -class ResolutionTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - - def test_resolutions(self): - resolutions = self.jira.resolutions() - self.assertGreaterEqual(len(resolutions), 1) - - def test_resolution(self): - resolution = self.jira.resolution("2") - self.assertEqual(resolution.id, "2") - self.assertEqual(resolution.name, "Won't Fix") + self.assertGreaterEqual(len(perms["permissions"]), 10) -@flaky -class SearchTests(unittest.TestCase): +class SearchTests(JiraTestCase): def setUp(self): - self.jira = JiraTestManager().jira_admin - self.project_b = JiraTestManager().project_b - self.test_manager = JiraTestManager() + JiraTestCase.setUp(self) self.issue = self.test_manager.project_b_issue1 def test_search_issues(self): issues = self.jira.search_issues("project=%s" % self.project_b) + issues = cast(ResultList[Issue], issues) self.assertLessEqual(len(issues), 50) # default maxResults for issue in issues: self.assertTrue(issue.key.startswith(self.project_b)) @@ -1729,6 +196,7 @@ def test_search_issues_async(self): issues = self.jira.search_issues( "project=%s" % self.project_b, maxResults=False ) + issues = cast(ResultList[Issue], issues) self.assertEqual(len(issues), issues.total) for issue in issues: self.assertTrue(issue.key.startswith(self.project_b)) @@ -1750,6 +218,7 @@ def test_search_issues_field_limiting(self): issues = self.jira.search_issues( "key=%s" % self.issue, fields="summary,comment" ) + issues = cast(ResultList[Issue], issues) self.assertTrue(hasattr(issues[0].fields, "summary")) self.assertTrue(hasattr(issues[0].fields, "comment")) self.assertFalse(hasattr(issues[0].fields, "reporter")) @@ -1757,6 +226,7 @@ def test_search_issues_field_limiting(self): def test_search_issues_expand(self): issues = self.jira.search_issues("key=%s" % self.issue, expand="changelog") + issues = cast(ResultList[Issue], issues) # self.assertTrue(hasattr(issues[0], 'names')) self.assertEqual(len(issues), 1) self.assertFalse(hasattr(issues[0], "editmeta")) @@ -1764,329 +234,17 @@ def test_search_issues_expand(self): self.assertEqual(issues[0].key, self.issue) -@unittest.skip("Skipped due to https://jira.atlassian.com/browse/JRA-59619") -@flaky -class SecurityLevelTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - - def test_security_level(self): - # This is hardcoded due to Atlassian bug: https://jira.atlassian.com/browse/JRA-59619 - sec_level = self.jira.security_level("10000") - self.assertEqual(sec_level.id, "10000") - - -@flaky -class ServerInfoTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - +class ServerInfoTests(JiraTestCase): def test_server_info(self): server_info = self.jira.server_info() self.assertIn("baseUrl", server_info) self.assertIn("version", server_info) -@flaky -class StatusTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - - def test_statuses(self): - found = False - statuses = self.jira.statuses() - for status in statuses: - if status.name == "Done": - found = True - # find status - s = self.jira.status(status.id) - self.assertEqual(s.id, status.id) - break - self.assertTrue(found, "Status Done not found. [%s]" % statuses) - self.assertGreater(len(statuses), 0) - - -@flaky -class StatusCategoryTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - - def test_statuscategories(self): - found = False - statuscategories = self.jira.statuscategories() - for statuscategory in statuscategories: - if statuscategory.id == 1 and statuscategory.name == u"No Category": - found = True - break - self.assertTrue( - found, "StatusCategory with id=1 not found. [%s]" % statuscategories - ) - self.assertGreater(len(statuscategories), 0) - - @flaky - def test_statuscategory(self): - statuscategory = self.jira.statuscategory(1) - self.assertEqual(statuscategory.id, 1) - self.assertEqual(statuscategory.name, "No Category") - - -@flaky -class UserTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - self.project_a = JiraTestManager().project_a - self.project_b = JiraTestManager().project_b - self.test_manager = JiraTestManager() - self.issue = self.test_manager.project_b_issue3 - - def test_user(self): - user = self.jira.user(self.test_manager.user_admin.name) - self.assertTrue(user.name) - self.assertRegex( - user.emailAddress, r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" - ) - - @pytest.mark.xfail(reason="query returns empty list") - def test_search_assignable_users_for_projects(self): - users = self.jira.search_assignable_users_for_projects( - self.test_manager.CI_JIRA_ADMIN, "%s,%s" % (self.project_a, self.project_b) - ) - self.assertGreaterEqual(len(users), 1) - usernames = map(lambda user: user.name, users) - self.assertIn(self.test_manager.CI_JIRA_ADMIN, usernames) - - @pytest.mark.xfail(reason="query returns empty list") - def test_search_assignable_users_for_projects_maxresults(self): - users = self.jira.search_assignable_users_for_projects( - self.test_manager.CI_JIRA_ADMIN, - "%s,%s" % (self.project_a, self.project_b), - maxResults=1, - ) - self.assertLessEqual(len(users), 1) - - @pytest.mark.xfail(reason="query returns empty list") - def test_search_assignable_users_for_projects_startat(self): - users = self.jira.search_assignable_users_for_projects( - self.test_manager.CI_JIRA_ADMIN, - "%s,%s" % (self.project_a, self.project_b), - startAt=1, - ) - self.assertGreaterEqual(len(users), 0) - - @not_on_custom_jira_instance - def test_search_assignable_users_for_issues_by_project(self): - users = self.jira.search_assignable_users_for_issues( - self.test_manager.CI_JIRA_ADMIN, project=self.project_b - ) - self.assertEqual(len(users), 1) - usernames = map(lambda user: user.name, users) - self.assertIn(self.test_manager.CI_JIRA_ADMIN, usernames) - - @pytest.mark.xfail(reason="query returns empty list") - def test_search_assignable_users_for_issues_by_project_maxresults(self): - users = self.jira.search_assignable_users_for_issues( - self.test_manager.CI_JIRA_USER, project=self.project_b, maxResults=1 - ) - self.assertLessEqual(len(users), 1) - - @pytest.mark.xfail(reason="query returns empty list") - def test_search_assignable_users_for_issues_by_project_startat(self): - users = self.jira.search_assignable_users_for_issues( - self.test_manager.CI_JIRA_USER, project=self.project_a, startAt=1 - ) - self.assertGreaterEqual(len(users), 0) - - @not_on_custom_jira_instance - def test_search_assignable_users_for_issues_by_issue(self): - users = self.jira.search_assignable_users_for_issues( - self.test_manager.CI_JIRA_ADMIN, issueKey=self.issue - ) - self.assertEqual(len(users), 1) - usernames = map(lambda user: user.name, users) - self.assertIn(self.test_manager.CI_JIRA_ADMIN, usernames) - - @pytest.mark.xfail(reason="query returns empty list") - def test_search_assignable_users_for_issues_by_issue_maxresults(self): - users = self.jira.search_assignable_users_for_issues( - self.test_manager.CI_JIRA_ADMIN, issueKey=self.issue, maxResults=2 - ) - self.assertLessEqual(len(users), 2) - - @pytest.mark.xfail(reason="query returns empty list") - def test_search_assignable_users_for_issues_by_issue_startat(self): - users = self.jira.search_assignable_users_for_issues( - self.test_manager.CI_JIRA_ADMIN, issueKey=self.issue, startAt=2 - ) - self.assertGreaterEqual(len(users), 0) - - @pytest.mark.xfail(reason="Jira may return 500") - def test_user_avatars(self): - # Tests the end-to-end user avatar creation process: upload as temporary, confirm after cropping, - # and selection. - size = os.path.getsize(TEST_ICON_PATH) - # filename = os.path.basename(TEST_ICON_PATH) - with open(TEST_ICON_PATH, "rb") as icon: - props = self.jira.create_temp_user_avatar( - JiraTestManager().CI_JIRA_ADMIN, TEST_ICON_PATH, size, icon.read() - ) - self.assertIn("cropperOffsetX", props) - self.assertIn("cropperOffsetY", props) - self.assertIn("cropperWidth", props) - self.assertTrue(props["needsCropping"]) - - props["needsCropping"] = False - avatar_props = self.jira.confirm_user_avatar( - JiraTestManager().CI_JIRA_ADMIN, props - ) - self.assertIn("id", avatar_props) - self.assertEqual(avatar_props["owner"], JiraTestManager().CI_JIRA_ADMIN) - - self.jira.set_user_avatar(JiraTestManager().CI_JIRA_ADMIN, avatar_props["id"]) - - avatars = self.jira.user_avatars(self.test_manager.CI_JIRA_ADMIN) - self.assertGreaterEqual( - len(avatars["system"]), 20 - ) # observed values between 20-24 so far - self.assertGreaterEqual(len(avatars["custom"]), 1) - - @unittest.skip("broken: set avatar returns 400") - def test_set_user_avatar(self): - def find_selected_avatar(avatars): - for avatar in avatars["system"]: - if avatar["isSelected"]: - return avatar - # else: - # raise Exception as e - # print(e) - - avatars = self.jira.user_avatars(self.test_manager.CI_JIRA_ADMIN) - - self.jira.set_user_avatar(self.test_manager.CI_JIRA_ADMIN, avatars["system"][0]) - avatars = self.jira.user_avatars(self.test_manager.CI_JIRA_ADMIN) - self.assertEqual(find_selected_avatar(avatars)["id"], avatars["system"][0]) - - self.jira.set_user_avatar(self.test_manager.CI_JIRA_ADMIN, avatars["system"][1]) - avatars = self.jira.user_avatars(self.test_manager.CI_JIRA_ADMIN) - self.assertEqual(find_selected_avatar(avatars)["id"], avatars["system"][1]) - - @unittest.skip("disable until I have permissions to write/modify") - # WRONG - def test_delete_user_avatar(self): - size = os.path.getsize(TEST_ICON_PATH) - filename = os.path.basename(TEST_ICON_PATH) - with open(TEST_ICON_PATH, "rb") as icon: - props = self.jira.create_temp_user_avatar( - self.test_manager.CI_JIRA_ADMIN, filename, size, icon.read() - ) - self.jira.delete_user_avatar(self.test_manager.CI_JIRA_ADMIN, props["id"]) - - def test_search_users(self): - users = self.jira.search_users(self.test_manager.CI_JIRA_ADMIN) - self.assertGreaterEqual(len(users), 1) - usernames = map(lambda user: user.name, users) - self.assertIn(self.test_manager.user_admin.name, usernames) - - def test_search_users_maxresults(self): - users = self.jira.search_users(self.test_manager.CI_JIRA_USER, maxResults=1) - self.assertGreaterEqual(1, len(users)) - - @flaky - def test_search_allowed_users_for_issue_by_project(self): - users = self.jira.search_allowed_users_for_issue( - self.test_manager.CI_JIRA_USER, projectKey=self.project_a - ) - self.assertGreaterEqual(len(users), 1) - - @not_on_custom_jira_instance - def test_search_allowed_users_for_issue_by_issue(self): - users = self.jira.search_allowed_users_for_issue("a", issueKey=self.issue) - self.assertGreaterEqual(len(users), 1) - - @pytest.mark.xfail(reason="query returns empty list") - def test_search_allowed_users_for_issue_maxresults(self): - users = self.jira.search_allowed_users_for_issue( - "a", projectKey=self.project_b, maxResults=2 - ) - self.assertLessEqual(len(users), 2) - - @pytest.mark.xfail(reason="query returns empty list") - def test_search_allowed_users_for_issue_startat(self): - users = self.jira.search_allowed_users_for_issue( - "c", projectKey=self.project_b, startAt=1 - ) - self.assertGreaterEqual(len(users), 0) - - def test_add_users_to_set(self): - users_set = set([self.test_manager.user_admin, self.test_manager.user_admin]) - self.assertEqual(len(users_set), 1) - - -@flaky -class VersionTests(unittest.TestCase): - def setUp(self): - self.manager = JiraTestManager() - self.jira = JiraTestManager().jira_admin - self.project_b = JiraTestManager().project_b - - def test_create_version(self): - name = "new version " + self.project_b - desc = "test version of " + self.project_b - release_date = "2015-03-11" - version = self.jira.create_version( - name, self.project_b, releaseDate=release_date, description=desc - ) - self.assertEqual(version.name, name) - self.assertEqual(version.description, desc) - self.assertEqual(version.releaseDate, release_date) - version.delete() - - @flaky - def test_create_version_with_project_obj(self): - project = self.jira.project(self.project_b) - version = self.jira.create_version( - "new version 2", - project, - releaseDate="2015-03-11", - description="test version!", - ) - self.assertEqual(version.name, "new version 2") - self.assertEqual(version.description, "test version!") - self.assertEqual(version.releaseDate, "2015-03-11") - version.delete() - - @flaky - def test_update_version(self): - - version = self.jira.create_version( - "new updated version 1", - self.project_b, - releaseDate="2015-03-11", - description="new to be updated!", - ) - version.update(name="new updated version name 1", description="new updated!") - self.assertEqual(version.name, "new updated version name 1") - self.assertEqual(version.description, "new updated!") - - v = self.jira.version(version.id) - self.assertEqual(v, version) - self.assertEqual(v.id, version.id) - - version.delete() - - def test_delete_version(self): - version_str = "test_delete_version:" + self.manager.jid - version = self.jira.create_version( - version_str, - self.project_b, - releaseDate="2015-03-11", - description="not long for this world", - ) - version.delete() - self.assertRaises(JIRAError, self.jira.version, version.id) - +class OtherTests(JiraTestCase): + def setUp(self) -> None: + pass # we don't need Jira instance here -@flaky -class OtherTests(unittest.TestCase): def test_session_invalid_login(self): try: JIRA( @@ -2097,6 +255,7 @@ def test_session_invalid_login(self): ) except Exception as e: self.assertIsInstance(e, JIRAError) + e = cast(JIRAError, e) # help mypy # 20161010: jira cloud returns 500 assert e.status_code in (401, 500, 403) str(JIRAError) # to see that this does not raise an exception @@ -2104,11 +263,7 @@ def test_session_invalid_login(self): assert False -@flaky -class SessionTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - +class SessionTests(JiraTestCase): def test_session(self): user = self.jira.session() self.assertIsNotNone(user.raw["self"]) @@ -2131,7 +286,7 @@ def test_session_server_offline(self): self.assertTrue(False, "Instantiation of invalid JIRA instance succeeded.") -class AsyncTests(unittest.TestCase): +class AsyncTests(JiraTestCase): def setUp(self): self.jira = JIRA( "https://jira.atlassian.com", @@ -2142,7 +297,7 @@ def setUp(self): ) def test_fetch_pages(self): - """Tests that the JIRA._fetch_pages method works as expected. """ + """Tests that the JIRA._fetch_pages method works as expected.""" params = {"startAt": 0} total = 26 expected_results = [] @@ -2170,13 +325,13 @@ def test_fetch_pages(self): items = self.jira._fetch_pages(Issue, "issues", "search", 0, False, params) self.assertEqual(len(items), total) self.assertEqual( - set(item.key for item in items), - set(expected_r["key"] for expected_r in expected_results), + {item.key for item in items}, + {expected_r["key"] for expected_r in expected_results}, ) def _create_issue_result_json(issue_id, summary, key, **kwargs): - """Returns a minimal json object for an issue. """ + """Returns a minimal json object for an issue.""" return { "id": "%s" % issue_id, "summary": summary, @@ -2186,7 +341,7 @@ def _create_issue_result_json(issue_id, summary, key, **kwargs): def _create_issue_search_results_json(issues, **kwargs): - """Returns a minimal json object for Jira issue search results. """ + """Returns a minimal json object for Jira issue search results.""" return { "startAt": kwargs.get("start_at", 0), "maxResults": kwargs.get("max_results", 50), @@ -2195,11 +350,7 @@ def _create_issue_search_results_json(issues, **kwargs): } -@flaky -class WebsudoTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - +class WebsudoTests(JiraTestCase): def test_kill_websudo(self): self.jira.kill_websudo() @@ -2207,11 +358,9 @@ def test_kill_websudo(self): # self.assertRaises(ConnectionError, JIRA) -@flaky -class UserAdministrationTests(unittest.TestCase): +class UserAdministrationTests(JiraTestCase): def setUp(self): - self.test_manager = JiraTestManager() - self.jira = self.test_manager.jira_admin + JiraTestCase.setUp(self) self.test_username = "test_%s" % self.test_manager.project_a self.test_email = "%s@example.com" % self.test_username self.test_password = rndpassword() @@ -2225,10 +374,10 @@ def _skip_pycontribs_instance(self): ) def _should_skip_for_pycontribs_instance(self): - return True - # return self.test_manager.CI_JIRA_ADMIN == "ci-admin" and ( - # self.test_manager.CI_JIRA_URL == "https://pycontribs.atlassian.net" - # ) + # return True + return self.test_manager.CI_JIRA_ADMIN == "ci-admin" and ( + self.test_manager.CI_JIRA_URL == "https://pycontribs.atlassian.net" + ) def test_add_and_remove_user(self): if self._should_skip_for_pycontribs_instance(): @@ -2280,7 +429,6 @@ def test_add_and_remove_user(self): result = self.jira.delete_user(self.test_username) assert result, True - @flaky def test_add_group(self): if self._should_skip_for_pycontribs_instance(): self._skip_pycontribs_instance() @@ -2289,9 +437,7 @@ def test_add_group(self): except JIRAError: pass - sleep( - 2 - ) # avoid 500 errors like https://travis-ci.org/pycontribs/jira/jobs/176544578#L552 + sleep(2) # avoid 500 errors result = self.jira.add_group(self.test_groupname) assert result, True @@ -2308,9 +454,7 @@ def test_remove_group(self): self._skip_pycontribs_instance() try: self.jira.add_group(self.test_groupname) - sleep( - 1 - ) # avoid 400: https://travis-ci.org/pycontribs/jira/jobs/176539521#L395 + sleep(1) # avoid 400 except JIRAError: pass @@ -2330,10 +474,6 @@ def test_remove_group(self): "Found group with name when it should have been deleted. Test Fails.", ) - @not_on_custom_jira_instance - @pytest.mark.xfail( - reason="query may return empty list: https://travis-ci.org/pycontribs/jira/jobs/191274505#L520" - ) def test_add_user_to_group(self): try: self.jira.add_user( @@ -2397,60 +537,10 @@ def test_remove_user_from_group(self): self.jira.delete_user(self.test_username) -class JiraShellTests(unittest.TestCase): +class JiraShellTests(JiraTestCase): + def setUp(self) -> None: + pass # Jira Instance not required + def test_jirashell_command_exists(self): result = os.system("jirashell --help") self.assertEqual(result, 0) - - -class JiraServiceDeskTests(unittest.TestCase): - def setUp(self): - self.jira = JiraTestManager().jira_admin - self.test_manager = JiraTestManager() - if not self.jira.supports_service_desk(): - pytest.skip("Skipping Service Desk not enabled") - - try: - self.jira.delete_project(self.test_manager.project_sd) - except Exception: - pass - - @pytest.mark.xfail(reason="Broken needs fixing") - def test_create_customer_request(self): - - self.jira.create_project( - key=self.test_manager.project_sd, - name=self.test_manager.project_sd_name, - ptype="service_desk", - template_name="IT Service Desk", - ) - service_desks = [] - for i in range(3): - service_desks = self.jira.service_desks() - if service_desks: - break - logging.warning("Service desk not reported...") - sleep(2) - self.assertTrue(service_desks, "No service desks were found!") - service_desk = service_desks[0] - - for i in range(3): - request_types = self.jira.request_types(service_desk) - if request_types: - logging.warning("Service desk request_types not reported...") - break - sleep(2) - self.assertTrue(request_types, "No request_types for service desk found!") - - request = self.jira.create_customer_request( - dict( - serviceDeskId=service_desk.id, - requestTypeId=int(request_types[0].id), - requestFieldValues=dict( - summary="Ticket title here", description="Ticket body here" - ), - ) - ) - - self.assertEqual(request.fields.summary, "Ticket title here") - self.assertEqual(request.fields.description, "Ticket body here") diff --git a/tox.ini b/tox.ini index 590b5a146..b49ac1c61 100644 --- a/tox.ini +++ b/tox.ini @@ -1,40 +1,23 @@ [tox] minversion = 3.8.0 requires = + tox-extra tox-pyenv envlist = - lint - pkg + py39 py38 py37 py36 - py35 - docs ignore_basepython_conflict = True skip_missing_interpreters = True skipdist = True -[testenv:docs] -extras = - docs -# changedir=docs -usedevelop = False -skipdist = False -setenv = - PYTHONHTTPSVERIFY=0 -commands = - # pip install "..[docs]" - bash -c "set | grep REQUESTS_CA_BUNDLE" - python -m sphinx \ - -a -n -W \ - -b html --color \ - -d "{toxworkdir}/docs_doctree" \ - docs/ "{toxworkdir}/docs_out" - - # Print out the output docs dir and a way to serve html: - python -c \ - 'import pathlib; '\ - 'docs_dir = pathlib.Path(r"{toxworkdir}") / "docs_out"; index_file = docs_dir / "index.html"; print(f"\nDocumentation available under `file://\{index_file\}`\n\nTo serve docs, use `python3 -m http.server --directory \{docs_dir\} 0`\n")' +[gh-actions] +python = + 3.6: py36 + 3.7: py37 + 3.8: py38 + 3.9: py39 [testenv] @@ -47,14 +30,23 @@ extras = test sitepackages=False commands= - bash -c 'find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf' + git clean -xdf jira tests python -m pip check + python make_local_jira_user.py python -m pytest {posargs} setenv = + PIP_CONSTRAINT={toxinidir}/constraints.txt PIP_LOG={envdir}/pip.log PIP_DISABLE_PIP_VERSION_CHECK=1 # Avoid 2020-01-01 warnings: https://github.com/pypa/pip/issues/6207 PYTHONWARNINGS=ignore:DEPRECATION::pip._internal.cli.base_command + CI_JIRA_URL=http://localhost:2990/jira + CI_JIRA_ADMIN=admin + CI_JIRA_ADMIN_PASSWORD=admin + CI_JIRA_USER=jira_user + CI_JIRA_USER_FULL_NAME=Newly Created CI User + CI_JIRA_USER_PASSWORD=jira + CI_JIRA_ISSUE=Task passenv = CI CI_JIRA_* @@ -62,46 +54,67 @@ passenv = PIP_* REQUESTS_CA_BUNDLE SSL_CERT_FILE - TRAVIS* TWINE_* XDG_CACHE_HOME -envars = - PIP_DISABLE_PIP_VERSION_CHECK=1 - PIP_USER=no + # For Windows users, getpass.get_user() needs USERNAME + USERNAME whitelist_externals = - bash - echo - find - grep - rm - xargs + git + +[testenv:deps] +description = Update dependency lock files +# Force it to use oldest supported version of python or we would lose ability +# to get pinning correctly. +basepython = python3.6 +deps = + pip-tools >= 6.2.0 + pre-commit >= 2.13.0 +commands = + pip-compile --upgrade -o constraints.txt setup.cfg --extra cli --extra docs --extra opt --extra async --extra test + {envpython} -m pre_commit autoupdate + +[testenv:docs] +extras = + docs +# changedir=docs +usedevelop = False +skipdist = False +setenv = + PYTHONHTTPSVERIFY=0 +commands = + sphinx-build \ + -a -n -v -W --keep-going \ + -b html --color \ + -d "{toxworkdir}/docs_doctree" \ + docs/ "{toxworkdir}/docs_out" + + # Print out the output docs dir and a way to serve html: + python -c \ + 'import pathlib; '\ + 'docs_dir = pathlib.Path(r"{toxworkdir}") / "docs_out"; index_file = docs_dir / "index.html"; print(f"\nDocumentation available under `file://\{index_file\}`\n\nTo serve docs, use `python3 -m http.server --directory \{docs_dir\} 0`\n")' [testenv:pkg] deps = - collective.checkdocs>=0.2 - pep517>=0.7.0 - pip>=19.2.3 - setuptools>=41.4 - twine>=2.0.0 - wheel>=0.33.6 + build>=0.3.1.post1 + pip>=21.1.1 + setuptools>=56.2.0 + twine>=3.4.1 + wheel>=0.36.2 commands = - rm -rf {toxinidir}/dist + git clean -xdf dist python setup.py check -m -s # disabled due to errors with older setuptools: # python setup.py sdist bdist_wheel - python -m pep517.build \ - --source \ - --binary \ - --out-dir {toxinidir}/dist/ \ - {toxinidir} - python -m twine check {toxinidir}/dist/* + python -m build --wheel --sdist . + python -m twine check dist/* +usedevelop = false [testenv:lint] deps = pre-commit>=1.17.0 commands= - bash -c "npm install && npm run spell" python -m pre_commit run --color=always {posargs:--all} -extras = +setenv = + PIP_CONSTRAINT= skip_install = true usedevelop = false @@ -110,9 +123,11 @@ usedevelop = false commands= python examples/maintenance.py -[testenv:upload] +[testenv:publish] +description = Publish package envdir = {toxworkdir}/pkg deps = {[testenv:pkg]deps} commands = {[testenv:pkg]commands} twine upload dist/* +usedevelop = false