././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/.github/ISSUE_TEMPLATE.md0000644000000000000000000000114300000000000016124 0ustar0000000000000000##### ISSUE TYPE - Bug Report - Feature Idea - How to... ##### Jenkinsapi VERSION ##### Jenkins VERSION ##### SUMMARY ##### EXPECTED RESULTS ##### ACTUAL RESULTS ##### USEFUL INFORMATION ``` ``` ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/.github/stale.yml0000644000000000000000000000400400000000000015251 0ustar0000000000000000# Configuration for probot-stale - https://github.com/probot/stale # Number of days of inactivity before an Issue or Pull Request becomes stale daysUntilStale: 60 # Number of days of inactivity before an Issue or Pull Request with the stale label is closed. # Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale. daysUntilClose: 7 # Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled) onlyLabels: [] # Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable exemptLabels: - pinned - security - "[Status] Maybe Later" - "feature request" - "help wanted" - "improvement request" # Set to true to ignore issues in a project (defaults to false) exemptProjects: false # Set to true to ignore issues in a milestone (defaults to false) exemptMilestones: false # Set to true to ignore issues with an assignee (defaults to false) exemptAssignees: false # Label to use when marking as stale staleLabel: stale # Comment to post when marking as stale. Set to `false` to disable markComment: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when removing the stale label. # unmarkComment: > # Your comment here. # Comment to post when closing a stale Issue or Pull Request. closeComment: > Closed due to inactivity # Limit the number of actions per hour, from 1-30. Default is 30 limitPerRun: 30 # Limit to only `issues` or `pulls` # only: issues # Optionally, specify configuration settings that are specific to just 'issues' or 'pulls': # pulls: # daysUntilStale: 30 # markComment: > # This pull request has been automatically marked as stale because it has not had # recent activity. It will be closed if no further activity occurs. Thank you # for your contributions. # issues: # exemptLabels: # - confirmed ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/.github/workflows/python-package.yml0000644000000000000000000000366700000000000021126 0ustar0000000000000000# This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python name: CI_TEST on: push: pull_request: branches: [ "master" ] jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.8", "3.9", "3.10"] token: ["stable", "latest"] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 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@v3 with: path: ${{ steps.pip-cache.outputs.dir }} key: >- ${{ matrix.python-version }}-pip-${{ hashFiles('setup.cfg') }}-${{ hashFiles('setup.py') }}-${{ hashFiles('tox.ini') }}-${{ hashFiles('.pre-commit-config.yaml') }} restore-keys: | ${{ matrix.python-version }}-pip- ${{ matrix.python-version }}- - 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 -r test-requirements.txt python -m pip install -r requirements.txt - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics flake8 . --count --exit-zero --max-complexity=10 --max-line-length=79 --statistics - name: Test with pytest env: JENKINS_VERSION: ${{ matrix.token }} run: | pytest -sv --cov=jenkinsapi --cov-report=term-missing --cov-report=xml jenkinsapi_tests ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674710100.5420542 jenkinsapi-0.3.13/.gitignore0000644000000000000000000000050000000000000014043 0ustar0000000000000000.svn .project .pydevproject *.pyc *.egg-info /build /dist .settings *.DS_Store localinstance_files/ .coverage/ .coverage nosetests.xml coverage*/ .idea/ include/ lib/ *.egg .tox/* *.sw? /jenkinsapi_tests/systests/coverage.xml /.cache /AUTHORS /ChangeLog .pytest_cache .eggs coverage.xml .venv/ .vscode/ *.war venv/ tags ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/.pre-commit-config.yaml0000644000000000000000000000171100000000000016341 0ustar0000000000000000--- repos: - repo: https://github.com/psf/black rev: 22.10.0 hooks: - id: black args: - --line-length=79 # these folders wont be formatted by black - --exclude="""\.git | \.__pycache__| \.hg| \.mypy_cache| \.tox| \.venv| _build| buck-out| build| dist""" language_version: python3 - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: end-of-file-fixer - id: trailing-whitespace - id: mixed-line-ending - id: check-byte-order-marker - id: check-executables-have-shebangs - id: check-merge-conflict - id: check-symlinks - id: check-vcs-permalinks - id: debug-statements - id: check-yaml files: .*\.(yaml|yml)$ - repo: https://github.com/PyCQA/flake8 rev: 5.0.4 hooks: - id: flake8 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/.travis.yml.todelete0000644000000000000000000000133000000000000015772 0ustar0000000000000000dist: xenial group: edge sudo: required language: python jdk: - oraclejdk8 python: - '2.7' - '3.5' - '3.6' - '3.7' env: - JENKINS_VERSION=stable - JENKINS_VERSION=latest install: - pip install tox-travis - python setup.py -q sdist bdist_wheel script: - tox jobs: include: - stage: test script: tox - stage: release script: skip deploy: user: lechat password: secure: Dn0M+smML+SzgHSVz8w05mkwkg1Eojp7WKvq8NiWSmqH7BlvTNjBszaYCEqIAdXY5vO9p9yx9mupoeLxXJLJlLer61OwHErrXKzUofLfgMJT/mF9WlUfJZgonJcyl5By/MU9vXIlFMAZNae393GJYhj4zQx8xoZXk8HWMMqNXLA= on: repo: pycontribs/jenkinsapi tags: true provider: pypi distributions: sdist bdist_wheel skip_cleanup: true ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/Makefile0000644000000000000000000000041700000000000013522 0ustar0000000000000000.PHONY: test lint tox coverage dist test: py.test -sv jenkinsapi_tests lint: pycodestyle pylint jenkinsapi/*.py tox: tox dist: python setup.py sdist bdist_wheel coverage: py.test -sv --cov=jenkinsapi --cov-report=term-missing --cov-report=xml jenkinsapi_tests ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/README.rst0000644000000000000000000001521300000000000013551 0ustar0000000000000000jenkinsapi ========== .. image:: https://badge.fury.io/py/jenkinsapi.png :target: http://badge.fury.io/py/jenkinsapi .. image:: https://travis-ci.com/pycontribs/jenkinsapi.png?branch=master :target: https://travis-ci.com/pycontribs/jenkinsapi .. image:: https://codecov.io/gh/pycontribs/jenkinsapi/branch/master/graph/badge.svg :target: https://codecov.io/gh/pycontribs/jenkinsapi .. image:: https://requires.io/github/pycontribs/jenkinsapi/requirements.png?branch=master :target: https://requires.io/github/pycontribs/jenkinsapi/requirements/?branch=master :alt: Requirements Status About this library ------------------- Jenkins is the market leading continuous integration system, originally created by Kohsuke Kawaguchi. Jenkins (and It's predecessor Hudson) are useful projects for automating common development tasks (e.g. unit-testing, production batches) - but they are somewhat Java-centric. Thankfully the designers have provided an excellent and complete REST interface. This library wraps up that interface as more conventional python objects in order to make many Jenkins oriented tasks easier to automate. This library allows you to automate most common Jenkins operations using Python, such as: * Ability to add/remove/query Jenkins jobs * Ability to execute jobs and: * Query the results of a completed build * Block until jobs are complete or run jobs asyncronously * Get objects representing the latest builds of a job * Work with build artifacts: * Search for artifacts by simple criteria * Install artifacts to custom-specified directory structures * Ability to search for builds by source code revision * Ability to add/remove/query: * Slaves (Webstart and SSH slaves) * Views (including nested views using NestedViews Jenkins plugin) * Credentials (username/password and ssh key) * Username/password auth support for jenkins instances with auth turned on * Ability to script jenkins installation including plugins For a full documentation spec of what this library supports see: http://jenkinsapi.readthedocs.io/en/latest/index.html Python versions --------------- The project has been tested against Python versions: * 2.7 * 3.4 * 3.5 * 3.6 * 3.7 Jenkins versions ---------------- Project tested on both stable (LTS) and latest Jenkins versions. Known issues ------------ * Job deletion operations fail unless Cross-Site scripting protection is disabled. For other issues, please refer to the support URL below. Important Links --------------- Support and bug-reports: https://github.com/pycontribs/jenkinsapi/issues?direction=desc&sort=comments&state=open Project source code: github: https://github.com/pycontribs/jenkinsapi Project documentation: https://jenkinsapi.readthedocs.org/en/latest/ Releases: http://pypi.python.org/pypi/jenkinsapi Installation ------------- Egg-files for this project are hosted on PyPi. Most Python users should be able to use pip or setuptools to automatically install this project. Using Pip or Setuptools ^^^^^^^^^^^^^^^^^^^^^^^ Most users can do the following: .. code-block:: bash pip install jenkinsapi Or: .. code-block:: bash easy_install jenkinsapi Both of these techniques can be combined with virtualenv to create an application-specific installation. Using your operating-system's package manager ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ubuntu users can now use apt to install this package: .. code-block:: bash apt-get install python-jenkinsapi Beware that this technique will get a somewhat older version of Jenkinsapi. Example ------- JenkinsAPI is intended to map the objects in Jenkins (e.g. Builds, Views, Jobs) into easily managed Python objects: .. code-block:: python >>> import jenkinsapi >>> from jenkinsapi.jenkins import Jenkins >>> J = Jenkins('http://localhost:8080') >>> J.version 1.542 >>> J.keys() # Jenkins objects appear to be dict-like, mapping keys (job-names) to ['foo', 'test_jenkinsapi'] >>> J['test_jenkinsapi'] >>> J['test_jenkinsapi'].get_last_good_build() ... More examples available on Github: https://github.com/pycontribs/jenkinsapi/tree/master/examples Testing ------- If you have installed the test dependencies on your system already, you can run the testsuite with the following command: .. code-block:: bash python setup.py test Otherwise using a virtualenv is recommended. Setuptools will automatically fetch missing test dependencies: .. code-block:: bash virtualenv source .venv/bin/active (venv) python setup.py test Development ----------- * Make sure that you have Java_ installed. * Create virtual environment for development * Install package in development mode .. code-block:: bash (venv) pip install -e . (venv) pip install -r test-requirements.txt * Make your changes, write tests and check your code .. code-block:: bash (venv) tox Project Contributors -------------------- * Aleksey Maksimov (ctpeko3a@gmail.com) * Salim Fadhley (sal@stodge.org) * Ramon van Alteren (ramon@vanalteren.nl) * Ruslan Lutsenko (ruslan.lutcenko@gmail.com) * Cleber J Santos (cleber@simplesconsultoria.com.br) * William Zhang (jollychang@douban.com) * Victor Garcia (bravejolie@gmail.com) * Bradley Harris (bradley@ninelb.com) * Kyle Rockman (kyle.rockman@mac.com) * Sascha Peilicke (saschpe@gmx.de) * David Johansen (david@makewhat.is) * Misha Behersky (bmwant@gmail.com) Please do not contact these contributors directly for support questions! Use the GitHub tracker instead. License -------- The MIT License (MIT): Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. .. _Java: http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/TODO0000644000000000000000000000025000000000000012545 0ustar0000000000000000TODO: * Clean up the fingerprint code * Clean up the resultset and results code * Add support for Jenkins 2.x features * Improve speed for large Jenkins installations ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/bin/pipelint0000755000000000000000000000153700000000000014410 0ustar0000000000000000#!/bin/bash set -eo pipefail INPUT=/dev/stdin if [ -t 0 ]; then if [ "$#" -ne 1 ]; then echo "ERROR: Illegal number of parameters." echo "INFO: Use 'pipefail Jenkinsfile' or 'cat Jenkinsfile | pipefail'" exit 1 fi INPUT=$1 fi # put credentials inside ~/.netrc # define JENKINS_URL in your user profile JENKINS_URL=${JENKINS_URL:-http://localhost:8080} # failure to get crumb is ignored as this may be diabled on the server side CRUMB="-H `curl -nfs "$JENKINS_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,%22:%22,//crumb)"`" || CRUMB='' # The tee+grep trick assures that the exit code is 0 only if the server replied with "successfully validated" curl -nfs -X POST $CRUMB -F "jenkinsfile=<-" $JENKINS_URL/pipeline-model-converter/validate <$INPUT \ | tee >(cat 1>&2) | grep 'successfully validated' >/dev/null ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/.gitignore0000644000000000000000000000004300000000000014612 0ustar0000000000000000/ html /docs_html.zip /html /build ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/build.properties0000644000000000000000000000012100000000000016034 0ustar0000000000000000docs.zipfile.filename=docs_html.zip docs.html.dir=html docs.source.dir=source ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/build.xml0000644000000000000000000000234700000000000014454 0ustar0000000000000000 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/.gitignore0000644000000000000000000000012000000000000016106 0ustar0000000000000000/jenkinsapi.utils.rst /jenkinsapi.command_line.rst /jenkinsapi.rst /modules.rst ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/_static/tmp.txt0000644000000000000000000000000000000000000017102 0ustar0000000000000000././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/_templates/tmp.txt0000644000000000000000000000000000000000000017611 0ustar0000000000000000././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/api.rst0000644000000000000000000000010400000000000015423 0ustar0000000000000000User API ======== .. automodule:: jenkinsapi.api :members: ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/artifact.rst0000644000000000000000000000011100000000000016445 0ustar0000000000000000Artifact ======== .. automodule:: jenkinsapi.artifact :members: ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/build.rst0000644000000000000000000000010000000000000015745 0ustar0000000000000000Build ===== .. automodule:: jenkinsapi.build :members: ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/conf.py0000644000000000000000000001772300000000000015436 0ustar0000000000000000# -*- coding: utf-8 -*- # # JenkinsAPI documentation build configuration file, created by # sphinx-quickstart on Mon Jan 09 16:35:17 2012. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import logging import jenkinsapi import pkg_resources dist = pkg_resources.working_set.by_key[jenkinsapi.__name__] VERSION = RELEASE = dist.version if __name__ == "__main__": logging.basicConfig() log = logging.getLogger(__name__) # CHANGE THIS PROJECT_NAME = "JenkinsAPI" PROJECT_AUTHORS = "Salim Fadhley, Ramon van Alteren, Ruslan Lutsenko" PROJECT_EMAILS = ( "salimfadhley@gmail.com, ramon@vanalteren.nl, ruslan.lutcenko@gmail.com" ) PROJECT_URL = "https://github.com/salimfadhley/jenkinsapi" SHORT_DESCRIPTION = "A Python API for accessing resources on a Jenkins \ continuous-integration server." # CHANGE THIS # -- General configuration ----------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.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.doctest", "sphinx.ext.viewcode", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = " JenkinsAPI" copyright = "2012, %s" % PROJECT_AUTHORS # The version info for the project you're documenting, acts as replacement for # built documents. # # The short X.Y version. version = VERSION # The full version, including alpha/beta/rc tags. release = VERSION # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "default" # 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 = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # 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' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "JenkinsAPIdoc" # -- Options for LaTeX output -------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ("index", "JenkinsAPI.tex", "JenkinsAPI Documentation", "xxx", "manual"), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [("index", "jenkinsapi", " JenkinsAPI Documentation", ["xxx"], 1)] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( "index", "JenkinsAPI", "JenkinsAPI Documentation", "xxx", "JenkinsAPI", "One line description of project.", "Miscellaneous", ), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/index.rst0000644000000000000000000001501600000000000015771 0ustar0000000000000000JenkinsAPI ========== Jenkins is the market leading continuous integration system, originally created by Kohsuke Kawaguchi. This API makes Jenkins even easier to use by providing an easy to use conventional Python interface. Jenkins (and It's predecessor Hudson) are fantastic projects - but they are somewhat Java-centric. Thankfully the designers have provided an excellent and complete REST interface. This library wraps up that interface as more conventional Python objects in order to make most Jenkins oriented tasks simpler. This library can help you: * Query the test-results of a completed build * Get a objects representing the latest builds of a job * Search for artifacts by simple criteria * Block until jobs are complete * Install artifacts to custom-specified directory structures * Username/password auth support for jenkins instances with auth turned on * Search for builds by subversion revision * Add, remove and query jenkins slaves Sections ======== .. toctree:: :maxdepth: 2 api artifact build using_jenkinsapi rules_for_contributors Important Links --------------- Support & bug-reports https://github.com/salimfadhley/jenkinsapi/issues?direction=desc&sort=comments&state=open Project source code github: https://github.com/salimfadhley/jenkinsapi Project documentation https://jenkinsapi.readthedocs.org/en/latest/ Releases http://pypi.python.org/pypi/jenkinsapi Installation ------------- Egg-files for this project are hosted on PyPi. Most Python users should be able to use pip or setuptools to automatically install this project. Most users can do the following: .. code-block:: bash pip install jenkinsapi Or.. .. code-block:: bash easy_install jenkinsapi * In Jenkins > 1.518 you will need to disable "Prevent Cross Site Request Forgery exploits". * Remember to set the Jenkins Location in general settings - Jenkins' REST web-interface will not work if this is set incorrectly. Examples -------- JenkinsAPI is intended to map the objects in Jenkins (e.g. Builds, Views, Jobs) into easily managed Python objects:: Python 2.7.4 (default, Apr 19 2013, 18:28:01) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import jenkinsapi >>> from jenkinsapi.jenkins import Jenkins >>> J = Jenkins('http://localhost:8080') >>> J.keys() # Jenkins objects appear to be dict-like, mapping keys (job-names) to ['foo', 'test_jenkinsapi'] >>> J['test_jenkinsapi'] >>> J['test_jenkinsapi'].get_last_good_build() JenkinsAPI lets you query the state of a running Jenkins server. It also allows you to change configuration and automate minor tasks on nodes and jobs. You can use Jenkins to get information about recently completed builds. For example, you can get the revision number of the last successful build in order to trigger some kind of release process.:: from jenkinsapi.jenkins import Jenkins def getSCMInfroFromLatestGoodBuild(url, jobName, username=None, password=None): J = Jenkins(url, username, password) job = J[jobName] lgb = job.get_last_good_build() return lgb.get_revision() if __name__ == '__main__': print getSCMInfroFromLatestGoodBuild('http://localhost:8080', 'fooJob') When used with the Git source-control system line 20 will print out something like '8b4f4e6f6d0af609bb77f95d8fb82ff1ee2bba0d' - which looks suspiciously like a Git revision number. Note: As of Jenkins version 1.426, and above, an API token can be specified instead of your real password, while authenticating the user against the Jenkins instance. Refer to the the Jenkis wiki page [Authenticating scripted clients](https://wiki.jenkins-ci.org/display/JENKINS/Authenticating+scripted+clients) for details about how a user can generate an API token. Once you have obtained an API token you can pass the API token instead of real password while creating an Jenkins server instance using Jenkins API. Tips & Tricks ------------- Getting the installed version of JenkinsAPI ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This package supports PEP-396 by implementing a __version__ attribute. This contains a string in the format x.y.z: >>> import jenkinsapi >>> print(jenkinsapi.__version__) 0.2.23 There is also a command-line tool for use in the shell: .. code-block:: bash $ jenkinsapi_version 0.2.23 Project Authors =============== * Salim Fadhley (sal@stodge.org) * Ramon van Alteren (ramon@vanalteren.nl) * Ruslan Lutsenko (ruslan.lutcenko@gmail.com) Plus many others, please see the README file for a more complete list of contributors and how to contact them. Extending and Improving JenkinsAPI ================================== JenkinsAPI is a pure-Python project and can be improved with almost any programmer's text-editor or IDE. I'd recommend the following project layout which has been shown to work with both SublimeText2 and Eclipse/PyDev * Make sure that pip and virtualenv are installed on your computer. On most Linux systems these can be installed directly by the OS package-manager. * Create a new virtualenv for the project:: virtualenv jenkinsapi * Change to the new directory and check out the project code into the **src** subdirectory:: cd jenkinsapi git clone https://github.com/salimfadhley/jenkinsapi.git src * Activate your jenkinsapi virtual environment:: cd bin source activate * Install the jenkinsapi project in 'developer mode' - this step will automatically download all of the project's dependancies:: cd ../src python setup.py develop * Test the project - this step will automatically download and install the project's test-only dependencies. Having these installed will be helpful during development:: python setup.py test * Set up your IDE/Editor configuration - the **misc** folder contains configuration for Sublime Text 2. I hope in time that other developers will contribute useful configurations for their favorite development tools. Testing ------- The project maintainers welcome any code-contributions. Please consider the following when you contribute code back to the project: * All contributions should come as github pull-requests. Please do not send code-snippets in email or as attachments to issues. * Please take a moment to clearly describe the intended goal of your pull-request. * Please ensure that any new feature is covered by a unit-test Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/rules_for_contributors.rst0000644000000000000000000000263500000000000021502 0ustar0000000000000000Rules for Contributors ====================== The JenkinsAPI project welcomes contributions via GitHub. Please bear in mind the following guidelines when preparing your pull-request. Python compatibility -------------------- The project currently targets Python 2.6 and Python 2.7. Support for Python 3.x will be introduced soon. Please do not add any features which will break our supported Python 2.x versions or make it harder for us to migrate to Python 3.x Test Driven Development ----------------------- Please do not submit pull requests without tests. That's really important. Our project is all about test-driven development. It would be embarrasing if our project failed because of a lack of tests! You might want to follow a typical test driven development cycle: http://en.wikipedia.org/wiki/Test-driven_development Put simply: Write your tests first and only implement features required to make your tests pass. Do not let your implementation get ahead of your tests. Features implemented without tests will be removed. Unmaintained features (which break because of changes in Jenkins) will also be removed. Check the CI status before comitting ------------------------------------ We have a Travis CI account - please verify that your branch works before making a pull request. Any problems? ------------- If you are stuck on something, please post to the issue tracker. Do not contact the developers directly. ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/ssl_certificate_verification0000644000000000000000000000420700000000000021760 0ustar0000000000000000SSL Certificate Verification ============================ There are times, when one would like to skip the SSL certificate verification. For instance, the system administrator has set a different and new SSL certificate to the Jenkins master causing `certificate verify failed` errors: SSLError: [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed Unfortunately, he's not available right now, and you have to finish your tasks using the JenkinsAPI library by the end of today. In these times, skipping the SSL certificate verification can be helpful. ***Note***: It's not recommended to disable SSL verifying on a regular basis. To really fix this, please read [this post](http://stackoverflow.com/questions/30830901/python-requests-throwing-ssl-errors/30831120#30831120) at StackOverflow. Disabling the SSL verify ------------------------ Before JenkinsAPI v??, if one wants to disable the SSL certificate verification, she/he will have to pass a `Requester` instance specifying that. It may look like this: from jenkinsapi.jenkins import Jenkins username = 'jenkins' password = 'changeme' baseurl = 'https://localhost:8443' jenkins = Jenkins(baseurl, username, password, requester=Requester(username, password, ssl_verify=False)) As you can see, the last line is quite long. Not to mention that we pass the `username` and the `password` variables twice. There must be a better way! Disabling the SSL verify in JenkinsAPI v?? ------------------------------------------ All these problems are gone thanks to `ssl_verify` argument. You're not asked to pass a `Requester` instance anymore for just disabling the SSL certificate verification. This is how it looks like: jenkins = Jenkins(baseurl, username, password, ssl_verify=False) Now, the code is more readable than before. Notes ----- If you specify both `ssl_verify` and `requester` arguments, then the `ssl_verify` argument will be ignored. For example: jenkins = jenkinsapi.Jenkins(baseurl, username, password, requester=Requester(username, password, ssl_verify=False), ssl_verify=True) will do SSL certificate verifying. ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/doc/source/using_jenkinsapi.rst0000644000000000000000000000767700000000000020240 0ustar0000000000000000Using Jenkins API ================= JenkinsAPI lets you query the state of a running Jenkins server. It also allows you to change configuration and automate minor tasks on nodes and jobs. Example 1: Get version of Jenkins --------------------------------- :: from jenkinsapi.jenkins import Jenkins def get_server_instance(): jenkins_url = 'http://jenkins_host:8080' server = Jenkins(jenkins_url, username='foouser', password='foopassword') return server if __name__ == '__main__': print get_server_instance().version The above code prints version of Jenkins running on the host *jenkins_host*. From Jenkins vesion 1.426 onward one can specify an API token instead of your real password while authenticating the user against Jenkins instance. Refer to the the Jenkis wiki page `Authenticating scripted clients `_ for details about how a user can generate an API token. Once you have API token you can pass the API token instead of real password while creating an Jenkins server instance using Jenkins API. Example 2: Get details of jobs running on Jenkins server -------------------------------------------------------- :: """Get job details of each job that is running on the Jenkins instance""" def get_job_details(): # Refer Example #1 for definition of function 'get_server_instance' server = get_server_instance() for job_name, job_instance in server.get_jobs(): print 'Job Name:%s' % (job_instance.name) print 'Job Description:%s' % (job_instance.get_description()) print 'Is Job running:%s' % (job_instance.is_running()) print 'Is Job enabled:%s' % (job_instance.is_enabled()) Example 3: Disable/Enable a Jenkins Job --------------------------------------- :: """Disable a Jenkins job""" def disable_job(): # Refer Example #1 for definition of function 'get_server_instance' server = get_server_instance() job_name = 'nightly-build-job' if (server.has_job(job_name)): job_instance = server.get_job(job_name) job_instance.disable() print 'Name:%s,Is Job Enabled ?:%s' % (job_name,job_instance.is_enabled()) Use the call ``job_instance.enable()`` to enable a Jenkins Job. Example 4: Get Plugin details ----------------------------- Below chunk of code gets the details of the plugins currently installed in the Jenkins instance. :: def get_plugin_details(): # Refer Example #1 for definition of function 'get_server_instance' server = get_server_instance() for plugin in server.get_plugins().values(): print "Short Name:%s" % (plugin.shortName) print "Long Name:%s" % (plugin.longName) print "Version:%s" % (plugin.version) print "URL:%s" % (plugin.url) print "Active:%s" % (plugin.active) print "Enabled:%s" % (plugin.enabled) Example 5: Getting version information from a completed build ------------------------------------------------------------- This is a typical use of JenkinsAPI - it was the very first use I had in mind when the project was first built: In a continuous-integration environment you want to be able to programatically detect the version-control information of the last succsessful build in order to trigger some kind of release process.:: from jenkinsapi.jenkins import Jenkins def getSCMInfroFromLatestGoodBuild(url, jobName, username=None, password=None): J = Jenkins(url, username, password) job = J[jobName] lgb = job.get_last_good_build() return lgb.get_revision() if __name__ == '__main__': print getSCMInfroFromLatestGoodBuild('http://localhost:8080', 'fooJob') When used with the Git source-control system line 20 will print out something like '8b4f4e6f6d0af609bb77f95d8fb82ff1ee2bba0d' - which looks suspiciously like a Git revision number. ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/__init__.py0000644000000000000000000000000000000000000015775 0ustar0000000000000000././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/addjob.xml0000644000000000000000000000101600000000000015641 0ustar0000000000000000 false true false false false false ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/add_command.py0000644000000000000000000000220100000000000017770 0ustar0000000000000000""" This example shows how to add new command to "Shell" build step """ from __future__ import print_function import xml.etree.ElementTree as et from jenkinsapi.jenkins import Jenkins J = Jenkins("http://localhost:8080") EMPTY_JOB_CONFIG = """ jkkjjk false true false false false false """ jobname = "foo_job" new_job = J.create_job(jobname, EMPTY_JOB_CONFIG) new_conf = new_job.get_config() root = et.fromstring(new_conf.strip()) builders = root.find("builders") shell = et.SubElement(builders, "hudson.tasks.Shell") command = et.SubElement(shell, "command") command.text = "ls" print(et.tostring(root)) J[jobname].update_config(et.tostring(root)) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/create_a_job.py0000644000000000000000000000110600000000000020142 0ustar0000000000000000""" This example shows how to create job from XML file and how to delete job """ from __future__ import print_function from pkg_resources import resource_string from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") job_name = "foo_job2" xml = resource_string("examples", "addjob.xml") print(xml) job = jenkins.create_job(jobname=job_name, xml=xml) # Get job from Jenkins by job name my_job = jenkins[job_name] print(my_job) # Delete job using method in Jenkins class # # Another way is to use: # # del jenkins[job_name] jenkins.delete_job(job_name) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/create_credentials.py0000644000000000000000000000376500000000000021402 0ustar0000000000000000""" This example shows how to create credentials """ import logging from jenkinsapi.jenkins import Jenkins from jenkinsapi.credential import UsernamePasswordCredential, SSHKeyCredential log_level = getattr(logging, "DEBUG") logging.basicConfig(level=log_level) logger = logging.getLogger() jenkins_url = "http://localhost:8080/" jenkins = Jenkins(jenkins_url) # Get a list of all global credentials creds = jenkins.credentials logging.info(jenkins.credentials.keys()) # Create username and password credential creds_description1 = "My_username_credential" cred_dict = { "description": creds_description1, "userName": "userName", "password": "password", } creds[creds_description1] = UsernamePasswordCredential(cred_dict) # Create ssh key credential that uses private key as a value # In jenkins credential dialog you need to paste credential # In your code it is adviced to read it from file # For simplicity of this example reading key from file is not shown here def get_private_key_from_file(): return "-----BEGIN RSA PRIVATE KEY-----" my_private_key = get_private_key_from_file() creds_description2 = "My_ssh_cred1" cred_dict = { "description": creds_description2, "userName": "userName", "passphrase": "", "private_key": my_private_key, } creds[creds_description2] = SSHKeyCredential(cred_dict) # Create ssh key credential that uses private key from path on Jenkins server my_private_key = "/home/jenkins/.ssh/special_key" creds_description3 = "My_ssh_cred2" cred_dict = { "description": creds_description3, "userName": "userName", "passphrase": "", "private_key": my_private_key, } creds[creds_description3] = SSHKeyCredential(cred_dict) # Remove credentials # We use credential description to find specific credential. This is the only # way to get specific credential from Jenkins via REST API del creds[creds_description1] del creds[creds_description2] del creds[creds_description3] # Remove all credentials for cred_descr in creds.keys(): del creds[cred_descr] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/create_nested_views.py0000644000000000000000000000422000000000000021567 0ustar0000000000000000""" How to create nested views using NestedViews Jenkins plugin This example requires NestedViews plugin to be installed in Jenkins You need to have at least one job in your Jenkins to see views """ from __future__ import print_function import logging from pkg_resources import resource_string from jenkinsapi.views import Views from jenkinsapi.jenkins import Jenkins log_level = getattr(logging, "DEBUG") logging.basicConfig(level=log_level) logger = logging.getLogger() jenkins_url = "http://127.0.0.1:8080/" jenkins = Jenkins(jenkins_url) job_name = "foo_job2" xml = resource_string("examples", "addjob.xml") j = jenkins.create_job(jobname=job_name, xml=xml) # Create ListView in main view logger.info("Attempting to create new nested view") top_view = jenkins.views.create("TopView", Views.NESTED_VIEW) logger.info("top_view is %s", top_view) if top_view is None: logger.error("View was not created") else: logger.info("View has been created") print("top_view.views=", top_view.views.keys()) logger.info("Attempting to create view inside nested view") sub_view = top_view.views.create("SubView") if sub_view is None: logger.info("View was not created") else: logger.error("View has been created") logger.info("Attempting to delete sub_view") del top_view.views["SubView"] if "SubView" in top_view.views: logger.error("SubView was not deleted") else: logger.info("SubView has been deleted") # Another way of creating sub view # This way sub view will have jobs in it logger.info("Attempting to create view with jobs inside nested view") top_view.views["SubView"] = job_name if "SubView" not in top_view.views: logger.error("View was not created") else: logger.info("View has been created") logger.info("Attempting to delete sub_view") del top_view.views["SubView"] if "SubView" in top_view.views: logger.error("SubView was not deleted") else: logger.info("SubView has been deleted") logger.info("Attempting to delete top view") del jenkins.views["TopView"] if "TopView" not in jenkins.views: logger.info("View has been deleted") else: logger.error("View was not deleted") # Delete job that we created jenkins.delete_job(job_name) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/create_slave.py0000644000000000000000000000452700000000000020214 0ustar0000000000000000""" How to create slaves/nodes """ import logging import requests from jenkinsapi.jenkins import Jenkins from jenkinsapi.utils.requester import Requester requests.packages.urllib3.disable_warnings() log_level = getattr(logging, "DEBUG") logging.basicConfig(level=log_level) logger = logging.getLogger() jenkins_url = "http://localhost:8080/" username = "default_user" # In case Jenkins requires authentication password = "default_password" jenkins = Jenkins( jenkins_url, requester=Requester( username, password, baseurl=jenkins_url, ssl_verify=False ), ) # Create JNLP(Java Webstart) slave node_dict = { "num_executors": 1, # Number of executors "node_description": "Test JNLP Node", # Just a user friendly text "remote_fs": "/tmp", # Remote workspace location "labels": "my_new_node", # Space separated labels string "exclusive": True, # Only run jobs assigned to it } new_jnlp_node = jenkins.nodes.create_node("My new webstart node", node_dict) node_dict = { "num_executors": 1, "node_description": "Test SSH Node", "remote_fs": "/tmp", "labels": "new_node", "exclusive": True, "host": "localhost", # Remote hostname "port": 22, # Remote post, usually 22 "credential_description": "localhost cred", # Credential to use # [Mandatory for SSH node!] # (see Credentials example) "jvm_options": "-Xmx2000M", # JVM parameters "java_path": "/bin/java", # Path to java "prefix_start_slave_cmd": "", "suffix_start_slave_cmd": "", "max_num_retries": 0, "retry_wait_time": 0, "retention": "OnDemand", # Change to 'Always' for # immediate slave launch "ondemand_delay": 1, "ondemand_idle_delay": 5, "env": [ # Environment variables {"key": "TEST", "value": "VALUE"}, {"key": "TEST2", "value": "value2"}, ], } new_ssh_node = jenkins.nodes.create_node("My new SSH node", node_dict) # Take this slave offline if new_ssh_node.is_online(): new_ssh_node.toggle_temporarily_offline() # Take this slave back online new_ssh_node.toggle_temporarily_offline() # Get a list of all slave names slave_names = jenkins.nodes.keys() # Get Node object my_node = jenkins.nodes["My new SSH node"] # Take this slave offline my_node.set_offline() # Delete slaves del jenkins.nodes["My new webstart node"] del jenkins.nodes["My new SSH node"] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/create_views.py0000644000000000000000000000456500000000000020241 0ustar0000000000000000""" How to create views """ import logging from pkg_resources import resource_string from jenkinsapi.jenkins import Jenkins logging.basicConfig(level=logging.INFO) logger = logging.getLogger() jenkins_url = "http://localhost:8080/" jenkins = Jenkins(jenkins_url, lazy=True) # Create ListView in main view logger.info("Attempting to create new view") test_view_name = "SimpleListView" # Views object appears as a dictionary of views if test_view_name not in jenkins.views: new_view = jenkins.views.create(test_view_name) if new_view is None: logger.error("View %s was not created", test_view_name) else: logger.info( "View %s has been created: %s", new_view.name, new_view.baseurl ) else: logger.info("View %s already exists", test_view_name) # No error is raised if view already exists logger.info("Attempting to create view that already exists") my_view = jenkins.views.create(test_view_name) logger.info("Create job and assign it to a view") job_name = "foo_job2" xml = resource_string("examples", "addjob.xml") my_job = jenkins.create_job(jobname=job_name, xml=xml) # add_job supports two parameters: job_name and job object # passing job object will remove verification calls to Jenkins my_view.add_job(job_name, my_job) assert len(my_view) == 1 logger.info("Attempting to delete view that already exists") del jenkins.views[test_view_name] if test_view_name in jenkins.views: logger.error("View was not deleted") else: logger.info("View has been deleted") # No error will be raised when attempting to remove non-existing view logger.info("Attempting to delete view that does not exist") del jenkins.views[test_view_name] # Create CategorizedJobsView config = """ .dev. Development .hml. Homologation """ view = jenkins.views.create( "My categorized jobs view", jenkins.views.CATEGORIZED_VIEW, config=config ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/delete_all_the_nodes_except_master.py0000644000000000000000000000065100000000000024616 0ustar0000000000000000""" How to delete slaves/nodes """ from __future__ import print_function import logging from jenkinsapi.jenkins import Jenkins logging.basicConfig() j = Jenkins("http://localhost:8080") for node_id, _ in j.get_nodes().iteritems(): if node_id != "master": print(node_id) j.delete_node(node_id) # Alternative way - this method will not delete 'master' for node in j.nodes.keys(): del j.nodes[node] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/get_config.py0000644000000000000000000000045700000000000017661 0ustar0000000000000000""" An example of how to use JenkinsAPI to fetch the config XML of a job. """ from __future__ import print_function from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") jobName = jenkins.keys()[0] # get the first job config = jenkins[jobName].get_config() print(config) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/get_plugin_information.py0000644000000000000000000000042000000000000022305 0ustar0000000000000000""" Get information about currently installed plugins """ from __future__ import print_function from jenkinsapi.jenkins import Jenkins plugin_name = "subversion" jenkins = Jenkins("http://localhost:8080") plugin = jenkins.get_plugins()[plugin_name] print(repr(plugin)) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/get_version_info_from_last_good_build.py0000644000000000000000000000043000000000000025340 0ustar0000000000000000""" Extract version information from the latest build. """ from __future__ import print_function from jenkinsapi.jenkins import Jenkins job_name = "foo" jenkins = Jenkins("http://localhost:8080") job = jenkins[job_name] lgb = job.get_last_good_build() print(lgb.get_revision()) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/query_a_build.py0000644000000000000000000000053200000000000020373 0ustar0000000000000000""" How to get build from job and query that build """ from __future__ import print_function from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") # Print all jobs in Jenkins print(jenkins.items()) job = jenkins.get_job("foo") build = job.get_last_build() print(build) mjn = build.get_master_job_name() print(mjn) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/readme.rst0000644000000000000000000000277400000000000017176 0ustar0000000000000000"How To..." examples ==================== This directory contains a set of examples or recipes for common tasks in JenkinsAPI. ====================== ================================================== Example Description ---------------------- -------------------------------------------------- add_command.py create new job and then add shell build step to it create_a_job.py create new job create_credentials.py create new credential create_nested_views.py create nested views using Nested Views Jenkins plugin create_slave.py create jnlp ans ssh slave create_views.py create views, assign and delete jobs in views delete_all_the_nodes.py delete all slaves except master get_config.py get job configuration XML get_plugin_infomation.py show information about plugin get_version_info_from_last_good_build.py get Git revision from last successful build query_a_build.py get build information search_artifact_by_regexp.py search for job artifacts using regular expression search_artifacts.py search for artifacts start_parameterized_build.py start a build with parameters use_crumbs.py how to work with CSRF protection enabled in Jenkins ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/search_artifact_by_regexp.py0000644000000000000000000000054700000000000022743 0ustar0000000000000000""" Search for job artifacts using regexp """ from __future__ import print_function import re from jenkinsapi.api import search_artifact_by_regexp jenkinsurl = "http://localhost:8080" jobid = "foo" artifact_regexp = re.compile(r"test1\.txt") # A file name I want. result = search_artifact_by_regexp(jenkinsurl, jobid, artifact_regexp) print((repr(result))) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/search_artifacts.py0000644000000000000000000000051600000000000021056 0ustar0000000000000000""" Search for job artifacts """ from __future__ import print_function from jenkinsapi.api import search_artifacts jenkinsurl = "http://localhost:8080" jobid = "foo" # I need a build that contains all of these artifact_ids = ["test1.txt", "test2.txt"] result = search_artifacts(jenkinsurl, jobid, artifact_ids) print((repr(result))) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/start_parameterized_build.py0000644000000000000000000000113500000000000022777 0ustar0000000000000000""" Start a Parameterized Build """ from __future__ import print_function from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") params = {"VERSION": "1.2.3", "PYTHON_VER": "2.7"} # This will start the job in non-blocking manner jenkins.build_job("foo", params) # This will start the job and will return a QueueItem object which # can be used to get build results job = jenkins["foo"] qi = job.invoke(build_params=params) # Block this script until build is finished if qi.is_queued() or qi.is_running(): qi.block_until_complete() build = qi.get_build() print(build) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/how_to/use_crumbs.py0000644000000000000000000000044500000000000017721 0ustar0000000000000000""" Example of using CrumbRequester - when CSRF protection is enabled in Jenkins """ from jenkinsapi.jenkins import Jenkins jenkins = Jenkins( "http://localhost:8080", username="admin", password="password", use_crumb=True, ) for job_name in jenkins.jobs: print(job_name) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/low_level/copy_a_job.py0000644000000000000000000000130700000000000020345 0ustar0000000000000000""" A lower-level implementation of copying a job in Jenkins """ from __future__ import print_function import requests from pkg_resources import resource_string from jenkinsapi.jenkins import Jenkins from jenkinsapi_tests.test_utils.random_strings import random_string J = Jenkins("http://localhost:8080") jobName = random_string() jobName2 = "%s_2" % jobName url = "http://localhost:8080/createItem?from=%s&name=%s&mode=copy" % ( jobName, jobName2, ) xml = resource_string("examples", "addjob.xml") j = J.create_job(jobname=jobName, xml=xml) h = {"Content-Type": "application/x-www-form-urlencoded"} response = requests.post(url, data="dysjsjsjs", headers=h) print(response.text.encode("UTF-8")) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6276681 jenkinsapi-0.3.13/examples/low_level/create_a_view_low_level.py0000644000000000000000000000114500000000000023106 0ustar0000000000000000""" A low level example: This is how JenkinsAPI creates views """ from __future__ import print_function import json import requests url = "http://localhost:8080/createView" str_view_name = "blahblah123" params = {} # {'name': str_view_name} headers = {"Content-Type": "application/x-www-form-urlencoded"} data = { "name": str_view_name, "mode": "hudson.model.ListView", "Submit": "OK", "json": json.dumps( {"name": str_view_name, "mode": "hudson.model.ListView"} ), } # Try 1 result = requests.post(url, params=params, data=data, headers=headers) print(result.text.encode("UTF-8")) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/examples/low_level/example_param_build.py0000644000000000000000000000105700000000000022235 0ustar0000000000000000from __future__ import print_function import json import requests def foo(): """ A low level example of how JenkinsAPI runs a parameterized build """ toJson = {"parameter": [{"name": "B", "value": "xyz"}]} url = "http://localhost:8080/job/ddd/build" # url = 'http://localhost:8000' headers = {"Content-Type": "application/x-www-form-urlencoded"} form = {"json": json.dumps(toJson)} response = requests.post(url, data=form, headers=headers) print(response.text.encode("UTF-8")) if __name__ == "__main__": foo() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/examples/low_level/login_with_auth.py0000644000000000000000000000036500000000000021430 0ustar0000000000000000""" A lower level example of how we login with authentication """ from __future__ import print_function from jenkinsapi import jenkins J = jenkins.Jenkins("http://localhost:8080", username="sal", password="foobar") J.poll() print(J.items()) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/examples/low_level/post_watcher.py0000644000000000000000000000303100000000000020737 0ustar0000000000000000""" Save this file as server.py >>> python server.py 0.0.0.0 8001 serving on 0.0.0.0:8001 or simply >>> python server.py Serving on localhost:8000 You can use this to test GET and POST methods. In order to run this example you will need the six compatibility library install it with pip before running this script: ``` pip install six ``` """ from six.moves import SimpleHTTPServer, socketserver import logging import cgi PORT = 8081 # <-- change this to be the actual port you want to run on INTERFACE = "localhost" class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): logging.warning("======= GET STARTED =======") logging.warning(self.headers) SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) def do_POST(self): logging.warning("======= POST STARTED =======") logging.warning(self.headers) form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={ "REQUEST_METHOD": "POST", "CONTENT_TYPE": self.headers["Content-Type"], }, ) logging.warning("======= POST VALUES =======") for item in form.list: logging.warning(item) logging.warning("\n") SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) Handler = ServerHandler httpd = socketserver.TCPServer(("", PORT), Handler) print( "Serving at: http://%(interface)s:%(port)s" % dict(interface=INTERFACE or "localhost", port=PORT) ) httpd.serve_forever() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/examples/low_level/readme.rst0000644000000000000000000000057400000000000017663 0ustar0000000000000000Low-Level Examples ================== These examoples are intended to explain how JenkinsAPI performs certain functions. While developing JenkinsAPI I created a number of small scripts like these in order to figure out the correct way to communicate. Ive retained a number of these as they provide some insights into how the various interfaces that Jenkins provides can be used. ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/.gitignore0000644000000000000000000000001500000000000016177 0ustar0000000000000000/__pycache__ ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1674739146.925603 jenkinsapi-0.3.13/jenkinsapi/__init__.py0000644000000000000000000000455700000000000016337 0ustar0000000000000000""" About this library ================== Jenkins is the market leading continuous integration system, originally created by Kohsuke Kawaguchi. This API makes Jenkins even easier to use by providing an easy to use conventional python interface. Jenkins (and It's predecessor Hudson) are fantastic projects - but they are somewhat Java-centric. Thankfully the designers have provided an excellent and complete REST interface. This library wraps up that interface as more conventional python objects in order to make most Jenkins oriented tasks simpler. This library can help you: * Query the test-results of a completed build * Get a objects representing the latest builds of a job * Search for artifacts by simple criteria * Block until jobs are complete * Install artifacts to custom-specified directory structures * username/password auth support for jenkins instances with auth turned on * Ability to search for builds by subversion revision * Ability to add/remove/query jenkins slaves Installing JenkinsAPI ===================== Egg-files for this project are hosted on PyPi. Most Python users should be able to use pip or distribute to automatically install this project. Most users can do the following: easy_install jenkinsapi If you'd like to install in multi-version mode: easy_install -m jenkinsapi Project Authors =============== * Salim Fadhley (sal@stodge.org) * Ramon van Alteren (ramon@vanalteren.nl) * Ruslan Lutsenko (ruslan.lutcenko@gmail.com) Current code lives on github: https://github.com/salimfadhley/jenkinsapi """ from jenkinsapi import ( # Modules command_line, utils, # Files api, artifact, build, config, constants, custom_exceptions, fingerprint, executors, executor, jenkins, jenkinsbase, job, node, result_set, result, view, ) __all__ = [ "command_line", "utils", "api", "artifact", "build", "config", "constants", "custom_exceptions", "executors", "executor", "fingerprint", "jenkins", "jenkinsbase", "job", "node", "result_set", "result", "view", ] __docformat__ = "epytext" # In case of jenkinsapi is not installed in 'develop' mode __version__ = "0.3.13" try: import pkg_resources __version__ = pkg_resources.working_set.by_key["jenkinsapi"].version except (ImportError, KeyError): pass ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/api.py0000644000000000000000000002126100000000000015340 0ustar0000000000000000""" This module is a collection of helpful, high-level functions for automating common tasks. Many of these functions were designed to be exposed to the command-line, hence they have simple string arguments. """ import os import time import logging import six import six.moves.urllib.parse as urlparse from jenkinsapi import constants from jenkinsapi.jenkins import Jenkins from jenkinsapi.artifact import Artifact from jenkinsapi.custom_exceptions import ArtifactsMissing, TimeOut, BadURL log = logging.getLogger(__name__) def get_latest_test_results( jenkinsurl, jobname, username=None, password=None, ssl_verify=True ): """ A convenience function to fetch down the very latest test results from a jenkins job. """ latestbuild = get_latest_build( jenkinsurl, jobname, username=username, password=password, ssl_verify=ssl_verify, ) res = latestbuild.get_resultset() return res def get_latest_build( jenkinsurl, jobname, username=None, password=None, ssl_verify=True ): """ A convenience function to fetch down the very latest test results from a jenkins job. """ jenkinsci = Jenkins( jenkinsurl, username=username, password=password, ssl_verify=ssl_verify ) job = jenkinsci[jobname] return job.get_last_build() def get_latest_complete_build( jenkinsurl, jobname, username=None, password=None, ssl_verify=True ): """ A convenience function to fetch down the very latest test results from a jenkins job. """ jenkinsci = Jenkins( jenkinsurl, username=username, password=password, ssl_verify=ssl_verify ) job = jenkinsci[jobname] return job.get_last_completed_build() def get_build( jenkinsurl, jobname, build_no, username=None, password=None, ssl_verify=True, ): """ A convenience function to fetch down the test results from a jenkins job by build number. """ jenkinsci = Jenkins( jenkinsurl, username=username, password=password, ssl_verify=ssl_verify ) job = jenkinsci[jobname] return job.get_build(build_no) def get_artifacts( jenkinsurl, jobid=None, build_no=None, username=None, password=None, ssl_verify=True, ): """ Find all the artifacts for the latest build of a job. """ jenkinsci = Jenkins( jenkinsurl, username=username, password=password, ssl_verify=ssl_verify ) job = jenkinsci[jobid] if build_no: build = job.get_build(build_no) else: build = job.get_last_good_build() artifacts = build.get_artifact_dict() log.info( msg="Found %i artifacts in '%s'" % (len(artifacts.keys()), build_no) ) return artifacts def search_artifacts( jenkinsurl, jobid, artifact_ids=None, username=None, password=None, ssl_verify=True, ): """ Search the entire history of a jenkins job for a list of artifact names. If same_build is true then ensure that all artifacts come from the same build of the job """ if not artifact_ids: return [] jenkinsci = Jenkins( jenkinsurl, username=username, password=password, ssl_verify=ssl_verify ) job = jenkinsci[jobid] build_ids = job.get_build_ids() for build_id in build_ids: build = job.get_build(build_id) artifacts = build.get_artifact_dict() if set(artifact_ids).issubset(set(artifacts.keys())): return dict((a, artifacts[a]) for a in artifact_ids) missing_artifacts = set(artifact_ids) - set(artifacts.keys()) log.debug( msg="Artifacts %s missing from %s #%i" % (", ".join(missing_artifacts), jobid, build_id) ) # noinspection PyUnboundLocalVariable raise ArtifactsMissing(missing_artifacts) def grab_artifact( jenkinsurl, jobid, artifactid, targetdir, username=None, password=None, strict_validation=False, ssl_verify=True, ): """ Convenience method to find the latest good version of an artifact and save it to a target directory. Directory is made automatically if not exists. """ artifacts = get_artifacts( jenkinsurl, jobid, username=username, password=password, ssl_verify=ssl_verify, ) artifact = artifacts[artifactid] if not os.path.exists(targetdir): os.makedirs(targetdir) artifact.save_to_dir(targetdir, strict_validation) def block_until_complete( jenkinsurl, jobs, maxwait=12000, interval=30, raise_on_timeout=True, username=None, password=None, ssl_verify=True, ): """ Wait until all of the jobs in the list are complete. """ assert maxwait > 0 assert maxwait > interval assert interval > 0 obj_jenkins = Jenkins( jenkinsurl, username=username, password=password, ssl_verify=ssl_verify ) obj_jobs = [obj_jenkins[jid] for jid in jobs] for time_left in range(maxwait, 0, -interval): still_running = [j for j in obj_jobs if j.is_queued_or_running()] if not still_running: return str_still_running = ", ".join('"%s"' % str(a) for a in still_running) log.warning( "Waiting for jobs %s to complete. Will wait another %is", str_still_running, time_left, ) time.sleep(interval) if raise_on_timeout: # noinspection PyUnboundLocalVariable raise TimeOut( "Waited too long for these jobs to complete: %s" % str_still_running ) def get_view_from_url(url, username=None, password=None, ssl_verify=True): """ Factory method """ matched = constants.RE_SPLIT_VIEW_URL.search(url) if not matched: raise BadURL("Cannot parse URL %s" % url) jenkinsurl, view_name = matched.groups() jenkinsci = Jenkins( jenkinsurl, username=username, password=password, ssl_verify=ssl_verify ) return jenkinsci.views[view_name] def get_nested_view_from_url( url, username=None, password=None, ssl_verify=True ): """ Returns View based on provided URL. Convenient for nested views. """ matched = constants.RE_SPLIT_VIEW_URL.search(url) if not matched: raise BadURL("Cannot parse URL %s" % url) jenkinsci = Jenkins( matched.group(0), username=username, password=password, ssl_verify=ssl_verify, ) return jenkinsci.get_view_by_url(url) def install_artifacts( artifacts, dirstruct, installdir, basestaticurl, strict_validation=False ): """ Install the artifacts. """ assert basestaticurl.endswith("/"), "Basestaticurl should end with /" installed = [] for reldir, artifactnames in dirstruct.items(): destdir = os.path.join(installdir, reldir) if not os.path.exists(destdir): log.warning("Making install directory %s", destdir) os.makedirs(destdir) else: assert os.path.isdir(destdir) for artifactname in artifactnames: destpath = os.path.abspath(os.path.join(destdir, artifactname)) if artifactname in artifacts.keys(): # The artifact must be loaded from jenkins theartifact = artifacts[artifactname] else: # It's probably a static file, # we can get it from the static collection staticurl = urlparse.urljoin(basestaticurl, artifactname) theartifact = Artifact(artifactname, staticurl, None) theartifact.save(destpath, strict_validation) installed.append(destpath) return installed def search_artifact_by_regexp( jenkinsurl, jobid, artifactRegExp, username=None, password=None, ssl_verify=True, ): """ Search the entire history of a hudson job for a build which has an artifact whose name matches a supplied regular expression. Return only that artifact. @param jenkinsurl: The base URL of the jenkins server @param jobid: The name of the job we are to search through @param artifactRegExp: A compiled regular expression object (not a re-string) @param username: Jenkins login user name, optional @param password: Jenkins login password, optional """ job = Jenkins( jenkinsurl, username=username, password=password, ssl_verify=ssl_verify ) j = job[jobid] build_ids = j.get_build_ids() for build_id in build_ids: build = j.get_build(build_id) artifacts = build.get_artifact_dict() it = six.iteritems(artifacts) for name, art in it: md_match = artifactRegExp.search(name) if md_match: return art raise ArtifactsMissing() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/artifact.py0000644000000000000000000001130700000000000016364 0ustar0000000000000000""" Artifacts can be used to represent data created as a side-effect of running a Jenkins build. Artifacts are files which are associated with a single build. A build can have any number of artifacts associated with it. This module provides a class called Artifact which allows you to download objects from the server and also access them as a stream. """ import os import logging import hashlib from jenkinsapi.fingerprint import Fingerprint from jenkinsapi.custom_exceptions import ArtifactBroken log = logging.getLogger(__name__) class Artifact(object): """ Represents a single Jenkins artifact, usually some kind of file generated as a by-product of executing a Jenkins build. """ def __init__(self, filename, url, build, relative_path=None): self.filename = filename self.url = url self.build = build self.relative_path = relative_path def save(self, fspath, strict_validation=False): """ Save the artifact to an explicit path. The containing directory must exist. Returns a reference to the file which has just been writen to. :param fspath: full pathname including the filename, str :return: filepath """ log.info(msg="Saving artifact @ %s to %s" % (self.url, fspath)) if not fspath.endswith(self.filename): log.warning( "Attempt to change the filename of artifact %s on save.", self.filename, ) if os.path.exists(fspath): if self.build: try: if self._verify_download(fspath, strict_validation): log.info( "Local copy of %s is already up to date.", self.filename, ) return fspath except ArtifactBroken: log.warning("Jenkins artifact could not be identified.") else: log.info( "This file did not originate from Jenkins, " "so cannot check." ) else: log.info("Local file is missing, downloading new.") filepath = self._do_download(fspath) self._verify_download(filepath, strict_validation) return fspath def get_jenkins_obj(self): return self.build.get_jenkins_obj() def get_data(self): """ Grab the text of the artifact """ response = self.get_jenkins_obj().requester.get_and_confirm_status( self.url ) return response.content def _do_download(self, fspath): """ Download the the artifact to a path. """ data = self.get_jenkins_obj().requester.get_and_confirm_status( self.url, stream=True ) with open(fspath, "wb") as out: for chunk in data.iter_content(chunk_size=1024): out.write(chunk) return fspath def _verify_download(self, fspath, strict_validation): """ Verify that a downloaded object has a valid fingerprint. """ local_md5 = self._md5sum(fspath) baseurl = self.build.job.jenkins.baseurl fp = Fingerprint(baseurl, local_md5, self.build.job.jenkins) valid = fp.validate_for_build( self.filename, self.build.job.get_full_name(), self.build.buildno ) if not valid or (fp.unknown and strict_validation): # strict = 404 as invalid raise ArtifactBroken( "Artifact %s seems to be broken, check %s" % (local_md5, baseurl) ) return True def _md5sum(self, fspath, chunksize=2**20): """ A MD5 hashing function intended to produce the same results as that used by Jenkins. """ md5 = hashlib.md5() with open(fspath, "rb") as f: for chunk in iter(lambda: f.read(chunksize), ""): if chunk: md5.update(chunk) else: break return md5.hexdigest() def save_to_dir(self, dirpath, strict_validation=False): """ Save the artifact to a folder. The containing directory must exist, but use the artifact's default filename. """ assert os.path.exists(dirpath) assert os.path.isdir(dirpath) outputfilepath = os.path.join(dirpath, self.filename) return self.save(outputfilepath, strict_validation) def __repr__(self): """ Produce a handy repr-string. """ return """<%s.%s %s>""" % ( self.__class__.__module__, self.__class__.__name__, self.url, ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674739024.6804104 jenkinsapi-0.3.13/jenkinsapi/build.py0000644000000000000000000004743600000000000015702 0ustar0000000000000000""" A Jenkins build represents a single execution of a Jenkins Job. Builds can be thought of as the second level of the Jenkins hierarchy beneath Jobs. Builds can have state, such as whether they are running or not. They can also have outcomes, such as whether they passed or failed. Build objects can be associated with Results and Artifacts. """ import time import logging import warnings import datetime from time import sleep import pytz from jenkinsapi import config from jenkinsapi.artifact import Artifact from jenkinsapi.result_set import ResultSet from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.constants import STATUS_SUCCESS from jenkinsapi.custom_exceptions import NoResults from jenkinsapi.custom_exceptions import JenkinsAPIException from six.moves.urllib.parse import quote from requests import HTTPError log = logging.getLogger(__name__) class Build(JenkinsBase): """ Represents a Jenkins build, executed in context of a job. """ STR_TOTALCOUNT = "totalCount" STR_TPL_NOTESTS_ERR = ( "%s has status %s, and does not have " "any test results" ) def __init__(self, url, buildno, job, depth=1): """ depth=1 is for backward compatibility consideration About depth, the deeper it is, the more build data you get back. If depth=0 is sufficient for you, don't go up to 1. For more information, see https://www.jenkins.io/doc/book/using/remote-access-api/#RemoteaccessAPI-Depthcontrol """ assert isinstance(buildno, int) self.buildno = buildno self.job = job self.depth = depth JenkinsBase.__init__(self, url) def _poll(self, tree=None): # For builds we need more information for downstream and # upstream builds so we override the poll to get at the extra # data for build objects url = self.python_api_url(self.baseurl) return self.get_data(url, params={"depth": self.depth}, tree=tree) def __str__(self): return self._data["fullDisplayName"] @property def name(self): return str(self) def get_description(self): return self._data["description"] def get_number(self): return self._data["number"] def get_status(self): return self._data["result"] def get_slave(self): return self._data["builtOn"] def get_revision(self): return getattr(self, "_get_%s_rev" % self._get_vcs(), lambda: None)() def get_revision_branch(self): return getattr( self, "_get_%s_rev_branch" % self._get_vcs(), lambda: None )() def get_repo_url(self): return getattr( self, "_get_%s_repo_url" % self._get_vcs(), lambda: None )() def get_params(self): """ Return a dictionary of params names and their values, or an empty dictionary if no parameters are returned. """ # This is what a parameter action looks like: # {'_class': 'hudson.model.ParametersAction', 'parameters': [ # {'_class': 'hudson.model.StringParameterValue', # 'value': '12', # 'name': 'FOO_BAR_BAZ'}]} actions = self._data.get("actions") if actions: parameters = {} for elem in actions: if elem.get("_class") == "hudson.model.ParametersAction": parameters = elem.get("parameters", {}) break return {pair["name"]: pair.get("value") for pair in parameters} return {} def get_changeset_items(self): """ Returns a list of changeSet items. Each item has structure as in following example: { "affectedPaths": [ "content/rcm/v00-rcm-xccdf.xml" ], "author" : { "absoluteUrl": "http://jenkins_url/user/username79", "fullName": "username" }, "commitId": "3097", "timestamp": 1414398423091, "date": "2014-10-27T08:27:03.091288Z", "msg": "commit message", "paths": [{ "editType": "edit", "file": "/some/path/of/changed_file" }], "revision": 3097, "user": "username" } """ if "changeSet" in self._data: if "items" in self._data["changeSet"]: return self._data["changeSet"]["items"] elif "changeSets" in self._data: if "items" in self._data["changeSets"]: return self._data["changeSets"]["items"] return [] def _get_vcs(self): """ Returns a string VCS. By default, 'git' will be used. """ vcs = "git" if "changeSet" in self._data and "kind" in self._data["changeSet"]: vcs = self._data["changeSet"]["kind"] or "git" elif "changeSets" in self._data and "kind" in self._data["changeSets"]: vcs = self._data["changeSets"]["kind"] or "git" return vcs def _get_svn_rev(self): warnings.warn( "This untested function may soon be removed from Jenkinsapi " "(get_svn_rev)." ) maxRevision = 0 for repoPathSet in self._data["changeSet"]["revisions"]: maxRevision = max(repoPathSet["revision"], maxRevision) return maxRevision def _get_git_rev(self): # Sometimes we have None as part of actions. Filter those actions # which have lastBuiltRevision in them _actions = [ x for x in self._data["actions"] if x and "lastBuiltRevision" in x ] if _actions: return _actions[0]["lastBuiltRevision"]["SHA1"] return None def _get_hg_rev(self): warnings.warn( "This untested function may soon be removed from Jenkinsapi " "(_get_hg_rev)." ) return [ x["mercurialNodeName"] for x in self._data["actions"] if "mercurialNodeName" in x ][0] def _get_svn_rev_branch(self): raise NotImplementedError("_get_svn_rev_branch is not yet implemented") def _get_git_rev_branch(self): # Sometimes we have None as part of actions. Filter those actions # which have lastBuiltRevision in them _actions = [ x for x in self._data["actions"] if x and "lastBuiltRevision" in x ] return _actions[0]["lastBuiltRevision"]["branch"] def _get_hg_rev_branch(self): raise NotImplementedError("_get_hg_rev_branch is not yet implemented") def _get_git_repo_url(self): # Sometimes we have None as part of actions. Filter those actions # which have lastBuiltRevision in them _actions = [ x for x in self._data["actions"] if x and "lastBuiltRevision" in x ] # old Jenkins version have key remoteUrl v/s the new version # has a list remoteUrls result = _actions[0].get("remoteUrls", _actions[0].get("remoteUrl")) if isinstance(result, list): result = ",".join(result) return result def _get_svn_repo_url(self): raise NotImplementedError("_get_svn_repo_url is not yet implemented") def _get_hg_repo_url(self): raise NotImplementedError("_get_hg_repo_url is not yet implemented") def get_duration(self): return datetime.timedelta(milliseconds=self._data["duration"]) def get_build_url(self): return self._data["url"] def get_artifacts(self): data = self.poll(tree="artifacts[relativePath,fileName]") for afinfo in data["artifacts"]: url = "%s/artifact/%s" % ( self.baseurl, quote(afinfo["relativePath"]), ) af = Artifact( afinfo["fileName"], url, self, relative_path=afinfo["relativePath"], ) yield af def get_artifact_dict(self): return dict((af.relative_path, af) for af in self.get_artifacts()) def get_upstream_job_name(self): """ Get the upstream job name if it exist, None otherwise :return: String or None """ try: return self.get_actions()["causes"][0]["upstreamProject"] except KeyError: return None def get_upstream_job(self): """ Get the upstream job object if it exist, None otherwise :return: Job or None """ if self.get_upstream_job_name(): return self.get_jenkins_obj().get_job(self.get_upstream_job_name()) return None def get_upstream_build_number(self): """ Get the upstream build number if it exist, None otherwise :return: int or None """ try: return int(self.get_actions()["causes"][0]["upstreamBuild"]) except KeyError: return None def get_upstream_build(self): """ Get the upstream build if it exist, None otherwise :return Build or None """ upstream_job = self.get_upstream_job() if upstream_job: return upstream_job.get_build(self.get_upstream_build_number()) return None def get_master_job_name(self): """ Get the master job name if it exist, None otherwise :return: String or None """ try: return self.get_actions()["parameters"][0]["value"] except KeyError: return None def get_master_job(self): """ Get the master job object if it exist, None otherwise :return: Job or None """ warnings.warn( "This untested function may soon be removed from Jenkinsapi " "(get_master_job)." ) if self.get_master_job_name(): return self.get_jenkins_obj().get_job(self.get_master_job_name()) return None def get_master_build_number(self): """ Get the master build number if it exist, None otherwise :return: int or None """ warnings.warn( "This untested function may soon be removed from Jenkinsapi " "(get_master_build_number)." ) try: return int(self.get_actions()["parameters"][1]["value"]) except KeyError: return None def get_master_build(self): """ Get the master build if it exist, None otherwise :return Build or None """ warnings.warn( "This untested function may soon be removed from Jenkinsapi " "(get_master_build)." ) master_job = self.get_master_job() if master_job: return master_job.get_build(self.get_master_build_number()) return None def get_downstream_jobs(self): """ Get the downstream jobs for this build :return List of jobs or None """ warnings.warn( "This untested function may soon be removed from Jenkinsapi " "(get_downstream_jobs)." ) downstream_jobs = [] try: for job_name in self.get_downstream_job_names(): downstream_jobs.append( self.get_jenkins_obj().get_job(job_name) ) return downstream_jobs except (IndexError, KeyError): return [] def get_downstream_job_names(self): """ Get the downstream job names for this build :return List of string or None """ downstream_job_names = self.job.get_downstream_job_names() downstream_names = [] try: fingerprints = self._data["fingerprint"] for fingerprint in fingerprints: for job_usage in fingerprint["usage"]: if job_usage["name"] in downstream_job_names: downstream_names.append(job_usage["name"]) return downstream_names except (IndexError, KeyError): return [] def get_downstream_builds(self): """ Get the downstream builds for this build :return List of Build or None """ downstream_job_names = self.get_downstream_job_names() downstream_builds = [] try: # pylint: disable=R1702 fingerprints = self._data["fingerprint"] for fingerprint in fingerprints: for job_usage in fingerprint["usage"]: if job_usage["name"] in downstream_job_names: job = self.get_jenkins_obj().get_job(job_usage["name"]) for job_range in job_usage["ranges"]["ranges"]: for build_id in range( job_range["start"], job_range["end"] ): downstream_builds.append( job.get_build(build_id) ) return downstream_builds except (IndexError, KeyError): return [] def get_matrix_runs(self): """ For a matrix job, get the individual builds for each matrix configuration :return: Generator of Build """ if "runs" in self._data: for rinfo in self._data["runs"]: number = rinfo["number"] if number == self._data["number"]: yield Build(rinfo["url"], number, self.job) def is_running(self): """ Return a bool if running. """ data = self.poll(tree="building") return data.get("building", False) def block(self): while self.is_running(): time.sleep(1) def is_good(self): """ Return a bool, true if the build was good. If the build is still running, return False. """ return (not self.is_running()) and self._data[ "result" ] == STATUS_SUCCESS def block_until_complete(self, delay=15): assert isinstance(delay, int) count = 0 while self.is_running(): total_wait = delay * count log.info( msg="Waited %is for %s #%s to complete" % (total_wait, self.job.name, self.name) ) sleep(delay) count += 1 def get_jenkins_obj(self): return self.job.get_jenkins_obj() def get_result_url(self): """ Return the URL for the object which provides the job's result summary. """ url_tpl = r"%stestReport/%s" return url_tpl % (self._data["url"], config.JENKINS_API) def get_resultset(self): """ Obtain detailed results for this build. """ result_url = self.get_result_url() if self.STR_TOTALCOUNT not in self.get_actions(): raise NoResults( "%s does not have any published results" % str(self) ) buildstatus = self.get_status() if not self.get_actions()[self.STR_TOTALCOUNT]: raise NoResults( self.STR_TPL_NOTESTS_ERR % (str(self), buildstatus) ) obj_results = ResultSet(result_url, build=self) return obj_results def has_resultset(self): """ Return a boolean, true if a result set is available. false if not. """ return self.STR_TOTALCOUNT in self.get_actions() def get_actions(self): all_actions = {} for dct_action in self._data["actions"]: if dct_action is None: continue all_actions.update(dct_action) return all_actions def get_causes(self): """ Returns a list of causes. There can be multiple causes lists and some of the can be empty. For instance, when a build is manually aborted, Jenkins could add an empty causes list to the actions dict. Empty ones are ignored. """ all_causes = [] for dct_action in self._data["actions"]: if dct_action is None: continue if "causes" in dct_action and dct_action["causes"]: all_causes.extend(dct_action["causes"]) return all_causes def get_timestamp(self): """ Returns build timestamp in UTC """ # Java timestamps are given in miliseconds since the epoch start! naive_timestamp = datetime.datetime( *time.gmtime(self._data["timestamp"] / 1000.0)[:6] ) return pytz.utc.localize(naive_timestamp) def get_console(self): """ Return the current state of the text console. """ url = "%s/consoleText" % self.baseurl content = self.job.jenkins.requester.get_url(url).content # This check was made for Python 3.x # In this version content is a bytes string # By contract this function must return string if isinstance(content, str): return content elif isinstance(content, bytes): return content.decode("ISO-8859-1") else: raise JenkinsAPIException("Unknown content type for console") def stream_logs(self, interval=0): """ Return generator which streams parts of text console. """ url = "%s/logText/progressiveText" % self.baseurl size = 0 more_data = True while more_data: resp = self.job.jenkins.requester.get_url( url, params={"start": size} ) content = resp.content if content: if isinstance(content, str): yield content elif isinstance(content, bytes): yield content.decode("ISO-8859-1") else: raise JenkinsAPIException( "Unknown content type for console" ) size = resp.headers["X-Text-Size"] more_data = resp.headers.get("X-More-Data") sleep(interval) def get_estimated_duration(self): """ Return the estimated build duration (in seconds) or none. """ try: eta_ms = self._data["estimatedDuration"] return max(0, eta_ms / 1000.0) except KeyError: return None def stop(self): """ Stops the build execution if it's running :return boolean True if succeded False otherwise or the build is not running """ if self.is_running(): url = "%s/stop" % self.baseurl # Starting from Jenkins 2.7 stop function sometimes breaks # on redirect to job page. Call to stop works fine, and # we don't need to have job page here. self.job.jenkins.requester.post_and_confirm_status( url, data="", valid=[ 302, 200, 500, ], ) return True return False def get_env_vars(self): """ Return the environment variables. This method is using the Environment Injector plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin """ url = self.python_api_url("%s/injectedEnvVars" % self.baseurl) try: data = self.get_data(url, params={"depth": self.depth}) except HTTPError as ex: warnings.warn( "Make sure the Environment Injector plugin " "is installed." ) raise ex return data["envMap"] def toggle_keep(self): """ Toggle "keep this build forever" on and off """ url = "%s/toggleLogKeep" % self.baseurl self.get_jenkins_obj().requester.post_and_confirm_status(url, data={}) self._data = self._poll() def is_kept_forever(self): return self._data["keepLog"] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/command_line/__init__.py0000644000000000000000000000005300000000000020747 0ustar0000000000000000""" __init__,py for commandline module """ ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/command_line/jenkins_invoke.py0000644000000000000000000000600400000000000022226 0ustar0000000000000000""" jenkinsapi class for invoking Jenkins """ import os import sys import logging import optparse from jenkinsapi import jenkins log = logging.getLogger(__name__) class JenkinsInvoke(object): """ JenkinsInvoke object implements class to call from command line """ @classmethod def mkparser(cls): parser = optparse.OptionParser() DEFAULT_BASEURL = os.environ.get( "JENKINS_URL", "http://localhost/jenkins" ) parser.help_text = ( "Execute a number of jenkins jobs on the server of your choice." + " Optionally block until the jobs are complete." ) parser.add_option( "-J", "--jenkinsbase", dest="baseurl", help="Base URL for the Jenkins server, default is %s" % DEFAULT_BASEURL, type="str", default=DEFAULT_BASEURL, ) parser.add_option( "--username", "-u", dest="username", help="Username for jenkins authentification", type="str", default=None, ) parser.add_option( "--password", "-p", dest="password", help="password for jenkins user auth", type="str", default=None, ) parser.add_option( "-b", "--block", dest="block", action="store_true", default=False, help="Block until each of the jobs is complete.", ) parser.add_option( "-t", "--token", dest="token", help="Optional security token.", default=None, ) return parser @classmethod def main(cls): parser = cls.mkparser() options, args = parser.parse_args() try: assert args, "Need to specify at least one job name" except AssertionError as err: log.critical(err.message) parser.print_help() sys.exit(1) invoker = cls(options, args) invoker() def __init__(self, options, jobs): self.options = options self.jobs = jobs self.api = self._get_api( baseurl=options.baseurl, username=options.username, password=options.password, ) def _get_api(self, baseurl, username, password): return jenkins.Jenkins(baseurl, username, password) def __call__(self): for job in self.jobs: self.invokejob( job, block=self.options.block, token=self.options.token ) def invokejob(self, jobname, block, token): assert isinstance(block, bool) assert isinstance(jobname, str) assert token is None or isinstance(token, str) job = self.api.get_job(jobname) job.invoke(securitytoken=token, block=block) def main(): logging.basicConfig() logging.getLogger("").setLevel(logging.INFO) JenkinsInvoke.main() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/command_line/jenkinsapi_version.py0000644000000000000000000000030000000000000023103 0ustar0000000000000000""" jenkinsapi.command_line.jenkinsapi_version """ from jenkinsapi import __version__ as version import sys def main(): sys.stdout.write(version) if __name__ == "__main__": main() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/config.py0000644000000000000000000000011700000000000016031 0ustar0000000000000000""" Jenkins configuration """ JENKINS_API = r"api/python" LOAD_TIMEOUT = 30 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/constants.py0000644000000000000000000000064000000000000016601 0ustar0000000000000000""" Constants for jenkinsapi """ import re STATUS_FAIL = "FAIL" STATUS_ERROR = "ERROR" STATUS_ABORTED = "ABORTED" STATUS_REGRESSION = "REGRESSION" STATUS_SUCCESS = "SUCCESS" STATUS_FIXED = "FIXED" STATUS_PASSED = "PASSED" RESULTSTATUS_FAILURE = "FAILURE" RESULTSTATUS_FAILED = "FAILED" RESULTSTATUS_SKIPPED = "SKIPPED" STR_RE_SPLIT_VIEW = "(.*)/view/([^/]*)/?" RE_SPLIT_VIEW_URL = re.compile(STR_RE_SPLIT_VIEW) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/credential.py0000644000000000000000000003067200000000000016707 0ustar0000000000000000""" Module for jenkinsapi Credential class """ import logging import xml.etree.cElementTree as ET log = logging.getLogger(__name__) class Credential(object): """ Base abstract class for credentials Credentials returned from Jenkins don't hold any sensitive information, so there is nothing useful can be done with existing credentials besides attaching them to Nodes or other objects. You can create concrete Credential instance: UsernamePasswordCredential or SSHKeyCredential by passing credential's description and credential dict. Each class expects specific credential dict, see below. """ # pylint: disable=unused-argument def __init__(self, cred_dict, jenkins_class=""): """ Create credential :param str description: as Jenkins doesn't allow human friendly names for credentials and makes "displayName" itself, there is no way to find credential later, this field is used to distinguish between credentials :param dict cred_dict: dict containing credential information """ self.credential_id = cred_dict.get("credential_id", "") self.description = cred_dict["description"] self.fullname = cred_dict.get("fullName", "") self.displayname = cred_dict.get("displayName", "") self.jenkins_class = jenkins_class def __str__(self): return self.description def get_attributes(self): pass def get_attributes_xml(self): pass def _get_attributes_xml(self, data): root = ET.Element(self.jenkins_class) for key in data: value = data[key] if isinstance(value, dict): node = ET.SubElement(root, key) if "stapler-class" in value: node.attrib["class"] = value["stapler-class"] for sub_key in value: ET.SubElement(node, sub_key).text = value[sub_key] else: ET.SubElement(root, key).text = data[key] return ET.tostring(root) class UsernamePasswordCredential(Credential): """ Username and password credential Constructor expects following dict: { 'credential_id': str, Automatically set by jenkinsapi 'displayName': str, Automatically set by Jenkins 'fullName': str, Automatically set by Jenkins 'typeName': str, Automatically set by Jenkins 'description': str, 'userName': str, 'password': str } When creating credential via jenkinsapi automatic fields not need to be in dict """ def __init__(self, cred_dict): jenkins_class = "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" # noqa super(UsernamePasswordCredential, self).__init__( cred_dict, jenkins_class ) if "typeName" in cred_dict: username = cred_dict["displayName"].split("/")[0] else: username = cred_dict["userName"] self.username = username self.password = cred_dict.get("password", None) def get_attributes(self): """ Used by Credentials object to create credential in Jenkins """ c_id = "" if self.credential_id is None else self.credential_id return { "stapler-class": self.jenkins_class, "Submit": "OK", "json": { "": "1", "credentials": { "stapler-class": self.jenkins_class, "id": c_id, "username": self.username, "password": self.password, "description": self.description, }, }, } def get_attributes_xml(self): """ Used by Credentials object to update a credential in Jenkins """ c_id = "" if self.credential_id is None else self.credential_id data = { "id": c_id, "username": self.username, "password": self.password, "description": self.description, } return super(UsernamePasswordCredential, self)._get_attributes_xml( data ) class SecretTextCredential(Credential): """ Secret text credential Constructor expects following dict: { 'credential_id': str, Automatically set by jenkinsapi 'displayName': str, Automatically set by Jenkins 'fullName': str, Automatically set by Jenkins 'typeName': str, Automatically set by Jenkins 'description': str, 'secret': str, } When creating credential via jenkinsapi automatic fields not need to be in dict """ def __init__(self, cred_dict): jenkins_class = ( "org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl" ) super(SecretTextCredential, self).__init__(cred_dict, jenkins_class) self.secret = cred_dict.get("secret", None) def get_attributes(self): """ Used by Credentials object to create credential in Jenkins """ c_id = "" if self.credential_id is None else self.credential_id return { "stapler-class": self.jenkins_class, "Submit": "OK", "json": { "": "1", "credentials": { "stapler-class": self.jenkins_class, "$class": self.jenkins_class, "id": c_id, "secret": self.secret, "description": self.description, }, }, } def get_attributes_xml(self): """ Used by Credentials object to update a credential in Jenkins """ c_id = "" if self.credential_id is None else self.credential_id data = { "id": c_id, "secret": self.secret, "description": self.description, } return super(SecretTextCredential, self)._get_attributes_xml(data) class SSHKeyCredential(Credential): """ SSH key credential Constructr expects following dict: { 'credential_id': str, Automatically set by jenkinsapi 'displayName': str, Automatically set by Jenkins 'fullName': str, Automatically set by Jenkins 'typeName': str, Automatically set by Jenkins 'description': str, 'userName': str, 'passphrase': str, SSH key passphrase, 'private_key': str Private SSH key } private_key value is parsed to find type of credential to create: private_key starts with - the value is private key itself These credential variations are no longer supported by SSH Credentials plugin. jenkinsapi will raise ValueError if they are used: private_key starts with / the value is a path to key private_key starts with ~ the value is a key from ~/.ssh When creating credential via jenkinsapi automatic fields not need to be in dict """ def __init__(self, cred_dict): jenkins_class = "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey" # noqa super(SSHKeyCredential, self).__init__(cred_dict, jenkins_class) if "typeName" in cred_dict: username = cred_dict["displayName"].split(" ")[0] else: username = cred_dict["userName"] self.username = username self.passphrase = cred_dict.get("passphrase", "") if "private_key" not in cred_dict or cred_dict["private_key"] is None: self.key_type = -1 self.key_value = None elif cred_dict["private_key"].startswith("-"): self.key_type = 0 self.key_value = cred_dict["private_key"] else: raise ValueError("Invalid private_key value") @property def attrs(self): if self.key_type == 0: c_class = self.jenkins_class + "$DirectEntryPrivateKeySource" elif self.key_type == 1: c_class = self.jenkins_class + "$FileOnMasterPrivateKeySource" elif self.key_type == 2: c_class = self.jenkins_class + "$UsersPrivateKeySource" else: c_class = None attrs = { "value": self.key_type, "privateKey": self.key_value, "stapler-class": c_class, } # We need one more attr when using the key file on master. if self.key_type == 1: attrs["privateKeyFile"] = self.key_value return attrs def get_attributes(self): """ Used by Credentials object to create credential in Jenkins """ c_id = "" if self.credential_id is None else self.credential_id return { "stapler-class": self.attrs["stapler-class"], "Submit": "OK", "json": { "": "1", "credentials": { "scope": "GLOBAL", "id": c_id, "username": self.username, "description": self.description, "privateKeySource": self.attrs, "passphrase": self.passphrase, "stapler-class": self.jenkins_class, "$class": self.jenkins_class, }, }, } def get_attributes_xml(self): """ Used by Credentials object to update a credential in Jenkins """ c_id = "" if self.credential_id is None else self.credential_id data = { "id": c_id, "username": self.username, "description": self.description, "privateKeySource": self.attrs, "passphrase": self.passphrase, } return super(SSHKeyCredential, self)._get_attributes_xml(data) class AmazonWebServicesCredentials(Credential): """ AWS credential using the CloudBees AWS Credentials Plugin See https://wiki.jenkins.io/display/JENKINS/CloudBees+AWS+Credentials+Plugin Constructor expects following dict: { 'credential_id': str, Automatically set by jenkinsapi 'displayName': str, Automatically set by Jenkins 'fullName': str, Automatically set by Jenkins 'description': str, 'accessKey': str, 'secretKey': str, 'iamRoleArn': str, 'iamMfaSerialNumber': str } When creating credential via jenkinsapi automatic fields not need to be in dict """ def __init__(self, cred_dict): jenkins_class = ( "com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl" ) super(AmazonWebServicesCredentials, self).__init__( cred_dict, jenkins_class ) self.access_key = cred_dict["accessKey"] self.secret_key = cred_dict["secretKey"] self.iam_role_arn = cred_dict.get("iamRoleArn", "") self.iam_mfa_serial_number = cred_dict.get("iamMfaSerialNumber", "") def get_attributes(self): """ Used by Credentials object to create credential in Jenkins """ c_id = "" if self.credential_id is None else self.credential_id return { "stapler-class": self.jenkins_class, "Submit": "OK", "json": { "": "1", "credentials": { "stapler-class": self.jenkins_class, "$class": self.jenkins_class, "id": c_id, "accessKey": self.access_key, "secretKey": self.secret_key, "iamRoleArn": self.iam_role_arn, "iamMfaSerialNumber": self.iam_mfa_serial_number, "description": self.description, }, }, } def get_attributes_xml(self): """ Used by Credentials object to update a credential in Jenkins """ c_id = "" if self.credential_id is None else self.credential_id data = { "id": c_id, "accessKey": self.access_key, "secretKey": self.secret_key, "iamRoleArn": self.iam_role_arn, "iamMfaSerialNumber": self.iam_mfa_serial_number, "description": self.description, } return super(AmazonWebServicesCredentials, self)._get_attributes_xml( data ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/credentials.py0000644000000000000000000001605200000000000017066 0ustar0000000000000000""" This module implements the Credentials class, which is intended to be a container-like interface for all of the Global credentials defined on a single Jenkins node. """ import logging from six.moves.urllib.parse import urlencode from jenkinsapi.credential import Credential from jenkinsapi.credential import UsernamePasswordCredential from jenkinsapi.credential import SecretTextCredential from jenkinsapi.credential import SSHKeyCredential from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.custom_exceptions import JenkinsAPIException log = logging.getLogger(__name__) class Credentials(JenkinsBase): """ This class provides a container-like API which gives access to all global credentials on a Jenkins node. Returns a list of Credential Objects. """ def __init__(self, baseurl, jenkins_obj): self.baseurl = baseurl self.jenkins = jenkins_obj JenkinsBase.__init__(self, baseurl) self.credentials = self._data["credentials"] def _poll(self, tree=None): url = self.python_api_url(self.baseurl) + "?depth=2" data = self.get_data(url, tree=tree) credentials = data["credentials"] for cred_id, cred_dict in credentials.items(): cred_dict["credential_id"] = cred_id credentials[cred_id] = self._make_credential(cred_dict) return data def __str__(self): return "Global Credentials @ %s" % self.baseurl def get_jenkins_obj(self): return self.jenkins def __iter__(self): for cred in self.credentials.values(): yield cred.description def __contains__(self, description): return description in self.keys() def iterkeys(self): return self.__iter__() def keys(self): return list(self.iterkeys()) def iteritems(self): for cred in self.credentials.values(): yield cred.description, cred def __getitem__(self, description): for cred in self.credentials.values(): if cred.description == description: return cred raise KeyError( 'Credential with description "%s" not found' % description ) def __len__(self): return len(self.keys()) def __setitem__(self, description, credential): """ Creates Credential in Jenkins using username, password and description Description must be unique in Jenkins instance because it is used to find Credential later. If description already exists - this method is going to update existing Credential :param str description: Credential description :param tuple credential_tuple: (username, password, description) tuple. """ if description not in self: params = credential.get_attributes() url = "%s/createCredentials" % self.baseurl try: self.jenkins.requester.post_and_confirm_status( url, params={}, data=urlencode(params) ) except JenkinsAPIException as jae: raise JenkinsAPIException( "Latest version of Credentials " "plugin is required to be able " "to create credentials. " "Original exception: %s" % str(jae) ) else: cred_id = self[description].credential_id credential.credential_id = cred_id params = credential.get_attributes_xml() url = "%s/credential/%s/config.xml" % (self.baseurl, cred_id) try: self.jenkins.requester.post_xml_and_confirm_status( url, params={}, data=params ) except JenkinsAPIException as jae: raise JenkinsAPIException( "Latest version of Credentials " "plugin is required to be able " "to update credentials. " "Original exception: %s" % str(jae) ) self.poll() self.credentials = self._data["credentials"] if description not in self: raise JenkinsAPIException("Problem creating/updating credential.") def get(self, item, default): return self[item] if item in self else default def __delitem__(self, description): if description not in self: raise KeyError( 'Credential with description "%s" not found' % description ) params = {"Submit": "OK", "json": {}} url = "%s/credential/%s/doDelete" % ( self.baseurl, self[description].credential_id, ) try: self.jenkins.requester.post_and_confirm_status( url, params={}, data=urlencode(params) ) except JenkinsAPIException as jae: raise JenkinsAPIException( "Latest version of Credentials " "required to be able to create " "credentials. Original exception: %s" % str(jae) ) self.poll() self.credentials = self._data["credentials"] if description in self: raise JenkinsAPIException("Problem deleting credential.") def _make_credential(self, cred_dict): if cred_dict["typeName"] == "Username with password": cr = UsernamePasswordCredential(cred_dict) elif cred_dict["typeName"] == "SSH Username with private key": cr = SSHKeyCredential(cred_dict) elif cred_dict["typeName"] == "Secret text": cr = SecretTextCredential(cred_dict) else: cr = Credential(cred_dict) return cr class Credentials2x(Credentials): """ This class provides a container-like API which gives access to all global credentials on a Jenkins node. Returns a list of Credential Objects. """ def _poll(self, tree=None): url = self.python_api_url(self.baseurl) + "?depth=2" data = self.get_data(url, tree=tree) credentials = data["credentials"] new_creds = {} for cred_dict in credentials: cred_dict["credential_id"] = cred_dict["id"] new_creds[cred_dict["id"]] = self._make_credential(cred_dict) data["credentials"] = new_creds return data class CredentialsById(Credentials2x): """ This class provides a container-like API which gives access to all global credentials on a Jenkins node. Returns a list of Credential Objects. """ def __iter__(self): for cred in self.credentials.values(): yield cred.credential_id def __contains__(self, credential_id): return credential_id in self.keys() def iteritems(self): for cred in self.credentials.values(): yield cred.credential_id, cred def __getitem__(self, credential_id): for cred in self.credentials.values(): if cred.credential_id == credential_id: return cred raise KeyError( 'Credential with credential_id "%s" not found' % credential_id ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/custom_exceptions.py0000644000000000000000000000457500000000000020353 0ustar0000000000000000"""Module for custom_exceptions. Where possible we try to throw exceptions with non-generic, meaningful names. """ class JenkinsAPIException(Exception): """Base class for all errors""" pass class NotFound(JenkinsAPIException): """Resource cannot be found""" pass class ArtifactsMissing(NotFound): """Cannot find a build with all of the required artifacts.""" pass class UnknownJob(KeyError, NotFound): """Jenkins does not recognize the job requested.""" pass class UnknownView(KeyError, NotFound): """Jenkins does not recognize the view requested.""" pass class UnknownNode(KeyError, NotFound): """Jenkins does not recognize the node requested.""" pass class UnknownQueueItem(KeyError, NotFound): """Jenkins does not recognize the requested queue item""" pass class UnknownPlugin(KeyError, NotFound): """Jenkins does not recognize the plugin requested.""" pass class NoBuildData(NotFound): """A job has no build data.""" pass class NotBuiltYet(NotFound): """A job has no build data.""" pass class ArtifactBroken(JenkinsAPIException): """An artifact is broken, wrong""" pass class TimeOut(JenkinsAPIException): """Some jobs have taken too long to complete.""" pass class NoResults(JenkinsAPIException): """A build did not publish any results.""" pass class FailedNoResults(NoResults): """A build did not publish any results because it failed""" pass class BadURL(ValueError, JenkinsAPIException): """A URL appears to be broken""" pass class NotAuthorized(JenkinsAPIException): """Not Authorized to access resource""" # Usually thrown when we get a 403 returned pass class NotSupportSCM(JenkinsAPIException): """ It's a SCM that does not supported by current version of jenkinsapi """ pass class NotConfiguredSCM(JenkinsAPIException): """It's a job that doesn't have configured SCM""" pass class NotInQueue(JenkinsAPIException): """It's a job that is not in the queue""" pass class PostRequired(JenkinsAPIException): """Method requires POST and not GET""" pass class BadParams(JenkinsAPIException): """Invocation was given bad or inappropriate params""" pass class AlreadyExists(JenkinsAPIException): """ Method requires POST and not GET """ pass ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/executor.py0000644000000000000000000000330100000000000016420 0ustar0000000000000000""" Module for jenkinsapi Executer class """ from jenkinsapi.jenkinsbase import JenkinsBase import logging log = logging.getLogger(__name__) class Executor(JenkinsBase): """ Class to hold information on nodes that are attached as slaves to the master jenkins instance """ def __init__(self, baseurl, nodename, jenkins_obj, number): """ Init a node object by providing all relevant pointers to it :param baseurl: basic url for querying information on a node :param nodename: hostname of the node :param jenkins_obj: ref to the jenkins obj :return: Node obj """ self.nodename = nodename self.number = number self.jenkins = jenkins_obj self.baseurl = baseurl JenkinsBase.__init__(self, baseurl) def __str__(self): return "%s %s" % (self.nodename, self.number) def get_jenkins_obj(self): return self.jenkins def get_progress(self): """Returns percentage""" return self.poll(tree="progress")["progress"] def get_number(self): """ Get Executor number. """ return self.poll(tree="number")["number"] def is_idle(self): """ Returns Boolean: whether Executor is idle or not. """ return self.poll(tree="idle")["idle"] def likely_stuck(self): """ Returns Boolean: whether Executor is likely stuck or not. """ return self.poll(tree="likelyStuck")["likelyStuck"] def get_current_executable(self): """ Returns the current Queue.Task this executor is running. """ return self.poll(tree="currentExecutable")["currentExecutable"] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/executors.py0000644000000000000000000000202500000000000016605 0ustar0000000000000000""" This module implements the Executors class, which is intended to be a container-like interface for all of the executors defined on a single Jenkins node. """ import logging from jenkinsapi.executor import Executor from jenkinsapi.jenkinsbase import JenkinsBase log = logging.getLogger(__name__) class Executors(JenkinsBase): """ This class provides a container-like API which gives access to all executors on a Jenkins node. Returns a list of Executor Objects. """ def __init__(self, baseurl, nodename, jenkins): self.nodename = nodename self.jenkins = jenkins JenkinsBase.__init__(self, baseurl) self.count = self._data["numExecutors"] def __str__(self): return "Executors @ %s" % self.baseurl def get_jenkins_obj(self): return self.jenkins def __iter__(self): for index in range(self.count): executor_url = "%s/executors/%s" % (self.baseurl, index) yield Executor(executor_url, self.nodename, self.jenkins, index) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/fingerprint.py0000644000000000000000000000777600000000000017135 0ustar0000000000000000""" Module for jenkinsapi Fingerprint """ from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.custom_exceptions import ArtifactBroken import re import requests import logging log = logging.getLogger(__name__) class Fingerprint(JenkinsBase): """ Represents a jenkins fingerprint on a single artifact file ?? """ RE_MD5 = re.compile("^([0-9a-z]{32})$") def __init__(self, baseurl, id_, jenkins_obj): logging.basicConfig() self.jenkins_obj = jenkins_obj assert self.RE_MD5.search(id_), ( "%s does not look like " "a valid id" % id_ ) url = "%s/fingerprint/%s/" % (baseurl, id_) JenkinsBase.__init__(self, url, poll=False) self.id_ = id_ self.unknown = False # Previously uninitialized in ctor def get_jenkins_obj(self): return self.jenkins_obj def __str__(self): return self.id_ def valid(self): """ Return True / False if valid. If returns True, self.unknown is set to either True or False, and can be checked if we have positive validity (fingerprint known at server) or negative validity (fingerprint not known at server, but not really an error). """ try: self.poll() self.unknown = False except requests.exceptions.HTTPError as err: # We can't really say anything about the validity of # fingerprints not found -- but the artifact can still # exist, so it is not possible to definitely say they are # valid or not. # The response object is of type: requests.models.Response # extract the status code from it response_obj = err.response if response_obj.status_code == 404: logging.warning( "MD5 cannot be checked if fingerprints are not " "enabled" ) self.unknown = True return True return False return True def validate_for_build(self, filename, job, build): if not self.valid(): log.info("Unknown to jenkins.") return False if self.unknown: # not request error, but unknown to jenkins return True if self._data["original"] is not None: if self._data["original"]["name"] == job: if self._data["original"]["number"] == build: return True if self._data["fileName"] != filename: log.info( msg="Filename from jenkins (%s) did not match provided (%s)" % (self._data["fileName"], filename) ) return False for usage_item in self._data["usage"]: if usage_item["name"] == job: for range_ in usage_item["ranges"]["ranges"]: if range_["start"] <= build <= range_["end"]: msg = ( "This artifact was generated by %s " "between build %i and %i" % (job, range_["start"], range_["end"]) ) log.info(msg=msg) return True return False def validate(self): try: assert self.valid() except AssertionError: raise ArtifactBroken( "Artifact %s seems to be broken, check %s" % (self.id_, self.baseurl) ) except requests.exceptions.HTTPError: raise ArtifactBroken( "Unable to validate artifact id %s using %s" % (self.id_, self.baseurl) ) return True def get_info(self): """ Returns a tuple of build-name, build# and artifact filename for a good build. """ self.poll() return ( self._data["original"]["name"], self._data["original"]["number"], self._data["fileName"], ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/jenkins.py0000644000000000000000000006203300000000000016232 0ustar0000000000000000""" Module for jenkinsapi Jenkins object """ import time import logging import warnings import six.moves.urllib.parse as urlparse from six.moves.urllib.request import Request, HTTPRedirectHandler, build_opener from six.moves.urllib.parse import quote as urlquote from six.moves.urllib.parse import urlencode from requests import HTTPError, ConnectionError from jenkinsapi import config from jenkinsapi.credentials import Credentials from jenkinsapi.credentials import Credentials2x from jenkinsapi.credentials import CredentialsById from jenkinsapi.executors import Executors from jenkinsapi.jobs import Jobs from jenkinsapi.job import Job from jenkinsapi.view import View from jenkinsapi.label import Label from jenkinsapi.nodes import Nodes from jenkinsapi.plugins import Plugins from jenkinsapi.plugin import Plugin from jenkinsapi.utils.requester import Requester from jenkinsapi.views import Views from jenkinsapi.queue import Queue from jenkinsapi.fingerprint import Fingerprint from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.custom_exceptions import JenkinsAPIException from jenkinsapi.utils.crumb_requester import CrumbRequester log = logging.getLogger(__name__) class Jenkins(JenkinsBase): """ Represents a jenkins environment. """ # pylint: disable=too-many-arguments def __init__( self, baseurl, username=None, password=None, requester=None, lazy=False, ssl_verify=True, cert=None, timeout=10, use_crumb=True, max_retries=None, ): """ :param baseurl: baseurl for jenkins instance including port, str :param username: username for jenkins auth, str :param password: password for jenkins auth, str :return: a Jenkins obj """ self.username = username self.password = password if requester is None: if use_crumb: requester = CrumbRequester else: requester = Requester self.requester = requester( username, password, baseurl=baseurl, ssl_verify=ssl_verify, cert=cert, timeout=timeout, max_retries=max_retries, ) else: self.requester = requester self.requester.timeout = timeout self.lazy = lazy self.jobs_container = None JenkinsBase.__init__(self, baseurl, poll=not lazy) def _poll(self, tree=None): url = self.python_api_url(self.baseurl) return self.get_data( url, tree="jobs[name,color,url]" if not tree else tree ) def _poll_if_needed(self): if self.lazy and self._data is None: self.poll() def _clone(self): return Jenkins( self.baseurl, username=self.username, password=self.password, requester=self.requester, ) def base_server_url(self): if config.JENKINS_API in self.baseurl: return self.baseurl[: -(len(config.JENKINS_API))] return self.baseurl def validate_fingerprint(self, id_): obj_fingerprint = Fingerprint(self.baseurl, id_, jenkins_obj=self) obj_fingerprint.validate() log.info(msg="Jenkins says %s is valid" % id_) # def reload(self): # '''Try and reload the configuration from disk''' # self.requester.get_url("%(baseurl)s/reload" % self.__dict__) def get_artifact_data(self, id_): obj_fingerprint = Fingerprint(self.baseurl, id_, jenkins_obj=self) obj_fingerprint.validate() return obj_fingerprint.get_info() def validate_fingerprint_for_build(self, digest, filename, job, build): obj_fingerprint = Fingerprint(self.baseurl, digest, jenkins_obj=self) return obj_fingerprint.validate_for_build(filename, job, build) def get_jenkins_obj(self): return self def get_jenkins_obj_from_url(self, url): return Jenkins(url, self.username, self.password, self.requester) def get_create_url(self): # This only ever needs to work on the base object return "%s/createItem" % self.baseurl def get_nodes_url(self): # This only ever needs to work on the base object return self.nodes.baseurl @property def jobs(self): if self.jobs_container is None: self.jobs_container = Jobs(self) return self.jobs_container def get_jobs(self): """ Fetch all the build-names on this Jenkins server. """ return self.jobs.iteritems() def get_jobs_info(self): """ Get the jobs information :return url, name """ for name, job in self.jobs.iteritems(): yield job.url, name def get_job(self, jobname): """ Get a job by name :param jobname: name of the job, str :return: Job obj """ return self.jobs[jobname] def get_job_by_url(self, url, job_name): """ Get a job by url :param url: jobs' url :param jobname: name of the job, str :return: Job obj """ return Job(url, job_name, self) def has_job(self, jobname): """ Does a job by the name specified exist :param jobname: string :return: boolean """ return jobname in self.jobs def create_job(self, jobname, xml): """ Create a job alternatively you can create job using Jobs object: self.jobs['job_name'] = config :param jobname: name of new job, str :param config: configuration of new job, xml :return: new Job obj """ return self.jobs.create(jobname, xml) def create_multibranch_pipeline_job( self, jobname, xml, block=True, delay=60 ): """ :return: list of new Job objects """ return self.jobs.create_multibranch_pipeline( jobname, xml, block, delay ) def copy_job(self, jobname, newjobname): return self.jobs.copy(jobname, newjobname) def build_job(self, jobname, params=None): """ Invoke a build by job name :param jobname: name of exist job, str :param params: the job params, dict :return: none """ self[jobname].invoke(build_params=params or {}) def delete_job(self, jobname): """ Delete a job by name :param jobname: name of a exist job, str :return: new jenkins_obj """ del self.jobs[jobname] def rename_job(self, jobname, newjobname): """ Rename a job :param jobname: name of a exist job, str :param newjobname: name of new job, str :return: new Job obj """ return self.jobs.rename(jobname, newjobname) def items(self): """ :param return: A list of pairs. Each pair will be (job name, Job object) """ return list(self.iteritems()) def get_jobs_list(self): return self.jobs.keys() def iterkeys(self): return self.jobs.iterkeys() def iteritems(self): return self.jobs.iteritems() def keys(self): return self.jobs.keys() def __str__(self): return "Jenkins server at %s" % self.baseurl @property def views(self): return Views(self) def get_view_by_url(self, str_view_url): # for nested view str_view_name = str_view_url.split("/view/")[-1].replace("/", "") return View(str_view_url, str_view_name, jenkins_obj=self) def delete_view_by_url(self, str_url): url = "%s/doDelete" % str_url self.requester.post_and_confirm_status(url, data="") self.poll() return self def get_label(self, label_name): label_url = "%s/label/%s" % (self.baseurl, label_name) return Label(label_url, label_name, jenkins_obj=self) def __getitem__(self, jobname): """ Get a job by name :param jobname: name of job, str :return: Job obj """ return self.jobs[jobname] def __len__(self): return len(self.jobs) def __contains__(self, jobname): """ Does a job by the name specified exist :param jobname: string :return: boolean """ return jobname in self.jobs def __delitem__(self, job_name): del self.jobs[job_name] def get_node(self, nodename): """Get a node object for a specific node""" return self.nodes[nodename] def get_node_url(self, nodename=""): """Return the url for nodes""" url = urlparse.urljoin( self.base_server_url(), "computer/%s" % urlquote(nodename) ) return url def get_queue_url(self): url = "%s/%s" % (self.base_server_url(), "queue") return url def get_queue(self): queue_url = self.get_queue_url() return Queue(queue_url, self) def get_nodes(self): return Nodes(self.baseurl, self) @property def nodes(self): return self.get_nodes() def has_node(self, nodename): """ Does a node by the name specified exist :param nodename: string, hostname :return: boolean """ self.poll() return nodename in self.nodes def delete_node(self, nodename): """ Remove a node from the managed slave list Please note that you cannot remove the master node :param nodename: string holding a hostname :return: None """ del self.nodes[nodename] def create_node( self, name, num_executors=2, node_description=None, remote_fs="/var/lib/jenkins", labels=None, exclusive=False, ): """ Create a new JNLP slave node by name. To create SSH node, please see description in Node class :param name: fqdn of slave, str :param num_executors: number of executors, int :param node_description: a freetext field describing the node :param remote_fs: jenkins path, str :param labels: labels to associate with slave, str :param exclusive: tied to specific job, boolean :return: node obj """ node_dict = { "num_executors": num_executors, "node_description": node_description, "remote_fs": remote_fs, "labels": labels, "exclusive": exclusive, } return self.nodes.create_node(name, node_dict) def create_node_with_config(self, name, config): """ Create a new slave node with specific configuration. Config should be resemble the output of node.get_node_attributes() :param str name: name of slave :param dict config: Node attributes for Jenkins API request to create node (See function output Node.get_node_attributes()) :return: node obj """ return self.nodes.create_node_with_config(name=name, config=config) def get_plugins_url(self, depth): # This only ever needs to work on the base object return "%s/pluginManager/api/python?depth=%i" % (self.baseurl, depth) def install_plugin( self, plugin, restart=True, force_restart=False, wait_for_reboot=True, no_reboot_warning=False, ): """ Install a plugin and optionally restart jenkins. @param plugin: Plugin (string or Plugin object) to be installed @param restart: Boolean, restart Jenkins when required by plugin @param force_restart: Boolean, force Jenkins to restart, ignoring plugin preferences @param no_warning: Don't show warning when restart is needed and restart parameters are set to False """ if not isinstance(plugin, Plugin): plugin = Plugin(plugin) self.plugins[plugin.shortName] = plugin if force_restart or (restart and self.plugins.restart_required): self.safe_restart(wait_for_reboot=wait_for_reboot) elif self.plugins.restart_required and not no_reboot_warning: warnings.warn( "System reboot is required, but automatic reboot is disabled. " "Please reboot manually." ) def install_plugins( self, plugin_list, restart=True, force_restart=False, wait_for_reboot=True, no_reboot_warning=False, ): """ Install a list of plugins and optionally restart jenkins. @param plugin_list: List of plugins (strings, Plugin objects or a mix of the two) to be installed @param restart: Boolean, restart Jenkins when required by plugin @param force_restart: Boolean, force Jenkins to restart, ignoring plugin preferences """ plugins = [ p if isinstance(p, Plugin) else Plugin(p) for p in plugin_list ] for plugin in plugins: self.install_plugin(plugin, restart=False, no_reboot_warning=True) if force_restart or (restart and self.plugins.restart_required): self.safe_restart(wait_for_reboot=wait_for_reboot) elif self.plugins.restart_required and not no_reboot_warning: warnings.warn( "System reboot is required, but automatic reboot is disabled. " "Please reboot manually." ) def delete_plugin( self, plugin, restart=True, force_restart=False, wait_for_reboot=True, no_reboot_warning=False, ): """ Delete a plugin and optionally restart jenkins. Will not delete dependencies. @param plugin: Plugin (string or Plugin object) to be deleted @param restart: Boolean, restart Jenkins when required by plugin @param force_restart: Boolean, force Jenkins to restart, ignoring plugin preferences """ if isinstance(plugin, Plugin): plugin = plugin.shortName del self.plugins[plugin] if force_restart or (restart and self.plugins.restart_required): self.safe_restart(wait_for_reboot=wait_for_reboot) elif self.plugins.restart_required and not no_reboot_warning: warnings.warn( "System reboot is required, but automatic reboot is disabled. " "Please reboot manually." ) def delete_plugins( self, plugin_list, restart=True, force_restart=False, wait_for_reboot=True, no_reboot_warning=False, ): """ Delete a list of plugins and optionally restart jenkins. Will not delete dependencies. @param plugin_list: List of plugins (strings, Plugin objects or a mix of the two) to be deleted @param restart: Boolean, restart Jenkins when required by plugin @param force_restart: Boolean, force Jenkins to restart, ignoring plugin preferences """ for plugin in plugin_list: self.delete_plugin(plugin, restart=False, no_reboot_warning=True) if force_restart or (restart and self.plugins.restart_required): self.safe_restart(wait_for_reboot=wait_for_reboot) elif self.plugins.restart_required and not no_reboot_warning: warnings.warn( "System reboot is required, but automatic reboot is disabled. " "Please reboot manually." ) def safe_restart(self, wait_for_reboot=True): """restarts jenkins when no jobs are running""" # NB: unlike other methods, the value of resp.status_code # here can be 503 even when everything is normal url = "%s/safeRestart" % (self.baseurl,) valid = self.requester.VALID_STATUS_CODES + [503, 500] resp = self.requester.post_and_confirm_status( url, data="", valid=valid ) if wait_for_reboot: self._wait_for_reboot() return resp def _wait_for_reboot(self): # We need to make sure all jobs have finished, # and that jenkins is actually restarting. # One way to be sure is to make sure jenkins is really down. wait = 5 count = 0 max_count = 30 self.__jenkins_is_unavailable() # Blocks until jenkins is restarting while count < max_count: time.sleep(wait) try: self.poll() len(self.plugins) # Make sure jenkins is fully started return # By this time jenkins is back online except (HTTPError, ConnectionError): msg = ( "Jenkins has not restarted yet! (This is" " try {0} of {1}, waited {2} seconds so far)" " Sleeping and trying again.." ) msg = msg.format(count, max_count, count * wait) log.debug(msg) count += 1 msg = ( "Jenkins did not come back from safe restart! " "Waited %s seconds altogether. This " "failure may cause other failures." ) log.critical(msg, count * wait) def __jenkins_is_unavailable(self): while True: try: self.requester.get_and_confirm_status( self.baseurl, valid=[503, 500] ) return True except ConnectionError: # This is also a possibility while Jenkins is restarting return True except HTTPError: # This is a return code that is not 503, # so Jenkins is likely available time.sleep(1) def safe_exit(self, wait_for_exit=True, max_wait=360): """ Restarts jenkins when no jobs are running, except for pipeline jobs """ # NB: unlike other methods, the value of resp.status_code # here can be 503 even when everything is normal url = "%s/safeExit" % (self.baseurl,) valid = self.requester.VALID_STATUS_CODES + [503, 500] resp = self.requester.post_and_confirm_status( url, data="", valid=valid ) if wait_for_exit: self._wait_for_exit(max_wait=max_wait) return resp def _wait_for_exit(self, max_wait=360): # We need to make sure all non pipeline jobs have finished, # and that jenkins is unavailable self.__jenkins_is_unresponsive(max_wait=max_wait) def __jenkins_is_unresponsive(self, max_wait=360): # Blocks until jenkins returns ConnectionError or JenkinsAPIException # Default wait is one hour is_alive = True wait = 0 while is_alive and wait < max_wait: try: self.requester.get_and_confirm_status( self.baseurl, valid=[200] ) time.sleep(1) wait += 1 is_alive = True except (ConnectionError, JenkinsAPIException): # Jenkins is finally down is_alive = False return True except HTTPError: # This is a return code that is not 503, # so Jenkins is likely available, and we need to wait time.sleep(1) wait += 1 is_alive = True def quiet_down(self): """ Put Jenkins in a Quiet mode, preparation for restart. No new builds started """ # NB: unlike other methods, the value of resp.status_code # here can be 503 even when everything is normal url = "%s/quietDown" % (self.baseurl,) valid = self.requester.VALID_STATUS_CODES + [503, 500] resp = self.requester.post_and_confirm_status( url, data="", valid=valid ) return resp def cancel_quiet_down(self): """Cancel the effect of the quiet-down command""" # NB: unlike other methods, the value of resp.status_code # here can be 503 even when everything is normal url = "%s/cancelQuietDown" % (self.baseurl,) valid = self.requester.VALID_STATUS_CODES + [503, 500] resp = self.requester.post_and_confirm_status( url, data="", valid=valid ) return resp @property def plugins(self): return self.get_plugins() def get_plugins(self, depth=1): url = self.get_plugins_url(depth=depth) return Plugins(url, self) def has_plugin(self, plugin_name): return plugin_name in self.plugins def get_executors(self, nodename): url = "%s/computer/%s" % (self.baseurl, nodename) return Executors(url, nodename, self) def get_master_data(self): url = "%s/computer/api/python" % self.baseurl return self.get_data(url) @property def version(self): """ Return version number of Jenkins """ response = self.requester.get_and_confirm_status(self.baseurl) version_key = "X-Jenkins" return response.headers.get(version_key, "0.0") def get_credentials(self, cred_class=Credentials2x): """ Return credentials """ if "credentials" not in self.plugins: raise JenkinsAPIException("Credentials plugin not installed") if self.plugins["credentials"].version.startswith("1."): url = "%s/credential-store/domain/_/" % self.baseurl return Credentials(url, self) url = "%s/credentials/store/system/domain/_/" % self.baseurl return cred_class(url, self) @property def credentials(self): return self.get_credentials(Credentials2x) @property def credentials_by_id(self): return self.get_credentials(CredentialsById) @property def is_quieting_down(self): url = "%s/api/python?tree=quietingDown" % (self.baseurl,) data = self.get_data(url=url) return data.get("quietingDown", False) def shutdown(self): url = "%s/exit" % self.baseurl self.requester.post_and_confirm_status(url, data="") def generate_new_api_token( self, new_token_name="Token By jenkinsapi python" ): subUrl = ( "/me/descriptorByName/jenkins.security." "ApiTokenProperty/generateNewToken" ) url = "%s%s" % (self.baseurl, subUrl) data = urlencode({"newTokenName": new_token_name}) response = self.requester.post_and_confirm_status(url, data=data) token = response.json()["data"]["tokenValue"] return token def run_groovy_script(self, script): """ Runs the requested groovy script on the Jenkins server returning the result as text. Raises a JenkinsAPIException if the returned HTTP response code from the POST request is not 200 OK. Example: server = Jenkins(...) script = 'println "Hello world!"' result = server.run_groovy_script(script) print(result) # will print "Hello world!" """ url = "%s/scriptText" % self.baseurl data = urlencode({"script": script}) response = self.requester.post_and_confirm_status(url, data=data) if response.status_code != 200: raise JenkinsAPIException( "Unexpected response %d." % response.status_code ) return response.text def use_auth_cookie(self): assert self.username and self.baseurl, ( "Please provide jenkins url, username " "and password to get the session ID cookie." ) login_url = "j_acegi_security_check" jenkins_url = "{0}/{1}".format(self.baseurl, login_url) data = urlencode( {"j_username": self.username, "j_password": self.password} ).encode("utf-8") class SmartRedirectHandler(HTTPRedirectHandler): def extract_cookie(self, setcookie): # Extracts the last cookie. # Example of set-cookie value for python2 # ('set-cookie', 'JSESSIONID.30blah=blahblahblah;Path=/; # HttpOnly, JSESSIONID.30ablah=blahblah;Path=/;HttpOnly'), return setcookie.split(",")[-1].split(";")[0].strip("\n\r ") def http_error_302(self, req, fp, code, msg, headers): # Jenkins can send several Set-Cookie values sometimes # The valid one is the last one for header, value in headers.items(): if header.lower() == "set-cookie": cookie = self.extract_cookie(value) req.headers["Cookie"] = cookie result = HTTPRedirectHandler.http_error_302( self, req, fp, code, msg, headers ) result.orig_status = code result.orig_headers = headers result.cookie = cookie return result request = Request(jenkins_url, data) opener = build_opener(SmartRedirectHandler()) res = opener.open(request) Requester.AUTH_COOKIE = res.cookie ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/jenkinsbase.py0000644000000000000000000000746100000000000017071 0ustar0000000000000000""" Module for JenkinsBase class """ import ast import pprint import logging from six.moves.urllib.parse import quote as urlquote from jenkinsapi import config from jenkinsapi.custom_exceptions import JenkinsAPIException logger = logging.getLogger(__name__) class JenkinsBase(object): """ This appears to be the base object that all other jenkins objects are inherited from """ def __repr__(self): return """<%s.%s %s>""" % ( self.__class__.__module__, self.__class__.__name__, str(self), ) def __str__(self): raise NotImplementedError def __init__(self, baseurl, poll=True): """ Initialize a jenkins connection """ self._data = None self.baseurl = self.strip_trailing_slash(baseurl) if poll: self.poll() def get_jenkins_obj(self): raise NotImplementedError( "Please implement this method on %s" % self.__class__.__name__ ) def __eq__(self, other): """ Return true if the other object represents a connection to the same server """ if not isinstance(other, self.__class__): return False return other.baseurl == self.baseurl @classmethod def strip_trailing_slash(cls, url): while url.endswith("/"): url = url[:-1] return url def poll(self, tree=None): data = self._poll(tree=tree) if "jobs" in data: data["jobs"] = self.resolve_job_folders(data["jobs"]) if not tree: self._data = data return data def _poll(self, tree=None): url = self.python_api_url(self.baseurl) return self.get_data(url, tree=tree) def get_data(self, url, params=None, tree=None): requester = self.get_jenkins_obj().requester if tree: if not params: params = {"tree": tree} else: params.update({"tree": tree}) response = requester.get_url(url, params) if response.status_code != 200: logger.error( "Failed request at %s with params: %s %s", url, params, tree if tree else "", ) response.raise_for_status() try: return ast.literal_eval(response.text) except Exception: logger.exception("Inappropriate content found at %s", url) raise JenkinsAPIException("Cannot parse %s" % response.content) def pprint(self): """ Print out all the data in this object for debugging. """ pprint.pprint(self._data) def resolve_job_folders(self, jobs): for job in list(jobs): if "color" not in job.keys(): jobs.remove(job) jobs += self.process_job_folder(job, self.baseurl) return jobs def process_job_folder(self, folder, folder_path): logger.debug("Processing folder %s in %s", folder["name"], folder_path) folder_path += "/job/%s" % urlquote(folder["name"]) data = self.get_data( self.python_api_url(folder_path), tree="jobs[name,color]" ) result = [] for job in data.get("jobs", []): if "color" not in job.keys(): result += self.process_job_folder(job, folder_path) else: job["url"] = "%s/job/%s" % (folder_path, urlquote(job["name"])) result.append(job) return result @classmethod def python_api_url(cls, url): if url.endswith(config.JENKINS_API): return url else: if url.endswith(r"/"): fmt = "%s%s" else: fmt = "%s/%s" return fmt % (url, config.JENKINS_API) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674739024.6804104 jenkinsapi-0.3.13/jenkinsapi/job.py0000644000000000000000000006464700000000000015360 0ustar0000000000000000""" Module for jenkinsapi Job """ import json import logging import xml.etree.ElementTree as ET import six.moves.urllib.parse as urlparse from collections import defaultdict from jenkinsapi.build import Build from jenkinsapi.custom_exceptions import ( NoBuildData, NotConfiguredSCM, NotFound, NotInQueue, NotSupportSCM, UnknownQueueItem, BadParams, ) from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.mutable_jenkins_thing import MutableJenkinsThing from jenkinsapi.queue import QueueItem from jenkinsapi.utils.compat import to_string SVN_URL = "./scm/locations/hudson.scm.SubversionSCM_-ModuleLocation/remote" GIT_URL = "./scm/userRemoteConfigs/hudson.plugins.git.UserRemoteConfig/url" HG_URL = "./scm/source" GIT_BRANCH = "./scm/branches/hudson.plugins.git.BranchSpec/name" HG_BRANCH = "./scm/branch" DEFAULT_HG_BRANCH_NAME = "default" log = logging.getLogger(__name__) class Job(JenkinsBase, MutableJenkinsThing): """ Represents a jenkins job A job can hold N builds which are the actual execution environments """ def __init__(self, url, name, jenkins_obj): self.name = name self.jenkins = jenkins_obj self._revmap = None self._config = None self._element_tree = None self._scm_prefix = "" self._scm_map = { "hudson.scm.SubversionSCM": "svn", "hudson.plugins.git.GitSCM": "git", "hudson.plugins.mercurial.MercurialSCM": "hg", "hudson.scm.NullSCM": "NullSCM", } self._scmurlmap = { "svn": lambda element_tree: list(element_tree.findall(SVN_URL)), "git": lambda element_tree: list( element_tree.findall(self._scm_prefix + GIT_URL) ), "hg": lambda element_tree: list(element_tree.findall(HG_URL)), None: lambda element_tree: [], } self._scmbranchmap = { "svn": lambda element_tree: [], "git": lambda element_tree: list( element_tree.findall(self._scm_prefix + GIT_BRANCH) ), "hg": self._get_hg_branch, None: lambda element_tree: [], } self.url = url JenkinsBase.__init__(self, self.url) def __str__(self): return self.name def get_description(self): return self._data["description"] def get_jenkins_obj(self): return self.jenkins # When the name of the hg branch used in the job is default hg branch (i.e. # default), Mercurial plugin doesn't store default branch name in # config XML file of the job. Create XML node corresponding to # default branch def _get_hg_branch(self, element_tree): branches = element_tree.findall(HG_BRANCH) if not branches: hg_default_branch = ET.Element("branch") hg_default_branch.text = DEFAULT_HG_BRANCH_NAME branches.append(hg_default_branch) return branches def poll(self, tree=None): data = super(Job, self).poll(tree=tree) if not tree and not self.jenkins.lazy: self._data = self._add_missing_builds(self._data) return data # pylint: disable=E1123 # Unexpected keyword arg 'params' def _add_missing_builds(self, data): """ Query Jenkins to get all builds of the job in the data object. Jenkins API loads the first 100 builds and thus may not contain all builds information. This method checks if all builds are loaded in the data object and updates it with the missing builds if needed. """ if not data.get("builds"): return data # do not call _buildid_for_type here: it would poll and do an infinite # loop oldest_loaded_build_number = data["builds"][-1]["number"] if "firstBuild" not in self._data or not self._data["firstBuild"]: first_build_number = oldest_loaded_build_number else: first_build_number = self._data["firstBuild"]["number"] all_builds_loaded = oldest_loaded_build_number == first_build_number if all_builds_loaded: return data response = self.poll(tree="allBuilds[number,url]") data["builds"] = response["allBuilds"] return data def _get_config_element_tree(self): """ The ElementTree objects creation is unnecessary, it can be a singleton per job """ if self._config is None: self.load_config() if self._element_tree is None: self._element_tree = ET.fromstring(self._config) return self._element_tree def get_build_triggerurl(self): if not self.has_params(): return "%s/build" % self.baseurl return "%s/buildWithParameters" % self.baseurl @staticmethod def _mk_json_from_build_parameters(build_params, file_params=None): """ Build parameters must be submitted in a particular format Key-Value pairs would be far too simple, no no! Watch and read on and behold! """ if not isinstance(build_params, dict): raise ValueError("Build parameters must be a dict") build_p = [ {"name": k, "value": to_string(v)} for k, v in sorted(build_params.items()) ] out = {"parameter": build_p} if file_params: file_p = [{"name": k, "file": k} for k in file_params.keys()] out["parameter"].extend(file_p) if len(out["parameter"]) == 1: out["parameter"] = out["parameter"][0] return out @staticmethod def mk_json_from_build_parameters(build_params, file_params=None): json_structure = Job._mk_json_from_build_parameters( build_params, file_params ) json_structure["statusCode"] = "303" json_structure["redirectTo"] = "." return json.dumps(json_structure) def invoke( self, securitytoken=None, block=False, build_params=None, cause=None, files=None, delay=5, quiet_period=None, ): assert isinstance(block, bool) if build_params and (not self.has_params()): raise BadParams("This job does not support parameters") params = {} # Via Get string if securitytoken: params["token"] = securitytoken # Either copy the params dict or make a new one. build_params = ( dict(build_params.items()) if build_params else {} ) # Via POSTed JSON url = self.get_build_triggerurl() # If quiet period is set, the build will have {quiet_period} seconds # quiet peroid before start. if quiet_period is not None: url += "?delay={0}sec".format(quiet_period) if cause: build_params["cause"] = cause # Build require params as form fields # and as Json. data = { "json": self.mk_json_from_build_parameters(build_params, files) } data.update(build_params) response = self.jenkins.requester.post_and_confirm_status( url, data=data, params=params, files=files, valid=[200, 201, 303], allow_redirects=False, ) redirect_url = response.headers["location"] # # Enterprise Jenkins implementations such as CloudBees locate their # queue REST API base https://server.domain.com/jenkins/queue/api/ # above the team-specific REST API base # https://server.domain.com/jenkins/job/my_team/api/ # queue_baseurl_candidates = [self.jenkins.baseurl] scheme, netloc, path, _, query, frag = urlparse.urlparse( self.jenkins.baseurl ) while path: path = "/".join(path.rstrip("/").split("/")[:-1]) queue_baseurl_candidates.append( urlparse.urlunsplit([scheme, netloc, path, query, frag]) ) redirect_url_valid = False for queue_baseurl_candidate in queue_baseurl_candidates: redirect_url_valid = redirect_url.startswith( "%s/queue/item" % queue_baseurl_candidate ) if redirect_url_valid: break if not redirect_url_valid: raise ValueError("Not a Queue URL: %s" % redirect_url) qi = QueueItem(redirect_url, self.jenkins) if block: qi.block_until_complete(delay=delay) return qi def _buildid_for_type(self, buildtype): """ Gets a buildid for a given type of build """ KNOWNBUILDTYPES = [ "lastStableBuild", "lastSuccessfulBuild", "lastBuild", "lastCompletedBuild", "firstBuild", "lastFailedBuild", ] assert buildtype in KNOWNBUILDTYPES, ( "Unknown build info type: %s" % buildtype ) data = self.poll(tree="%s[number]" % buildtype) if not data.get(buildtype): raise NoBuildData(buildtype) return data[buildtype]["number"] def get_first_buildnumber(self): """ Get the numerical ID of the first build. """ return self._buildid_for_type("firstBuild") def get_last_stable_buildnumber(self): """ Get the numerical ID of the last stable build. """ return self._buildid_for_type("lastStableBuild") def get_last_good_buildnumber(self): """ Get the numerical ID of the last good build. """ return self._buildid_for_type("lastSuccessfulBuild") def get_last_failed_buildnumber(self): """ Get the numerical ID of the last failed build. """ return self._buildid_for_type(buildtype="lastFailedBuild") def get_last_buildnumber(self): """ Get the numerical ID of the last build. """ return self._buildid_for_type("lastBuild") def get_last_completed_buildnumber(self): """ Get the numerical ID of the last complete build. """ return self._buildid_for_type("lastCompletedBuild") def get_build_dict(self): builds = self.poll(tree="builds[number,url]") if not builds: raise NoBuildData(repr(self)) builds = self._add_missing_builds(builds) builds = builds["builds"] last_build = self.poll(tree="lastBuild[number,url]")["lastBuild"] if ( builds and last_build and builds[0]["number"] != last_build["number"] ): builds = [last_build] + builds # FIXME SO how is this supposed to work if build is false-y? # I don't think that builds *can* be false here, so I don't # understand the test above. return dict((build["number"], build["url"]) for build in builds) def get_build_by_params(self, build_params, order=1): first_build_number = self.get_first_buildnumber() last_build_number = self.get_last_buildnumber() if order != 1 and order != -1: raise ValueError( "Direction should be ascending or descending (1/-1)" ) for number in range(first_build_number, last_build_number + 1)[ ::order ]: build = self.get_build(number) if build.get_params() == build_params: return build raise NoBuildData( "No build with such params {params}".format(params=build_params) ) def get_revision_dict(self): """ Get dictionary of all revisions with a list of buildnumbers (int) that used that particular revision """ revs = defaultdict(list) if "builds" not in self._data: raise NoBuildData(repr(self)) for buildnumber in self.get_build_ids(): revs[self.get_build(buildnumber).get_revision()].append( buildnumber ) return revs def get_build_ids(self): """ Return a sorted list of all good builds as ints. """ return reversed(sorted(self.get_build_dict().keys())) def get_next_build_number(self): """ Return the next build number that Jenkins will assign. """ return self._data.get("nextBuildNumber", 0) def get_last_stable_build(self): """ Get the last stable build """ bn = self.get_last_stable_buildnumber() return self.get_build(bn) def get_last_good_build(self): """ Get the last good build """ bn = self.get_last_good_buildnumber() return self.get_build(bn) def get_last_build(self): """ Get the last build """ bn = self.get_last_buildnumber() return self.get_build(bn) def get_first_build(self): bn = self.get_first_buildnumber() return self.get_build(bn) def get_last_build_or_none(self): """ Get the last build or None if there is no builds """ try: return self.get_last_build() except NoBuildData: return None def get_last_completed_build(self): """ Get the last build regardless of status """ bn = self.get_last_completed_buildnumber() return self.get_build(bn) def get_buildnumber_for_revision(self, revision, refresh=False): """ :param revision: subversion revision to look for, int :param refresh: boolean, whether or not to refresh the revision -> buildnumber map :return: list of buildnumbers, [int] """ if self.get_scm_type() == "svn" and not isinstance(revision, int): revision = int(revision) if self._revmap is None or refresh: self._revmap = self.get_revision_dict() try: return self._revmap[revision] except KeyError: raise NotFound("Couldn't find a build with that revision") def get_build(self, buildnumber): assert isinstance(buildnumber, int) try: url = self.get_build_dict()[buildnumber] return Build(url, buildnumber, job=self) except KeyError: raise NotFound("Build #%s not found" % buildnumber) def delete_build(self, build_number): """ Remove build :param int build_number: Build number :raises NotFound: When build is not found """ try: url = self.get_build_dict()[build_number] url = "%s/doDelete" % url self.jenkins.requester.post_and_confirm_status(url, data="") self.jenkins.poll() except KeyError: raise NotFound("Build #%s not found" % build_number) def get_build_metadata(self, buildnumber): """ Get the build metadata for a given build number. For large builds with tons of tests, this method is faster than get_build by returning less data. """ if not isinstance(buildnumber, int): raise ValueError('Parameter "buildNumber" must be int') try: url = self.get_build_dict()[buildnumber] return Build(url, buildnumber, job=self, depth=0) except KeyError: raise NotFound("Build #%s not found" % buildnumber) def __delitem__(self, build_number): self.delete_build(build_number) def __getitem__(self, buildnumber): return self.get_build(buildnumber) def __len__(self): return len(self.get_build_dict()) def is_queued_or_running(self): return self.is_queued() or self.is_running() def is_queued(self): data = self.poll(tree="inQueue") return data.get("inQueue", False) def get_queue_item(self): """ Return a QueueItem if this object is in a queue, otherwise raise an exception """ if not self.is_queued(): raise UnknownQueueItem() q_item = self.poll(tree="queueItem[url]") qi_url = urlparse.urljoin( self.jenkins.baseurl, q_item["queueItem"]["url"] ) return QueueItem(qi_url, self.jenkins) def is_running(self): # self.poll() try: build = self.get_last_build_or_none() if build is not None: return build.is_running() except NoBuildData: log.info( "No build info available for %s, assuming not running.", str(self), ) return False def get_config(self): """ Returns the config.xml from the job """ response = self.jenkins.requester.get_and_confirm_status( "%(baseurl)s/config.xml" % self.__dict__ ) return response.text def load_config(self): self._config = self.get_config() def get_scm_type(self): element_tree = self._get_config_element_tree() scm_element = element_tree.find("scm") if not scm_element: multibranch_scm_prefix = "properties/org.jenkinsci.plugins.\ workflow.multibranch.BranchJobProperty/branch/" multibranch_path = multibranch_scm_prefix + "scm" scm_element = element_tree.find(multibranch_path) if scm_element: # multibranch pipeline. self._scm_prefix = multibranch_scm_prefix scm_class = scm_element.get("class") if scm_element else None scm = self._scm_map.get(scm_class) if not scm: raise NotSupportSCM( 'SCM class "%s" not supported by API for job "%s"' % (scm_class, self.name) ) if scm == "NullSCM": raise NotConfiguredSCM( 'SCM is not configured for job "%s"' % self.name ) return scm def get_scm_url(self): """ Get list of project SCM urls For some SCM's jenkins allow to configure and use number of SCM url's : return: list of SCM urls """ element_tree = self._get_config_element_tree() scm = self.get_scm_type() scm_url_list = [ scm_url.text for scm_url in self._scmurlmap[scm](element_tree) ] return scm_url_list def get_scm_branch(self): """ Get list of SCM branches : return: list of SCM branches """ element_tree = self._get_config_element_tree() scm = self.get_scm_type() return [ scm_branch.text for scm_branch in self._scmbranchmap[scm](element_tree) ] def modify_scm_branch(self, new_branch, old_branch=None): """ Modify SCM ("Source Code Management") branch name for configured job. :param new_branch : new repository branch name to set. If job has multiple branches configured and "old_branch" not provided - method will allways modify first url. :param old_branch (optional): exact value of branch name to be replaced. For some SCM's jenkins allow set multiple branches per job this parameter intended to indicate which branch need to be modified """ element_tree = self._get_config_element_tree() scm = self.get_scm_type() scm_branch_list = self._scmbranchmap[scm](element_tree) if scm_branch_list and not old_branch: scm_branch_list[0].text = new_branch self.update_config(ET.tostring(element_tree)) else: for scm_branch in scm_branch_list: if scm_branch.text == old_branch: scm_branch.text = new_branch self.update_config(ET.tostring(element_tree)) def modify_scm_url(self, new_source_url, old_source_url=None): """ Modify SCM ("Source Code Management") url for configured job. :param new_source_url : new repository url to set. If job has multiple repositories configured and "old_source_url" not provided - method will allways modify first url. :param old_source_url (optional): for some SCM's jenkins allows settting multiple repositories per job this parameter intended to indicate which repository need to be modified """ element_tree = self._get_config_element_tree() scm = self.get_scm_type() scm_url_list = self._scmurlmap[scm](element_tree) if scm_url_list and not old_source_url: scm_url_list[0].text = new_source_url self.update_config(ET.tostring(element_tree)) else: for scm_url in scm_url_list: if scm_url.text == old_source_url: scm_url.text = new_source_url self.update_config(ET.tostring(element_tree)) def get_config_xml_url(self): return "%s/config.xml" % self.baseurl def update_config(self, config, full_response=False): """ Update the config.xml to the job Also refresh the ElementTree object since the config has changed :param full_response (optional): if True, it will return the full response object instead of just the response text. Useful for debugging and validation workflows. """ url = self.get_config_xml_url() config = str(config) # cast unicode in case of Python 2 response = self.jenkins.requester.post_url(url, params={}, data=config) self._element_tree = ET.fromstring(config) if full_response: return response return response.text def get_downstream_jobs(self): """ Get all the possible downstream jobs :return List of Job """ downstream_jobs = [] try: for j in self._data["downstreamProjects"]: downstream_jobs.append(self.get_jenkins_obj()[j["name"]]) except KeyError: return [] return downstream_jobs def get_downstream_job_names(self): """ Get all the possible downstream job names :return List of String """ downstream_jobs = [] try: for j in self._data["downstreamProjects"]: downstream_jobs.append(j["name"]) except KeyError: return [] return downstream_jobs def get_upstream_job_names(self): """ Get all the possible upstream job names :return List of String """ upstream_jobs = [] try: for j in self._data["upstreamProjects"]: upstream_jobs.append(j["name"]) except KeyError: return [] return upstream_jobs def get_upstream_jobs(self): """ Get all the possible upstream jobs :return List of Job """ upstream_jobs = [] try: for j in self._data["upstreamProjects"]: upstream_jobs.append(self.get_jenkins_obj().get_job(j["name"])) except KeyError: return [] return upstream_jobs def is_enabled(self): data = self.poll(tree="color") return "disabled" not in data.get("color", "") def disable(self): """ Disable job """ url = "%s/disable" % self.baseurl return self.get_jenkins_obj().requester.post_url(url, data="") def enable(self): """ Enable job """ url = "%s/enable" % self.baseurl return self.get_jenkins_obj().requester.post_url(url, data="") def delete_from_queue(self): """ Delete a job from the queue only if it's enqueued :raise NotInQueue if the job is not in the queue """ if not self.is_queued(): raise NotInQueue() queue_id = self._data["queueItem"]["id"] url = urlparse.urljoin( self.get_jenkins_obj().get_queue().baseurl, "queue/cancelItem?id=%s" % queue_id, ) self.get_jenkins_obj().requester.post_and_confirm_status(url, data="") return True def get_params(self): """ Get the parameters for this job. Format varies by parameter type. Here is an example string parameter: { 'type': 'StringParameterDefinition', 'description': 'Parameter description', 'defaultParameterValue': {'value': 'default value'}, 'name': 'FOO_BAR' } """ places = ["actions", "property"] found_definitions = False for place in places: if found_definitions: return actions = (x for x in self._data[place] if x is not None) for action in actions: try: for param in action["parameterDefinitions"]: found_definitions = True yield param except KeyError: continue def get_params_list(self): """ Gets the list of parameter names for this job. """ return [param["name"] for param in self.get_params()] def has_params(self): """ If job has parameters, returns True, else False """ if any( "parameterDefinitions" in a for a in (self._data["actions"]) if a ): return True if any( "parameterDefinitions" in a for a in (self._data["property"]) if a ): return True return False def has_queued_build(self, build_params): """ Returns True if a build with build_params is currently queued. """ queue = self.jenkins.get_queue() queued_builds = queue.get_queue_items_for_job(self.name) for build in queued_builds: if build.get_parameters() == build_params: return True return False @staticmethod def get_full_name_from_url_and_baseurl(url, baseurl): """ Get the full name for a job (including parent folders) from the job URL. """ path = url.replace(baseurl, "") split = path.split("/") split = [urlparse.unquote(part) for part in split[::2] if part] return "/".join(split) def get_full_name(self): """ Get the full name for a job (including parent folders) from the job URL. """ return Job.get_full_name_from_url_and_baseurl( self.url, self.jenkins.baseurl ) def toggle_keep_build(self, build_number): self.get_build(build_number).toggle_keep() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/jobs.py0000644000000000000000000002153500000000000015530 0ustar0000000000000000""" This module implements the Jobs class, which is intended to be a container-like interface for all of the jobs defined on a single Jenkins server. """ import logging import time from jenkinsapi.job import Job from jenkinsapi.custom_exceptions import JenkinsAPIException, UnknownJob log = logging.getLogger(__name__) class Jobs(object): """ This class provides a container-like API which gives access to all jobs defined on the Jenkins server. It behaves like a dict in which keys are Job-names and values are actual jenkinsapi.Job objects. """ def __init__(self, jenkins): self.jenkins = jenkins self._data = [] def _del_data(self, job_name): if not self._data: return for num, job_data in enumerate(self._data): if job_data["name"] == job_name: del self._data[num] return def __len__(self): return len(self.keys()) def poll(self, tree="jobs[name,color,url]"): return self.jenkins.poll(tree=tree) def __delitem__(self, job_name): """ Delete a job by name :param str job_name: name of a existing job :raises JenkinsAPIException: When job is not deleted """ if job_name in self: try: delete_job_url = self[job_name].get_delete_url() self.jenkins.requester.post_and_confirm_status( delete_job_url, data="some random bytes..." ) self._del_data(job_name) except JenkinsAPIException: # Sometimes jenkins throws NPE when removing job # It removes job ok, but it is good to be sure # so we re-try if job was not deleted if job_name in self: delete_job_url = self[job_name].get_delete_url() self.jenkins.requester.post_and_confirm_status( delete_job_url, data="some random bytes..." ) self._del_data(job_name) def __setitem__(self, key, value): """ Create Job :param str key: Job name :param str value: XML configuration of the job .. code-block:: python api = Jenkins('http://localhost:8080/') new_job = api.jobs['my_new_job'] = config_xml """ return self.create(key, value) def __getitem__(self, job_name): if job_name in self: job_data = [ job_row for job_row in self._data if job_row["name"] == job_name or Job.get_full_name_from_url_and_baseurl( job_row["url"], self.jenkins.baseurl ) == job_name ][0] return Job(job_data["url"], job_data["name"], self.jenkins) else: raise UnknownJob(job_name) def iteritems(self): """ Iterate over the names & objects for all jobs """ for job in self.itervalues(): if job.name != job.get_full_name(): yield job.get_full_name(), job else: yield job.name, job def __contains__(self, job_name): """ True if job_name exists in Jenkins """ return job_name in self.keys() def iterkeys(self): """ Iterate over the names of all available jobs """ if not self._data: self._data = self.poll().get("jobs", []) for row in self._data: if row["name"] != Job.get_full_name_from_url_and_baseurl( row["url"], self.jenkins.baseurl ): yield Job.get_full_name_from_url_and_baseurl( row["url"], self.jenkins.baseurl ) else: yield row["name"] def itervalues(self): """ Iterate over all available jobs """ if not self._data: self._data = self.poll().get("jobs", []) for row in self._data: yield Job(row["url"], row["name"], self.jenkins) def keys(self): """ Return a list of the names of all jobs """ return list(self.iterkeys()) def create(self, job_name, config): """ Create a job :param str jobname: Name of new job :param str config: XML configuration of new job :returns Job: new Job object """ if job_name in self: return self[job_name] if not config: raise JenkinsAPIException("Job XML config cannot be empty") params = {"name": job_name} try: if isinstance( config, unicode ): # pylint: disable=undefined-variable config = str(config) except NameError: # Python2 already a str pass self.jenkins.requester.post_xml_and_confirm_status( self.jenkins.get_create_url(), data=config, params=params ) # Reset to get it refreshed from Jenkins self._data = [] return self[job_name] def create_multibranch_pipeline( self, job_name, config, block=True, delay=60 ): """ Create a multibranch pipeline job :param str jobname: Name of new job :param str config: XML configuration of new job :param block: block until scan is finished? :param delay: max delay to wait for scan to finish (seconds) :returns list of new Jobs after scan """ if not config: raise JenkinsAPIException("Job XML config cannot be empty") params = {"name": job_name} try: if isinstance( config, unicode ): # pylint: disable=undefined-variable config = str(config) except NameError: # Python2 already a str pass self.jenkins.requester.post_xml_and_confirm_status( self.jenkins.get_create_url(), data=config, params=params ) # Reset to get it refreshed from Jenkins self._data = [] # Launch a first scan / indexing to discover the branches... self.jenkins.requester.post_and_confirm_status( "{}/job/{}/build".format(self.jenkins.baseurl, job_name), data="", valid=[200, 302], # expect 302 without redirects allow_redirects=False, ) start_time = time.time() # redirect-url does not work with indexing; # so the only workaround found is to parse the console output # until scan has finished. scan_finished = False while not scan_finished and block and time.time() < start_time + delay: indexing_console_text = self.jenkins.requester.get_url( "{}/job/{}/indexing/consoleText".format( self.jenkins.baseurl, job_name ) ) if ( indexing_console_text.text.strip() .split("\n")[-1] .startswith("Finished:") ): scan_finished = True time.sleep(1) # now search for all jobs created; those who start with job_name + '/' jobs = [] for name in self.jenkins.get_jobs_list(): if name.startswith(job_name + "/"): jobs.append(self[name]) return jobs def copy(self, job_name, new_job_name): """ Copy a job :param str job_name: Name of an existing job :param new_job_name: Name of new job :returns Job: new Job object """ params = {"name": new_job_name, "mode": "copy", "from": job_name} self.jenkins.requester.post_and_confirm_status( self.jenkins.get_create_url(), params=params, data="" ) self._data = [] return self[new_job_name] def rename(self, job_name, new_job_name): """ Rename a job :param str job_name: Name of an existing job :param str new_job_name: Name of new job :returns Job: new Job object """ params = {"newName": new_job_name} rename_job_url = self[job_name].get_rename_url() self.jenkins.requester.post_and_confirm_status( rename_job_url, params=params, data="" ) self._data = [] return self[new_job_name] def build(self, job_name, params=None, **kwargs): """ Executes build of a job :param str job_name: Job name :param dict params: Job parameters :param kwargs: Parameters for Job.invoke() function :returns QueueItem: Object to track build progress """ if params: assert isinstance(params, dict) return self[job_name].invoke(build_params=params, **kwargs) return self[job_name].invoke(**kwargs) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/label.py0000644000000000000000000000250100000000000015642 0ustar0000000000000000""" Module for jenkinsapi labels """ from jenkinsapi.jenkinsbase import JenkinsBase import logging log = logging.getLogger(__name__) class Label(JenkinsBase): """ Class to hold information on labels that tied to a collection of jobs """ def __init__(self, baseurl, labelname, jenkins_obj): """ Init a label object by providing all relevant pointers to it :param baseurl: basic url for querying information on a node :param labelname: name of the label :param jenkins_obj: ref to the jenkins obj :return: Label obj """ self.labelname = labelname self.jenkins = jenkins_obj self.baseurl = baseurl JenkinsBase.__init__(self, baseurl) def __str__(self): return "%s" % (self.labelname) def get_jenkins_obj(self): return self.jenkins def is_online(self): return not self.poll(tree="offline")["offline"] def get_tied_jobs(self): """ Get a list of jobs. """ if self.get_tied_job_names(): for job in self.get_tied_job_names(): yield self.get_jenkins_obj().get_job(job["name"]) def get_tied_job_names(self): """ Get a list of the name of tied jobs. """ return self.poll(tree="tiedJobs[name]")["tiedJobs"] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/mutable_jenkins_thing.py0000644000000000000000000000047500000000000021136 0ustar0000000000000000""" Module for MutableJenkinsThing """ class MutableJenkinsThing(object): """ A mixin for certain mutable objects which can be renamed and deleted. """ def get_delete_url(self): return "%s/doDelete" % self.baseurl def get_rename_url(self): return "%s/doRename" % self.baseurl ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/node.py0000644000000000000000000004332200000000000015516 0ustar0000000000000000""" Module for jenkinsapi Node class """ import json import logging import xml.etree.ElementTree as ET import time from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.custom_exceptions import PostRequired, TimeOut from jenkinsapi.custom_exceptions import JenkinsAPIException from six.moves.urllib.parse import quote as urlquote log = logging.getLogger(__name__) class Node(JenkinsBase): """ Class to hold information on nodes that are attached as slaves to the master jenkins instance """ def __init__(self, jenkins_obj, baseurl, nodename, node_dict, poll=True): """ Init a node object by providing all relevant pointers to it :param jenkins_obj: ref to the jenkins obj :param baseurl: basic url for querying information on a node If url is not set - object will construct it itself. This is useful when node is being created and not exists in Jenkins yet :param nodename: hostname of the node :param dict node_dict: Dict with node parameters as described below :param bool poll: set to False if node does not exist or automatic refresh from Jenkins is not required. Default is True. If baseurl parameter is set to None - poll parameter will be set to False JNLP Node: { 'num_executors': int, 'node_description': str, 'remote_fs': str, 'labels': str, 'exclusive': bool } SSH Node: { 'num_executors': int, 'node_description': str, 'remote_fs': str, 'labels': str, 'exclusive': bool, 'host': str, 'port': int 'credential_description': str, 'jvm_options': str, 'java_path': str, 'prefix_start_slave_cmd': str, 'suffix_start_slave_cmd': str 'max_num_retries': int, 'retry_wait_time': int, 'retention': str ('Always' or 'OnDemand') 'ondemand_delay': int (only for OnDemand retention) 'ondemand_idle_delay': int (only for OnDemand retention) 'env': [ { 'key':'TEST', 'value':'VALUE' }, { 'key':'TEST2', 'value':'value2' } ], 'tool_location': [ { "key": "hudson.tasks.Maven$MavenInstallation$DescriptorImpl@Maven 3.0.5", # noqa "home": "/home/apache-maven-3.0.5/" }, { "key": "hudson.plugins.git.GitTool$DescriptorImpl@Default", "home": "/home/git-3.0.5/" }, ] } :return: None :return: Node obj """ self.name = nodename self.jenkins = jenkins_obj if not baseurl: poll = False baseurl = "%s/computer/%s" % (self.jenkins.baseurl, self.name) JenkinsBase.__init__(self, baseurl, poll=poll) self.node_attributes = node_dict self._element_tree = None self._config = None def get_node_attributes(self): """ Gets node attributes as dict Used by Nodes object when node is created :return: Node attributes dict formatted for Jenkins API request to create node """ na = self.node_attributes if not na.get("credential_description", False): # If credentials description is not present - we will create # JNLP node launcher = {"stapler-class": "hudson.slaves.JNLPLauncher"} else: try: credential = self.jenkins.credentials[ na["credential_description"] ] except KeyError: raise JenkinsAPIException( 'Credential with description "%s"' " not found" % na["credential_description"] ) retries = na["max_num_retries"] if "max_num_retries" in na else "" re_wait = na["retry_wait_time"] if "retry_wait_time" in na else "" launcher = { "stapler-class": "hudson.plugins.sshslaves.SSHLauncher", "$class": "hudson.plugins.sshslaves.SSHLauncher", "host": na["host"], "port": na["port"], "credentialsId": credential.credential_id, "jvmOptions": na["jvm_options"], "javaPath": na["java_path"], "prefixStartSlaveCmd": na["prefix_start_slave_cmd"], "suffixStartSlaveCmd": na["suffix_start_slave_cmd"], "maxNumRetries": retries, "retryWaitTime": re_wait, } retention = { "stapler-class": "hudson.slaves.RetentionStrategy$Always", "$class": "hudson.slaves.RetentionStrategy$Always", } if "retention" in na and na["retention"].lower() == "ondemand": retention = { "stapler-class": "hudson.slaves.RetentionStrategy$Demand", "$class": "hudson.slaves.RetentionStrategy$Demand", "inDemandDelay": na["ondemand_delay"], "idleDelay": na["ondemand_idle_delay"], } node_props = {"stapler-class-bag": "true"} if "env" in na: node_props.update( { "hudson-slaves-EnvironmentVariablesNodeProperty": { "env": na["env"] } } ) if "tool_location" in na: node_props.update( { "hudson-tools-ToolLocationNodeProperty": { "locations": na["tool_location"] } } ) params = { "name": self.name, "type": "hudson.slaves.DumbSlave$DescriptorImpl", "json": json.dumps( { "name": self.name, "nodeDescription": na.get("node_description", ""), "numExecutors": na["num_executors"], "remoteFS": na["remote_fs"], "labelString": na["labels"], "mode": "EXCLUSIVE" if na["exclusive"] else "NORMAL", "retentionStrategy": retention, "type": "hudson.slaves.DumbSlave", "nodeProperties": node_props, "launcher": launcher, } ), } return params def get_jenkins_obj(self): return self.jenkins def __str__(self): return self.name def is_online(self): return not self.poll(tree="offline")["offline"] def is_temporarily_offline(self): return self.poll(tree="temporarilyOffline")["temporarilyOffline"] def is_jnlpagent(self): return self._data["jnlpAgent"] def is_idle(self): return self.poll(tree="idle")["idle"] def set_online(self): """ Set node online. Before change state verify client state: if node set 'offline' but 'temporarilyOffline' is not set - client has connection problems and AssertionError raised. If after run node state has not been changed raise AssertionError. """ self.poll() # Before change state check if client is connected if self._data["offline"] and not self._data["temporarilyOffline"]: raise AssertionError( "Node is offline and not marked as " "temporarilyOffline, check client " "connection: offline = %s, " "temporarilyOffline = %s" % (self._data["offline"], self._data["temporarilyOffline"]) ) if self._data["offline"] and self._data["temporarilyOffline"]: self.toggle_temporarily_offline() if self._data["offline"]: raise AssertionError( "The node state is still offline, " "check client connection:" " offline = %s, " "temporarilyOffline = %s" % (self._data["offline"], self._data["temporarilyOffline"]) ) def set_offline(self, message="requested from jenkinsapi"): """ Set node offline. If after run node state has not been changed raise AssertionError. : param message: optional string explain why you are taking this node offline """ if not self._data["offline"]: self.toggle_temporarily_offline(message) data = self.poll(tree="offline,temporarilyOffline") if not data["offline"]: raise AssertionError( "The node state is still online:" + "offline = %s , temporarilyOffline = %s" % (data["offline"], data["temporarilyOffline"]) ) def toggle_temporarily_offline(self, message="requested from jenkinsapi"): """ Switches state of connected node (online/offline) and set 'temporarilyOffline' property (True/False) Calling the same method again will bring node status back. :param message: optional string can be used to explain why you are taking this node offline """ initial_state = self.is_temporarily_offline() url = ( self.baseurl + "/toggleOffline?offlineMessage=" + urlquote(message) ) try: html_result = self.jenkins.requester.get_and_confirm_status(url) except PostRequired: html_result = self.jenkins.requester.post_and_confirm_status( url, data={} ) self.poll() log.debug(html_result) state = self.is_temporarily_offline() if initial_state == state: raise AssertionError( "The node state has not changed: temporarilyOffline = %s" % state ) def update_offline_reason(self, reason): """ Update offline reason on a temporary offline clsuter """ if self.is_temporarily_offline(): url = ( self.baseurl + "/changeOfflineCause?offlineMessage=" + urlquote(reason) ) self.jenkins.requester.post_and_confirm_status(url, data={}) def offline_reason(self): return self._data["offlineCauseReason"] @property def _et(self): return self._get_config_element_tree() def _get_config_element_tree(self): """ Returns an xml element tree for the node's config.xml. The resulting tree is cached for quick lookup. """ if self._config is None: self.load_config() if self._element_tree is None: self._element_tree = ET.fromstring(self._config) return self._element_tree def get_config(self): """ Returns the config.xml from the node. """ response = self.jenkins.requester.get_and_confirm_status( "%(baseurl)s/config.xml" % self.__dict__ ) return response.text def load_config(self): """ Loads the config.xml for the node allowing it to be re-queried without generating new requests. """ if self.name == "Built-In Node": raise JenkinsAPIException("Built-In node does not have config.xml") self._config = self.get_config() self._get_config_element_tree() def upload_config(self, config_xml): """ Uploads config_xml to the config.xml for the node. """ if self.name == "Built-In Node": raise JenkinsAPIException("Built-In node does not have config.xml") self.jenkins.requester.post_and_confirm_status( "%(baseurl)s/config.xml" % self.__dict__, data=config_xml ) def get_labels(self): """ Returns the labels for a slave as a string with each label separated by the ' ' character. """ return self.get_config_element("label") def get_num_executors(self): try: return self.get_config_element("numExecutors") except JenkinsAPIException: return self._data["numExecutors"] def set_num_executors(self, value): """ Sets number of executors for node Warning! Setting number of executors on master node will erase all other settings """ set_value = value if isinstance(value, str) else str(value) if self.name == "Built-In Node": # master node doesn't have config.xml, so we're going to submit # form here data = "json=%s" % urlquote( json.dumps( { "numExecutors": set_value, "nodeProperties": {"stapler-class-bag": "true"}, } ) ) url = self.baseurl + "/configSubmit" self.jenkins.requester.post_and_confirm_status(url, data=data) else: self.set_config_element("numExecutors", set_value) self.poll() def get_config_element(self, el_name): """ Returns simple config element. Better not to be used to return "nodeProperties" or "launcher" """ return self._et.find(el_name).text def set_config_element(self, el_name, value): """ Sets simple config element """ self._et.find(el_name).text = value xml_str = ET.tostring(self._et) self.upload_config(xml_str) def get_monitor(self, monitor_name, poll_monitor=True): """ Polls the node returning one of the monitors in the monitorData branch of the returned node api tree. """ monitor_data_key = "monitorData" if poll_monitor: # polling as monitors like response time can be updated monitor_data = self.poll(tree=monitor_data_key)[monitor_data_key] else: monitor_data = self._data[monitor_data_key] full_monitor_name = "hudson.node_monitors.{0}".format(monitor_name) if full_monitor_name not in monitor_data: raise AssertionError("Node monitor %s not found" % monitor_name) return monitor_data[full_monitor_name] def get_available_physical_memory(self): """ Returns the node's available physical memory in bytes. """ monitor_data = self.get_monitor("SwapSpaceMonitor") return monitor_data["availablePhysicalMemory"] def get_available_swap_space(self): """ Returns the node's available swap space in bytes. """ monitor_data = self.get_monitor("SwapSpaceMonitor") return monitor_data["availableSwapSpace"] def get_total_physical_memory(self): """ Returns the node's total physical memory in bytes. """ monitor_data = self.get_monitor("SwapSpaceMonitor") return monitor_data["totalPhysicalMemory"] def get_total_swap_space(self): """ Returns the node's total swap space in bytes. """ monitor_data = self.get_monitor("SwapSpaceMonitor") return monitor_data["totalSwapSpace"] def get_workspace_path(self): """ Returns the local path to the node's Jenkins workspace directory. """ monitor_data = self.get_monitor("DiskSpaceMonitor") return monitor_data["path"] def get_workspace_size(self): """ Returns the size in bytes of the node's Jenkins workspace directory. """ monitor_data = self.get_monitor("DiskSpaceMonitor") return monitor_data["size"] def get_temp_path(self): """ Returns the local path to the node's temp directory. """ monitor_data = self.get_monitor("TemporarySpaceMonitor") return monitor_data["path"] def get_temp_size(self): """ Returns the size in bytes of the node's temp directory. """ monitor_data = self.get_monitor("TemporarySpaceMonitor") return monitor_data["size"] def get_architecture(self): """ Returns the system architecture of the node eg. "Linux (amd64)". """ # no need to poll as the architecture will never change return self.get_monitor("ArchitectureMonitor", poll_monitor=False) def block_until_idle(self, timeout, poll_time=5): """ Blocks until the node become idle. :param timeout: Time in second when the wait is aborted. :param poll_time: Interval in seconds between each check. :@raise TimeOut """ start_time = time.time() while not self.is_idle() and (time.time() - start_time) < timeout: log.debug( "Waiting for the node to become idle. Elapsed time: %s", (time.time() - start_time), ) time.sleep(poll_time) if not self.is_idle(): raise TimeOut( "The node has not become idle after {} minutes.".format( timeout / 60 ) ) def get_response_time(self): """ Returns the node's average response time. """ monitor_data = self.get_monitor("ResponseTimeMonitor") return monitor_data["average"] def get_clock_difference(self): """ Returns the difference between the node's clock and the master Jenkins clock. Used to detect out of sync clocks. """ monitor_data = self.get_monitor("ClockMonitor") return monitor_data["diff"] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/nodes.py0000644000000000000000000001334200000000000015700 0ustar0000000000000000""" Module for jenkinsapi nodes """ import logging from six.moves.urllib.parse import urlencode from jenkinsapi.node import Node from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.custom_exceptions import JenkinsAPIException from jenkinsapi.custom_exceptions import UnknownNode from jenkinsapi.custom_exceptions import PostRequired log = logging.getLogger(__name__) class Nodes(JenkinsBase): """ Class to hold information on a collection of nodes """ def __init__(self, baseurl, jenkins_obj): """ Handy access to all of the nodes on your Jenkins server """ self.jenkins = jenkins_obj JenkinsBase.__init__( self, baseurl.rstrip("/") if "/computer" in baseurl else baseurl.rstrip("/") + "/computer", ) def get_jenkins_obj(self): return self.jenkins def __str__(self): return "Nodes @ %s" % self.baseurl def __contains__(self, node_name): return node_name in self.keys() def iterkeys(self): """ Return an iterator over the container's node names. Using iterkeys() while creating nodes may raise a RuntimeError or fail to iterate over all entries. """ for item in self._data["computer"]: yield item["displayName"] def keys(self): """ Return a copy of the container's list of node names. """ return list(self.iterkeys()) def _make_node(self, nodename): """ Creates an instance of Node for the given nodename. This function assumes the returned node exists. """ if nodename.lower() == "built-in node": nodeurl = "%s/(%s)" % (self.baseurl, "built-in") else: nodeurl = "%s/%s" % (self.baseurl, nodename) return Node(self.jenkins, nodeurl, nodename, node_dict={}) def iteritems(self): """ Return an iterator over the container's (name, node) pairs. Using iteritems() while creating nodes may raise a RuntimeError or fail to iterate over all entries. """ for item in self._data["computer"]: nodename = item["displayName"] try: yield nodename, self._make_node(nodename) except Exception: raise JenkinsAPIException("Unable to iterate nodes") def items(self): """ Return a copy of the container's list of (name, node) pairs. """ return list(self.iteritems()) def itervalues(self): """ Return an iterator over the container's nodes. Using itervalues() while creating nodes may raise a RuntimeError or fail to iterate over all entries. """ for item in self._data["computer"]: try: yield self._make_node(item["displayName"]) except Exception: raise JenkinsAPIException("Unable to iterate nodes") def values(self): """ Return a copy of the container's list of nodes. """ return list(self.itervalues()) def __getitem__(self, nodename): if nodename in self: return self._make_node(nodename) raise UnknownNode(nodename) def __len__(self): return len(self.keys()) def __delitem__(self, item): if item in self and item != "Built-In Node": url = "%s/doDelete" % self[item].baseurl try: self.jenkins.requester.get_and_confirm_status(url) except PostRequired: # Latest Jenkins requires POST here. GET kept for compatibility self.jenkins.requester.post_and_confirm_status(url, data={}) self.poll() else: if item != "Built-In Node": raise UnknownNode("Node %s does not exist" % item) log.info("Requests to remove built-in node ignored") def __setitem__(self, name, node_dict): if not isinstance(node_dict, dict): raise ValueError('"node_dict" parameter must be a Node dict') if name not in self: self.create_node(name, node_dict) self.poll() def create_node(self, name, node_dict): """ Create a new slave node :param str name: name of slave :param dict node_dict: node dict (See Node class) :return: node obj """ if name in self: return self[name] node = Node( jenkins_obj=self.jenkins, baseurl=None, nodename=name, node_dict=node_dict, poll=False, ) url = "%s/computer/doCreateItem?%s" % ( self.jenkins.baseurl, urlencode(node.get_node_attributes()), ) data = {"json": urlencode(node.get_node_attributes())} self.jenkins.requester.post_and_confirm_status(url, data=data) self.poll() return self[name] def create_node_with_config(self, name, config): """ Create a new slave node with specific configuration. Config should be resemble the output of node.get_node_attributes() :param str name: name of slave :param dict config: Node attributes for Jenkins API request to create node (See function output Node.get_node_attributes()) :return: node obj """ if name in self: return self[name] if not isinstance(config, dict): return None url = "%s/computer/doCreateItem?%s" % ( self.jenkins.baseurl, urlencode(config), ) data = {"json": urlencode(config)} self.jenkins.requester.post_and_confirm_status(url, data=data) self.poll() return self[name] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/plugin.py0000644000000000000000000000424700000000000016072 0ustar0000000000000000""" Module for jenkinsapi Plugin """ class Plugin(object): """ Plugin class """ def __init__(self, plugin_dict): if isinstance(plugin_dict, dict): self.__dict__ = plugin_dict else: self.__dict__ = self.to_plugin(plugin_dict) def to_plugin(self, plugin_string): plugin_string = str(plugin_string) if "@" not in plugin_string or len(plugin_string.split("@")) != 2: usage_err = ( "plugin specification must be a string like " '"plugin-name@version", not "{0}"' ) usage_err = usage_err.format(plugin_string) raise ValueError(usage_err) shortName, version = plugin_string.split("@") return {"shortName": shortName, "version": version} def __eq__(self, other): return self.__dict__ == other.__dict__ def __str__(self): return self.shortName def __repr__(self): return "<%s.%s %s>" % ( self.__class__.__module__, self.__class__.__name__, str(self), ) def get_attributes(self): """ Used by Plugins object to install plugins in Jenkins """ return ' ' % ( self.shortName, self.version, ) def is_latest(self, update_center_dict): """ Used by Plugins object to determine if plugin can be installed through the update center (when plugin version is latest version), or must be installed by uploading the plugin hpi file. """ if self.version == "latest": return True center_plugin = update_center_dict["plugins"][self.shortName] return center_plugin["version"] == self.version def get_download_link(self, update_center_dict): latest_version = update_center_dict["plugins"][self.shortName][ "version" ] latest_url = update_center_dict["plugins"][self.shortName]["url"] return latest_url.replace( "/".join((self.shortName, latest_version)), "/".join((self.shortName, self.version)), ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/plugins.py0000644000000000000000000002501600000000000016252 0ustar0000000000000000""" jenkinsapi plugins """ from __future__ import print_function import logging import time import re try: from StringIO import StringIO from urllib import urlencode except ImportError: # Python3 from io import BytesIO as StringIO from urllib.parse import urlencode import json import requests from jenkinsapi.plugin import Plugin from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.custom_exceptions import UnknownPlugin from jenkinsapi.custom_exceptions import JenkinsAPIException from jenkinsapi.utils.jsonp_to_json import jsonp_to_json from jenkinsapi.utils.manifest import read_manifest log = logging.getLogger(__name__) class Plugins(JenkinsBase): """ Plugins class for jenkinsapi """ def __init__(self, url, jenkins_obj): self.jenkins_obj = jenkins_obj JenkinsBase.__init__(self, url) # print('DEBUG: Plugins._data=', self._data) def get_jenkins_obj(self): return self.jenkins_obj def check_updates_server(self): url = "%s/pluginManager/checkUpdatesServer" % self.jenkins_obj.baseurl self.jenkins_obj.requester.post_and_confirm_status( url, params={}, data={} ) @property def update_center_dict(self): update_center = "https://updates.jenkins.io/update-center.json" jsonp = requests.get(update_center).content.decode("utf-8") return json.loads(jsonp_to_json(jsonp)) def _poll(self, tree=None): return self.get_data(self.baseurl, tree=tree) def keys(self): return self.get_plugins_dict().keys() __iter__ = keys def iteritems(self): return self._get_plugins() def values(self): return [a[1] for a in self.iteritems()] def _get_plugins(self): if "plugins" in self._data: for p_dict in self._data["plugins"]: yield p_dict["shortName"], Plugin(p_dict) def get_plugins_dict(self): return dict(self._get_plugins()) def __len__(self): return len(self.get_plugins_dict().keys()) def __getitem__(self, plugin_name): try: return self.get_plugins_dict()[plugin_name] except KeyError: raise UnknownPlugin(plugin_name) def __setitem__(self, shortName, plugin): """ Installs plugin in Jenkins. If plugin already exists - this method is going to uninstall the existing plugin and install the specified version if it is not already installed. :param shortName: Plugin ID :param plugin a Plugin object to be installed. """ if self.plugin_version_already_installed(plugin): return if plugin.is_latest(self.update_center_dict): self._install_plugin_from_updatecenter(plugin) else: self._install_specific_version(plugin) self._wait_until_plugin_installed(plugin) def _install_plugin_from_updatecenter(self, plugin): """ Latest versions of plugins can be installed from the update center (and don't need a restart.) """ xml_str = plugin.get_attributes() url = ( "%s/pluginManager/installNecessaryPlugins" % self.jenkins_obj.baseurl ) self.jenkins_obj.requester.post_xml_and_confirm_status( url, data=xml_str ) @property def update_center_install_status(self): """ Jenkins 2.x specific """ url = "%s/updateCenter/installStatus" % self.jenkins_obj.baseurl status = self.jenkins_obj.requester.get_url(url) if status.status_code == 404: raise JenkinsAPIException( "update_center_install_status not available for Jenkins 1.X" ) return status.json() @property def restart_required(self): """ Call after plugin installation to check if Jenkins requires a restart """ try: jobs = self.update_center_install_status["data"]["jobs"] except JenkinsAPIException: return True # Jenkins 1.X has no update_center return any([job for job in jobs if job["requiresRestart"] == "true"]) def _install_specific_version(self, plugin): """ Plugins that are not the latest version have to be uploaded. """ download_link = plugin.get_download_link( update_center_dict=self.update_center_dict ) downloaded_plugin = self._download_plugin(download_link) plugin_dependencies = self._get_plugin_dependencies(downloaded_plugin) log.debug("Installing dependencies for plugin '%s'", plugin.shortName) self.jenkins_obj.install_plugins(plugin_dependencies) url = "%s/pluginManager/uploadPlugin" % self.jenkins_obj.baseurl requester = self.jenkins_obj.requester downloaded_plugin.seek(0) requester.post_and_confirm_status( url, files={"file": ("plugin.hpi", downloaded_plugin)}, data={}, params={}, ) def _get_plugin_dependencies(self, downloaded_plugin): """ Returns a list of all dependencies for a downloaded plugin """ plugin_dependencies = [] manifest = read_manifest(downloaded_plugin) manifest_dependencies = manifest.main_section.get( "Plugin-Dependencies" ) if manifest_dependencies: dependencies = manifest_dependencies.split(",") for dep in dependencies: # split plugin:version;resolution:optional entries components = dep.split(";") dep_plugin = components[0] name = dep_plugin.split(":")[0] # install latest dependency, avoids multiple # versions of the same dep plugin_dependencies.append( Plugin({"shortName": name, "version": "latest"}) ) return plugin_dependencies def _download_plugin(self, download_link): downloaded_plugin = StringIO() downloaded_plugin.write(requests.get(download_link).content) return downloaded_plugin def _plugin_has_finished_installation(self, plugin): """ Return True if installation is marked as 'Success' or 'SuccessButRequiresRestart' in Jenkins' update_center, else return False. """ try: jobs = self.update_center_install_status["data"]["jobs"] for job in jobs: if job["name"] == plugin.shortName and job[ "installStatus" ] in [ "Success", "SuccessButRequiresRestart", ]: return True return False except JenkinsAPIException: return False # lack of update_center in Jenkins 1.X def plugin_version_is_being_installed(self, plugin): """ Return true if plugin is currently being installed. """ try: jobs = self.update_center_install_status["data"]["jobs"] except JenkinsAPIException: return False # lack of update_center in Jenkins 1.X return any( [ job for job in jobs if job["name"] == plugin.shortName and job["version"] == plugin.version ] ) def plugin_version_already_installed(self, plugin): """ Check if plugin version is already installed """ if plugin.shortName not in self: if self.plugin_version_is_being_installed(plugin): return True return False installed_plugin = self[plugin.shortName] if plugin.version == installed_plugin.version: return True elif plugin.version == "latest": # we don't have an exact version, we first check if Jenkins # knows about an update if ( hasattr(installed_plugin, "hasUpdates") and installed_plugin.hasUpdates ): return False # Jenkins may not have an up-to-date catalogue, # so check update-center directly latest_version = self.update_center_dict["plugins"][ plugin.shortName ]["version"] return installed_plugin.version == latest_version return False def __delitem__(self, shortName): if re.match(".*@.*", shortName): real_shortName = re.compile("(.*)@(.*)").search(shortName).group(1) raise ValueError( ("Plugin shortName can't contain version. '%s' should be '%s'") % (shortName, real_shortName) ) if shortName not in self: raise KeyError( 'Plugin with ID "%s" not found, cannot uninstall' % shortName ) if self[shortName].deleted: raise JenkinsAPIException( 'Plugin "%s" already marked for uninstall. ' "Restart jenkins for uninstall to complete." ) params = {"Submit": "OK", "json": {}} url = "%s/pluginManager/plugin/%s/doUninstall" % ( self.jenkins_obj.baseurl, shortName, ) self.jenkins_obj.requester.post_and_confirm_status( url, params={}, data=urlencode(params) ) self.poll() if not self[shortName].deleted: raise JenkinsAPIException( "Problem uninstalling plugin '%s'." % shortName ) def _wait_until_plugin_installed(self, plugin, maxwait=120, interval=1): for _ in range(maxwait, 0, -interval): self.poll() if self._plugin_has_finished_installation(plugin): return True if plugin.shortName in self: return True # for Jenkins 1.X time.sleep(interval) if self.jenkins_obj.version.startswith("2"): raise JenkinsAPIException( "Problem installing plugin '%s'." % plugin.shortName ) log.warning( "Plugin '%s' not found in loaded plugins." "You may need to restart Jenkins.", plugin.shortName, ) return False def __contains__(self, plugin_name): """ True if plugin_name is the name of a defined plugin """ return plugin_name in self.keys() def __str__(self): plugins = [ plugin["shortName"] for plugin in self._data.get("plugins", []) ] return str(sorted(plugins)) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/queue.py0000644000000000000000000001206700000000000015717 0ustar0000000000000000""" Queue module for jenkinsapi """ import logging import time from requests import HTTPError from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.custom_exceptions import UnknownQueueItem, NotBuiltYet log = logging.getLogger(__name__) class Queue(JenkinsBase): """ Class that represents the Jenkins queue """ def __init__(self, baseurl, jenkins_obj): """ Init the Jenkins queue object :param baseurl: basic url for the queue :param jenkins_obj: ref to the jenkins obj """ self.jenkins = jenkins_obj JenkinsBase.__init__(self, baseurl) def __str__(self): return self.baseurl def get_jenkins_obj(self): return self.jenkins def iteritems(self): for item in self._data["items"]: queue_id = item["id"] item_baseurl = "%s/item/%i" % (self.baseurl, queue_id) yield item["id"], QueueItem( baseurl=item_baseurl, jenkins_obj=self.jenkins ) def iterkeys(self): for item in self._data["items"]: yield item["id"] def itervalues(self): for item in self._data["items"]: yield QueueItem(self.jenkins, **item) def keys(self): return list(self.iterkeys()) def values(self): return list(self.itervalues()) def __len__(self): return len(self._data["items"]) def __getitem__(self, item_id): self_as_dict = dict(self.iteritems()) if item_id in self_as_dict: return self_as_dict[item_id] else: raise UnknownQueueItem(item_id) def _get_queue_items_for_job(self, job_name): for item in self._data["items"]: if "name" in item["task"] and item["task"]["name"] == job_name: yield QueueItem( self.get_queue_item_url(item), jenkins_obj=self.jenkins ) def get_queue_items_for_job(self, job_name): return list(self._get_queue_items_for_job(job_name)) def get_queue_item_url(self, item): return "%s/item/%i" % (self.baseurl, item["id"]) def delete_item(self, queue_item): self.delete_item_by_id(queue_item.queue_id) def delete_item_by_id(self, item_id): deleteurl = "%s/cancelItem?id=%s" % (self.baseurl, item_id) self.get_jenkins_obj().requester.post_url(deleteurl) class QueueItem(JenkinsBase): """An individual item in the queue""" def __init__(self, baseurl, jenkins_obj): self.jenkins = jenkins_obj JenkinsBase.__init__(self, baseurl) @property def queue_id(self): return self._data["id"] @property def name(self): return self._data["task"]["name"] @property def why(self): return self._data.get("why") def get_jenkins_obj(self): return self.jenkins def get_job(self): """ Return the job associated with this queue item """ return self.jenkins.get_job_by_url( self._data["task"]["url"], self._data["task"]["name"], ) def get_parameters(self): """returns parameters of queue item""" actions = self._data.get("actions", []) for action in actions: if isinstance(action, dict) and "parameters" in action: parameters = action["parameters"] return dict( [(x["name"], x.get("value", None)) for x in parameters] ) return [] def __repr__(self): return "<%s.%s %s>" % ( self.__class__.__module__, self.__class__.__name__, str(self), ) def __str__(self): return "%s Queue #%i" % (self.name, self.queue_id) def get_build(self): build_number = self.get_build_number() job = self.get_job() return job[build_number] def block_until_complete(self, delay=5): build = self.block_until_building(delay) return build.block_until_complete(delay=delay) def block_until_building(self, delay=5): while True: try: self.poll() return self.get_build() except NotBuiltYet: time.sleep(delay) continue except HTTPError as http_error: log.debug(str(http_error)) time.sleep(delay) continue def is_running(self): """Return True if this queued item is running.""" try: return self.get_build().is_running() except NotBuiltYet: return False def is_queued(self): """Return True if this queued item is queued.""" try: self.get_build() return False except NotBuiltYet: return True def get_build_number(self): try: return self._data["executable"]["number"] except (KeyError, TypeError): raise NotBuiltYet() def get_job_name(self): try: return self._data["task"]["name"] except KeyError: raise NotBuiltYet() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/result.py0000644000000000000000000000115200000000000016102 0ustar0000000000000000""" Module for jenkinsapi Result """ class Result(object): """ Result class """ def __init__(self, **kwargs): self.__dict__.update(kwargs) def __str__(self): return "%s %s %s" % (self.className, self.name, self.status) def __repr__(self): module_name = self.__class__.__module__ class_name = self.__class__.__name__ self_str = str(self) return "<%s.%s %s>" % (module_name, class_name, self_str) def identifier(self): """ Calculate an ID for this object. """ return "%s.%s" % (self.className, self.name) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/result_set.py0000644000000000000000000000273300000000000016763 0ustar0000000000000000""" Module for jenkinsapi ResultSet """ from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.result import Result class ResultSet(JenkinsBase): """ Represents a result from a completed Jenkins run. """ def __init__(self, url, build): """ Init a resultset :param url: url for a build, str :param build: build obj """ self.build = build JenkinsBase.__init__(self, url) def get_jenkins_obj(self): return self.build.job.get_jenkins_obj() def __str__(self): return "Test Result for %s" % str(self.build) @property def name(self): return str(self) def keys(self): return [a[0] for a in self.iteritems()] def items(self): return [a for a in self.iteritems()] def iteritems(self): for suite in self._data.get("suites", []): for case in suite["cases"]: result = Result(**case) yield result.identifier(), result for report_set in self._data.get("childReports", []): if report_set["result"]: for suite in report_set["result"]["suites"]: for case in suite["cases"]: result = Result(**case) yield result.identifier(), result def __len__(self): return len(self.items()) def __getitem__(self, key): self_as_dict = dict(self.iteritems()) return self_as_dict[key] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/utils/__init__.py0000644000000000000000000000004200000000000017460 0ustar0000000000000000""" Module __init__ for utils """ ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674739024.6804104 jenkinsapi-0.3.13/jenkinsapi/utils/compat.py0000644000000000000000000000113700000000000017212 0ustar0000000000000000""" Module for Python 2 and Python 3 compatibility """ import six import sys if sys.version_info[0] >= 3: unicode = str def needs_encoding(data): """ Check whether data is Python 2 unicode variable and needs to be encoded """ if six.PY2 and isinstance(data, unicode): return True return False def to_string(data, encoding="utf-8"): """ Return string representation for the data. In case of Python 2 and unicode do additional encoding before """ encoded_text = data.encode(encoding) if needs_encoding(data) else data return str(encoded_text) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/utils/crumb_requester.py0000644000000000000000000000525600000000000021144 0ustar0000000000000000# Code from https://github.com/ros-infrastructure/ros_buildfarm # (c) Open Source Robotics Foundation import ast import logging from jenkinsapi.utils.requester import Requester logger = logging.getLogger(__name__) class CrumbRequester(Requester): """Adapter for Requester inserting the crumb in every request.""" def __init__(self, *args, **kwargs): super(CrumbRequester, self).__init__(*args, **kwargs) self._baseurl = kwargs["baseurl"] self._last_crumb_data = None def post_url( self, url, params=None, data=None, files=None, headers=None, allow_redirects=True, **kwargs ): if self._last_crumb_data: # first try request with previous crumb if available response = self._post_url_with_crumb( self._last_crumb_data, url, params, data, files, headers, allow_redirects, **kwargs ) # code 403 might indicate that the crumb is not valid anymore if response.status_code != 403: return response # fetch new crumb (if server has crumbs enabled) if self._last_crumb_data is not False: self._last_crumb_data = self._get_crumb_data() return self._post_url_with_crumb( self._last_crumb_data, url, params, data, files, headers, allow_redirects, **kwargs ) def _get_crumb_data(self): response = self.get_url(self._baseurl + "/crumbIssuer/api/python") if response.status_code in [404]: logger.warning("The Jenkins master does not require a crumb") return False if response.status_code not in [200]: raise RuntimeError("Failed to fetch crumb: %s" % response.text) crumb_issuer_response = ast.literal_eval(response.text) crumb_request_field = crumb_issuer_response["crumbRequestField"] crumb = crumb_issuer_response["crumb"] logger.debug("Fetched crumb: %s", crumb) return {crumb_request_field: crumb} def _post_url_with_crumb( self, crumb_data, url, params, data, files, headers, allow_redirects, **kwargs ): if crumb_data: if headers is None: headers = crumb_data else: headers.update(crumb_data) return super(CrumbRequester, self).post_url( url, params, data, files, headers, allow_redirects, **kwargs ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674739024.6804104 jenkinsapi-0.3.13/jenkinsapi/utils/jenkins_launcher.py0000644000000000000000000002324200000000000021252 0ustar0000000000000000import os import time import shutil import logging import datetime import tempfile import posixpath import requests from requests.adapters import HTTPAdapter from urllib3 import Retry import threading import subprocess from pkg_resources import resource_stream from tarfile import TarFile from six.moves import queue from six.moves.urllib.parse import urlparse from jenkinsapi.jenkins import Jenkins from jenkinsapi.custom_exceptions import JenkinsAPIException log = logging.getLogger(__name__) class FailedToStart(Exception): pass class TimeOut(Exception): pass class StreamThread(threading.Thread): def __init__(self, name, q, stream, fn_log): threading.Thread.__init__(self) self.name = name self.queue = q self.stream = stream self.fn_log = fn_log self._stop = threading.Event() def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() def run(self): log.info("Starting %s", self.name) while True: if self._stop.isSet(): break line = self.stream.readline() if line: self.fn_log(line.rstrip()) self.queue.put((self.name, line)) else: break self.queue.put((self.name, None)) class JenkinsLancher(object): """ Launch jenkins """ JENKINS_WEEKLY_WAR_URL = "http://updates.jenkins.io/latest/jenkins.war" JENKINS_LTS_WAR_URL = ( "https://updates.jenkins.io/stable/latest/jenkins.war" ) def __init__( self, local_orig_dir, systests_dir, war_name, plugin_urls=None, jenkins_url=None, ): if jenkins_url is not None: self.jenkins_url = jenkins_url self.http_port = urlparse(jenkins_url).port self.start_new_instance = False else: import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("", 0)) sock.listen(1) port = sock.getsockname()[1] sock.close() self.http_port = port self.jenkins_url = "http://localhost:%s" % self.http_port self.start_new_instance = True self.threads = [] self.war_path = os.path.join(local_orig_dir, war_name) self.local_orig_dir = local_orig_dir self.systests_dir = systests_dir self.war_filename = war_name if "JENKINS_HOME" not in os.environ: self.jenkins_home = tempfile.mkdtemp(prefix="jenkins-home-") os.environ["JENKINS_HOME"] = self.jenkins_home else: self.jenkins_home = os.environ["JENKINS_HOME"] self.jenkins_process = None self.queue = queue.Queue() self.plugin_urls = plugin_urls or [] if os.environ.get("JENKINS_VERSION", "stable") == "stable": self.JENKINS_WAR_URL = self.JENKINS_LTS_WAR_URL else: self.JENKINS_WAR_URL = self.JENKINS_WEEKLY_WAR_URL def update_war(self): os.chdir(self.systests_dir) if os.path.exists(self.war_path): log.info( "War file already present, delete it to redownload and" " update jenkins" ) else: log.info("Downloading Jenkins War") script_dir = os.path.join(self.systests_dir, "get-jenkins-war.sh") subprocess.check_call( [ script_dir, self.JENKINS_WAR_URL, self.local_orig_dir, self.war_filename, ] ) def update_config(self): tarball = TarFile.open( fileobj=resource_stream( "jenkinsapi_tests.systests", "jenkins_home.tar.gz" ) ) tarball.extractall(path=self.jenkins_home) def install_plugins(self): plugin_dest_dir = os.path.join(self.jenkins_home, "plugins") log.info("Plugins will be installed in '%s'", plugin_dest_dir) if not os.path.exists(plugin_dest_dir): os.mkdir(plugin_dest_dir) for url in self.plugin_urls: self.install_plugin(url, plugin_dest_dir) def install_plugin(self, hpi_url, plugin_dest_dir): sess = requests.Session() adapter = HTTPAdapter( max_retries=Retry(total=5, backoff_factor=1, allowed_methods=None) ) sess.mount("http://", adapter) sess.mount("https://", adapter) path = urlparse(hpi_url).path filename = posixpath.basename(path) plugin_orig_dir = os.path.join(self.local_orig_dir, "plugins") if not os.path.exists(plugin_orig_dir): os.mkdir(plugin_orig_dir) plugin_orig_path = os.path.join(plugin_orig_dir, filename) plugin_dest_path = os.path.join(plugin_dest_dir, filename) if os.path.exists(plugin_orig_path): log.info( "%s already locally present, delete the file to redownload" " and update", filename, ) else: log.info("Downloading %s from %s", filename, hpi_url) with sess.get(hpi_url, stream=True) as hget: hget.raise_for_status() with open(plugin_orig_path, "wb") as hpi: for chunk in hget.iter_content(chunk_size=8192): hpi.write(chunk) log.info("Installing %s", filename) shutil.copy(plugin_orig_path, plugin_dest_path) # Create an empty .pinned file, so that the downloaded plugin # will be used, instead of the version bundled in jenkins.war # See https://wiki.jenkins-ci.org/display/JENKINS/Pinned+Plugins open(plugin_dest_path + ".pinned", "a").close() def stop(self): if self.start_new_instance: log.info("Shutting down jenkins.") # Start the threads for thread in self.threads: thread.stop() Jenkins(self.jenkins_url).shutdown() # self.jenkins_process.terminate() # self.jenkins_process.wait() # Do not remove jenkins home if JENKINS_URL is set if "JENKINS_URL" not in os.environ: shutil.rmtree(self.jenkins_home, ignore_errors=True) log.info("Jenkins stopped.") def block_until_jenkins_ready(self, timeout): start_time = datetime.datetime.now() timeout_time = start_time + datetime.timedelta(seconds=timeout) while True: try: Jenkins(self.jenkins_url) log.info("Jenkins is finally ready for use.") except JenkinsAPIException: log.info("Jenkins is not yet ready...") if datetime.datetime.now() > timeout_time: raise TimeOut("Took too long for Jenkins to become ready...") time.sleep(5) def start(self, timeout=60): if self.start_new_instance: self.jenkins_home = os.environ.get( "JENKINS_HOME", self.jenkins_home ) self.update_war() self.update_config() self.install_plugins() os.chdir(self.local_orig_dir) jenkins_command = [ "java", "-Djenkins.install.runSetupWizard=false", "-Dhudson.DNSMultiCast.disabled=true", "-jar", self.war_filename, "--httpPort=%d" % self.http_port, ] log.info("About to start Jenkins...") log.info("%s> %s", os.getcwd(), " ".join(jenkins_command)) self.jenkins_process = subprocess.Popen( jenkins_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) self.threads = [ StreamThread( "out", self.queue, self.jenkins_process.stdout, log.info ), StreamThread( "err", self.queue, self.jenkins_process.stderr, log.warning ), ] # Start the threads for thread in self.threads: thread.start() while True: try: streamName, line = self.queue.get( block=True, timeout=timeout ) # Python 3.x if isinstance(line, bytes): line = line.decode("UTF-8") except queue.Empty: log.warning("Input ended unexpectedly") break else: if line: if "Failed to initialize Jenkins" in line: raise FailedToStart(line) if "Invalid or corrupt jarfile" in line: raise FailedToStart(line) if "is fully up and running" in line: log.info(line) return else: log.warning("Stream %s has terminated", streamName) self.block_until_jenkins_ready(timeout) if __name__ == "__main__": logging.basicConfig() logging.getLogger("").setLevel(logging.INFO) log.info("Hello!") jl = JenkinsLancher( "/home/aleksey/src/jenkinsapi_lechat/jenkinsapi_tests" "/systests/localinstance_files", "/home/aleksey/src/jenkinsapi_lechat/jenkinsapi_tests/systests", "jenkins.war", ) jl.start() log.info("Jenkins was launched...") time.sleep(10) log.info("...now to shut it down!") jl.stop() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/utils/jsonp_to_json.py0000644000000000000000000000051600000000000020613 0ustar0000000000000000""" Module for converting jsonp to json. """ from __future__ import print_function def jsonp_to_json(jsonp): try: l_index = jsonp.index("(") + 1 r_index = jsonp.rindex(")") except ValueError: print("Input is not in jsonp format.") return None res = jsonp[l_index:r_index] return res ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/utils/krb_requester.py0000644000000000000000000000250400000000000020603 0ustar0000000000000000""" Kerberos aware Requester """ from jenkinsapi.utils.requester import Requester from requests_kerberos import HTTPKerberosAuth, OPTIONAL # pylint: disable=W0222 class KrbRequester(Requester): """ A class which carries out HTTP requests with Kerberos/GSSAPI authentication. """ def __init__(self, *args, **kwargs): """ :param ssl_verify: flag indicating if server certificate in HTTPS requests should be verified :param baseurl: Jenkins' base URL :param mutual_auth: type of mutual authentication, use one of REQUIRED, OPTIONAL or DISABLED from requests_kerberos package """ super(KrbRequester, self).__init__(*args, **kwargs) self.mutual_auth = ( kwargs["mutual_auth"] if "mutual_auth" in kwargs else OPTIONAL ) def get_request_dict( self, params=None, data=None, files=None, headers=None, **kwargs ): req_dict = super(KrbRequester, self).get_request_dict( params=params, data=data, files=files, headers=headers, **kwargs ) if self.mutual_auth: auth = HTTPKerberosAuth(self.mutual_auth) else: auth = HTTPKerberosAuth() req_dict["auth"] = auth return req_dict ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/utils/manifest.py0000644000000000000000000000636500000000000017545 0ustar0000000000000000""" This module enables Manifest file parsing. Copied from https://chromium.googlesource.com/external/googleappengine/python/+/master /google/appengine/tools/jarfile.py """ import zipfile _MANIFEST_NAME = "META-INF/MANIFEST.MF" class InvalidJarError(Exception): """ InvalidJar exception class """ pass class Manifest(object): """The parsed manifest from a jar file. Attributes: main_section: a dict representing the main (first) section of the manifest. Each key is a string that is an attribute, such as 'Manifest-Version', and the corresponding value is a string that is the value of the attribute, such as '1.0'. sections: a dict representing the other sections of the manifest. Each key is a string that is the value of the 'Name' attribute for the section, and the corresponding value is a dict like the main_section one, for the other attributes. """ def __init__(self, main_section, sections): self.main_section = main_section self.sections = sections def read_manifest(jar_file_name): """Read and parse the manifest out of the given jar. Args: jar_file_name: the name of the jar from which the manifest is to be read. Returns: A parsed Manifest object, or None if the jar has no manifest. Raises: IOError: if the jar does not exist or cannot be read. """ with zipfile.ZipFile(jar_file_name) as jar: try: manifest_string = jar.read(_MANIFEST_NAME).decode("UTF-8") except KeyError: return None return _parse_manifest(manifest_string) def _parse_manifest(manifest_string): """Parse a Manifest object out of the given string. Args: manifest_string: a str or unicode that is the manifest contents. Returns: A Manifest object parsed out of the string. Raises: InvalidJarError: if the manifest is not well-formed. """ manifest_string = "\n".join(manifest_string.splitlines()).rstrip("\n") section_strings = manifest_string.split("\n\n") parsed_sections = [_parse_manifest_section(s) for s in section_strings] main_section = parsed_sections[0] sections = dict() try: for entry in parsed_sections[1:]: sections[entry["Name"]] = entry except KeyError: raise InvalidJarError( "Manifest entry has no Name attribute: %s" % entry ) return Manifest(main_section, sections) def _parse_manifest_section(section): """Parse a dict out of the given manifest section string. Args: section: a str or unicode that is the manifest section. It looks something like this (without the >): > Name: section-name > Some-Attribute: some value > Another-Attribute: another value Returns: A dict where the keys are the attributes (here, 'Name', 'Some-Attribute', 'Another-Attribute'), and the values are the corresponding attribute values. Raises: InvalidJarError: if the manifest section is not well-formed. """ section = section.replace("\n ", "") try: return dict(line.split(": ", 1) for line in section.split("\n")) except ValueError: raise InvalidJarError("Invalid manifest %r" % section) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/utils/requester.py0000644000000000000000000001725700000000000017760 0ustar0000000000000000""" Module for jenkinsapi requester (which is a wrapper around python-requests) """ import requests import six.moves.urllib.parse as urlparse from jenkinsapi.custom_exceptions import JenkinsAPIException, PostRequired # import logging # these two lines enable debugging at httplib level # (requests->urllib3->httplib) # you will see the REQUEST, including HEADERS and DATA, and RESPONSE # with HEADERS but without DATA. # the only thing missing will be the response.body which is not logged. # import httplib # httplib.HTTPConnection.debuglevel = 1 # you need to initialize logging, otherwise you will not see anything # from requests # logging.basicConfig() # logging.getLogger().setLevel(logging.DEBUG) # requests_log = logging.getLogger("requests.packages.urllib3") # requests_log.setLevel(logging.DEBUG) # requests_log.propagate = True requests.adapters.DEFAULT_RETRIES = 5 class Requester(object): """ A class which carries out HTTP requests. You can replace this class with one of your own implementation if you require some other way to access Jenkins. This default class can handle simple authentication only. """ VALID_STATUS_CODES = [ 200, ] AUTH_COOKIE = None def __init__(self, *args, **kwargs): username = None password = None ssl_verify = True cert = None baseurl = None timeout = 10 if len(args) == 1: (username,) = args elif len(args) == 2: username, password = args elif len(args) == 3: username, password, ssl_verify = args elif len(args) == 4: username, password, ssl_verify, cert = args elif len(args) == 5: username, password, ssl_verify, cert, baseurl = args elif len(args) == 6: username, password, ssl_verify, cert, baseurl, timeout = args elif len(args) > 6: raise ValueError("To much positional arguments given!") baseurl = kwargs.get("baseurl", baseurl) self.base_scheme = ( urlparse.urlsplit(baseurl).scheme if baseurl else None ) self.username = kwargs.get("username", username) self.password = kwargs.get("password", password) if self.username: assert self.password, ( "Please provide both username and password " "or don't provide them at all" ) if self.password: assert self.username, ( "Please provide both username and password " "or don't provide them at all" ) self.ssl_verify = kwargs.get("ssl_verify", ssl_verify) self.cert = kwargs.get("cert", cert) self.timeout = kwargs.get("timeout", timeout) self.session = requests.Session() self.max_retries = kwargs.get("max_retries") if self.max_retries is not None: retry_adapter = requests.adapters.HTTPAdapter( max_retries=self.max_retries ) self.session.mount("http://", retry_adapter) self.session.mount("https://", retry_adapter) def get_request_dict( self, params=None, data=None, files=None, headers=None, **kwargs ): requestKwargs = kwargs if self.username: requestKwargs["auth"] = (self.username, self.password) if params: assert isinstance( params, dict ), "Params must be a dict, got %s" % repr(params) requestKwargs["params"] = params if headers: assert isinstance( headers, dict ), "headers must be a dict, got %s" % repr(headers) requestKwargs["headers"] = headers if self.AUTH_COOKIE: currentheaders = requestKwargs.get("headers", {}) currentheaders.update({"Cookie": self.AUTH_COOKIE}) requestKwargs["headers"] = currentheaders requestKwargs["verify"] = self.ssl_verify requestKwargs["cert"] = self.cert if data: # It may seem odd, but some Jenkins operations require posting # an empty string. requestKwargs["data"] = data if files: requestKwargs["files"] = files requestKwargs["timeout"] = self.timeout return requestKwargs def _update_url_scheme(self, url): """ Updates scheme of given url to the one used in Jenkins baseurl. """ if self.base_scheme and not url.startswith("%s://" % self.base_scheme): url_split = urlparse.urlsplit(url) url = urlparse.urlunsplit( [ self.base_scheme, url_split.netloc, url_split.path, url_split.query, url_split.fragment, ] ) return url def get_url( self, url, params=None, headers=None, allow_redirects=True, stream=False, ): requestKwargs = self.get_request_dict( params=params, headers=headers, allow_redirects=allow_redirects, stream=stream, ) return self.session.get(self._update_url_scheme(url), **requestKwargs) def post_url( self, url, params=None, data=None, files=None, headers=None, allow_redirects=True, **kwargs ): requestKwargs = self.get_request_dict( params=params, data=data, files=files, headers=headers, allow_redirects=allow_redirects, **kwargs ) return self.session.post(self._update_url_scheme(url), **requestKwargs) def post_xml_and_confirm_status( self, url, params=None, data=None, valid=None ): headers = {"Content-Type": "text/xml"} return self.post_and_confirm_status( url, params=params, data=data, headers=headers, valid=valid ) def post_and_confirm_status( self, url, params=None, data=None, files=None, headers=None, valid=None, allow_redirects=True, ): valid = valid or self.VALID_STATUS_CODES if not headers and not files: headers = {"Content-Type": "application/x-www-form-urlencoded"} assert data is not None, "Post messages must have data" response = self.post_url( url, params, data, files, headers, allow_redirects ) if response.status_code not in valid: raise JenkinsAPIException( "Operation failed. url={0}, data={1}, headers={2}, " "status={3}, text={4}".format( response.url, data, headers, response.status_code, response.text.encode("UTF-8"), ) ) return response def get_and_confirm_status( self, url, params=None, headers=None, valid=None, stream=False ): valid = valid or self.VALID_STATUS_CODES response = self.get_url(url, params, headers, stream=stream) if response.status_code not in valid: if response.status_code == 405: # POST required raise PostRequired("POST required for url {0}".format(url)) raise JenkinsAPIException( "Operation failed. url={0}, headers={1}, status={2}, " "text={3}".format( response.url, headers, response.status_code, response.text.encode("UTF-8"), ) ) return response ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674739024.6804104 jenkinsapi-0.3.13/jenkinsapi/utils/simple_post_logger.py0000644000000000000000000000170300000000000021623 0ustar0000000000000000from __future__ import print_function try: from SimpleHTTPServer import SimpleHTTPRequestHandler except ImportError: from http.server import SimpleHTTPRequestHandler try: import SocketServer as socketserver except ImportError: import socketserver import logging import cgi PORT = 8080 class ServerHandler(SimpleHTTPRequestHandler): def do_GET(self): logging.error(self.headers) super().do_GET() def do_POST(self): logging.error(self.headers) form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={ "REQUEST_METHOD": "POST", "CONTENT_TYPE": self.headers["Content-Type"], }, ) for item in form.list: logging.error(item) super().do_GET() Handler = ServerHandler httpd = socketserver.TCPServer(("", PORT), Handler) print("serving at port", PORT) httpd.serve_forever() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/view.py0000644000000000000000000001314700000000000015545 0ustar0000000000000000""" Module for jenkinsapi views """ import six import logging from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.job import Job from jenkinsapi.custom_exceptions import NotFound log = logging.getLogger(__name__) class View(JenkinsBase): """ View class """ def __init__(self, url, name, jenkins_obj): self.name = name self.jenkins_obj = jenkins_obj JenkinsBase.__init__(self, url) self.deleted = False def __len__(self): return len(self.get_job_dict().keys()) def __str__(self): return self.name def __repr__(self): return self.name def __getitem__(self, job_name): assert isinstance(job_name, str) api_url = self.python_api_url(self.get_job_url(job_name)) return Job(api_url, job_name, self.jenkins_obj) def __contains__(self, job_name): """ True if view_name is the name of a defined view """ return job_name in self.keys() def delete(self): """ Remove this view object """ url = "%s/doDelete" % self.baseurl self.jenkins_obj.requester.post_and_confirm_status(url, data="") self.jenkins_obj.poll() self.deleted = True def keys(self): return self.get_job_dict().keys() def iteritems(self): it = six.iteritems(self.get_job_dict()) for name, url in it: yield name, Job(url, name, self.jenkins_obj) def values(self): return [a[1] for a in self.iteritems()] def items(self): return [a for a in self.iteritems()] def _get_jobs(self): if "jobs" in self._data: for viewdict in self._data["jobs"]: yield viewdict["name"], viewdict["url"] def get_job_dict(self): return dict(self._get_jobs()) def get_job_url(self, str_job_name): if str_job_name in self: return self.get_job_dict()[str_job_name] else: # noinspection PyUnboundLocalVariable views_jobs = ", ".join(self.get_job_dict().keys()) raise NotFound( "Job %s is not known, available jobs" " in view are: %s" % (str_job_name, views_jobs) ) def get_jenkins_obj(self): return self.jenkins_obj def add_job(self, job_name, job=None): """ Add job to a view :param job_name: name of the job to be added :param job: Job object to be added :return: True if job has been added, False if job already exists or job not known to Jenkins """ if not job: if job_name in self.get_job_dict(): log.warning( "Job %s is already in the view %s", job_name, self.name ) return False else: # Since this call can be made from nested view, # which doesn't have any jobs, we can miss existing job # Thus let's create top level Jenkins and ask him # http://jenkins:8080/view/CRT/view/CRT-FB/view/CRT-SCRT-1301/ top_jenkins = self.get_jenkins_obj().get_jenkins_obj_from_url( self.baseurl.split("view/")[0] ) if not top_jenkins.has_job(job_name): log.error( msg='Job "%s" is not known to Jenkins' % job_name ) return False else: job = top_jenkins.get_job(job_name) log.info(msg="Creating job %s in view %s" % (job_name, self.name)) url = "%s/addJobToView" % self.baseurl params = {"name": job_name} self.get_jenkins_obj().requester.post_and_confirm_status( url, data={}, params=params ) self.poll() log.debug( msg='Job "%s" has been added to a view "%s"' % (job.name, self.name) ) return True def remove_job(self, job_name): """ Remove job from a view :param job_name: name of the job to be removed :return: True if job has been removed, False if job not assigned to this view """ if job_name not in self: return False url = "%s/removeJobFromView" % self.baseurl params = {"name": job_name} self.get_jenkins_obj().requester.post_and_confirm_status( url, data={}, params=params ) self.poll() log.debug( msg='Job "%s" has been added to a view "%s"' % (job_name, self.name) ) return True def _get_nested_views(self): for viewdict in self._data.get("views", []): yield viewdict["name"], viewdict["url"] def get_nested_view_dict(self): return dict(self._get_nested_views()) def get_config_xml_url(self): return "%s/config.xml" % self.baseurl def get_config(self): """ Return the config.xml from the view """ url = self.get_config_xml_url() response = self.get_jenkins_obj().requester.get_and_confirm_status(url) return response.text def update_config(self, config): """ Update the config.xml to the view """ url = self.get_config_xml_url() config = str(config) # cast unicode in case of Python 2 response = self.get_jenkins_obj().requester.post_url( url, params={}, data=config ) return response.text @property def views(self): return ( self.get_jenkins_obj().get_jenkins_obj_from_url(self.baseurl).views ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi/views.py0000644000000000000000000001007100000000000015721 0ustar0000000000000000""" Module for jenkinsapi Views """ import logging import json from jenkinsapi.view import View from jenkinsapi.custom_exceptions import JenkinsAPIException log = logging.getLogger(__name__) class Views(object): """ An abstraction on a Jenkins object's views """ LIST_VIEW = "hudson.model.ListView" NESTED_VIEW = "hudson.plugins.nested_view.NestedView" CATEGORIZED_VIEW = ( "org.jenkinsci.plugins.categorizedview.CategorizedJobsView" ) MY_VIEW = "hudson.model.MyView" DASHBOARD_VIEW = "hudson.plugins.view.dashboard.Dashboard" PIPELINE_VIEW = ( "au.com.centrumsystems.hudson." "plugin.buildpipeline.BuildPipelineView" ) def __init__(self, jenkins): self.jenkins = jenkins self._data = None def poll(self, tree=None): self._data = self.jenkins.poll( tree="views[name,url]" if tree is None else tree ) def __len__(self): return len(self.keys()) def __delitem__(self, view_name): if view_name == "All": raise ValueError("Cannot delete this view: %s" % view_name) if view_name in self: self[view_name].delete() self.poll() def __setitem__(self, view_name, job_names_list): new_view = self.create(view_name) if isinstance(job_names_list, str): job_names_list = [job_names_list] for job_name in job_names_list: if not new_view.add_job(job_name): # Something wrong - delete view del self[new_view] raise TypeError("Job %s does not exist in Jenkins" % job_name) def __getitem__(self, view_name): self.poll() for row in self._data.get("views", []): if row["name"] == view_name: return View(row["url"], row["name"], self.jenkins) raise KeyError("View %s not found" % view_name) def iteritems(self): """ Get the names & objects for all views """ self.poll() for row in self._data.get("views", []): name = row["name"] url = row["url"] yield name, View(url, name, self.jenkins) def __contains__(self, view_name): """ True if view_name is the name of a defined view """ return view_name in self.keys() def iterkeys(self): """ Get the names of all available views """ self.poll() for row in self._data.get("views", []): yield row["name"] def keys(self): """ Return a list of the names of all views """ return list(self.iterkeys()) def create(self, view_name, view_type=LIST_VIEW, config=None): """ Create a view :param view_name: name of new view, str :param view_type: type of the view, one of the constants in Views, str :param config: XML configuration of the new view :return: new View obj or None if view was not created """ log.info('Creating "%s" view "%s"', view_type, view_name) if view_name in self: log.warning('View "%s" already exists', view_name) return self[view_name] url = "%s/createView" % self.jenkins.baseurl if view_type == self.CATEGORIZED_VIEW: if not config: raise JenkinsAPIException( "Job XML config cannot be empty for CATEGORIZED_VIEW" ) params = {"name": view_name} self.jenkins.requester.post_xml_and_confirm_status( url, data=config, params=params ) else: headers = {"Content-Type": "application/x-www-form-urlencoded"} data = { "name": view_name, "mode": view_type, "Submit": "OK", "json": json.dumps({"name": view_name, "mode": view_type}), } self.jenkins.requester.post_and_confirm_status( url, data=data, headers=headers ) self.poll() return self[view_name] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/__init__.py0000644000000000000000000000000000000000000017534 0ustar0000000000000000././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/conftest.py0000644000000000000000000000074200000000000017637 0ustar0000000000000000import os import logging logging.basicConfig( format="%(module)s.%(funcName)s %(levelname)s: %(message)s", level=logging.INFO, ) level = ( logging.WARNING if "LOG_LEVEL" not in os.environ else os.environ["LOG_LEVEL"].upper().strip() ) modules = [ "requests.packages.urllib3.connectionpool", "requests", "urllib3", "urllib3.connectionpool", ] for module_name in modules: logger = logging.getLogger(module_name) logger.setLevel(level) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/__init__.py0000644000000000000000000000000000000000000021435 0ustar0000000000000000././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/config.xml0000644000000000000000000000226700000000000021334 0ustar0000000000000000 1.0 2 NORMAL true ${JENKINS_HOME}/workspace/${ITEM_FULLNAME} ${ITEM_ROOTDIR}/builds 0 All false false All 0 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674739024.6804104 jenkinsapi-0.3.13/jenkinsapi_tests/systests/conftest.py0000644000000000000000000001444600000000000021546 0ustar0000000000000000import os import logging import pytest from jenkinsapi.jenkins import Jenkins from jenkinsapi.utils.jenkins_launcher import JenkinsLancher log = logging.getLogger(__name__) state = {} # User/password for authentication testcases ADMIN_USER = "admin" ADMIN_PASSWORD = "admin" # Extra plugins required by the systests PLUGIN_DEPENDENCIES = [ "http://updates.jenkins.io/latest/" "apache-httpcomponents-client-4-api.hpi", "http://updates.jenkins.io/latest/jsch.hpi", "http://updates.jenkins.io/latest/trilead-api.hpi", "http://updates.jenkins.io/latest/workflow-api.hpi", "http://updates.jenkins.io/latest/display-url-api.hpi", "http://updates.jenkins.io/latest/workflow-step-api.hpi", "http://updates.jenkins.io/latest/workflow-scm-step.hpi", "http://updates.jenkins.io/latest/junit.hpi", "http://updates.jenkins.io/latest/script-security.hpi", "http://updates.jenkins.io/latest/matrix-project.hpi", "http://updates.jenkins.io/latest/credentials.hpi", "http://updates.jenkins.io/latest/ssh-credentials.hpi", "http://updates.jenkins.io/latest/scm-api.hpi", "http://updates.jenkins.io/latest/mailer.hpi", "http://updates.jenkins.io/latest/git.hpi", "http://updates.jenkins.io/latest/git-client.hpi", "http://updates.jenkins.io/latest/jakarta-mail-api.hpi", "https://updates.jenkins.io/latest/nested-view.hpi", "https://updates.jenkins.io/latest/ssh-slaves.hpi", "https://updates.jenkins.io/latest/structs.hpi", "http://updates.jenkins.io/latest/plain-credentials.hpi", "http://updates.jenkins.io/latest/envinject.hpi", "http://updates.jenkins.io/latest/envinject-api.hpi", "http://updates.jenkins.io/latest/jdk-tool.hpi", "http://updates.jenkins.io/latest/credentials-binding.hpi", "http://updates.jenkins.io/latest/jakarta-activation-api.hpi", "http://updates.jenkins.io/latest/caffeine-api.hpi", "http://updates.jenkins.io/latest/script-security.hpi", "http://updates.jenkins.io/latest/checks-api.hpi", "http://updates.jenkins.io/latest/jackson2-api.hpi", "http://updates.jenkins.io/latest/bootstrap5-api.hpi", "http://updates.jenkins.io/latest/echarts-api.hpi", "http://updates.jenkins.io/latest/ionicons-api.hpi", "http://updates.jenkins.io/latest/plugin-util-api.hpi", "http://updates.jenkins.io/latest/mina-sshd-api-core.hpi", "http://updates.jenkins.io/latest/mina-sshd-api-common.hpi", "http://updates.jenkins.io/latest/font-awesome-api.hpi", "http://updates.jenkins.io/latest/popper2-api.hpi", "http://updates.jenkins.io/latest/commons-text-api.hpi", "http://updates.jenkins.io/latest/commons-lang3-api.hpi", "http://updates.jenkins.io/latest/plugin-util-api.hpi", "http://updates.jenkins.io/latest/snakeyaml-api.hpi", "http://updates.jenkins.io/latest/workflow-support.hpi", "http://updates.jenkins.io/latest/jquery3-api.hpi", "http://updates.jenkins.io/latest/checks-api.hpi", ] def _delete_all_jobs(jenkins): jenkins.poll() for name in jenkins.keys(): del jenkins[name] def _delete_all_views(jenkins): all_view_names = jenkins.views.keys()[1:] for name in all_view_names: del jenkins.views[name] def _delete_all_credentials(jenkins): all_cred_names = jenkins.credentials.keys() for name in all_cred_names: del jenkins.credentials[name] def _create_admin_user(launched_jenkins): # Groovy script that creates a user "admin/admin" in jenkins # and enable security. "admin" user will be the only user and # have admin permissions. Anonymous cannot read anything. create_admin_groovy = """ import jenkins.model.* import hudson.security.* def instance = Jenkins.getInstance() def hudsonRealm = new HudsonPrivateSecurityRealm(false) hudsonRealm.createAccount('{0}','{1}') instance.setSecurityRealm(hudsonRealm) def strategy = new FullControlOnceLoggedInAuthorizationStrategy() strategy.setAllowAnonymousRead(false) instance.setAuthorizationStrategy(strategy) """.format( ADMIN_USER, ADMIN_PASSWORD ) url = launched_jenkins.jenkins_url jenkins_instance = Jenkins(url) jenkins_instance.run_groovy_script(create_admin_groovy) def _disable_security(launched_jenkins): # Groovy script that disables security in jenkins, # reverting the changes made in "_create_admin_user" function. disable_security_groovy = """ import jenkins.model.* import hudson.security.* def instance = Jenkins.getInstance() instance.disableSecurity() instance.save() """ url = launched_jenkins.jenkins_url jenkins_instance = Jenkins(url, ADMIN_USER, ADMIN_PASSWORD) jenkins_instance.run_groovy_script(disable_security_groovy) @pytest.fixture(scope="session") def launched_jenkins(): systests_dir, _ = os.path.split(__file__) local_orig_dir = os.path.join(systests_dir, "localinstance_files") if not os.path.exists(local_orig_dir): os.mkdir(local_orig_dir) war_name = "jenkins.war" launcher = JenkinsLancher( local_orig_dir, systests_dir, war_name, PLUGIN_DEPENDENCIES, jenkins_url=os.getenv("JENKINS_URL", None), ) launcher.start() yield launcher log.info("All tests finished") launcher.stop() @pytest.fixture(scope="function") def jenkins(launched_jenkins): url = launched_jenkins.jenkins_url jenkins_instance = Jenkins(url, timeout=30) _delete_all_jobs(jenkins_instance) _delete_all_views(jenkins_instance) _delete_all_credentials(jenkins_instance) return jenkins_instance @pytest.fixture(scope="function") def lazy_jenkins(launched_jenkins): url = launched_jenkins.jenkins_url jenkins_instance = Jenkins(url, lazy=True) _delete_all_jobs(jenkins_instance) _delete_all_views(jenkins_instance) _delete_all_credentials(jenkins_instance) return jenkins_instance @pytest.fixture(scope="function") def jenkins_admin_admin( launched_jenkins, jenkins ): # pylint: disable=unused-argument # Using "jenkins" fixture makes sure that jobs/views/credentials are # cleaned before security is enabled. url = launched_jenkins.jenkins_url _create_admin_user(launched_jenkins) jenkins_admin_instance = Jenkins(url, ADMIN_USER, ADMIN_PASSWORD) yield jenkins_admin_instance jenkins_admin_instance.requester.__class__.AUTH_COOKIE = None _disable_security(launched_jenkins) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/get-jenkins-war.sh0000755000000000000000000000113100000000000022676 0ustar0000000000000000#!/bin/bash #JENKINS_WAR_URL="http://mirrors.jenkins-ci.org/war/latest/jenkins.war" if [[ "$#" -ne 3 ]]; then echo "Usage: $0 jenkins_url path_to_store_jenkins war_filename" exit 1 fi readonly JENKINS_WAR_URL=$1 readonly JENKINS_PATH=$2 readonly WAR_FILENAME=$3 echo "Downloading $JENKINS_WAR_URL to ${JENKINS_PATH}" if [[ $(type -t wget) ]]; then wget -O ${JENKINS_PATH}/${WAR_FILENAME} -q $JENKINS_WAR_URL elif [[ $(type -t curl) ]]; then curl -sSL -o ${JENKINS_PATH}/${WAR_FILENAME} $JENKINS_WAR_URL else echo "Could not find wget or curl" exit 1 fi echo "Jenkins downloaded" ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/jenkins_home.tar.gz0000644000000000000000000001327000000000000023141 0ustar0000000000000000‹85Wí<xÕÖy‘®CH€ÉîÌöHX)RI£HqvæîfÈîÌ23›d)‚€RB MŠBP‚€RC£HG%J•&¡# ðß;³»)"ññ0¼ÿ™óAf÷–ÓÏ™sïÜYP<¥`%ÓA ÈÚHA| (ψÎÀ4Æj 2‘JõzJÀq\§Ñ`ðJèµxÉ«´¡ÒãzJCh´®RéU:/ Z‚ÿ8‘ä!+¤¤ Àù§ãÊë—Á<×ÿ'`&­xÞLTÂsÁÿ ˈ i ¡m O BÇÓÏŠ†ÿøâ_C¸â_Mèa.€Ýz•¾2þ+´¤ZeÂ5:©#4­3™Uh€–Ôã´–"MÞÏ›ÁJø[ÁÿfÆ ì¤˜?Àû¿  •j<fÒaÇšŸžF9÷ ×»ã_¥Váèþ'TÆE€/Ö=<6$¥:{qRõ¤`±Ô½92cFY³ÄN¥25¼@+Â8€m¬+t)9áËÔŠ“èó.ƒþ±àº(à%¨d;LÓ4èÍ %yZ<ï?ß*ÿO]bÿO남\ÿW ¨¢åJø/÷úÖI°.—*ˆ@ &TŽ¢M€gAƃ^¯}Rüãžõ?N¨aüãj­Ê Ó> âåÁ?<þÝö—KJEÚ$|j(/ÿk<öGù_…á„VW¹ÿS1@TdÎ Ô”ŽÐà³ICiÕ„š6¨5ÒlÐáj³Á ¥T@MeÒ•:ˆ¤5ú Ê@˜UzIë(³Ù¬Ñéõ”™ÔkpI«6àz¤1«5Aj4zWT&h_½'q­&(JeÐ} &$bÖ‘xš4©T„ŠÖãZdVã¸AG˜Ì¸Z‚0ãAW›L&³A­ÓS7LÀ ÕªôZ¥2ÀvÚ¤¥U&­6(ˆ&L-\ÒÓZ“š5­Õ@Ô´N¥×zÊDšÕ­áyëÿy#môˆNù ¸ðú;h øÇÿüùZ¥úCü« ¢2þ+’_ôÞåU×_9wmòg}-„~z8¨ÍÅ:GšÔÅô­é¶5;¬î™/(çŸÞ–˜öÍŽ…ys(ÕY#õd ïL¯³òŽe´ÙÙüÅ•µNumá?¾àý‹>ü×U«ñyNѰú§>¯¹Ýgö¡_ë ÒöÝ~mïƒqêñªúît31¢gì|rfkQ^ë¬=ÈLŸé5úBÇü¹UØ„ý»¶¼›Õã"?ÿVwT㎩_íùú@Í®Kµ:ÔŸóp¿úh÷‰½nÕžtý°¯¦Ù¤”MÄý˜/5Ó>;îsôÔï‹3Uöë lè¾ïÞŽúŽì= Ì ¶¶¹é;ù§ë«ï&E[ O.[Óöò†ÉÙKÖ69Ћ¹Ñ1kl0¾öÚªNø®ÄÞ+«Ä©Nk×;ð“íæ5œ5úãZ£Î.öZ¾2f†ºsÕõb:9ÞxèÅ[=áÈŸkä£ám²ÄŽk,ž½ÀöÂÓÞ¸>t©5ê^ƒØ3VPÔtæ°ë §|­ñ‘ßæ®:¡}ÈäÜïê¿(nsA?jð¤›/~?ãUßï}'ÓWF~9‡ŠçýóÑÜaÇæ>Ü/nûfÛ½úÞ#Ò ë37,æ·úNÈk¼ìÐ}¢ÃŠéUR–oüþè/ÖES;¾ÒùÕu~ªÙ¬ÏAjRû‡;ë.Ó4Þzðnçå±µš¾·=¾z~ËÚ{Ã;ĺiC×ïvalÿ‰ÜÔŠßc:å:“;U¯[E5pê¤+—&×3½®ûð˜e4ešòðÓ“½Ïïo~Þ'‹9÷kí•+»œW-v?bi½ý÷:\FgûÕ?¬±8ØùÛµþCÆ|òh™êA•“cl>"iÓ{¹y¼æÂņoG]Xt-àøü%Y5 súGßeš~éÈêŸNÍiqk±¬g½—ó~^Øÿó:Gçe­©7çŠ{¨¿×Ösjî½{ >7‡4yÁr0±ðݶû>ÈòŸã³©ë/Ió"Î)sNúœÞÖ¸þ×oŸ÷Ý=ýTŠÉíóYûZ¡Ù?ÇOð·zξG;æÞÐ~×›ü¼¯ÎFÔ®zϷ﬎‡û5Ø•Õð_þ•ýù£__ÿz×á»ÞŸ²«ö±Mû«¶óJΫŠßžT}wòñ£Ç)¯Ú¯ç&õ+œÖvÓñ†¯™¼gç¯Ùê·üæ`Ñ»YÍ’VâñêüfV¿ám,9õoÝ{¿CÑT,ú­^ ãε¸Ñ~ ±ƒþ☽öcT³K#’üQ_Çlˆ¾_X”ùÐÞ¯1sŽbý@~ž~ÜÅ.'FÛŒ™}ŒM™0®Yh?ZóéÈÍÙ»|™•íÞ ¾S³~¿¹{nÕºskãÜŸÏŸëS [vvJæa:EspÖŸtµê'—šm?kã€w}>ñ¢GÞÌ¥äM|çÂÜc­w¿µ|gRΊAê·â»ê£úñjËA'.r³s>ís‚κP£GvWãÒ5#vWa 0☟mÜÑÉ- û×Î:¿Ï{Å£áYyQ­²š¦W¥¦Þ»B5^§õΩ9¼úÝŠ©çSÔ˜ Ö XQ`\ZðrD­EçF|^Û«Mb×~'ZÎî·›™úÖº¾gTË*ª‰Ö‚K yùëVù~7Ð1"­õßÐï;<³vFÝI«¬¦ß^é}ÂØô zîØþ5†üƽ¸´JÐÜžÞ âÖNžÛ¼(ŸèUmþÑœfaÍß4x¾#1ãPŸ£Æ Ûçï¹É-|aòƒ6i«fÕ{©å{e‰7«’×òÚÄÌiôeß.TCêîGùwºé²¦çÌ«µöææî\¨W3‹nÿ0ª_F‚rcȪáïc³²&9Óêз5tÛ½âV›û«þõmHó‘dµorëÅmîwYW­öÒ8Ý„¡Ó±D¿:ïŽÝùä²Ã½¶âH¯ïD]­¹_kûå[¼Nݘº+ãÛãl䮋ãt¶Üa©Â4Ó"éç›Íï86åõ9÷R÷Ã÷ïÌ;U°uÒƒ£æÝ?ŒoðpßûÇ|bÞî;çÅfg:5:¹ó ýGé]·üXØpÏ´ñáF¢€j[íã¨üïÿ†Z¸-ñ€n˜Á¶¶Yï%u·¬¨FLJ´D3C¶¥ŽÕ¬ùÞɘ o6}kË‹K¦Ç·ê·çî'ÝYíÎ >§«¿ü£¹Ûï…Œ¸W¦:ºÒxE,ú6å“„S7;¯%?îpiáÔÑ˾ÌÛ’|áÓ5ßoÙ™7ñ‰ío×`+‚Ý={aÊ¥ßâWö|3}ñŒ•Ã/¥l¹”yûr«Ë; z­K¹Ñþ,%äöïQóñÂu9ÛW:•{A=Ú·wj_;¿=Á|äóCkØÿí»šÎ¹=ê6Αÿj›‹Q—¬õÙ–mT?ïûá? ÊîÿEÊ×d‘±*¬pMž ¨À Ç>5¿¾ÿ‡žÿèù¿ŽÐVÖ•ûÿlHuÐÇ*l Ðæ?MŠ ®žÛ=#(þuOˆ•ºÌùtþ¯rýW!Ü=ŸM—3|çv„o‡Žzp4ÃZ:·KNŠ4´ëbôÐM£7†IŸÐø‘¡®bÁJøYntðV£ë@ŠCò'¡ìq¹9’ýl0ô¿`%š…°+eôòU0>oõüσ{ÿ÷ï¤öÿŸ°ÿóÇýB­Óè+÷ÿ+Ê{þó,N€–Sÿ:=Qöü§N[™ÿ+þžóŸ®#iGrÃÊ@g@­ H—÷¡3nž›,yó©Žl–b¸"SÚÈtH@–ÝÛ]X¡6E úÛ ‹ç¹L§_„tÖ/Dp²T$›Î¥^:Edå´ !v+çD‡elgSxz®³\ ÷(`-è(¥"\ºBô¬ðvª& #ENÂ/8L®;}.ʦHôtövŸKVé¸f[1‚Öc=öõ‡$ " þ} ¾½7T“û^•ææΓ§)B­LwF ‰Œ´Ù­~ÝÏ3é°ˆNAâOH ,qöôñ»W¬nôpR‰9ŠÄÄ!tàHd(ÒÃ;å´d0l çÐ$饶ÒÊ…–àì‚SP<õäù®éòlE¨Ô/·EIm~ò%Ø8XGCï—¤‚Zd‡-°´Î=ü»º.w %í¤‰±BO‹‘ÎOñ~Ñ$Œ×—PWH=«Sîü_Út6’‘Öèl—¼5ÀR`çYQ¤«%ÒÝÞ÷ 4Ê}þ[öùWë*ó…@¢ỏ7³ýÖlI>Ù-ÚˆOù ÁAáS_d¹êìÍ/m½6vÜ*ë¹'Ϲ³~â©Cþí–_lxïƒãî,òn´|ìÒUíæÿ´kRÌÖÖÂÚ言¤Ñk'0×Ãf øyyÑ>¾áGØÍ}¾U†Íœ9jõÕÐoŸïÐooPûóùßõ°±¿ìj—Û­Å—…[Z~xhx‹s—.Ì?ÜÉÐ÷Ô…Ï[%Q†øÃwÇ-²ž2¯PÔ W¶¹Q3ù£SWG´Þ¢ßpô…‚Gú·}ŒcbO:<½íø)g_nóh×OC^¾¼ú–oü›‹ª4ú¢0ñ`»ZpnÖWdƒí_ÕyÿžÏ£„­¯/=,dx7Ñõðv#`ÖŽ-¯ì'÷Ócd7‰Ú¶øtÛ™í¹E\óv¦Çó¶GEƒÿÒÓ_–.Pny–4Êßÿ+ÿj=†*B¼òü_…ª«Ë3Üìy ”³ÿ£Ò굞ú_Eè ý5*^iÿŠ€¿ºÿ#-Ò Í¨¡¥w…aÁËK&Äp,Ë-Áµ ›!£»X£ÒÂr¬É`…æ*¤#…8³Ù5-Xéš í•O!ØÅ±2¬tA¬Ã†žY8¤‘ª`e©ïhÚê4ÆÆ%Ä„D+¥/¨Õ!7_F‘w€`eÉ4‚„U%Ç3C¥÷OÀâ„%;)[»ëh×EÈãû%³Ò@·VÊ[i®á €´Úþ UbÉA~± \³]Z‚Å&@ï›Å£ô2¿G}%:ÐpX¼¢Óö±$Ô©¥,ÿn;ÉûÀñê&o<¶ÓÅ’çý‘0†7ú +ù²Â¥§Sé7,2)Ûú×VAÿÂzä¬ìµ¯õ†ã/ »w5mè›õWí̽:îάo©ýZ—3ù³gûÿöUd‹c]¹å;/í›{»ö¦‚ˆi_³óW®ômy©úE|D¯«t^Ò£_j\“3î?r^Ìé~¹QöÃZ×ûy¨[v­I ={øhMû!›Ý£rÕM3{ç_˜]kxã"§%fõm:¾Ê’/Ozá­Ë½Bã;^¾_Û£›ß‘«/$7ÈT| ÜZ7aöÍ5cŽ×_ØüAÔ‚¦»köynèNî97ÿáö:SëG¬ú±s8^#ymè+±W«Ð~ûÁ¼æ‹ê?ø3YßþO¯o‹÷ÿÿ>åÅ?ñ‡ýô“`•ñ_ # èÌ@e T0ÐDŽnÒƒ‰‚U{a6!³Ð”‰2ã:B‹kÔÚ M©àH½æyó_ •P •P Oÿšÿ\././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/job_configs.py0000644000000000000000000002470600000000000022203 0ustar0000000000000000""" A selection of job objects used in testing. """ EMPTY_JOB = """\ false true false false false false """.strip() LONG_RUNNING_JOB = """ false true false false false false sleep 100 """.strip() SHORTISH_JOB = """ false true false false false false ping -c 5 127.0.0.1 """.strip() SCM_GIT_JOB = """ false 2 https://github.com/salimfadhley/jenkinsapi.git ** false false false false false false false false false false Default true true false false false false """.strip() JOB_WITH_ARTIFACTS = """ Ping a load of stuff for about 10s false true false false false false ping -c 10 127.0.0.1 > out.txt gzip < out.txt > out.gz *.txt,*.gz false *.* true """.strip() MATRIX_JOB = """ false true false false false false foo one two three ping -c 10 127.0.0.1 """.strip() JOB_WITH_FILE = """ false file.txt true false false false false cat file.txt * false """.strip() JOB_WITH_PARAMETERS = """ A build that explores the wonderous possibilities of parameterized builds. false B B, like buzzing B. true false false false false ping -c 1 127.0.0.1 | tee out.txt echo $A > a.txt echo $B > b.txt * false true """.strip() # noqa JOB_WITH_FILE_AND_PARAMS = """ false file.txt B B, like buzzing B. true false false false false cat file.txt;echo $B > file1.txt * false """.strip() JOB_WITH_ENV_VARS = """\ false true false false false false return [\'key1\': \'value1\', \'key2\': \'value2\'] false """.strip() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_authentication.py0000644000000000000000000000514400000000000023772 0ustar0000000000000000""" System tests for authentication functionality """ import pytest from jenkinsapi.utils.requester import Requester from requests import HTTPError as REQHTTPError from jenkinsapi.jenkins import Jenkins def test_normal_authentication(jenkins_admin_admin): # No problem with the righ user/pass jenkins_user = Jenkins( jenkins_admin_admin.baseurl, jenkins_admin_admin.username, jenkins_admin_admin.password, ) assert jenkins_user is not None # We cannot connect if no user/pass with pytest.raises(REQHTTPError) as http_excep: Jenkins(jenkins_admin_admin.baseurl) assert Requester.AUTH_COOKIE is None assert http_excep.value.response.status_code == 403 # def test_auth_cookie(jenkins_admin_admin): # initial_cookie_value = None # final_cookie_value = "JSESSIONID" # assert initial_cookie_value == Requester.AUTH_COOKIE # # jenkins_admin_admin.use_auth_cookie() # # result = Requester.AUTH_COOKIE # assert result is not None # assert final_cookie_value in result # # # def test_wrongauth_cookie(jenkins_admin_admin): # initial_cookie_value = None # assert initial_cookie_value == Requester.AUTH_COOKIE # # jenkins_admin_admin.username = "fakeuser" # jenkins_admin_admin.password = "fakepass" # # with pytest.raises(HTTPError) as http_excep: # jenkins_admin_admin.use_auth_cookie() # # assert Requester.AUTH_COOKIE is None # assert http_excep.value.code == 401 # # # def test_verify_cookie_isworking(jenkins_admin_admin): # initial_cookie_value = None # final_cookie_value = "JSESSIONID" # assert initial_cookie_value == Requester.AUTH_COOKIE # # # Remove requester user/pass # jenkins_admin_admin.requester.username = None # jenkins_admin_admin.requester.password = None # # # Verify that we cannot connect # with pytest.raises(REQHTTPError) as http_excep: # jenkins_admin_admin.poll() # # assert Requester.AUTH_COOKIE is None # assert http_excep.value.response.status_code == 403 # # # Retrieve the auth cookie, we can because we # # have right values for jenkins_admin_admin.username # # and jenkins_admin_admin.password # jenkins_admin_admin.use_auth_cookie() # # result = Requester.AUTH_COOKIE # assert result is not None # assert final_cookie_value in result # # # Verify that we can connect even with no requester user/pass # # If we have the cookie the requester user/pass is not needed # jenkins_admin_admin.poll() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_credentials.py0000644000000000000000000000753600000000000023257 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import logging import pytest from jenkinsapi_tests.test_utils.random_strings import random_string from jenkinsapi.credentials import Credentials from jenkinsapi.credentials import UsernamePasswordCredential from jenkinsapi.credentials import SecretTextCredential from jenkinsapi.credential import SSHKeyCredential log = logging.getLogger(__name__) def test_get_credentials(jenkins): creds = jenkins.credentials assert isinstance(creds, Credentials) is True def test_delete_inexistant_credential(jenkins): with pytest.raises(KeyError): creds = jenkins.credentials del creds[random_string()] def test_create_user_pass_credential(jenkins): creds = jenkins.credentials cred_descr = random_string() cred_dict = { "description": cred_descr, "userName": "userName", "password": "password", } creds[cred_descr] = UsernamePasswordCredential(cred_dict) assert cred_descr in creds cred = creds[cred_descr] assert isinstance(cred, UsernamePasswordCredential) is True assert cred.password is None assert cred.description == cred_descr del creds[cred_descr] def test_update_user_pass_credential(jenkins): creds = jenkins.credentials cred_descr = random_string() cred_dict = { "description": cred_descr, "userName": "userName", "password": "password", } creds[cred_descr] = UsernamePasswordCredential(cred_dict) cred = creds[cred_descr] cred.userName = "anotheruser" cred.password = "password2" cred = creds[cred_descr] assert isinstance(cred, UsernamePasswordCredential) is True assert cred.userName == "anotheruser" assert cred.password == "password2" def test_create_ssh_credential(jenkins): creds = jenkins.credentials cred_descr = random_string() cred_dict = { "description": cred_descr, "userName": "userName", "passphrase": "", "private_key": "-----BEGIN RSA PRIVATE KEY-----", } creds[cred_descr] = SSHKeyCredential(cred_dict) assert cred_descr in creds cred = creds[cred_descr] assert isinstance(cred, SSHKeyCredential) is True assert cred.description == cred_descr del creds[cred_descr] cred_dict = { "description": cred_descr, "userName": "userName", "passphrase": "", "private_key": "/tmp/key", } with pytest.raises(ValueError): creds[cred_descr] = SSHKeyCredential(cred_dict) cred_dict = { "description": cred_descr, "userName": "userName", "passphrase": "", "private_key": "~/.ssh/key", } with pytest.raises(ValueError): creds[cred_descr] = SSHKeyCredential(cred_dict) cred_dict = { "description": cred_descr, "userName": "userName", "passphrase": "", "private_key": "invalid", } with pytest.raises(ValueError): creds[cred_descr] = SSHKeyCredential(cred_dict) def test_delete_credential(jenkins): creds = jenkins.credentials cred_descr = random_string() cred_dict = { "description": cred_descr, "userName": "userName", "password": "password", } creds[cred_descr] = UsernamePasswordCredential(cred_dict) assert cred_descr in creds del creds[cred_descr] assert cred_descr not in creds def test_create_secret_text_credential(jenkins): """ Tests the creation of a secret text. """ creds = jenkins.credentials cred_descr = random_string() cred_dict = {"description": cred_descr, "secret": "newsecret"} creds[cred_descr] = SecretTextCredential(cred_dict) assert cred_descr in creds cred = creds[cred_descr] assert isinstance(cred, SecretTextCredential) is True assert cred.secret is None assert cred.description == cred_descr del creds[cred_descr] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_crumbs_requester.py0000644000000000000000000000657000000000000024351 0ustar0000000000000000import time import json import logging import pytest from six import StringIO from six.moves.urllib.parse import urljoin from jenkinsapi.jenkins import Jenkins from jenkinsapi.utils.crumb_requester import CrumbRequester from jenkinsapi_tests.test_utils.random_strings import random_string from jenkinsapi_tests.systests.job_configs import JOB_WITH_FILE log = logging.getLogger(__name__) DEFAULT_JENKINS_PORT = 8080 ENABLE_CRUMBS_CONFIG = { "hudson-security-csrf-GlobalCrumbIssuerConfiguration": { "csrf": { "issuer": { "value": "0", "stapler-class": "hudson.security.csrf.DefaultCrumbIssuer", "$class": "hudson.security.csrf.DefaultCrumbIssuer", "excludeClientIPFromCrumb": False, } } } } DISABLE_CRUMBS_CONFIG = { "hudson-security-csrf-GlobalCrumbIssuerConfiguration": {}, } SECURITY_SETTINGS = { "": "0", "markupFormatter": { "stapler-class": "hudson.markup.EscapedMarkupFormatter", "$class": "hudson.markup.EscapedMarkupFormatter", }, "org-jenkinsci-main-modules-sshd-SSHD": { "port": {"value": "", "type": "disabled"} }, "jenkins-CLI": {"enabled": False}, # This is not required if envinject plugin is not installed # but since it is installed for test suite - we must have this config # If this is not present - Jenkins will return error "org-jenkinsci-plugins-envinject-EnvInjectPluginConfiguration": { "enablePermissions": False, "hideInjectedVars": False, "enableLoadingFromMaster": False, }, "jenkins-model-DownloadSettings": {"useBrowser": False}, "slaveAgentPort": {"value": "", "type": "disable"}, "agentProtocol": [ "CLI-connect", "CLI2-connect", "JNLP-connect", "JNLP2-connect", "JNLP4-connect", ], "core:apply": "", } @pytest.fixture(scope="function") def crumbed_jenkins(jenkins): ENABLE_CRUMBS_CONFIG.update(SECURITY_SETTINGS) DISABLE_CRUMBS_CONFIG.update(SECURITY_SETTINGS) jenkins.requester.post_and_confirm_status( urljoin(jenkins.baseurl, "/configureSecurity/configure"), data={"Submit": "save", "json": json.dumps(ENABLE_CRUMBS_CONFIG)}, headers={"Content-Type": "application/x-www-form-urlencoded"}, ) log.info("Enabled Jenkins security") crumbed = Jenkins( jenkins.baseurl, requester=CrumbRequester(baseurl=jenkins.baseurl) ) yield crumbed crumbed.requester.post_and_confirm_status( jenkins.baseurl + "/configureSecurity/configure", data={"Submit": "save", "json": json.dumps(DISABLE_CRUMBS_CONFIG)}, headers={"Content-Type": "application/x-www-form-urlencoded"}, ) log.info("Disabled Jenkins security") def test_invoke_job_with_file(crumbed_jenkins): file_data = random_string() param_file = StringIO(file_data) job_name = "create1_%s" % random_string() job = crumbed_jenkins.create_job(job_name, JOB_WITH_FILE) assert job.has_params() assert len(job.get_params_list()) job.invoke(block=True, files={"file.txt": param_file}) build = job.get_last_build() while build.is_running(): time.sleep(0.25) artifacts = build.get_artifact_dict() assert isinstance(artifacts, dict) is True art_file = artifacts["file.txt"] assert art_file.get_data().decode("utf-8").strip() == file_data ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_downstream_upstream.py0000644000000000000000000000624500000000000025061 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import time import logging import pytest from jenkinsapi.custom_exceptions import NoBuildData log = logging.getLogger(__name__) JOB_CONFIGS = { "A": """ false true false false false false B SUCCESS 0 BLUE """, "B": """ false true false false false false C SUCCESS 0 BLUE """, "C": """ false true false false false false """, } DELAY = 10 def test_stream_relationship(jenkins): """ Can we keep track of the relationships between upstream & downstream jobs? """ for job_name, job_config in JOB_CONFIGS.items(): jenkins.create_job(job_name, job_config) time.sleep(1) jenkins["A"].invoke() for _ in range(10): try: jenkins["C"].get_last_completed_buildnumber() > 0 except NoBuildData: log.info( "Waiting %i seconds for until the final job has run", DELAY ) time.sleep(DELAY) else: break else: pytest.fail("Jenkins took too long to run these jobs") assert jenkins["C"].get_upstream_jobs() == [jenkins["B"]] assert jenkins["B"].get_upstream_jobs() == [jenkins["A"]] assert jenkins["A"].get_downstream_jobs() == [jenkins["B"]] assert jenkins["B"].get_downstream_jobs() == [jenkins["C"]] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_env_vars.py0000644000000000000000000000107600000000000022576 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import time from jenkinsapi_tests.systests.job_configs import JOB_WITH_ENV_VARS from jenkinsapi_tests.test_utils.random_strings import random_string def test_get_env_vars(jenkins): job_name = "get_env_vars_create1_%s" % random_string() job = jenkins.create_job(job_name, JOB_WITH_ENV_VARS) job.invoke(block=True) build = job.get_last_build() while build.is_running(): time.sleep(0.25) data = build.get_env_vars() assert data["key1"] == "value1" assert data["key2"] == "value2" ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_executors.py0000644000000000000000000000432100000000000022770 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import time import logging from jenkinsapi_tests.systests.job_configs import LONG_RUNNING_JOB from jenkinsapi_tests.test_utils.random_strings import random_string log = logging.getLogger(__name__) def test_get_executors(jenkins): node_name = random_string() node_dict = { "num_executors": 2, "node_description": "Test JNLP Node", "remote_fs": "/tmp", "labels": "systest_jnlp", "exclusive": True, } jenkins.nodes.create_node(node_name, node_dict) executors = jenkins.get_executors(node_name) assert executors.count == 2 for count, execs in enumerate(executors): assert count == execs.get_number() assert execs.is_idle() is True def test_running_executor(jenkins): node_name = random_string() node_dict = { "num_executors": 1, "node_description": "Test JNLP Node", "remote_fs": "/tmp", "labels": "systest_jnlp", "exclusive": True, } jenkins.nodes.create_node(node_name, node_dict) job_name = "create_%s" % random_string() job = jenkins.create_job(job_name, LONG_RUNNING_JOB) qq = job.invoke() qq.block_until_building() if job.is_running() is False: time.sleep(1) executors = jenkins.get_executors(node_name) all_idle = True for execs in executors: if execs.is_idle() is False: all_idle = False assert execs.get_progress() != -1 assert execs.get_current_executable() == qq.get_build_number() assert execs.likely_stuck() is False assert all_idle is True, "Executor should have been triggered." def test_idle_executors(jenkins): node_name = random_string() node_dict = { "num_executors": 1, "node_description": "Test JNLP Node", "remote_fs": "/tmp", "labels": "systest_jnlp", "exclusive": True, } jenkins.nodes.create_node(node_name, node_dict) executors = jenkins.get_executors(node_name) for execs in executors: assert execs.get_progress() == -1 assert execs.get_current_executable() is None assert execs.likely_stuck() is False assert execs.is_idle() is True ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_generate_new_api_token.py0000644000000000000000000000127400000000000025447 0ustar0000000000000000""" System tests for generation new api token for logged in user """ import pytest import logging from jenkinsapi.utils.crumb_requester import CrumbRequester log = logging.getLogger(__name__) @pytest.mark.generate_new_api_token def test_generate_new_api_token(jenkins_admin_admin): jenkins_admin_admin.requester = CrumbRequester( baseurl=jenkins_admin_admin.baseurl, username=jenkins_admin_admin.username, password=jenkins_admin_admin.password, ) jenkins_admin_admin.poll() new_token = ( jenkins_admin_admin.generate_new_api_token() ) # generate new token log.info("newly generated token: %s", new_token) assert new_token is not None ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_invocation.py0000644000000000000000000000751200000000000023125 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import time import logging import pytest from jenkinsapi.build import Build from jenkinsapi.queue import QueueItem from jenkinsapi_tests.test_utils.random_strings import random_string from jenkinsapi_tests.systests.job_configs import LONG_RUNNING_JOB from jenkinsapi_tests.systests.job_configs import SHORTISH_JOB, EMPTY_JOB from jenkinsapi.custom_exceptions import BadParams, NotFound log = logging.getLogger(__name__) def test_invocation_object(jenkins): job_name = "Acreate_%s" % random_string() job = jenkins.create_job(job_name, SHORTISH_JOB) qq = job.invoke() assert isinstance(qq, QueueItem) # Let Jenkins catchup qq.block_until_building() assert qq.get_build_number() == 1 def test_get_block_until_build_running(jenkins): job_name = "Bcreate_%s" % random_string() job = jenkins.create_job(job_name, LONG_RUNNING_JOB) qq = job.invoke() time.sleep(3) bn = qq.block_until_building(delay=3).get_number() assert isinstance(bn, int) build = qq.get_build() assert isinstance(build, Build) assert build.is_running() build.stop() # if we call next line right away - Jenkins have no time to stop job # so we wait a bit time.sleep(1) assert not build.is_running() console = build.get_console() assert isinstance(console, str) assert "Started by user" in console def test_get_block_until_build_complete(jenkins): job_name = "Ccreate_%s" % random_string() job = jenkins.create_job(job_name, SHORTISH_JOB) qq = job.invoke() qq.block_until_complete() assert not qq.get_build().is_running() def test_mi_and_get_last_build(jenkins): job_name = "Dcreate_%s" % random_string() job = jenkins.create_job(job_name, SHORTISH_JOB) for _ in range(3): ii = job.invoke() ii.block_until_complete(delay=2) build_number = job.get_last_good_buildnumber() assert build_number == 3 build = job.get_build(build_number) assert isinstance(build, Build) build = job.get_build_metadata(build_number) assert isinstance(build, Build) def test_mi_and_get_build_number(jenkins): job_name = "Ecreate_%s" % random_string() job = jenkins.create_job(job_name, EMPTY_JOB) for invocation in range(3): qq = job.invoke() qq.block_until_complete(delay=1) build_number = qq.get_build_number() assert build_number == invocation + 1 def test_mi_and_delete_build(jenkins): job_name = "Ecreate_%s" % random_string() job = jenkins.create_job(job_name, EMPTY_JOB) for invocation in range(3): qq = job.invoke() qq.block_until_complete(delay=1) build_number = qq.get_build_number() assert build_number == invocation + 1 # Delete build using Job.delete_build job.get_build(1) job.delete_build(1) with pytest.raises(NotFound): job.get_build(1) # Delete build using Job as dictionary of builds assert isinstance(job[2], Build) del job[2] with pytest.raises(NotFound): job.get_build(2) with pytest.raises(NotFound): job.delete_build(99) def test_give_params_on_non_parameterized_job(jenkins): job_name = "Ecreate_%s" % random_string() job = jenkins.create_job(job_name, EMPTY_JOB) with pytest.raises(BadParams): job.invoke(build_params={"foo": "bar", "baz": 99}) def test_keep_build_toggle(jenkins): job_name = "Ecreate_%s" % random_string() job = jenkins.create_job(job_name, EMPTY_JOB) qq = job.invoke() qq.block_until_complete(delay=1) build = job.get_last_build() assert not build.is_kept_forever() build.toggle_keep() assert build.is_kept_forever() build_number = job.get_last_buildnumber() job.toggle_keep_build(build_number) build = job.get_last_build() assert not build.is_kept_forever() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_jenkins.py0000644000000000000000000001276200000000000022420 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import pytest from jenkinsapi.job import Job from jenkinsapi.jobs import Jobs from jenkinsapi.build import Build from jenkinsapi.queue import QueueItem from jenkinsapi_tests.systests.job_configs import EMPTY_JOB from jenkinsapi_tests.test_utils.random_strings import random_string from jenkinsapi.custom_exceptions import UnknownJob def job_present(jenkins, name): jenkins.poll() assert name in jenkins, "Job %r is absent in jenkins." % name assert isinstance(jenkins.get_job(name), Job) is True assert isinstance(jenkins[name], Job) is True def job_absent(jenkins, name): jenkins.poll() assert name not in jenkins, "Job %r is present in jenkins." % name def test_create_job(jenkins): job_name = "create_%s" % random_string() jenkins.create_job(job_name, EMPTY_JOB) job_present(jenkins, job_name) def test_create_job_with_plus(jenkins): job_name = "create+%s" % random_string() jenkins.create_job(job_name, EMPTY_JOB) job_present(jenkins, job_name) job = jenkins[job_name] assert job_name in job.url def test_create_dup_job(jenkins): job_name = "create_%s" % random_string() old_job = jenkins.create_job(job_name, EMPTY_JOB) job_present(jenkins, job_name) new_job = jenkins.create_job(job_name, EMPTY_JOB) assert new_job == old_job def test_get_jobs_info(jenkins): job_name = "create_%s" % random_string() job = jenkins.create_job(job_name, EMPTY_JOB) jobs_info = list(jenkins.get_jobs_info()) assert len(jobs_info) == 1 for url, name in jobs_info: assert url == job.url assert name == job.name def test_create_job_through_jobs_dict(jenkins): job_name = "create_%s" % random_string() jenkins.jobs[job_name] = EMPTY_JOB job_present(jenkins, job_name) def test_enable_disable_job(jenkins): job_name = "create_%s" % random_string() jenkins.create_job(job_name, EMPTY_JOB) job_present(jenkins, job_name) j = jenkins[job_name] j.invoke(block=True) # run this at least once j.disable() assert j.is_enabled() is False, "A disabled job is reporting incorrectly" j.enable() assert j.is_enabled() is True, "An enabled job is reporting incorrectly" def test_get_job_and_update_config(jenkins): job_name = "config_%s" % random_string() jenkins.create_job(job_name, EMPTY_JOB) job_present(jenkins, job_name) config = jenkins[job_name].get_config() assert config.strip() == EMPTY_JOB.strip() jenkins[job_name].update_config(EMPTY_JOB) def test_invoke_job(jenkins): job_name = "create_%s" % random_string() job = jenkins.create_job(job_name, EMPTY_JOB) job.invoke(block=True) assert isinstance(job.get_build(1), Build) def test_invocation_object(jenkins): job_name = "create_%s" % random_string() job = jenkins.create_job(job_name, EMPTY_JOB) ii = job.invoke() assert isinstance(ii, QueueItem) is True def test_get_jobs_list(jenkins): job1_name = "first_%s" % random_string() job2_name = "second_%s" % random_string() jenkins.create_job(job1_name, EMPTY_JOB) jenkins.create_job(job2_name, EMPTY_JOB) assert len(jenkins.jobs) >= 2 job_list = jenkins.get_jobs_list() assert [job1_name, job2_name] == job_list def test_get_job(jenkins): job1_name = "first_%s" % random_string() jenkins.create_job(job1_name, EMPTY_JOB) job = jenkins[job1_name] assert isinstance(job, Job) is True assert job.name == job1_name def test_get_jobs(jenkins): job1_name = "first_%s" % random_string() job2_name = "second_%s" % random_string() jenkins.create_job(job1_name, EMPTY_JOB) jenkins.create_job(job2_name, EMPTY_JOB) jobs = jenkins.jobs assert isinstance(jobs, Jobs) is True assert len(jobs) >= 2 for job_name, job in jobs.iteritems(): assert isinstance(job_name, str) is True assert isinstance(job, Job) is True def test_get_job_that_does_not_exist(jenkins): with pytest.raises(UnknownJob): jenkins["doesnot_exist"] def test_has_job(jenkins): job1_name = "first_%s" % random_string() jenkins.create_job(job1_name, EMPTY_JOB) assert jenkins.has_job(job1_name) is True assert job1_name in jenkins def test_has_no_job(jenkins): assert jenkins.has_job("doesnt_exist") is False assert "doesnt_exist" not in jenkins def test_delete_job(jenkins): job1_name = "delete_me_%s" % random_string() jenkins.create_job(job1_name, EMPTY_JOB) jenkins.delete_job(job1_name) job_absent(jenkins, job1_name) def test_rename_job(jenkins): job1_name = "A__%s" % random_string() job2_name = "B__%s" % random_string() jenkins.create_job(job1_name, EMPTY_JOB) jenkins.rename_job(job1_name, job2_name) job_absent(jenkins, job1_name) job_present(jenkins, job2_name) def test_copy_job(jenkins): template_job_name = "TPL%s" % random_string() copied_job_name = "CPY%s" % random_string() jenkins.create_job(template_job_name, EMPTY_JOB) j = jenkins.copy_job(template_job_name, copied_job_name) job_present(jenkins, template_job_name) job_present(jenkins, copied_job_name) assert isinstance(j, Job) is True assert j.name == copied_job_name def test_get_master_data(jenkins): master_data = jenkins.get_master_data() assert master_data["totalExecutors"] == 2 def test_run_groovy_script(jenkins): expected_result = "Hello world!" result = jenkins.run_groovy_script('print "%s"' % expected_result) assert result.strip() == "Hello world!" ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_jenkins_artifacts.py0000644000000000000000000000401000000000000024443 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import os from posixpath import join import re import time import gzip import shutil import tempfile import logging from jenkinsapi_tests.systests.job_configs import JOB_WITH_ARTIFACTS from jenkinsapi_tests.test_utils.random_strings import random_string log = logging.getLogger(__name__) def test_artifacts(jenkins): job_name = "create_%s" % random_string() job = jenkins.create_job(job_name, JOB_WITH_ARTIFACTS) job.invoke(block=True) build = job.get_last_build() while build.is_running(): time.sleep(1) artifacts = build.get_artifact_dict() assert isinstance(artifacts, dict) is True text_artifact = artifacts["out.txt"] binary_artifact = artifacts["out.gz"] tempDir = tempfile.mkdtemp() try: # Verify that we can handle text artifacts text_artifact.save_to_dir(tempDir, strict_validation=True) text_file_path = join(tempDir, text_artifact.filename) assert os.path.exists(text_file_path) with open(text_file_path, "rb") as f: read_back_text = f.read().strip() read_back_text = read_back_text.decode("ascii") log.info("Text artifact: %s", read_back_text) assert ( re.match(r"^PING \S+ \(127.0.0.1\)", read_back_text) is not None ) assert read_back_text.endswith("ms") is True # Verify that we can hande binary artifacts binary_artifact.save_to_dir(tempDir, strict_validation=True) bin_file_path = join(tempDir, binary_artifact.filename) assert os.path.exists(bin_file_path) with gzip.open(bin_file_path, "rb") as f: read_back_text = f.read().strip() read_back_text = read_back_text.decode("ascii") assert ( re.match(r"^PING \S+ \(127.0.0.1\)", read_back_text) is not None ) assert read_back_text.endswith("ms") is True finally: shutil.rmtree(tempDir) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_jenkins_matrix.py0000644000000000000000000000161600000000000024000 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import re import time from jenkinsapi_tests.systests.job_configs import MATRIX_JOB from jenkinsapi_tests.test_utils.random_strings import random_string def test_invoke_matrix_job(jenkins): job_name = "create_%s" % random_string() job = jenkins.create_job(job_name, MATRIX_JOB) queueItem = job.invoke() queueItem.block_until_complete() build = job.get_last_build() while build.is_running(): time.sleep(1) set_of_groups = set() for run in build.get_matrix_runs(): assert run.get_number() == build.get_number() assert run.get_upstream_build() == build match_result = re.search("\xbb (.*) #\\d+$", run.name) assert match_result is not None set_of_groups.add(match_result.group(1)) build.get_master_job_name() assert set_of_groups == set(["one", "two", "three"]) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_nodes.py0000644000000000000000000001314600000000000022064 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import logging import pytest from jenkinsapi.node import Node from jenkinsapi.credential import SSHKeyCredential from jenkinsapi_tests.test_utils.random_strings import random_string log = logging.getLogger(__name__) TOOL_KEY = "hudson.tasks.Maven$MavenInstallation$DescriptorImpl@Maven 3.0.5" def test_online_offline(jenkins): """ Can we flip the online / offline state of the master node. """ # Master node name should be case insensitive # mn0 = jenkins.get_node('MaStEr') mn = jenkins.get_node("Built-In Node") # self.assertEqual(mn, mn0) mn.set_online() # It should already be online, hence no-op assert mn.is_online() is True mn.set_offline() # We switch that suckah off mn.set_offline() # This should be a no-op assert mn.is_online() is False mn.set_online() # Switch it back on assert mn.is_online() is True def test_create_jnlp_node(jenkins): node_name = random_string() node_dict = { "num_executors": 1, "node_description": "Test JNLP Node", "remote_fs": "/tmp", "labels": "systest_jnlp", "exclusive": True, "tool_location": [ { "key": TOOL_KEY, "home": "/home/apache-maven-3.0.5/", }, ], } node = jenkins.nodes.create_node(node_name, node_dict) assert isinstance(node, Node) is True del jenkins.nodes[node_name] def test_create_ssh_node(jenkins): node_name = random_string() creds = jenkins.get_credentials() cred_descr = random_string() cred_dict = { "description": cred_descr, "userName": "username", "passphrase": "", "private_key": "-----BEGIN RSA PRIVATE KEY-----", } creds[cred_descr] = SSHKeyCredential(cred_dict) node_dict = { "num_executors": 1, "node_description": "Description %s" % node_name, "remote_fs": "/tmp", "labels": node_name, "exclusive": False, "host": "127.0.0.1", "port": 22, "credential_description": cred_descr, "jvm_options": "", "java_path": "", "prefix_start_slave_cmd": "", "suffix_start_slave_cmd": "", "retention": "ondemand", "ondemand_delay": 0, "ondemand_idle_delay": 5, "tool_location": [ { "key": TOOL_KEY, "home": "/home/apache-maven-3.0.5/", }, ], } node = jenkins.nodes.create_node(node_name, node_dict) assert isinstance(node, Node) is True del jenkins.nodes[node_name] jenkins.nodes[node_name] = node_dict assert isinstance(jenkins.nodes[node_name], Node) is True del jenkins.nodes[node_name] def test_delete_node(jenkins): node_name = random_string() node_dict = { "num_executors": 1, "node_description": "Test JNLP Node", "remote_fs": "/tmp", "labels": "systest_jnlp", "exclusive": True, } jenkins.nodes.create_node(node_name, node_dict) del jenkins.nodes[node_name] with pytest.raises(KeyError): jenkins.nodes[node_name] with pytest.raises(KeyError): del jenkins.nodes["not_exist"] def test_delete_all_nodes(jenkins): nodes = jenkins.nodes for name in nodes.keys(): del nodes[name] assert len(jenkins.nodes) == 1 def test_get_node_labels(jenkins): node_name = random_string() node_labels = "LABEL1 LABEL2" node_dict = { "num_executors": 1, "node_description": "Test Node with Labels", "remote_fs": "/tmp", "labels": node_labels, "exclusive": True, } node = jenkins.nodes.create_node(node_name, node_dict) assert node.get_labels() == node_labels del jenkins.nodes[node_name] def test_get_executors(jenkins): node_name = random_string() node_labels = "LABEL1 LABEL2" node_dict = { "num_executors": 1, "node_description": "Test Node with Labels", "remote_fs": "/tmp", "labels": node_labels, "exclusive": True, } node = jenkins.nodes.create_node(node_name, node_dict) with pytest.raises(AttributeError): assert node.get_config_element("executors") == "1" assert node.get_config_element("numExecutors") == "1" del jenkins.nodes[node_name] def test_set_executors(jenkins): node_name = random_string() node_labels = "LABEL1 LABEL2" node_dict = { "num_executors": 1, "node_description": "Test Node with Labels", "remote_fs": "/tmp", "labels": node_labels, "exclusive": True, } node = jenkins.nodes.create_node(node_name, node_dict) assert node.set_config_element("numExecutors", "5") is None assert node.get_config_element("numExecutors") == "5" del jenkins.nodes[node_name] def test_set_master_executors(jenkins): node = jenkins.nodes["Built-In Node"] assert node.get_num_executors() == 2 node.set_num_executors(5) assert node.get_num_executors() == 5 node.set_num_executors(2) def test_offline_reason(jenkins): node_name = random_string() node_labels = "LABEL1 LABEL2" node_dict = { "num_executors": 1, "node_description": "Test Node with Labels", "remote_fs": "/tmp", "labels": node_labels, "exclusive": True, } node = jenkins.nodes.create_node(node_name, node_dict) node.toggle_temporarily_offline("test1") node.poll() assert node.offline_reason() == "test1" node.update_offline_reason("test2") node.poll() assert node.offline_reason() == "test2" del jenkins.nodes[node_name] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_parameterized_builds.py0000644000000000000000000001004100000000000025141 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import time from six import StringIO from jenkinsapi_tests.test_utils.random_strings import random_string from jenkinsapi_tests.systests.job_configs import JOB_WITH_FILE from jenkinsapi_tests.systests.job_configs import JOB_WITH_FILE_AND_PARAMS from jenkinsapi_tests.systests.job_configs import JOB_WITH_PARAMETERS def test_invoke_job_with_file(jenkins): file_data = random_string() param_file = StringIO(file_data) job_name = "create1_%s" % random_string() job = jenkins.create_job(job_name, JOB_WITH_FILE) assert job.has_params() is True assert len(job.get_params_list()) != 0 job.invoke(block=True, files={"file.txt": param_file}) build = job.get_last_build() while build.is_running(): time.sleep(0.25) artifacts = build.get_artifact_dict() assert isinstance(artifacts, dict) is True art_file = artifacts["file.txt"] assert art_file.get_data().decode("utf-8").strip() == file_data def test_invoke_job_parameterized(jenkins): param_B = random_string() job_name = "create2_%s" % random_string() job = jenkins.create_job(job_name, JOB_WITH_PARAMETERS) job.invoke(block=True, build_params={"B": param_B}) build = job.get_last_build() artifacts = build.get_artifact_dict() artB = artifacts["b.txt"] assert artB.get_data().decode("UTF-8", "replace").strip() == param_B assert param_B in build.get_console() def test_parameterized_job_build_queuing(jenkins): """ Accept multiple builds of parameterized jobs with unique parameters. """ job_name = "create_%s" % random_string() job = jenkins.create_job(job_name, JOB_WITH_PARAMETERS) # Latest Jenkins schedules builds to run right away, so remove all # executors from master node to investigate queue master = jenkins.nodes["Built-In Node"] num_executors = master.get_num_executors() master.set_num_executors(0) for i in range(3): param_B = random_string() params = {"B": param_B} job.invoke(build_params=params) assert job.has_queued_build(params) is True master.set_num_executors(num_executors) while job.has_queued_build(params): time.sleep(0.25) build = job.get_last_build() while build.is_running(): time.sleep(0.25) artifacts = build.get_artifact_dict() assert isinstance(artifacts, dict) is True artB = artifacts["b.txt"] assert artB.get_data().decode("utf-8").strip() == param_B assert param_B in build.get_console() def test_parameterized_multiple_builds_get_the_same_queue_item(jenkins): """ Multiple attempts to run the same parameterized build will get the same queue item. """ job_name = "create_%s" % random_string() job = jenkins.create_job(job_name, JOB_WITH_PARAMETERS) # Latest Jenkins schedules builds to run right away, so remove all # executors from master node to investigate queue master = jenkins.nodes["Built-In Node"] num_executors = master.get_num_executors() master.set_num_executors(0) for i in range(3): params = {"B": random_string()} qq0 = job.invoke(build_params=params) qq1 = job.invoke(build_params=params) assert qq0 == qq1 master.set_num_executors(num_executors) def test_invoke_job_with_file_and_params(jenkins): file_data = random_string() param_data = random_string() param_file = StringIO(file_data) job_name = "create_%s" % random_string() job = jenkins.create_job(job_name, JOB_WITH_FILE_AND_PARAMS) assert job.has_params() is True assert len(job.get_params_list()) != 0 qi = job.invoke( block=True, files={"file.txt": param_file}, build_params={"B": param_data}, ) build = qi.get_build() artifacts = build.get_artifact_dict() assert isinstance(artifacts, dict) is True art_file = artifacts["file.txt"] assert art_file.get_data().decode("utf-8").strip() == file_data art_param = artifacts["file1.txt"] assert art_param.get_data().decode("utf-8").strip() == param_data ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_plugins.py0000644000000000000000000000630600000000000022435 0ustar0000000000000000""" System tests for `jenkinsapi.plugins` module. """ import logging import pytest from jenkinsapi_tests.test_utils.random_strings import random_string from jenkinsapi.plugin import Plugin log = logging.getLogger(__name__) def test_plugin_data(jenkins): # It takes time to get plugins json from remote timeout = jenkins.requester.timeout jenkins.requester.timeout = 60 jenkins.plugins.check_updates_server() jenkins.requester.timeout = timeout assert "mailer" in jenkins.plugins def test_get_missing_plugin(jenkins): plugins = jenkins.get_plugins() with pytest.raises(KeyError): plugins["lsdajdaslkjdlkasj"] # this plugin surely does not exist! def test_get_single_plugin(jenkins): plugins = jenkins.get_plugins() plugin_name, plugin = next(plugins.iteritems()) assert isinstance(plugin_name, str) assert isinstance(plugin, Plugin) def test_get_single_plugin_depth_2(jenkins): plugins = jenkins.get_plugins(depth=2) _, plugin = next(plugins.iteritems()) assert isinstance(plugin, Plugin) def test_delete_inexistant_plugin(jenkins): with pytest.raises(KeyError): del jenkins.plugins[random_string()] # def test_install_uninstall_plugin(jenkins): # plugin_name = "suppress-stack-trace" # # plugin_dict = { # "shortName": plugin_name, # "version": "latest", # } # jenkins.plugins[plugin_name] = Plugin(plugin_dict) # # assert plugin_name in jenkins.plugins # # plugin = jenkins.get_plugins()[plugin_name] # assert isinstance(plugin, Plugin) # assert plugin.shortName == plugin_name # # del jenkins.plugins[plugin_name] # assert jenkins.plugins[plugin_name].deleted # # # def test_install_multiple_plugins(jenkins): # plugin_one_name = "keyboard-shortcuts-plugin" # plugin_one_version = "latest" # plugin_one = "@".join((plugin_one_name, plugin_one_version)) # plugin_two = Plugin( # {"shortName": "emotional-jenkins-plugin", "version": "latest"} # ) # # assert isinstance(plugin_two, Plugin) # # plugin_list = [plugin_one, plugin_two] # # jenkins.install_plugins(plugin_list) # # assert plugin_one_name in jenkins.plugins # assert plugin_two.shortName in jenkins.plugins # # del jenkins.plugins["keyboard-shortcuts-plugin"] # del jenkins.plugins["emotional-jenkins-plugin"] # # # def test_downgrade_plugin(jenkins): # plugin_name = "console-badge" # plugin_version = "latest" # plugin = Plugin({"shortName": plugin_name, "version": plugin_version}) # # assert isinstance(plugin, Plugin) # # # Need to restart when not installing the latest version # jenkins.install_plugins([plugin]) # # installed_plugin = jenkins.plugins[plugin_name] # # assert installed_plugin.version == "1.1" # # older_plugin = Plugin({"shortName": plugin_name, "version": "1.0"}) # jenkins.install_plugins( # [older_plugin], restart=True, wait_for_reboot=True) # installed_older_plugin = jenkins.plugins[plugin_name] # # assert installed_older_plugin.version == "1.0" # # del jenkins.plugins[plugin_name] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_queue.py0000644000000000000000000000571300000000000022101 0ustar0000000000000000""" All kinds of testing on Jenkins Queues """ import time import logging import pytest from jenkinsapi.queue import Queue from jenkinsapi.queue import QueueItem from jenkinsapi.job import Job from jenkinsapi_tests.test_utils.random_strings import random_string from jenkinsapi_tests.systests.job_configs import LONG_RUNNING_JOB log = logging.getLogger(__name__) @pytest.fixture(scope="function") def no_executors(jenkins, request): master = jenkins.nodes["Built-In Node"] num_executors = master.get_num_executors() master.set_num_executors(0) def restore(): master.set_num_executors(num_executors) request.addfinalizer(restore) return num_executors def test_get_queue(jenkins): qq = jenkins.get_queue() assert isinstance(qq, Queue) is True def test_invoke_many_jobs(jenkins, no_executors): job_names = [random_string() for _ in range(5)] jobs = [] while len(jenkins.get_queue()) != 0: log.info("Sleeping to get queue empty...") time.sleep(1) for job_name in job_names: j = jenkins.create_job(job_name, LONG_RUNNING_JOB) jobs.append(j) j.invoke() assert j.is_queued_or_running() is True queue = jenkins.get_queue() reprString = repr(queue) assert queue.baseurl in reprString assert len(queue) == 5, queue.keys() assert isinstance(queue[queue.keys()[0]].get_job(), Job) is True items = queue.get_queue_items_for_job(job_names[2]) assert isinstance(items, list) is True assert len(items) == 1 assert isinstance(items[0], QueueItem) is True assert items[0].get_parameters() == [] for _, item in queue.iteritems(): queue.delete_item(item) queue.poll() assert len(queue) == 0 def test_start_and_stop_long_running_job(jenkins): job_name = random_string() j = jenkins.create_job(job_name, LONG_RUNNING_JOB) j.invoke() time.sleep(1) assert j.is_queued_or_running() is True while j.is_queued(): time.sleep(0.5) if j.is_running(): time.sleep(1) j.get_first_build().stop() time.sleep(1) assert j.is_queued_or_running() is False def test_queueitem_for_why_field(jenkins, no_executors): job_names = [random_string() for _ in range(2)] jobs = [] for job_name in job_names: j = jenkins.create_job(job_name, LONG_RUNNING_JOB) jobs.append(j) j.invoke() queue = jenkins.get_queue() for _, item in queue.iteritems(): assert isinstance(item.why, str) is True # Clean up after ourselves for _, item in queue.iteritems(): queue.delete_item(item) def test_queueitem_from_job(jenkins, no_executors): job_name = random_string() j = jenkins.create_job(job_name, LONG_RUNNING_JOB) j.invoke() qi = j.get_queue_item() assert isinstance(qi, QueueItem) assert qi.get_job() == j assert qi.get_job_name() == job_name assert qi.name == job_name assert qi.is_queued() assert not qi.is_running() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_quiet_down.py0000644000000000000000000000114500000000000023126 0ustar0000000000000000""" System tests for setting jenkins in quietDown mode """ import logging log = logging.getLogger(__name__) def test_quiet_down_and_cancel_quiet_down(jenkins): jenkins.poll() # jenkins should be alive jenkins.quiet_down() # put Jenkins in quietDown mode # is_quieting_down = jenkins.is_quieting_down assert jenkins.is_quieting_down is True jenkins.poll() # jenkins should be alive jenkins.cancel_quiet_down() # leave quietDown mode # is_quieting_down = jenkins_api['quietingDown'] assert jenkins.is_quieting_down is False jenkins.poll() # jenkins should be alive ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_restart.py0000644000000000000000000000371200000000000022436 0ustar0000000000000000""" System tests for restarting jenkins NB: this test will be very time consuming because after restart it will wait for jenkins to boot """ import time import logging import pytest from requests import HTTPError, ConnectionError log = logging.getLogger(__name__) def wait_for_restart(jenkins): wait = 15 count = 0 max_count = 30 success = False msg = ( "Jenkins has not restarted yet! (This is try %s of %s, " "waited %s seconds so far) " "Sleeping %s seconds and trying again..." ) while count < max_count or not success: time.sleep(wait) try: jenkins.poll() log.info("Jenkins restarted successfully.") success = True break except HTTPError as ex: log.info(ex) except ConnectionError as ex: log.info(ex) log.info(msg, count + 1, max_count, count * wait, wait) count += 1 if not success: msg = ( "Jenkins did not come back from safe restart! " "Waited {0} seconds altogether. This " "failure may cause other failures." ) log.critical(msg.format(count * wait)) pytest.fail(msg) def test_safe_restart_wait(jenkins): jenkins.poll() # jenkins should be alive jenkins.safe_restart() # restart and wait for reboot (default) jenkins.poll() # jenkins should be alive again def test_safe_restart_dont_wait(jenkins): jenkins.poll() # jenkins should be alive jenkins.safe_restart(wait_for_reboot=False) # Jenkins sleeps for 10 seconds before actually restarting time.sleep(11) with pytest.raises((HTTPError, ConnectionError)): # this is a 503: jenkins is still restarting jenkins.poll() # the test is now complete, but other tests cannot run until # jenkins has finished restarted. to avoid cascading failure # we have to wait for reboot to finish. wait_for_restart(jenkins) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_safe_exit.py0000644000000000000000000000227100000000000022720 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import time import logging from jenkinsapi.build import Build from jenkinsapi_tests.test_utils.random_strings import random_string from jenkinsapi_tests.systests.job_configs import LONG_RUNNING_JOB log = logging.getLogger(__name__) def test_safe_exit(jenkins): job_name = "Bcreate_%s" % random_string() job = jenkins.create_job(job_name, LONG_RUNNING_JOB) qq = job.invoke() time.sleep(3) bn = qq.block_until_building(delay=3).get_number() assert isinstance(bn, int) build = qq.get_build() assert isinstance(build, Build) assert build.is_running() # A job is now running and safe_exit should await running jobs # Call, but wait only for 5 seconds then cancel exit jenkins.safe_exit(wait_for_exit=False) time.sleep(5) jenkins.cancel_quiet_down() # leave quietDown mode assert jenkins.is_quieting_down is False build.stop() # if we call next line right away - Jenkins have no time to stop job # so we wait a bit while build.is_running(): time.sleep(0.5) console = build.get_console() assert isinstance(console, str) assert "Started by user" in console ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_scm.py0000644000000000000000000000225000000000000021530 0ustar0000000000000000# ''' # System tests for `jenkinsapi.jenkins` module. # ''' # To run unittests on python 2.6 please use unittest2 library # try: # import unittest2 as unittest # except ImportError: # import unittest # from jenkinsapi_tests.systests.base import BaseSystemTest # from jenkinsapi_tests.test_utils.random_strings import random_string # from jenkinsapi_tests.systests.job_configs import SCM_GIT_JOB # # Maybe have a base class for all SCM test activites? # class TestSCMGit(BaseSystemTest): # # Maybe it makes sense to move plugin dependencies outside the code. # # Have a config to dependencies mapping from the launcher can use # # to install plugins. # def test_get_revision(self): # job_name = 'git_%s' % random_string() # job = self.jenkins.create_job(job_name, SCM_GIT_JOB) # ii = job.invoke() # ii.block(until='completed') # self.assertFalse(ii.is_running()) # b = ii.get_build() # try: # self.assertIsInstance(b.get_revision(), basestring) # except NameError: # # Python3 # self.assertIsInstance(b.get_revision(), str) # if __name__ == '__main__': # unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/systests/test_views.py0000644000000000000000000001317400000000000022112 0ustar0000000000000000""" System tests for `jenkinsapi.jenkins` module. """ import logging from jenkinsapi.view import View from jenkinsapi.views import Views from jenkinsapi.job import Job from jenkinsapi.api import get_view_from_url from jenkinsapi_tests.systests.job_configs import EMPTY_JOB from jenkinsapi_tests.systests.view_configs import VIEW_WITH_FILTER_AND_REGEX from jenkinsapi_tests.test_utils.random_strings import random_string log = logging.getLogger(__name__) def create_job(jenkins, job_name="whatever"): job = jenkins.create_job(job_name, EMPTY_JOB) return job def test_make_views(jenkins): view_name = random_string() assert view_name not in jenkins.views new_view = jenkins.views.create(view_name) assert view_name in jenkins.views assert isinstance(new_view, View) is True assert view_name == str(new_view) # Can we create a view that already exists? existing = jenkins.views.create(view_name) assert existing == new_view # Can we use the API convenience methods new_view_1 = get_view_from_url(new_view.baseurl) assert new_view == new_view_1 del jenkins.views[view_name] def test_add_job_to_view(jenkins): job_name = random_string() create_job(jenkins, job_name) view_name = random_string() assert view_name not in jenkins.views new_view = jenkins.views.create(view_name) assert view_name in jenkins.views assert isinstance(new_view, View) is True assert job_name not in new_view assert new_view.add_job(job_name) is True assert job_name in new_view assert isinstance(new_view[job_name], Job) is True assert len(new_view) == 1 for j_name, j in new_view.iteritems(): assert j_name == job_name assert isinstance(j, Job) is True for j in new_view.values(): assert isinstance(j, Job) is True jobs = new_view.items() assert isinstance(jobs, list) is True assert isinstance(jobs[0], tuple) is True assert new_view.add_job(job_name) is False assert new_view.add_job("unknown") is False del jenkins.views[view_name] def test_create_and_delete_views(jenkins): view1_name = random_string() new_view = jenkins.views.create(view1_name) assert isinstance(new_view, View) is True assert view1_name in jenkins.views del jenkins.views[view1_name] assert view1_name not in jenkins.views def test_create_and_delete_views_by_url(jenkins): view1_name = random_string() new_view = jenkins.views.create(view1_name) assert isinstance(new_view, View) is True assert view1_name in jenkins.views view_url = new_view.baseurl view_by_url = jenkins.get_view_by_url(view_url) assert isinstance(view_by_url, View) is True jenkins.delete_view_by_url(view_url) assert view1_name not in jenkins.views def test_delete_view_which_does_not_exist(jenkins): view1_name = random_string() assert view1_name not in jenkins.views del jenkins.views[view1_name] def test_update_view_config(jenkins): view_name = random_string() new_view = jenkins.views.create(view_name) assert isinstance(new_view, View) is True assert view_name in jenkins.views config = jenkins.views[view_name].get_config().strip() new_view_config = VIEW_WITH_FILTER_AND_REGEX % view_name assert config != new_view_config jenkins.views[view_name].update_config(new_view_config) config = jenkins.views[view_name].get_config().strip() assert config == new_view_config def test_make_nested_views(jenkins): job = create_job(jenkins) top_view_name = random_string() sub1_view_name = random_string() sub2_view_name = random_string() assert top_view_name not in jenkins.views tv = jenkins.views.create(top_view_name, Views.NESTED_VIEW) assert top_view_name in jenkins.views assert isinstance(tv, View) is True # Empty sub view sv1 = tv.views.create(sub1_view_name) assert sub1_view_name in tv.views assert isinstance(sv1, View) is True # Sub view with job in it tv.views[sub2_view_name] = job.name assert sub2_view_name in tv.views sv2 = tv.views[sub2_view_name] assert isinstance(sv2, View) is True assert job.name in sv2 # Can we use the API convenience methods new_view = get_view_from_url(sv2.baseurl) assert new_view == sv2 def test_add_to_view_after_copy(jenkins): # This test is for issue #291 job = create_job(jenkins) new_job_name = random_string() view_name = random_string() new_view = jenkins.views.create(view_name) new_view = jenkins.views[view_name] new_job = jenkins.copy_job(job.name, new_job_name) assert new_view.add_job(new_job.name) is True assert new_job.name in new_view def test_get_job_config(jenkins): # This test is for issue #301 job = create_job(jenkins) view_name = random_string() new_view = jenkins.views.create(view_name) assert new_view.add_job(job.name) is True assert " %s true true regex false """.strip() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/test_utils/__init__.py0000644000000000000000000000000000000000000021733 0ustar0000000000000000././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/test_utils/random_strings.py0000644000000000000000000000037200000000000023241 0ustar0000000000000000from __future__ import print_function import random import string def random_string(length=10): return "".join( random.choice(string.ascii_lowercase) for i in range(length) ) if __name__ == "__main__": print(random_string()) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/__init__.py0000644000000000000000000000000000000000000021576 0ustar0000000000000000././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/configs.py0000644000000000000000000002472000000000000021506 0ustar0000000000000000# flake8: noqa from jenkinsapi import config JOB_DATA = { "actions": [ { "parameterDefinitions": [ { "defaultParameterValue": { "name": "param1", "value": "test1", }, "description": "", "name": "param1", "type": "StringParameterDefinition", }, { "defaultParameterValue": {"name": "param2", "value": ""}, "description": "", "name": "param2", "type": "StringParameterDefinition", }, ] } ], "description": "test job", "displayName": "foo", "displayNameOrNull": None, "name": "foo", "url": "http://halob:8080/job/foo/", "buildable": True, "builds": [ {"number": 3, "url": "http://halob:8080/job/foo/3/"}, {"number": 2, "url": "http://halob:8080/job/foo/2/"}, {"number": 1, "url": "http://halob:8080/job/foo/1/"}, ], # allBuilds is not present in job dict returned by Jenkins # it is inserted here to test _add_missing_builds() "allBuilds": [ {"number": 3, "url": "http://halob:8080/job/foo/3/"}, {"number": 2, "url": "http://halob:8080/job/foo/2/"}, {"number": 1, "url": "http://halob:8080/job/foo/1/"}, ], "color": "blue", "firstBuild": {"number": 1, "url": "http://halob:8080/job/foo/1/"}, "healthReport": [ { "description": "Build stability: No recent builds failed.", "iconUrl": "health-80plus.png", "score": 100, } ], "inQueue": False, "keepDependencies": False, # build running "lastBuild": {"number": 4, "url": "http://halob:8080/job/foo/4/"}, "lastCompletedBuild": {"number": 3, "url": "http://halob:8080/job/foo/3/"}, "lastFailedBuild": None, "lastStableBuild": {"number": 3, "url": "http://halob:8080/job/foo/3/"}, "lastSuccessfulBuild": { "number": 3, "url": "http://halob:8080/job/foo/3/", }, "lastUnstableBuild": None, "lastUnsuccessfulBuild": None, "nextBuildNumber": 4, "property": [], "queueItem": None, "concurrentBuild": False, # test1 job exists, test2 does not "downstreamProjects": [{"name": "test1"}, {"name": "test2"}], "scm": {}, "upstreamProjects": [], } URL_DATA = {"http://halob:8080/job/foo/%s" % config.JENKINS_API: JOB_DATA} BUILD_DATA = { "actions": [ { "causes": [ { "shortDescription": "Started by user anonymous", "userId": None, "userName": "anonymous", } ] } ], "artifacts": [], "building": False, "builtOn": "localhost", "changeSet": { "items": [ { "affectedPaths": ["content/rcm/v00-rcm-xccdf.xml"], "author": { "absoluteUrl": "http://jenkins_url/user/username79", "fullName": "username", }, "commitId": "3097", "timestamp": 1414398423091, "date": "2014-10-27T08:27:03.091288Z", "msg": "commit message", "paths": [ {"editType": "edit", "file": "/some/path/of/changed_file"} ], "revision": 3097, "user": "username", } ], "kind": None, }, "culprits": [], "description": "Best build ever!", "duration": 5782, "estimatedDuration": 106, "executor": None, "fingerprint": [ { "fileName": "BuildId.json", "hash": "e3850a45ab64aa34c1aa66e30c1a8977", "original": {"name": "ArtifactGenerateJob", "number": 469}, "timestamp": 1380270162488, "usage": [ { "name": "test1", "ranges": {"ranges": [{"end": 567, "start": 566}]}, }, { "name": "test2", "ranges": {"ranges": [{"end": 150, "start": 139}]}, }, ], } ], "fullDisplayName": "foo #1", "id": "2013-05-31_23-15-40", "keepLog": False, "number": 1, "result": "SUCCESS", "timestamp": 1370042140000, "url": "http://localhost:8080/job/foo/1/", "runs": [ {"number": 1, "url": "http//localhost:8080/job/foo/SHARD_NUM=1/1/"}, {"number": 2, "url": "http//localhost:8080/job/foo/SHARD_NUM=1/2/"}, ], } BUILD_DATA_PIPELINE = { "actions": [ { "causes": [ { "shortDescription": "Started by user anonymous", "userId": None, "userName": "anonymous", } ] } ], "artifacts": [], "building": False, "builtOn": "localhost", "changeSets": { "items": [ { "affectedPaths": ["content/rcm/v00-rcm-xccdf.xml"], "author": { "absoluteUrl": "http://jenkins_url/user/username79", "fullName": "username", }, "commitId": "3097", "timestamp": 1414398423091, "date": "2014-10-27T08:27:03.091288Z", "msg": "commit message", "paths": [ {"editType": "edit", "file": "/some/path/of/changed_file"} ], "revision": 3097, "user": "username", } ], "kind": None, }, "culprits": [], "description": "Best build ever!", "duration": 5782, "estimatedDuration": 106, "executor": None, "fingerprint": [ { "fileName": "BuildId.json", "hash": "e3850a45ab64aa34c1aa66e30c1a8977", "original": {"name": "ArtifactGenerateJob", "number": 469}, "timestamp": 1380270162488, "usage": [ { "name": "test1", "ranges": {"ranges": [{"end": 567, "start": 566}]}, }, { "name": "test2", "ranges": {"ranges": [{"end": 150, "start": 139}]}, }, ], } ], "fullDisplayName": "foo #1", "id": "2013-05-31_23-15-40", "keepLog": False, "number": 1, "result": "SUCCESS", "timestamp": 1370042140000, "url": "http://localhost:8080/job/foo/1/", "runs": [ {"number": 1, "url": "http//localhost:8080/job/foo/SHARD_NUM=1/1/"}, {"number": 2, "url": "http//localhost:8080/job/foo/SHARD_NUM=1/2/"}, ], } BUILD_SCM_DATA = { "actions": [ {"causes": [{"shortDescription": "Started by an SCM change"}]}, {}, { "buildsByBranchName": { "origin/HEAD": { "buildNumber": 2, "buildResult": None, "revision": { "SHA1": "d2a5d435fa2df3bff572bd06e43c86544749c5d2", "branch": [ { "SHA1": "d2a5d435fa2df3bff572bd06e43c86544749c5d2", "name": "origin/HEAD", }, { "SHA1": "d2a5d435fa2df3bff572bd06e43c86544749c5d2", "name": "origin/master", }, ], }, }, "origin/master": { "buildNumber": 2, "buildResult": None, "revision": { "SHA1": "d2a5d435fa2df3bff572bd06e43c86544749c5d2", "branch": [ { "SHA1": "d2a5d435fa2df3bff572bd06e43c86544749c5d2", "name": "origin/HEAD", }, { "SHA1": "d2a5d435fa2df3bff572bd06e43c86544749c5d2", "name": "origin/master", }, ], }, }, "origin/python_3_compatibility": { "buildNumber": 1, "buildResult": None, "revision": { "SHA1": "c9d1c96bc926ff63a5209c51b3ed537e62ea50e6", "branch": [ { "SHA1": "c9d1c96bc926ff63a5209c51b3ed537e62ea50e6", "name": "origin/python_3_compatibility", } ], }, }, "origin/unstable": { "buildNumber": 3, "buildResult": None, "revision": { "SHA1": "7def9ed6e92580f37d00e4980c36c4d36e68f702", "branch": [ { "SHA1": "7def9ed6e92580f37d00e4980c36c4d36e68f702", "name": "origin/unstable", } ], }, }, }, "lastBuiltRevision": { "SHA1": "7def9ed6e92580f37d00e4980c36c4d36e68f702", "branch": [ { "SHA1": "7def9ed6e92580f37d00e4980c36c4d36e68f702", "name": "origin/unstable", } ], }, "remoteUrls": ["https://github.com/salimfadhley/jenkinsapi.git"], "scmName": "", }, {}, {}, ], "artifacts": [], "building": False, "builtOn": "", "changeSet": {"items": [], "kind": "git"}, "culprits": [], "description": None, "duration": 1051, "estimatedDuration": 2260, "executor": None, "fullDisplayName": "git_yssrtigfds #3", "id": "2013-06-30_01-54-35", "keepLog": False, "number": 3, "result": "SUCCESS", "timestamp": 1372553675652, "url": "http://localhost:8080/job/git_yssrtigfds/3/", } BUILD_ENV_VARS = { "_class": "org.jenkinsci.plugins.envinject.EnvInjectVarList", "envMap": {"KEY": "VALUE"}, } ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_artifact.py0000644000000000000000000001653200000000000022714 0ustar0000000000000000import pytest from mock import Mock, patch, call from requests.exceptions import HTTPError from jenkinsapi.artifact import Artifact from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.fingerprint import Fingerprint from jenkinsapi.custom_exceptions import ArtifactBroken try: import unittest2 as unittest except ImportError: import unittest @pytest.fixture() def artifact(mocker): return Artifact( "artifact.zip", "http://foo/job/TestJob/1/artifact/artifact.zip", mocker.MagicMock(), ) def test_verify_download_valid_positive(artifact, monkeypatch): def fake_md5(cls, fspath): # pylint: disable=unused-argument return "097c42989a9e5d9dcced7b35ec4b0486" monkeypatch.setattr(Artifact, "_md5sum", fake_md5) def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(JenkinsBase, "_poll", fake_poll) def fake_validate( cls, filename, job, build # pylint: disable=unused-argument ): # pylint: disable=unused-argument return True monkeypatch.setattr(Fingerprint, "validate_for_build", fake_validate) assert artifact._verify_download( "/tmp/artifact.zip", strict_validation=False ) def test_verify_download_valid_positive_with_rename(artifact, monkeypatch): def fake_md5(cls, fspath): # pylint: disable=unused-argument return "097c42989a9e5d9dcced7b35ec4b0486" monkeypatch.setattr(Artifact, "_md5sum", fake_md5) def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(JenkinsBase, "_poll", fake_poll) def fake_validate( cls, filename, job, build # pylint: disable=unused-argument ): # pylint: disable=unused-argument return filename == "artifact.zip" monkeypatch.setattr(Fingerprint, "validate_for_build", fake_validate) assert artifact._verify_download( "/tmp/temporary_filename", strict_validation=False ) def test_verify_download_valid_negative(artifact, monkeypatch): def fake_md5(cls, fspath): # pylint: disable=unused-argument return "097c42989a9e5d9dcced7b35ec4b0486" monkeypatch.setattr(Artifact, "_md5sum", fake_md5) class FakeResponse(object): status_code = 404 text = "{}" class FakeHTTPError(HTTPError): def __init__(self): self.response = FakeResponse() def fake_poll(cls, tree=None): # pylint: disable=unused-argument raise FakeHTTPError() monkeypatch.setattr(JenkinsBase, "_poll", fake_poll) def fake_validate( cls, filename, job, build # pylint: disable=unused-argument ): # pylint: disable=unused-argument return True monkeypatch.setattr(Fingerprint, "validate_for_build", fake_validate) assert artifact._verify_download( "/tmp/artifact.zip", strict_validation=False ) def test_verify_dl_valid_negative_strict(artifact, monkeypatch): def fake_md5(cls, fspath): # pylint: disable=unused-argument return "097c42989a9e5d9dcced7b35ec4b0486" monkeypatch.setattr(Artifact, "_md5sum", fake_md5) class FakeResponse(object): status_code = 404 text = "{}" class FakeHTTPError(HTTPError): def __init__(self): self.response = FakeResponse() def fake_poll(cls, tree=None): # pylint: disable=unused-argument raise FakeHTTPError() monkeypatch.setattr(JenkinsBase, "_poll", fake_poll) with pytest.raises(ArtifactBroken) as ab: artifact._verify_download("/tmp/artifact.zip", strict_validation=True) assert ( "Artifact 097c42989a9e5d9dcced7b35ec4b0486 seems to be broken" in str(ab.value) ) def test_verify_download_invalid(artifact, monkeypatch): def fake_md5(cls, fspath): # pylint: disable=unused-argument return "097c42989a9e5d9dcced7b35ec4b0486" monkeypatch.setattr(Artifact, "_md5sum", fake_md5) def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(JenkinsBase, "_poll", fake_poll) def fake_validate( cls, filename, job, build # pylint: disable=unused-argument ): # pylint: disable=unused-argument return False monkeypatch.setattr(Fingerprint, "validate_for_build", fake_validate) with pytest.raises(ArtifactBroken) as ab: artifact._verify_download("/tmp/artifact.zip", strict_validation=True) assert ( "Artifact 097c42989a9e5d9dcced7b35ec4b0486 seems to be broken" in str(ab.value) ) class ArtifactTest(unittest.TestCase): def setUp(self): self._build = build = Mock() build.buildno = 9999 job = self._build.job job.jenkins.baseurl = "http://localhost" job.name = "TestJob" self._artifact = Artifact( "artifact.zip", "http://localhost/job/TestJob/9999/artifact/artifact.zip", build, ) @patch("jenkinsapi.artifact.os.path.exists", spec=True, return_value=True) def test_save_has_valid_local_copy(self, mock_exists): artifact = self._artifact artifact._verify_download = Mock(return_value=True) assert artifact.save("/tmp/artifact.zip") == "/tmp/artifact.zip" mock_exists.assert_called_once_with("/tmp/artifact.zip") artifact._verify_download.assert_called_once_with( "/tmp/artifact.zip", False ) @patch("jenkinsapi.artifact.os.path.exists", spec=True, return_value=True) def test_save_has_invalid_local_copy_dl_again(self, mock_exists): artifact = self._artifact artifact._verify_download = Mock(side_effect=[ArtifactBroken, True]) artifact._do_download = Mock(return_value="/tmp/artifact.zip") assert artifact.save("/tmp/artifact.zip", True) == "/tmp/artifact.zip" mock_exists.assert_called_once_with("/tmp/artifact.zip") artifact._do_download.assert_called_once_with("/tmp/artifact.zip") assert ( artifact._verify_download.mock_calls == [call("/tmp/artifact.zip", True)] * 2 ) @patch("jenkinsapi.artifact.os.path.exists", spec=True, return_value=True) def test_has_invalid_lcl_copy_dl_but_invalid(self, mock_exists): artifact = self._artifact artifact._verify_download = Mock( side_effect=[ArtifactBroken, ArtifactBroken] ) artifact._do_download = Mock(return_value="/tmp/artifact.zip") with pytest.raises(ArtifactBroken): artifact.save("/tmp/artifact.zip", True) mock_exists.assert_called_once_with("/tmp/artifact.zip") artifact._do_download.assert_called_once_with("/tmp/artifact.zip") assert ( artifact._verify_download.mock_calls == [call("/tmp/artifact.zip", True)] * 2 ) @patch("jenkinsapi.artifact.os.path.exists", spec=True, return_value=False) def test_save_has_no_local_copy(self, mock_exists): artifact = self._artifact artifact._do_download = Mock(return_value="/tmp/artifact.zip") artifact._verify_download = Mock(return_value=True) assert artifact.save("/tmp/artifact.zip") == "/tmp/artifact.zip" mock_exists.assert_called_once_with("/tmp/artifact.zip") artifact._do_download.assert_called_once_with("/tmp/artifact.zip") artifact._verify_download.assert_called_once_with( "/tmp/artifact.zip", False ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_build.py0000644000000000000000000001671200000000000022216 0ustar0000000000000000import requests import pytest import pytz from . import configs import datetime from jenkinsapi.build import Build from jenkinsapi.job import Job @pytest.fixture(scope="function") def jenkins(mocker): return mocker.MagicMock() @pytest.fixture(scope="function") def job(monkeypatch, jenkins): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return configs.JOB_DATA monkeypatch.setattr(Job, "_poll", fake_poll) fake_job = Job("http://", "Fake_Job", jenkins) return fake_job @pytest.fixture(scope="function") def build(job, monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return configs.BUILD_DATA monkeypatch.setattr(Build, "_poll", fake_poll) return Build("http://", 97, job) @pytest.fixture(scope="function") def build_pipeline(job, monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return configs.BUILD_DATA_PIPELINE monkeypatch.setattr(Build, "_poll", fake_poll) return Build("http://", 97, job) def test_timestamp(build): assert isinstance(build.get_timestamp(), datetime.datetime) expected = pytz.utc.localize(datetime.datetime(2013, 5, 31, 23, 15, 40)) assert build.get_timestamp() == expected def test_name(build): with pytest.raises(AttributeError): build.id() assert build.name == "foo #1" def test_duration(build): expected = datetime.timedelta(milliseconds=5782) assert build.get_duration() == expected assert build.get_duration().seconds == 5 assert build.get_duration().microseconds == 782000 assert str(build.get_duration()) == "0:00:05.782000" def test_get_causes(build): assert build.get_causes() == [ { "shortDescription": "Started by user anonymous", "userId": None, "userName": "anonymous", } ] def test_get_changeset(build): assert build.get_changeset_items() == [ { "affectedPaths": ["content/rcm/v00-rcm-xccdf.xml"], "author": { "absoluteUrl": "http://jenkins_url/user/username79", "fullName": "username", }, "commitId": "3097", "timestamp": 1414398423091, "date": "2014-10-27T08:27:03.091288Z", "msg": "commit message", "paths": [ {"editType": "edit", "file": "/some/path/of/changed_file"} ], "revision": 3097, "user": "username", } ] def test_get_changeset_pipeline(build_pipeline): assert build_pipeline.get_changeset_items() == [ { "affectedPaths": ["content/rcm/v00-rcm-xccdf.xml"], "author": { "absoluteUrl": "http://jenkins_url/user/username79", "fullName": "username", }, "commitId": "3097", "timestamp": 1414398423091, "date": "2014-10-27T08:27:03.091288Z", "msg": "commit message", "paths": [ {"editType": "edit", "file": "/some/path/of/changed_file"} ], "revision": 3097, "user": "username", } ] def test_get_description(build): assert build.get_description() == "Best build ever!" def test_get_slave(build): assert build.get_slave() == "localhost" def test_get_revision_no_scm(build): """with no scm, get_revision should return None""" assert build.get_revision() is None def test_downstream(build): expected = ["test1", "test2"] assert build.get_downstream_job_names() == expected def test_get_params(build): expected = { "first_param": "first_value", "second_param": "second_value", } build._data = { "actions": [ { "_class": "hudson.model.ParametersAction", "parameters": [ {"name": "first_param", "value": "first_value"}, {"name": "second_param", "value": "second_value"}, ], } ] } params = build.get_params() assert params == expected def test_get_build_url(build): expected = "http://foo/1" build._data = {"url": "http://foo/1"} url = build.get_build_url() assert url == expected def test_get_params_different_order(build): """ Dictionary with `parameters` key is not always the first element in `actions` list, so we need to search through whole array. This test covers such a case """ expected = { "first_param": "first_value", "second_param": "second_value", } build._data = { "actions": [ { "not_parameters": "some_data", }, { "another_action": "some_value", }, { "_class": "hudson.model.ParametersAction", "parameters": [ {"name": "first_param", "value": "first_value"}, {"name": "second_param", "value": "second_value"}, ], }, ] } params = build.get_params() assert params == expected def test_only_ParametersAction_parameters_considered(build): """Actions other than ParametersAction can have dicts called parameters.""" expected = { "param": "value", } build._data = { "actions": [ { "_class": "hudson.model.SomeOtherAction", "parameters": [ {"name": "Not", "value": "OurValue"}, ], }, { "_class": "hudson.model.ParametersAction", "parameters": [ {"name": "param", "value": "value"}, ], }, ] } params = build.get_params() assert params == expected def test_ParametersWithNoValueSetValueNone_issue_583(build): """SecretParameters don't share their value in the API.""" expected = { "some-secret": None, } build._data = { "actions": [ { "_class": "hudson.model.ParametersAction", "parameters": [ {"name": "some-secret"}, ], } ] } params = build.get_params() assert params == expected def test_build_env_vars(monkeypatch, build): def fake_get_data(cls, tree=None, params=None): return configs.BUILD_ENV_VARS monkeypatch.setattr(Build, "get_data", fake_get_data) assert build.get_env_vars() == configs.BUILD_ENV_VARS["envMap"] def test_build_env_vars_wo_injected_env_vars_plugin(monkeypatch, build): def fake_get_data(cls, tree=None, params=None): raise requests.HTTPError("404") monkeypatch.setattr(Build, "get_data", fake_get_data) with pytest.raises(requests.HTTPError) as excinfo: with pytest.warns(None) as record: build.get_env_vars() assert "404" == str(excinfo.value) assert len(record) == 1 expected = UserWarning( "Make sure the Environment Injector " "plugin is installed." ) assert str(record[0].message) == str(expected) def test_build_env_vars_other_exception(monkeypatch, build): def fake_get_data(cls, tree=None, params=None): raise ValueError() monkeypatch.setattr(Build, "get_data", fake_get_data) with pytest.raises(Exception) as excinfo: with pytest.warns(None) as record: build.get_env_vars() assert "" == str(excinfo.value) assert len(record) == 0 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_build_scm_git.py0000644000000000000000000000327500000000000023723 0ustar0000000000000000import six import pytest from . import configs from jenkinsapi.build import Build from jenkinsapi.job import Job @pytest.fixture(scope="function") def jenkins(mocker): return mocker.MagicMock() @pytest.fixture(scope="function") def job(monkeypatch, jenkins): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return configs.JOB_DATA monkeypatch.setattr(Job, "_poll", fake_poll) fake_job = Job("http://", "Fake_Job", jenkins) return fake_job @pytest.fixture(scope="function") def build(job, monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return configs.BUILD_SCM_DATA monkeypatch.setattr(Build, "_poll", fake_poll) return Build("http://", 97, job) def test_git_scm(build): """ Can we extract git build revision data from a build object? """ assert isinstance(build.get_revision(), six.string_types) assert build.get_revision() == "7def9ed6e92580f37d00e4980c36c4d36e68f702" def test_git_revision_branch(build): """ Can we extract git build branch from a build object? """ assert isinstance(build.get_revision_branch(), list) assert len(build.get_revision_branch()) == 1 assert isinstance(build.get_revision_branch()[0], dict) assert ( build.get_revision_branch()[0]["SHA1"] == "7def9ed6e92580f37d00e4980c36c4d36e68f702" ) assert build.get_revision_branch()[0]["name"] == "origin/unstable" def test_git_repo_url(build): """ Can we Extract git repo url for a given build """ assert isinstance(build.get_repo_url(), str) assert ( build.get_repo_url() == "https://github.com/salimfadhley/jenkinsapi.git" ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674739024.6804104 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_compat.py0000644000000000000000000000112500000000000022372 0ustar0000000000000000# -*- coding: utf-8 -*- import six from jenkinsapi.utils.compat import ( to_string, needs_encoding, ) def test_needs_encoding_py2(): if six.PY2: unicode_str = "юникод" assert needs_encoding(unicode_str) assert not needs_encoding("string") assert not needs_encoding(5) assert not needs_encoding(["list", "of", "strings"]) def test_to_string(): assert isinstance(to_string(5), str) assert isinstance(to_string("string"), str) assert isinstance(to_string(["list", "of", "strings"]), str) assert isinstance(to_string("unicode"), str) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_executors.py0000644000000000000000000002040700000000000023134 0ustar0000000000000000import pytest import mock from jenkinsapi.jenkins import Jenkins from jenkinsapi.executors import Executors from jenkinsapi.executor import Executor DATAM = { "assignedLabels": [{}], "description": None, "jobs": [], "mode": "NORMAL", "nodeDescription": "the master Jenkins node", "nodeName": "", "numExecutors": 2, "overallLoad": {}, "primaryView": {"name": "All", "url": "http://localhost:8080/"}, "quietingDown": False, "slaveAgentPort": 0, "unlabeledLoad": {}, "useCrumbs": False, "useSecurity": False, "views": [ {"name": "All", "url": "http://localhost:8080/"}, {"name": "BigMoney", "url": "http://localhost:8080/view/BigMoney/"}, ], } DATA0 = { "actions": [], "displayName": "host0.host.com", "executors": [{}, {}, {}, {}, {}, {}, {}, {}], "icon": "computer.png", "idle": False, "jnlpAgent": True, "launchSupported": False, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.SwapSpaceMonitor": { "availablePhysicalMemory": 8462417920, "availableSwapSpace": 0, "totalPhysicalMemory": 75858042880, "totalSwapSpace": 0, }, "hudson.node_monitors.ArchitectureMonitor": "Linux (amd64)", "hudson.node_monitors.ResponseTimeMonitor": {"average": 2}, "hudson.node_monitors.TemporarySpaceMonitor": { "path": "/tmp", "size": 430744551424, }, "hudson.node_monitors.DiskSpaceMonitor": { "path": "/data/jenkins", "size": 1214028627968, }, "hudson.node_monitors.ClockMonitor": {"diff": 1}, }, "numExecutors": 8, "offline": False, "offlineCause": None, "offlineCauseReason": "", "oneOffExecutors": [{}, {}], "temporarilyOffline": False, } DATA1 = { "actions": [], "displayName": "host1.host.com", "executors": [{}, {}], "icon": "computer.png", "idle": False, "jnlpAgent": True, "launchSupported": False, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.SwapSpaceMonitor": { "availablePhysicalMemory": 8462417920, "availableSwapSpace": 0, "totalPhysicalMemory": 75858042880, "totalSwapSpace": 0, }, "hudson.node_monitors.ArchitectureMonitor": "Linux (amd64)", "hudson.node_monitors.ResponseTimeMonitor": {"average": 2}, "hudson.node_monitors.TemporarySpaceMonitor": { "path": "/tmp", "size": 430744551424, }, "hudson.node_monitors.DiskSpaceMonitor": { "path": "/data/jenkins", "size": 1214028627968, }, "hudson.node_monitors.ClockMonitor": {"diff": 1}, }, "numExecutors": 2, "offline": False, "offlineCause": None, "offlineCauseReason": "", "oneOffExecutors": [{}, {}], "temporarilyOffline": False, } DATA2 = { "actions": [], "displayName": "host2.host.com", "executors": [{}, {}, {}, {}], "icon": "computer.png", "idle": False, "jnlpAgent": True, "launchSupported": False, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.SwapSpaceMonitor": { "availablePhysicalMemory": 8462417920, "availableSwapSpace": 0, "totalPhysicalMemory": 75858042880, "totalSwapSpace": 0, }, "hudson.node_monitors.ArchitectureMonitor": "Linux (amd64)", "hudson.node_monitors.ResponseTimeMonitor": {"average": 2}, "hudson.node_monitors.TemporarySpaceMonitor": { "path": "/tmp", "size": 430744551424, }, "hudson.node_monitors.DiskSpaceMonitor": { "path": "/data/jenkins", "size": 1214028627968, }, "hudson.node_monitors.ClockMonitor": {"diff": 1}, }, "numExecutors": 4, "offline": False, "offlineCause": None, "offlineCauseReason": "", "oneOffExecutors": [{}, {}], "temporarilyOffline": False, } DATA3 = { "actions": [], "displayName": "host3.host.com", "executors": [{}], "icon": "computer.png", "idle": False, "jnlpAgent": True, "launchSupported": False, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.SwapSpaceMonitor": { "availablePhysicalMemory": 8462417920, "availableSwapSpace": 0, "totalPhysicalMemory": 75858042880, "totalSwapSpace": 0, }, "hudson.node_monitors.ArchitectureMonitor": "Linux (amd64)", "hudson.node_monitors.ResponseTimeMonitor": {"average": 2}, "hudson.node_monitors.TemporarySpaceMonitor": { "path": "/tmp", "size": 430744551424, }, "hudson.node_monitors.DiskSpaceMonitor": { "path": "/data/jenkins", "size": 1214028627968, }, "hudson.node_monitors.ClockMonitor": {"diff": 1}, }, "numExecutors": 1, "offline": False, "offlineCause": None, "offlineCauseReason": "", "oneOffExecutors": [{}, {}], "temporarilyOffline": False, } EXEC0 = { "currentExecutable": { "number": 4168, "url": "http://localhost:8080/job/testjob/4168/", }, "currentWorkUnit": {}, "idle": False, "likelyStuck": False, "number": 0, "progress": 48, } EXEC1 = { "currentExecutable": None, "currentWorkUnit": None, "idle": True, "likelyStuck": False, "number": 0, "progress": -1, } @pytest.fixture(scope="function") def jenkins(monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return DATAM monkeypatch.setattr(Jenkins, "_poll", fake_poll) return Jenkins("http://localhost:8080") def test_repr(jenkins): # Can we produce a repr string for this object assert repr(jenkins) def test_check_url(jenkins): assert jenkins.baseurl == "http://localhost:8080" def test_get_executors(jenkins, monkeypatch): def fake_poll_extr(cls, tree=None): # pylint: disable=unused-argument return EXEC0 def fake_poll_extrs(cls, tree=None): # pylint: disable=unused-argument return DATA3 monkeypatch.setattr(Executor, "_poll", fake_poll_extr) monkeypatch.setattr(Executors, "_poll", fake_poll_extrs) exec_info = jenkins.get_executors(DATA3["displayName"]) assert isinstance(exec_info, object) assert isinstance(repr(exec_info), str) for ex in exec_info: assert ex.get_progress() == 48, "Should return 48 %" def testis_idle(jenkins, monkeypatch): def fake_poll_extr(cls, tree=None): # pylint: disable=unused-argument return EXEC1 def fake_poll_extrs(cls, tree=None): # pylint: disable=unused-argument return DATA3 monkeypatch.setattr(Executor, "_poll", fake_poll_extr) monkeypatch.setattr(Executors, "_poll", fake_poll_extrs) exec_info = jenkins.get_executors("host3.host.com") assert isinstance(exec_info, object) for ex in exec_info: assert ex.get_progress() == -1, "Should return 48 %" assert ex.is_idle() is True, "Should return True" assert repr(ex) == "" @mock.patch.object(Executor, "_poll") def test_likely_stuck(jenkins, monkeypatch): def fake_poll_extr(cls, tree=None): # pylint: disable=unused-argument return EXEC0 monkeypatch.setattr(Executor, "_poll", fake_poll_extr) baseurl = "http://localhost:8080/computer/host0.host.com/executors/0" nodename = "host0.host.com" single_executer = Executor(baseurl, nodename, jenkins, "0") assert single_executer.likely_stuck() is False def test_get_current_executable(jenkins, monkeypatch): def fake_poll_extr(cls, tree=None): # pylint: disable=unused-argument return EXEC0 monkeypatch.setattr(Executor, "_poll", fake_poll_extr) baseurl = "http://localhost:8080/computer/host0.host.com/executors/0" nodename = "host0.host.com" single_executer = Executor(baseurl, nodename, jenkins, "0") assert single_executer.get_current_executable()["number"] == 4168 assert ( single_executer.get_current_executable()["url"] == "http://localhost:8080/job/testjob/4168/" ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_fingerprint.py0000644000000000000000000000560600000000000023446 0ustar0000000000000000import pytest import hashlib from jenkinsapi.jenkins import Jenkins from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.fingerprint import Fingerprint from jenkinsapi.utils.requester import Requester from requests.exceptions import HTTPError @pytest.fixture(scope="function") def jenkins(monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(Jenkins, "_poll", fake_poll) return Jenkins( "http://localhost:8080", username="foouser", password="foopassword" ) @pytest.fixture(scope="module") def dummy_md5(): md = hashlib.md5() md.update("some dummy string".encode("ascii")) return md.hexdigest() def test_object_creation(jenkins, dummy_md5, monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(JenkinsBase, "_poll", fake_poll) fp_instance = Fingerprint("http://foo:8080", dummy_md5, jenkins) assert isinstance(fp_instance, Fingerprint) assert str(fp_instance) == dummy_md5 assert fp_instance.valid() def test_valid_for_404(jenkins, dummy_md5, monkeypatch): class FakeResponse(object): status_code = 404 text = "{}" class FakeHTTPError(HTTPError): def __init__(self): self.response = FakeResponse() def fake_poll(cls, tree=None): # pylint: disable=unused-argument raise FakeHTTPError() monkeypatch.setattr(JenkinsBase, "_poll", fake_poll) def fake_get_url( url, # pylint: disable=unused-argument params=None, # pylint: disable=unused-argument headers=None, # pylint: disable=unused-argument allow_redirects=True, # pylint: disable=unused-argument stream=False, ): # pylint: disable=unused-argument return FakeResponse() monkeypatch.setattr(Requester, "get_url", fake_get_url) fingerprint = Fingerprint("http://foo:8080", dummy_md5, jenkins) assert fingerprint.valid() is True def test_invalid_for_401(jenkins, dummy_md5, monkeypatch): class FakeResponse(object): status_code = 401 text = "{}" class FakeHTTPError(HTTPError): def __init__(self): self.response = FakeResponse() def fake_poll(cls, tree=None): # pylint: disable=unused-argument raise FakeHTTPError() monkeypatch.setattr(JenkinsBase, "_poll", fake_poll) def fake_get_url( url, # pylint: disable=unused-argument params=None, # pylint: disable=unused-argument headers=None, # pylint: disable=unused-argument allow_redirects=True, # pylint: disable=unused-argument stream=False, ): # pylint: disable=unused-argument return FakeResponse() monkeypatch.setattr(Requester, "get_url", fake_get_url) fingerprint = Fingerprint("http://foo:8080", dummy_md5, jenkins) assert fingerprint.valid() is not True ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_jenkins.py0000644000000000000000000003045000000000000022553 0ustar0000000000000000import pytest from collections import namedtuple import jenkinsapi from jenkinsapi.plugins import Plugins from jenkinsapi.utils.requester import Requester from jenkinsapi.jenkins import Jenkins from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.job import Job from jenkinsapi.custom_exceptions import JenkinsAPIException DATA = {} TWO_JOBS_DATA = { "jobs": [ { "name": "job_one", "url": "http://localhost:8080/job/job_one", "color": "blue", }, { "name": "job_two", "url": "http://localhost:8080/job/job_two", "color": "blue", }, ] } MULTIBRANCH_JOBS_DATA = { "jobs": [ { "name": "multibranch-repo/master", "url": "http://localhost:8080/job/multibranch-repo/job/master", "color": "blue", }, { "name": "multibranch-repo/develop", "url": "http://localhost:8080/job/multibranch-repo/job/develop", "color": "blue", }, ] } SCAN_MULTIBRANCH_PIPELINE_LOG = """ Started by timer [Fri Jul 05 06:46:00 CEST 2019] Starting branch indexing... Connecting to https://stash.macq.eu using Jenkins/****** (jenkins-ldap) Repository type: Git Looking up internal/base for branches Checking branch master from internal/base 'Jenkinsfile' found Met criteria No changes detected: master (still at 26d4d8a673f57a957fd5a23f5adfe0be02089294) 1 branches were processed Looking up internal/base for pull requests 0 pull requests were processed [Fri Jul 05 06:46:01 CEST 2019] Finished branch indexing. Indexing took 1.1 sec Finished: SUCCESS """ @pytest.fixture(scope="function") def jenkins(monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(Jenkins, "_poll", fake_poll) return Jenkins( "http://localhost:8080", username="foouser", password="foopassword" ) def test__clone(jenkins): cloned = jenkins._clone() assert id(cloned) != id(jenkins) assert cloned == jenkins def test_stored_passwords(jenkins): assert jenkins.requester.password == "foopassword" assert jenkins.requester.username == "foouser" def test_reload(monkeypatch): class FakeResponse(object): status_code = 200 text = "{}" def fake_get_url( url, # pylint: disable=unused-argument params=None, # pylint: disable=unused-argument headers=None, # pylint: disable=unused-argument allow_redirects=True, # pylint: disable=unused-argument stream=False, ): # pylint: disable=unused-argument return FakeResponse() monkeypatch.setattr(Requester, "get_url", fake_get_url) mock_requester = Requester(username="foouser", password="foopassword") jenkins = Jenkins( "http://localhost:8080/", username="foouser", password="foopassword", requester=mock_requester, ) jenkins.poll() def test_get_jobs_list(monkeypatch): def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument return TWO_JOBS_DATA def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(JenkinsBase, "_poll", fake_jenkins_poll) monkeypatch.setattr(Jenkins, "_poll", fake_jenkins_poll) monkeypatch.setattr(Job, "_poll", fake_job_poll) jenkins = Jenkins( "http://localhost:8080/", username="foouser", password="foopassword" ) for idx, job_name in enumerate(jenkins.get_jobs_list()): assert job_name == TWO_JOBS_DATA["jobs"][idx]["name"] for idx, job_name in enumerate(jenkins.jobs.keys()): assert job_name == TWO_JOBS_DATA["jobs"][idx]["name"] def test_create_new_job_fail(mocker, monkeypatch): def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument return TWO_JOBS_DATA def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(JenkinsBase, "_poll", fake_jenkins_poll) monkeypatch.setattr(Jenkins, "_poll", fake_jenkins_poll) monkeypatch.setattr(Job, "_poll", fake_job_poll) mock_requester = Requester(username="foouser", password="foopassword") mock_requester.post_xml_and_confirm_status = mocker.MagicMock( return_value="" ) jenkins = Jenkins( "http://localhost:8080/", username="foouser", password="foopassword", requester=mock_requester, ) with pytest.raises(JenkinsAPIException) as ar: jenkins.create_job("job_new", None) assert "Job XML config cannot be empty" in str(ar.value) def test_create_multibranch_pipeline_job(mocker, monkeypatch): def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument # return multibranch jobs and other jobs. # create_multibranch_pipeline_job is supposed to filter out # the MULTIBRANCH jobs return {"jobs": TWO_JOBS_DATA["jobs"] + MULTIBRANCH_JOBS_DATA["jobs"]} def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(JenkinsBase, "_poll", fake_jenkins_poll) monkeypatch.setattr(Jenkins, "_poll", fake_jenkins_poll) monkeypatch.setattr(Job, "_poll", fake_job_poll) mock_requester = Requester(username="foouser", password="foopassword") mock_requester.post_xml_and_confirm_status = mocker.MagicMock( return_value="" ) mock_requester.post_and_confirm_status = mocker.MagicMock(return_value="") get_response = namedtuple("get_response", "text") mock_requester.get_url = mocker.MagicMock( return_value=get_response(text=SCAN_MULTIBRANCH_PIPELINE_LOG) ) jenkins = Jenkins( "http://localhost:8080/", username="foouser", password="foopassword", requester=mock_requester, ) jobs = jenkins.create_multibranch_pipeline_job( "multibranch-repo", "multibranch-xml-content" ) for idx, job_instance in enumerate(jobs): assert job_instance.name == MULTIBRANCH_JOBS_DATA["jobs"][idx]["name"] # make sure we didn't get more jobs. assert len(MULTIBRANCH_JOBS_DATA["jobs"]) == len(jobs) def test_get_jenkins_obj_from_url(mocker, monkeypatch): def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument return TWO_JOBS_DATA def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(JenkinsBase, "_poll", fake_jenkins_poll) monkeypatch.setattr(Jenkins, "_poll", fake_jenkins_poll) monkeypatch.setattr(Job, "_poll", fake_job_poll) mock_requester = Requester(username="foouser", password="foopassword") mock_requester.post_xml_and_confirm_status = mocker.MagicMock( return_value="" ) jenkins = Jenkins( "http://localhost:8080/", username="foouser", password="foopassword", requester=mock_requester, ) new_jenkins = jenkins.get_jenkins_obj_from_url("http://localhost:8080/") assert new_jenkins == jenkins new_jenkins = jenkins.get_jenkins_obj_from_url("http://localhost:8080/foo") assert new_jenkins != jenkins def test_get_jenkins_obj(mocker, monkeypatch): def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument return TWO_JOBS_DATA def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(JenkinsBase, "_poll", fake_jenkins_poll) monkeypatch.setattr(Jenkins, "_poll", fake_jenkins_poll) monkeypatch.setattr(Job, "_poll", fake_job_poll) mock_requester = Requester(username="foouser", password="foopassword") mock_requester.post_xml_and_confirm_status = mocker.MagicMock( return_value="" ) jenkins = Jenkins( "http://localhost:8080/", username="foouser", password="foopassword", requester=mock_requester, ) new_jenkins = jenkins.get_jenkins_obj() assert new_jenkins == jenkins def test_get_version(monkeypatch): class MockResponse(object): def __init__(self): self.headers = {} self.headers["X-Jenkins"] = "1.542" def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(Jenkins, "_poll", fake_poll) def fake_get(cls, *arga, **kwargs): # pylint: disable=unused-argument return MockResponse() monkeypatch.setattr(Requester, "get_and_confirm_status", fake_get) jenkins = Jenkins( "http://foobar:8080/", username="foouser", password="foopassword" ) assert jenkins.version == "1.542" def test_get_version_nonexistent(mocker): class MockResponse(object): status_code = 200 headers = {} text = "{}" mock_requester = Requester(username="foouser", password="foopassword") mock_requester.get_url = mocker.MagicMock(return_value=MockResponse()) jenkins = Jenkins( "http://localhost:8080", username="foouser", password="foopassword", requester=mock_requester, ) assert jenkins.version == "0.0" def test_get_master_data(mocker): class MockResponse(object): status_code = 200 headers = {} text = "{}" mock_requester = Requester(username="foouser", password="foopassword") mock_requester.get_url = mocker.MagicMock(return_value=MockResponse()) jenkins = Jenkins( "http://localhost:808", username="foouser", password="foopassword", requester=mock_requester, ) jenkins.get_data = mocker.MagicMock( return_value={"busyExecutors": 59, "totalExecutors": 75} ) data = jenkins.get_master_data() assert data["busyExecutors"] == 59 assert data["totalExecutors"] == 75 def test_get_create_url(monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(Jenkins, "_poll", fake_poll) # Jenkins URL w/o slash jenkins = Jenkins( "http://localhost:8080", username="foouser", password="foopassword" ) assert jenkins.get_create_url() == "http://localhost:8080/createItem" # Jenkins URL w/ slash jenkins = Jenkins( "http://localhost:8080/", username="foouser", password="foopassword" ) assert jenkins.get_create_url() == "http://localhost:8080/createItem" def test_has_plugin(monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(Jenkins, "_poll", fake_poll) def fake_plugin_poll(cls, tree=None): # pylint: disable=unused-argument return { "plugins": [ { "deleted": False, "hasUpdate": True, "downgradable": False, "dependencies": [{}, {}, {}, {}], "longName": "Jenkins Subversion Plug-in", "active": True, "shortName": "subversion", "backupVersion": None, "url": "http://wiki.jenkins-ci.org/" "display/JENKINS/Subversion+Plugin", "enabled": True, "pinned": False, "version": "1.45", "supportsDynamicLoad": "MAYBE", "bundled": True, } ] } monkeypatch.setattr(Plugins, "_poll", fake_plugin_poll) jenkins = Jenkins( "http://localhost:8080/", username="foouser", password="foopassword" ) assert jenkins.has_plugin("subversion") is True def test_get_use_auth_cookie(mocker, monkeypatch): COOKIE_VALUE = "FAKE_COOKIE" def fake_opener(redirect_handler): # pylint: disable=unused-argument mock_response = mocker.MagicMock() mock_response.cookie = COOKIE_VALUE mock_opener = mocker.MagicMock() mock_opener.open.return_value = mock_response return mock_opener def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(Jenkins, "_poll", fake_poll) monkeypatch.setattr(Requester, "AUTH_COOKIE", None) monkeypatch.setattr(jenkinsapi.jenkins, "build_opener", fake_opener) jenkins = Jenkins( "http://localhost:8080", username="foouser", password="foopassword" ) jenkins.use_auth_cookie() assert Requester.AUTH_COOKIE == COOKIE_VALUE ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_job.py0000644000000000000000000002400400000000000021662 0ustar0000000000000000# -*- coding: utf-8 -*- import pytest import mock import json from . import configs from jenkinsapi.job import Job from jenkinsapi.build import Build from jenkinsapi.jenkins import Jenkins from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.custom_exceptions import NoBuildData @pytest.fixture(scope="function") def jenkins(monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(Jenkins, "_poll", fake_poll) new_jenkins = Jenkins("http://halob:8080/") return new_jenkins @pytest.fixture(scope="function") def job(jenkins, monkeypatch): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument return configs.JOB_DATA monkeypatch.setattr(JenkinsBase, "get_data", fake_get_data) new_job = Job("http://halob:8080/job/foo/", "foo", jenkins) return new_job @pytest.fixture(scope="function") def job_tree(jenkins, monkeypatch): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument if tree is not None and "builds" in tree: return {"builds": configs.JOB_DATA["builds"]} else: return {"lastBuild": configs.JOB_DATA["lastBuild"]} monkeypatch.setattr(Job, "get_data", fake_get_data) new_job = Job("http://halob:8080/job/foo/", "foo", jenkins) return new_job @pytest.fixture(scope="function") def job_tree_empty(jenkins, monkeypatch): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(Job, "get_data", fake_get_data) new_job = Job("http://halob:8080/job/foo/", "foo", jenkins) return new_job def test_repr(job): # Can we produce a repr string for this object assert repr(job) == "" def test_name(job): with pytest.raises(AttributeError): job.id() assert job.name == "foo" def test_next_build_number(job): assert job.get_next_build_number() == 4 def test_lastcompleted_build_number(job): assert job.get_last_completed_buildnumber() == 3 def test_lastgood_build_number(job): assert job.get_last_good_buildnumber() == 3 def test_special_urls(job): assert job.baseurl == "http://halob:8080/job/foo" assert job.get_delete_url() == "http://halob:8080/job/foo/doDelete" assert job.get_rename_url() == "http://halob:8080/job/foo/doRename" def test_get_description(job): assert job.get_description() == "test job" def test_get_build_triggerurl(job): assert ( job.get_build_triggerurl() == "http://halob:8080/job/foo/buildWithParameters" ) def test_wrong__mk_json_from_build_parameters(job): with pytest.raises(ValueError) as ar: job._mk_json_from_build_parameters(build_params="bad parameter") assert str(ar.value) == "Build parameters must be a dict" def test_unicode_mk_json(job): json = job._mk_json_from_build_parameters( {"age": 20, "name": "å“å“", "country": "USA", "height": 1.88} ) assert isinstance(json, dict) def test_wrong_field__build_id_for_type(job): with pytest.raises(AssertionError): job._buildid_for_type("wrong") def test_get_last_good_buildnumber(job): ret = job.get_last_good_buildnumber() assert ret == 3 def test_get_last_stable_buildnumber(job): ret = job.get_last_stable_buildnumber() assert ret == 3 def test_get_last_failed_buildnumber(job): with pytest.raises(NoBuildData): job.get_last_failed_buildnumber() def test_get_last_buildnumber(job): ret = job.get_last_buildnumber() assert ret == 4 def test_get_last_completed_buildnumber(job): ret = job.get_last_completed_buildnumber() assert ret == 3 def test_get_build_dict(job_tree): ret = job_tree.get_build_dict() assert isinstance(ret, dict) assert len(ret) == 4 def test_get_build_metadata(job_tree): with pytest.raises(ValueError) as ve: job_tree.get_build_metadata("abc") assert 'Parameter "buildNumber" must be int' in str(ve.value) def test_nobuilds_get_build_dict(job_tree_empty): with pytest.raises(NoBuildData): job_tree_empty.get_build_dict() def test_get_build_ids(job): # We don't want to deal with listreverseiterator here # So we convert result to a list ret = list(job.get_build_ids()) assert isinstance(ret, list) assert len(ret) == 4 def test_nobuilds_get_revision_dict(jenkins, monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {"name": "foo"} monkeypatch.setattr(Job, "_poll", fake_poll) job = Job("http://halob:8080/job/foo/", "foo", jenkins) with pytest.raises(NoBuildData): job.get_revision_dict() def test_nobuilds_get_last_build(jenkins, monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {"name": "foo"} monkeypatch.setattr(Job, "_poll", fake_poll) job = Job("http://halob:8080/job/foo/", "foo", jenkins) with pytest.raises(NoBuildData): job.get_last_build() def test__add_missing_builds_not_all_loaded(jenkins, monkeypatch): def fake_get_data(cls, url, tree): # pylint: disable=unused-argument return configs.JOB_DATA.copy() monkeypatch.setattr(JenkinsBase, "get_data", fake_get_data) job = Job("http://halob:8080/job/foo/", "foo", jenkins) # to test this function we change data to not have one build # and set it to mark that firstBuild was not loaded # in that condition function will call j.get_data # and will use syntetic field 'allBuilds' to # repopulate 'builds' field with all builds mock_data = configs.JOB_DATA.copy() mock_data["firstBuild"] = {"number": 1} del mock_data["builds"][-1] job._data = mock_data assert len(mock_data["builds"]) == 2 new_data = job._add_missing_builds(mock_data) assert len(new_data["builds"]) == 3 def test__add_missing_builds_no_first_build(job, mocker): mocker.spy(JenkinsBase, "get_data") initial_call_count = job.get_data.call_count mock_data = configs.JOB_DATA.copy() mock_data["firstBuild"] = None job._data = mock_data job._add_missing_builds(mock_data) assert initial_call_count == job.get_data.call_count @mock.patch.object(JenkinsBase, "get_data") def test__add_missing_builds_no_builds(job, mocker): mocker.spy(JenkinsBase, "get_data") initial_call_count = job.get_data.call_count mock_data = configs.JOB_DATA.copy() mock_data["builds"] = None job._data = mock_data job._add_missing_builds(mock_data) assert initial_call_count == job.get_data.call_count def test_get_params(job): params = list(job.get_params()) assert len(params) == 2 def test_get_params_list(job): assert job.has_params() is True params = job.get_params_list() assert isinstance(params, list) assert len(params) == 2 assert params == ["param1", "param2"] def json_equal(json_a, json_b): dict_a = json.loads(json_a) dict_b = json.loads(json_b) assert dict_a == dict_b def test_get_json_for_single_param(): params = {"B": "one two three"} expected = ( '{"parameter": {"name": "B", "value": "one two three"}, ' '"statusCode": "303", "redirectTo": "."}' ) json_equal(Job.mk_json_from_build_parameters(params), expected) def test_get_json_for_many_params(): params = {"B": "Honey", "A": "Boo", "C": 2} expected = ( '{"parameter": [{"name": "A", "value": "Boo"}, ' '{"name": "B", "value": "Honey"}, ' '{"name": "C", "value": "2"}], ' '"statusCode": "303", "redirectTo": "."}' ) json_equal(Job.mk_json_from_build_parameters(params), expected) def test__mk_json_from_build_parameters(job): params = {"param1": "value1", "param2": "value2"} expected = { "parameter": [ {"name": "param1", "value": "value1"}, {"name": "param2", "value": "value2"}, ] } result = job._mk_json_from_build_parameters(build_params=params) assert isinstance(result, dict) assert result == expected def test_wrong_mk_json_from_build_parameters(job): with pytest.raises(ValueError) as ar: job.mk_json_from_build_parameters(build_params="bad parameter") assert "Build parameters must be a dict" in str(ar.value) def test_get_build_by_params(jenkins, monkeypatch, mocker): build_params = {"param1": "value1"} fake_builds = ( mocker.Mock(get_params=lambda: {}), mocker.Mock(get_params=lambda: {}), mocker.Mock(get_params=lambda: build_params), ) build_call_count = [0] def fake_get_build(cls, number): # pylint: disable=unused-argument build_call_count[0] += 1 return fake_builds[number - 1] monkeypatch.setattr(Job, "get_first_buildnumber", lambda x: 1) monkeypatch.setattr(Job, "get_last_buildnumber", lambda x: 3) monkeypatch.setattr(Job, "get_build", fake_get_build) mocker.spy(Build, "get_params") mocker.spy(Job, "get_build") job = Job("http://localhost/jobs/foo", "foo", jenkins) result = job.get_build_by_params(build_params) assert job.get_build.call_count == 3 assert build_call_count[0] == 3 assert result == fake_builds[2] def test_get_build_by_params_not_found(jenkins, monkeypatch, mocker): build_params = {"param1": "value1"} fake_builds = ( mocker.Mock(get_params=lambda: {}), mocker.Mock(get_params=lambda: {}), mocker.Mock(get_params=lambda: {}), ) build_call_count = [0] def fake_get_build(cls, number): # pylint: disable=unused-argument build_call_count[0] += 1 return fake_builds[number - 1] monkeypatch.setattr(Job, "get_first_buildnumber", lambda x: 1) monkeypatch.setattr(Job, "get_last_buildnumber", lambda x: 3) monkeypatch.setattr(Job, "get_build", fake_get_build) mocker.spy(Build, "get_params") mocker.spy(Job, "get_build") job = Job("http://localhost/jobs/foo", "foo", jenkins) with pytest.raises(NoBuildData): job.get_build_by_params(build_params) assert job.get_build.call_count == 3 assert build_call_count[0] == 3 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_job_folders.py0000644000000000000000000001672400000000000023412 0ustar0000000000000000import pytest import mock from jenkinsapi.jenkins import JenkinsBase @pytest.fixture(scope="function") def jenkinsbase(): return JenkinsBase("http://localhost:8080/", poll=False) def test_called_in__poll(jenkinsbase, monkeypatch, mocker): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return { "description": "My jobs", "jobs": [ { "name": "Foo", "url": "http://localhost:8080/job/Foo", "color": "blue", } ], "name": "All", "property": [], "url": "http://localhost:8080/view/All/", } monkeypatch.setattr(JenkinsBase, "_poll", fake_poll) stub = mocker.stub() monkeypatch.setattr(JenkinsBase, "resolve_job_folders", stub) jenkinsbase.poll() stub.assert_called_once_with( [ { "name": "Foo", "url": "http://localhost:8080/job/Foo", "color": "blue", }, ], ) def test_no_folders(jenkinsbase): jobs = [ { "name": "Foo", "url": "http://localhost:8080/job/Foo", "color": "blue", }, { "name": "Bar", "url": "http://localhost:8080/job/Bar", "color": "disabled", }, ] assert jenkinsbase.resolve_job_folders(jobs) == [ { "name": "Foo", "url": "http://localhost:8080/job/Foo", "color": "blue", }, { "name": "Bar", "url": "http://localhost:8080/job/Bar", "color": "disabled", }, ] def test_empty_folder(jenkinsbase, monkeypatch, mocker): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument return {"jobs": []} monkeypatch.setattr(JenkinsBase, "get_data", fake_get_data) spy = mocker.spy(jenkinsbase, "get_data") jobs = [ { "name": "Folder1", "url": "http://localhost:8080/job/Folder1", }, ] assert jenkinsbase.resolve_job_folders(jobs) == [] spy.assert_called_once_with( "http://localhost:8080/job/Folder1/api/python", tree="jobs[name,color]" ) def test_folder_job_mix(jenkinsbase, monkeypatch, mocker): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument return { "jobs": [ { "name": "Bar", "url": "http://localhost:8080/job/Folder1/job/Bar", "color": "disabled", } ] } monkeypatch.setattr(JenkinsBase, "get_data", fake_get_data) spy = mocker.spy(jenkinsbase, "get_data") jobs = [ { "name": "Foo", "url": "http://localhost:8080/job/Foo", "color": "blue", }, { "name": "Folder1", "url": "http://localhost:8080/job/Folder1", }, ] assert jenkinsbase.resolve_job_folders(jobs) == [ { "name": "Foo", "url": "http://localhost:8080/job/Foo", "color": "blue", }, { "name": "Bar", "url": "http://localhost:8080/job/Folder1/job/Bar", "color": "disabled", }, ] spy.assert_called_once_with( "http://localhost:8080/job/Folder1/api/python", tree="jobs[name,color]" ) def test_multiple_folders(jenkinsbase, monkeypatch, mocker): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument # first call if "Folder1" in url: return { "jobs": [ { "name": "Foo", "url": "http://localhost:8080/job/Folder1/job/Foo", "color": "disabled", }, ] } if "Folder2" in url: # second call return { "jobs": [ { "name": "Bar", "url": "http://localhost:8080/job/Folder2/job/Bar", "color": "blue", }, ] } monkeypatch.setattr(JenkinsBase, "get_data", fake_get_data) spy = mocker.spy(jenkinsbase, "get_data") jobs = [ { "name": "Folder1", "url": "http://localhost:8080/job/Folder1", }, { "name": "Folder2", "url": "http://localhost:8080/job/Folder2", }, ] assert jenkinsbase.resolve_job_folders(jobs) == [ { "name": "Foo", "url": "http://localhost:8080/job/Folder1/job/Foo", "color": "disabled", }, { "name": "Bar", "url": "http://localhost:8080/job/Folder2/job/Bar", "color": "blue", }, ] assert spy.call_args_list == [ mock.call( "http://localhost:8080/job/Folder1/api/python", tree="jobs[name,color]", ), mock.call( "http://localhost:8080/job/Folder2/api/python", tree="jobs[name,color]", ), ] def test_multiple_folder_levels(jenkinsbase, monkeypatch, mocker): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument if "Folder1" in url and "Folder2" not in url: # first call return { "jobs": [ { "name": "Bar", "url": "http://localhost:8080/job/Folder1/job/Bar", "color": "disabled", }, { "name": "Folder2", "url": "http://localhost:8080/job/Folder1/job/Folder2", }, ] } if "Folder2" in url: # second call return { "jobs": [ { "name": "Baz", "url": ( "http://localhost:8080/job/Folder1/" "job/Folder2/job/Baz" ), "color": "disabled", }, ] } monkeypatch.setattr(JenkinsBase, "get_data", fake_get_data) spy = mocker.spy(jenkinsbase, "get_data") jobs = [ { "name": "Foo", "url": "http://localhost:8080/job/Foo", "color": "blue", }, { "name": "Folder1", "url": "http://localhost:8080/job/Folder1", }, ] assert jenkinsbase.resolve_job_folders(jobs) == [ { "name": "Foo", "url": "http://localhost:8080/job/Foo", "color": "blue", }, { "name": "Bar", "url": "http://localhost:8080/job/Folder1/job/Bar", "color": "disabled", }, { "name": "Baz", "url": ( "http://localhost:8080/job/Folder1" "/job/Folder2/job/Baz" ), "color": "disabled", }, ] assert spy.call_args_list == [ mock.call( "http://localhost:8080/job/Folder1/api/python", tree="jobs[name,color]", ), mock.call( "http://localhost:8080/job/Folder1" "/job/Folder2/api/python", tree="jobs[name,color]", ), ] ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_job_get_all_builds.py0000644000000000000000000002330600000000000024717 0ustar0000000000000000import mock # To run unittests on python 2.6 please use unittest2 library try: import unittest2 as unittest except ImportError: import unittest from jenkinsapi import config from jenkinsapi.job import Job from jenkinsapi.jenkinsbase import JenkinsBase class TestJobGetAllBuilds(unittest.TestCase): # this job has builds JOB1_DATA = { "actions": [], "description": "test job", "displayName": "foo", "displayNameOrNull": None, "name": "foo", "url": "http://halob:8080/job/foo/", "buildable": True, # do as if build 1 & 2 are not returned by jenkins "builds": [{"number": 3, "url": "http://halob:8080/job/foo/3/"}], "color": "blue", "firstBuild": {"number": 1, "url": "http://halob:8080/job/foo/1/"}, "healthReport": [ { "description": "Build stability: No recent builds failed.", "iconUrl": "health-80plus.png", "score": 100, } ], "inQueue": False, "keepDependencies": False, # build running "lastBuild": {"number": 4, "url": "http://halob:8080/job/foo/4/"}, "lastCompletedBuild": { "number": 3, "url": "http://halob:8080/job/foo/3/", }, "lastFailedBuild": None, "lastStableBuild": { "number": 3, "url": "http://halob:8080/job/foo/3/", }, "lastSuccessfulBuild": { "number": 3, "url": "http://halob:8080/job/foo/3/", }, "lastUnstableBuild": None, "lastUnsuccessfulBuild": None, "nextBuildNumber": 4, "property": [], "queueItem": None, "concurrentBuild": False, "downstreamProjects": [], "scm": {}, "upstreamProjects": [], } JOB1_ALL_BUILDS_DATA = { "allBuilds": [ {"number": 3, "url": "http://halob:8080/job/foo/3/"}, {"number": 2, "url": "http://halob:8080/job/foo/2/"}, {"number": 1, "url": "http://halob:8080/job/foo/1/"}, ], } JOB1_API_URL = "http://halob:8080/job/foo/%s" % config.JENKINS_API JOB2_DATA = { "actions": [], "buildable": True, "builds": [], "color": "notbuilt", "concurrentBuild": False, "description": "", "displayName": "look_ma_no_builds", "displayNameOrNull": None, "downstreamProjects": [], "firstBuild": None, "healthReport": [], "inQueue": False, "keepDependencies": False, "lastBuild": None, "lastCompletedBuild": None, "lastFailedBuild": None, "lastStableBuild": None, "lastSuccessfulBuild": None, "lastUnstableBuild": None, "lastUnsuccessfulBuild": None, "name": "look_ma_no_builds", "nextBuildNumber": 1, "property": [{}], "queueItem": None, "scm": {}, "upstreamProjects": [], "url": "http://halob:8080/job/look_ma_no_builds/", } JOB2_API_URL = ( "http://halob:8080/job/look_ma_no_builds/%s" % config.JENKINS_API ) # Full list available immediatly JOB3_DATA = { "actions": [], "description": "test job", "displayName": "fullfoo", "displayNameOrNull": None, "name": "fullfoo", "url": "http://halob:8080/job/fullfoo/", "buildable": True, # all builds have been returned by Jenkins "builds": [ {"number": 3, "url": "http://halob:8080/job/fullfoo/3/"}, {"number": 2, "url": "http://halob:8080/job/fullfoo/2/"}, {"number": 1, "url": "http://halob:8080/job/fullfoo/1/"}, ], "color": "blue", "firstBuild": {"number": 1, "url": "http://halob:8080/job/fullfoo/1/"}, "healthReport": [ { "description": "Build stability: No recent builds failed.", "iconUrl": "health-80plus.png", "score": 100, } ], "inQueue": False, "keepDependencies": False, # build running "lastBuild": {"number": 4, "url": "http://halob:8080/job/fullfoo/4/"}, "lastCompletedBuild": { "number": 3, "url": "http://halob:8080/job/fullfoo/3/", }, "lastFailedBuild": None, "lastStableBuild": { "number": 3, "url": "http://halob:8080/job/fullfoo/3/", }, "lastSuccessfulBuild": { "number": 3, "url": "http://halob:8080/job/fullfoo/3/", }, "lastUnstableBuild": None, "lastUnsuccessfulBuild": None, "nextBuildNumber": 4, "property": [], "queueItem": None, "concurrentBuild": False, "downstreamProjects": [], "scm": {}, "upstreamProjects": [], } JOB3_ALL_BUILDS_DATA = { "allBuilds": [ {"number": 3, "url": "http://halob:8080/job/fullfoo/3/"}, {"number": 2, "url": "http://halob:8080/job/fullfoo/2/"}, {"number": 1, "url": "http://halob:8080/job/fullfoo/1/"}, ], } JOB3_API_URL = "http://halob:8080/job/fullfoo/%s" % config.JENKINS_API URL_DATA = { JOB1_API_URL: JOB1_DATA, (JOB1_API_URL, "allBuilds[number,url]"): JOB1_ALL_BUILDS_DATA, JOB2_API_URL: JOB2_DATA, JOB3_API_URL: JOB3_DATA, # this one below should never be used (JOB3_API_URL, "allBuilds[number,url]"): JOB3_ALL_BUILDS_DATA, } def fakeGetData(self, url, params=None, tree=None): TestJobGetAllBuilds.__get_data_call_count += 1 if params is None: try: return dict(TestJobGetAllBuilds.URL_DATA[url]) except KeyError: raise Exception("Missing data for url: %s" % url) else: try: return dict(TestJobGetAllBuilds.URL_DATA[(url, str(params))]) except KeyError: raise Exception( "Missing data for url: %s with parameters %s" % (url, repr(params)) ) def fakeGetDataTree(self, url, **args): TestJobGetAllBuilds.__get_data_call_count += 1 try: if args["tree"]: if "builds" in args["tree"]: return { "builds": TestJobGetAllBuilds.URL_DATA[url]["builds"] } elif "allBuilds" in args["tree"]: return TestJobGetAllBuilds.URL_DATA[(url, args["tree"])] elif "lastBuild" in args["tree"]: return { "lastBuild": TestJobGetAllBuilds.URL_DATA[url][ "lastBuild" ] } else: return dict(TestJobGetAllBuilds.URL_DATA[url]) except KeyError: raise Exception("Missing data for %s" % url) @mock.patch.object(JenkinsBase, "get_data", fakeGetDataTree) def setUp(self): TestJobGetAllBuilds.__get_data_call_count = 0 self.J = mock.MagicMock() # Jenkins object self.j = Job("http://halob:8080/job/foo/", "foo", self.J) @mock.patch.object(JenkinsBase, "get_data", fakeGetDataTree) def test_get_build_dict(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically ret = self.j.get_build_dict() self.assertTrue(isinstance(ret, dict)) self.assertEqual(len(ret), 4) @mock.patch.object(JenkinsBase, "get_data", fakeGetDataTree) def test_incomplete_builds_list_will_call_jenkins_twice(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically, and to have two calls # to the Jenkins API TestJobGetAllBuilds.__get_data_call_count = 0 self.J.lazy = False self.j = Job("http://halob:8080/job/foo/", "foo", self.J) self.assertEqual(TestJobGetAllBuilds.__get_data_call_count, 2) @mock.patch.object(JenkinsBase, "get_data", fakeGetDataTree) def test_lazy_builds_list_will_not_call_jenkins_twice(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically, and to have two calls # to the Jenkins API TestJobGetAllBuilds.__get_data_call_count = 0 self.J.lazy = True self.j = Job("http://halob:8080/job/foo/", "foo", self.J) self.assertEqual(TestJobGetAllBuilds.__get_data_call_count, 1) self.J.lazy = False @mock.patch.object(JenkinsBase, "get_data", fakeGetDataTree) def test_complete_builds_list_will_call_jenkins_once(self): # The job data contains all builds, so we will not gather remaining # builds TestJobGetAllBuilds.__get_data_call_count = 0 self.j = Job("http://halob:8080/job/fullfoo/", "fullfoo", self.J) self.assertEqual(TestJobGetAllBuilds.__get_data_call_count, 1) @mock.patch.object(JenkinsBase, "get_data", fakeGetDataTree) def test_nobuilds_get_build_dict(self): j = Job( "http://halob:8080/job/look_ma_no_builds/", "look_ma_no_builds", self.J, ) ret = j.get_build_dict() self.assertTrue(isinstance(ret, dict)) self.assertEqual(len(ret), 0) @mock.patch.object(JenkinsBase, "get_data", fakeGetDataTree) def test_get_build_ids(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically ret = list(self.j.get_build_ids()) self.assertTrue(isinstance(ret, list)) self.assertEqual(len(ret), 4) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_job_scm_hg.py0000644000000000000000000002114600000000000023206 0ustar0000000000000000# flake8: noqa # import mock # # # To run unittests on python 2.6 please use unittest2 library # try: # import unittest2 as unittest # except ImportError: # import unittest # # from jenkinsapi import config # from jenkinsapi.job import Job # from jenkinsapi.jenkinsbase import JenkinsBase # # # CFG_NODE = """ # # # http://cm5/hg/sandbox/v01.0/int # # false # # http://cm5/hg/sandbox/v01.0/int/ # # # # """ # # # TODO: Make JOB_DATA to be one coming from Hg job # class TestHgJob(unittest.TestCase): # JOB_DATA = { # "actions": [], # "description": "test job", # "displayName": "foo", # "displayNameOrNull": None, # "name": "foo", # "url": "http://halob:8080/job/foo/", # "buildable": True, # "builds": [ # {"number": 3, "url": "http://halob:8080/job/foo/3/"}, # {"number": 2, "url": "http://halob:8080/job/foo/2/"}, # {"number": 1, "url": "http://halob:8080/job/foo/1/"}, # ], # "color": "blue", # "firstBuild": {"number": 1, "url": "http://halob:8080/job/foo/1/"}, # "healthReport": [ # { # "description": "Build stability: No recent builds failed.", # "iconUrl": "health-80plus.png", # "score": 100, # } # ], # "inQueue": False, # "keepDependencies": False, # # build running # "lastBuild": {"number": 4, "url": "http://halob:8080/job/foo/4/"}, # "lastCompletedBuild": { # "number": 3, # "url": "http://halob:8080/job/foo/3/", # }, # "lastFailedBuild": None, # "lastStableBuild": { # "number": 3, # "url": "http://halob:8080/job/foo/3/", # }, # "lastSuccessfulBuild": { # "number": 3, # "url": "http://halob:8080/job/foo/3/", # }, # "lastUnstableBuild": None, # "lastUnsuccessfulBuild": None, # "nextBuildNumber": 4, # "property": [], # "queueItem": None, # "concurrentBuild": False, # "downstreamProjects": [], # "scm": {}, # "upstreamProjects": [], # } # # URL_DATA = {"http://halob:8080/job/foo/%s" % config.JENKINS_API: JOB_DATA} # # def fakeGetData(self, url, *args, **kwargs): # try: # return TestHgJob.URL_DATA[url] # except KeyError: # raise Exception("Missing data for %s" % url) # # @mock.patch.object(JenkinsBase, "get_data", fakeGetData) # def setUp(self): # self.J = mock.MagicMock() # Jenkins object # self.j = Job("http://halob:8080/job/foo/", "foo", self.J) # # def configtree_with_branch(self): # config_node = CFG_NODE # return config_node # # def configtree_with_default_branch(self): # config_node = CFG_NODE # return config_node # # def configtree_multibranch_git(self): # config_node = """ # # false # # # # # H H * * H(6-7) # # # # # # SUCCESS # 0 # BLUE # true # # # # # # # -1 # 5 # -1 # 5 # # # # # a2d4bcda-6141-4af2-8088-39139a147902 # # master # GIT # # # 2 # # # origin # +refs/heads/master:refs/remotes/origin/master # ssh://git@bitbucket.site/project-name/reponame.git # jenkins-stash # # # # # master # # # false # # https://bitbucket.site/projects/project-name/repos/reponame # # # # # false # # # # # # # # # Jenkinsfile # # # false # # """ # return config_node # # @mock.patch.object(Job, "get_config", configtree_with_branch) # def test_hg_attributes(self): # expected_url = ["http://cm5/hg/sandbox/v01.0/int"] # self.j.load_config() # self.assertEqual(self.j.get_scm_type(), "hg") # self.assertEqual(self.j.get_scm_url(), expected_url) # self.assertEqual(self.j.get_scm_branch(), ["testme"]) # # @mock.patch.object(Job, "get_config", configtree_with_default_branch) # def test_hg_attributes_default_branch(self): # self.j.load_config() # self.assertEqual(self.j.get_scm_branch(), ["default"]) # # @mock.patch.object(Job, "get_config", configtree_multibranch_git) # def test_git_attributes_multibranch(self): # expected_url = ["ssh://git@bitbucket.site/project-name/reponame.git"] # self.j.load_config() # self.assertEqual(self.j.get_scm_type(), "git") # self.assertEqual(self.j.get_scm_url(), expected_url) # self.assertEqual(self.j.get_scm_branch(), ["master"]) # # # if __name__ == "__main__": # unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_label.py0000644000000000000000000000426700000000000022200 0ustar0000000000000000import pytest from jenkinsapi.label import Label DATA = { "actions": [], "busyExecutors": 0, "clouds": [], "description": None, "idleExecutors": 0, "loadStatistics": {}, "name": "jenkins-slave", "nodes": [], "offline": True, "tiedJobs": [ { "name": "test_job1", "url": "http://jtest:8080/job/test_job1/", "color": "blue", }, { "name": "test_job2", "url": "http://jtest:8080/job/test_job2/", "color": "blue", }, { "name": "test_job3", "url": "http://jtest:8080/job/test_job3/", "color": "blue", }, { "name": "test_job4", "url": "http://jtest:8080/job/test_job4/", "color": "blue", }, ], "totalExecutors": 0, "propertiesList": [], } DATA_JOB_NAMES = { "tiedJobs": [ {"name": "test_job1"}, {"name": "test_job2"}, {"name": "test_job3"}, {"name": "test_job4"}, ] } DATA_JOBS = [ { "url": "http://jtest:8080/job/test_job1/", "color": "blue", "name": "test_job1", }, { "url": "http://jtest:8080/job/test_job2/", "color": "blue", "name": "test_job2", }, { "url": "http://jtest:8080/job/test_job3/", "color": "blue", "name": "test_job3", }, { "url": "http://jtest:8080/job/test_job4/", "color": "blue", "name": "test_job4", }, ] @pytest.fixture(scope="function") def label(monkeypatch, mocker): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return DATA monkeypatch.setattr(Label, "_poll", fake_poll) jenkins = mocker.MagicMock() return Label("http://foo:8080", "jenkins-slave", jenkins) def test_repr(label): # Can we produce a repr string for this object repr(label) def test_name(label): with pytest.raises(AttributeError): label.id() assert label.labelname == "jenkins-slave" def test_get_tied_job_names(label): assert label.get_tied_job_names() == DATA_JOBS def test_online(label): assert label.is_online() is False ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_misc.py0000644000000000000000000000065000000000000022044 0ustar0000000000000000import jenkinsapi def test_jenkinsapi_version(): """Verify that we can get the jenkinsapi version number from the package's __version__ property. """ version = jenkinsapi.__version__ # only first two parts must be interger, 1.0.dev5 being a valid version. parts = [int(x) for x in version.split(".")[0:2]] for part in parts: assert part >= 0, "Implausible version number: %r" % version ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_node.py0000644000000000000000000000765600000000000022053 0ustar0000000000000000import pytest from jenkinsapi.node import Node DATA = { "actions": [], "displayName": "bobnit", "executors": [{}], "icon": "computer.png", "idle": True, "jnlpAgent": False, "launchSupported": True, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.SwapSpaceMonitor": { "availablePhysicalMemory": 7681417216, "availableSwapSpace": 12195983360, "totalPhysicalMemory": 8374497280, "totalSwapSpace": 12195983360, }, "hudson.node_monitors.ArchitectureMonitor": "Linux (amd64)", "hudson.node_monitors.ResponseTimeMonitor": {"average": 64}, "hudson.node_monitors.TemporarySpaceMonitor": { "path": "/tmp", "size": 250172776448, }, "hudson.node_monitors.DiskSpaceMonitor": { "path": "/home/sal/jenkins", "size": 170472026112, }, "hudson.node_monitors.ClockMonitor": {"diff": 6736}, }, "numExecutors": 1, "offline": False, "offlineCause": None, "oneOffExecutors": [], "temporarilyOffline": False, } @pytest.fixture(scope="function") def node(monkeypatch, mocker): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return DATA monkeypatch.setattr(Node, "_poll", fake_poll) jenkins = mocker.MagicMock() return Node(jenkins, "http://foo:8080", "bobnit", {}) def test_repr(node): # Can we produce a repr string for this object repr(node) def test_name(node): with pytest.raises(AttributeError): node.id() assert node.name == "bobnit" def test_online(node): assert node.is_online() is True def test_available_physical_memory(node): monitor = DATA["monitorData"]["hudson.node_monitors.SwapSpaceMonitor"] expected_value = monitor["availablePhysicalMemory"] assert node.get_available_physical_memory() == expected_value def test_available_swap_space(node): monitor = DATA["monitorData"]["hudson.node_monitors.SwapSpaceMonitor"] expected_value = monitor["availableSwapSpace"] assert node.get_available_swap_space() == expected_value def test_total_physical_memory(node): monitor = DATA["monitorData"]["hudson.node_monitors.SwapSpaceMonitor"] expected_value = monitor["totalPhysicalMemory"] assert node.get_total_physical_memory() == expected_value def test_total_swap_space(node): monitor = DATA["monitorData"]["hudson.node_monitors.SwapSpaceMonitor"] expected_value = monitor["totalSwapSpace"] assert node.get_total_swap_space() == expected_value def test_workspace_path(node): monitor = DATA["monitorData"]["hudson.node_monitors.DiskSpaceMonitor"] expected_value = monitor["path"] assert node.get_workspace_path() == expected_value def test_workspace_size(node): monitor = DATA["monitorData"]["hudson.node_monitors.DiskSpaceMonitor"] expected_value = monitor["size"] assert node.get_workspace_size() == expected_value def test_temp_path(node): monitor = DATA["monitorData"]["hudson.node_monitors.TemporarySpaceMonitor"] expected_value = monitor["path"] assert node.get_temp_path() == expected_value def test_temp_size(node): monitor = DATA["monitorData"]["hudson.node_monitors.TemporarySpaceMonitor"] expected_value = monitor["size"] assert node.get_temp_size() == expected_value def test_architecture(node): expected_value = DATA["monitorData"][ "hudson.node_monitors.ArchitectureMonitor" ] assert node.get_architecture() == expected_value def test_response_time(node): monitor = DATA["monitorData"]["hudson.node_monitors.ResponseTimeMonitor"] expected_value = monitor["average"] assert node.get_response_time() == expected_value def test_clock_difference(node): monitor = DATA["monitorData"]["hudson.node_monitors.ClockMonitor"] expected_value = monitor["diff"] assert node.get_clock_difference() == expected_value ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_nodes.py0000644000000000000000000002147700000000000022233 0ustar0000000000000000import pytest from jenkinsapi.jenkins import Jenkins from jenkinsapi.nodes import Nodes from jenkinsapi.node import Node DATA0 = { "assignedLabels": [{}], "description": None, "jobs": [], "mode": "NORMAL", "nodeDescription": "the master Jenkins node", "nodeName": "", "numExecutors": 2, "overallLoad": {}, "primaryView": {"name": "All", "url": "http://halob:8080/"}, "quietingDown": False, "slaveAgentPort": 0, "unlabeledLoad": {}, "useCrumbs": False, "useSecurity": False, "views": [ {"name": "All", "url": "http://halob:8080/"}, {"name": "FodFanFo", "url": "http://halob:8080/view/FodFanFo/"}, ], } DATA1 = { "busyExecutors": 0, "computer": [ { "actions": [], "displayName": "master", "executors": [{}, {}], "icon": "computer.png", "idle": True, "jnlpAgent": False, "launchSupported": True, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.ArchitectureMonitor": "Linux (amd64)", "hudson.node_monitors.ClockMonitor": {"diff": 0}, "hudson.node_monitors.DiskSpaceMonitor": { "path": "/var/lib/jenkins", "size": 671924924416, }, "hudson.node_monitors.ResponseTimeMonitor": {"average": 0}, "hudson.node_monitors.SwapSpaceMonitor": { "availablePhysicalMemory": 3174686720, "availableSwapSpace": 17163087872, "totalPhysicalMemory": 16810180608, "totalSwapSpace": 17163087872, }, "hudson.node_monitors.TemporarySpaceMonitor": { "path": "/tmp", "size": 671924924416, }, }, "numExecutors": 2, "offline": False, "offlineCause": None, "oneOffExecutors": [], "temporarilyOffline": False, }, { "actions": [], "displayName": "bobnit", "executors": [{}], "icon": "computer-x.png", "idle": True, "jnlpAgent": False, "launchSupported": True, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.ArchitectureMonitor": "Linux (amd64)", "hudson.node_monitors.ClockMonitor": {"diff": 4261}, "hudson.node_monitors.DiskSpaceMonitor": { "path": "/home/sal/jenkins", "size": 169784860672, }, "hudson.node_monitors.ResponseTimeMonitor": {"average": 29}, "hudson.node_monitors.SwapSpaceMonitor": { "availablePhysicalMemory": 4570710016, "availableSwapSpace": 12195983360, "totalPhysicalMemory": 8374497280, "totalSwapSpace": 12195983360, }, "hudson.node_monitors.TemporarySpaceMonitor": { "path": "/tmp", "size": 249737277440, }, }, "numExecutors": 1, "offline": True, "offlineCause": {}, "oneOffExecutors": [], "temporarilyOffline": False, }, { "actions": [], "displayName": "halob", "executors": [{}], "icon": "computer-x.png", "idle": True, "jnlpAgent": True, "launchSupported": False, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.ArchitectureMonitor": None, "hudson.node_monitors.ClockMonitor": None, "hudson.node_monitors.DiskSpaceMonitor": None, "hudson.node_monitors.ResponseTimeMonitor": None, "hudson.node_monitors.SwapSpaceMonitor": None, "hudson.node_monitors.TemporarySpaceMonitor": None, }, "numExecutors": 1, "offline": True, "offlineCause": None, "oneOffExecutors": [], "temporarilyOffline": False, }, ], "displayName": "nodes", "totalExecutors": 2, } DATA2 = { "actions": [], "displayName": "master", "executors": [{}, {}], "icon": "computer.png", "idle": True, "jnlpAgent": False, "launchSupported": True, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.ArchitectureMonitor": "Linux (amd64)", "hudson.node_monitors.ClockMonitor": {"diff": 0}, "hudson.node_monitors.DiskSpaceMonitor": { "path": "/var/lib/jenkins", "size": 671942561792, }, "hudson.node_monitors.ResponseTimeMonitor": {"average": 0}, "hudson.node_monitors.SwapSpaceMonitor": { "availablePhysicalMemory": 2989916160, "availableSwapSpace": 17163087872, "totalPhysicalMemory": 16810180608, "totalSwapSpace": 17163087872, }, "hudson.node_monitors.TemporarySpaceMonitor": { "path": "/tmp", "size": 671942561792, }, }, "numExecutors": 2, "offline": False, "offlineCause": None, "oneOffExecutors": [], "temporarilyOffline": False, } DATA3 = { "actions": [], "displayName": "halob", "executors": [{}], "icon": "computer-x.png", "idle": True, "jnlpAgent": True, "launchSupported": False, "loadStatistics": {}, "manualLaunchAllowed": True, "monitorData": { "hudson.node_monitors.ArchitectureMonitor": None, "hudson.node_monitors.ClockMonitor": None, "hudson.node_monitors.DiskSpaceMonitor": None, "hudson.node_monitors.ResponseTimeMonitor": None, "hudson.node_monitors.SwapSpaceMonitor": None, "hudson.node_monitors.TemporarySpaceMonitor": None, }, "numExecutors": 1, "offline": True, "offlineCause": None, "oneOffExecutors": [], "temporarilyOffline": False, } @pytest.fixture(scope="function") def nodes(monkeypatch): def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument return DATA0 monkeypatch.setattr(Jenkins, "_poll", fake_jenkins_poll) def fake_nodes_poll(cls, tree=None): # pylint: disable=unused-argument return DATA1 monkeypatch.setattr(Nodes, "_poll", fake_nodes_poll) jenkins = Jenkins("http://foo:8080") return jenkins.get_nodes() def fake_node_poll(self, tree=None): # pylint: disable=unused-argument """ Fakes a poll of data by returning the correct section of the DATA1 test block. """ for node_poll in DATA1["computer"]: if node_poll["displayName"] == self.name: return node_poll return DATA2 def test_repr(nodes): # Can we produce a repr string for this object repr(nodes) def test_baseurl(nodes): assert nodes.baseurl == "http://foo:8080/computer" def test_get_master_node(nodes, monkeypatch): monkeypatch.setattr(Node, "_poll", fake_node_poll) node = nodes["master"] assert isinstance(node, Node) def test_get_nonmaster_node(nodes, monkeypatch): monkeypatch.setattr(Node, "_poll", fake_node_poll) node = nodes["halob"] assert isinstance(node, Node) def test_iterkeys(nodes): expected_names = set(["master", "bobnit", "halob"]) actual_names = set([n for n in nodes.iterkeys()]) assert actual_names == expected_names def test_keys(nodes): expected_names = set(["master", "bobnit", "halob"]) actual_names = set(nodes.keys()) assert actual_names == expected_names def items_test_case(nodes_method, monkeypatch): monkeypatch.setattr(Node, "_poll", fake_node_poll) expected_names = set(["master", "bobnit", "halob"]) actual_names = set() for name, node in nodes_method(): assert name == node.name assert isinstance(node, Node) actual_names.add(name) assert actual_names == expected_names def test_iteritems(nodes, monkeypatch): items_test_case(nodes.iteritems, monkeypatch) def test_items(nodes, monkeypatch): items_test_case(nodes.items, monkeypatch) def values_test_case(nodes_method, monkeypatch): monkeypatch.setattr(Node, "_poll", fake_node_poll) expected_names = set(["master", "bobnit", "halob"]) actual_names = set() for node in nodes_method(): assert isinstance(node, Node) actual_names.add(node.name) assert actual_names == expected_names def test_itervalues(nodes, monkeypatch): values_test_case(nodes.itervalues, monkeypatch) def test_values(nodes, monkeypatch): values_test_case(nodes.values, monkeypatch) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_plugins.py0000644000000000000000000003052400000000000022575 0ustar0000000000000000""" jenkinsapi_tests.test_plugins """ import mock # To run unittests on python 2.6 please use unittest2 library try: import unittest2 as unittest except ImportError: import unittest try: from StringIO import StringIO # python2 except ImportError: from io import BytesIO as StringIO # python3 import zipfile from jenkinsapi.jenkins import Requester from jenkinsapi.jenkins import Jenkins from jenkinsapi.plugins import Plugins from jenkinsapi.plugin import Plugin class TestPlugins(unittest.TestCase): DATA = { "plugins": [ { "deleted": False, "hasUpdate": True, "downgradable": False, "dependencies": [{}, {}, {}, {}], "longName": "Jenkins Subversion Plug-in", "active": True, "shortName": "subversion", "backupVersion": None, "url": "http://wiki.jenkins-ci.org/display/" "JENKINS/Subversion+Plugin", "enabled": True, "pinned": False, "version": "1.45", "supportsDynamicLoad": "MAYBE", "bundled": True, }, { "deleted": False, "hasUpdate": True, "downgradable": False, "dependencies": [{}, {}], "longName": "Maven Integration plugin", "active": True, "shortName": "maven-plugin", "backupVersion": None, "url": "http://wiki.jenkins-ci.org/display/JENKINS/" "Maven+Project+Plugin", "enabled": True, "pinned": False, "version": "1.521", "supportsDynamicLoad": "MAYBE", "bundled": True, }, ] } @mock.patch.object(Jenkins, "_poll") def setUp(self, _poll_jenkins): _poll_jenkins.return_value = {} self.J = Jenkins("http://localhost:8080") @mock.patch.object(Plugins, "_poll") def test_get_plugins(self, _poll_plugins): _poll_plugins.return_value = self.DATA # Can we produce a repr string for this object self.assertIsInstance(self.J.get_plugins(), Plugins) @mock.patch.object(Plugins, "_poll") def test_no_plugins_str(self, _poll_plugins): _poll_plugins.return_value = {} plugins = self.J.get_plugins() self.assertEqual(str(plugins), "[]") @mock.patch.object(Plugins, "_poll") def test_plugins_str(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins() self.assertEqual(str(plugins), "['maven-plugin', 'subversion']") @mock.patch.object(Plugins, "_poll") def test_plugins_len(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins() self.assertEqual(len(plugins), 2) @mock.patch.object(Plugins, "_poll") def test_plugins_contains(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins() self.assertIn("subversion", plugins) self.assertIn("maven-plugin", plugins) @mock.patch.object(Plugins, "_poll") def test_plugins_values(self, _poll_plugins): _poll_plugins.return_value = self.DATA p = Plugin( { "deleted": False, "hasUpdate": True, "downgradable": False, "dependencies": [{}, {}, {}, {}], "longName": "Jenkins Subversion Plug-in", "active": True, "shortName": "subversion", "backupVersion": None, "url": "http://wiki.jenkins-ci.org/display/JENKINS/" "Subversion+Plugin", "enabled": True, "pinned": False, "version": "1.45", "supportsDynamicLoad": "MAYBE", "bundled": True, } ) plugins = self.J.get_plugins().values() self.assertIn(p, plugins) @mock.patch.object(Plugins, "_poll") def test_plugins_keys(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins().keys() self.assertIn("subversion", plugins) self.assertIn("maven-plugin", plugins) @mock.patch.object(Plugins, "_poll") def test_plugins_empty(self, _poll_plugins): _poll_plugins.return_value = {} # list() is required here for python 3.x compatibility plugins = list(self.J.get_plugins().keys()) self.assertEqual([], plugins) @mock.patch.object(Plugins, "_poll") def test_plugin_get_by_name(self, _poll_plugins): _poll_plugins.return_value = self.DATA p = Plugin( { "deleted": False, "hasUpdate": True, "downgradable": False, "dependencies": [{}, {}, {}, {}], "longName": "Jenkins Subversion Plug-in", "active": True, "shortName": "subversion", "backupVersion": None, "url": "http://wiki.jenkins-ci.org/display/JENKINS/" "Subversion+Plugin", "enabled": True, "pinned": False, "version": "1.45", "supportsDynamicLoad": "MAYBE", "bundled": True, } ) plugin = self.J.get_plugins()["subversion"] self.assertEqual(p, plugin) @mock.patch.object(Plugins, "_poll") def test_get_plugin_details(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugin = self.J.get_plugins()["subversion"] self.assertEqual("1.45", plugin.version) self.assertEqual("subversion", plugin.shortName) self.assertEqual("Jenkins Subversion Plug-in", plugin.longName) self.assertEqual( "http://wiki.jenkins-ci.org/display/JENKINS/" "Subversion+Plugin", plugin.url, ) @mock.patch.object(Requester, "post_xml_and_confirm_status") def test_install_plugin_bad_input(self, _post): with self.assertRaises(ValueError): self.J.install_plugin("test") @mock.patch.object(Requester, "post_xml_and_confirm_status") def test_delete_plugin_bad_input(self, _post): with self.assertRaises(ValueError): self.J.delete_plugin("test@latest") @mock.patch.object(Plugins, "update_center_dict") @mock.patch.object(Plugins, "_poll") @mock.patch.object(Plugins, "plugin_version_already_installed") @mock.patch.object(Plugins, "restart_required") @mock.patch.object(Plugins, "_wait_until_plugin_installed") @mock.patch.object(Requester, "post_xml_and_confirm_status") @mock.patch.object(Jenkins, "safe_restart") def test_install_plugin_good_input( self, _reboot, _post, _wait, _restart_required, already_installed, _poll_plugins, _center_dict, ): _poll_plugins.return_value = self.DATA already_installed.return_value = False self.J.install_plugin("test@latest") expected_data = ' ' _post.assert_called_with( "/".join( [self.J.baseurl, "pluginManager", "installNecessaryPlugins"] ), data=expected_data, ) @mock.patch.object(Plugins, "update_center_dict") @mock.patch.object(Plugins, "_poll") @mock.patch.object(Plugins, "plugin_version_already_installed") @mock.patch.object( Plugins, "restart_required", new_callable=mock.mock.PropertyMock ) @mock.patch.object(Plugins, "_wait_until_plugin_installed") @mock.patch.object(Requester, "post_xml_and_confirm_status") @mock.patch.object(Jenkins, "safe_restart") def test_install_plugins_good_input_no_restart_required( self, _restart, _post, _wait, restart_required, already_installed, _poll_plugins, _center_dict, ): _poll_plugins.return_value = self.DATA restart_required.return_value = False already_installed.return_value = False self.J.install_plugins(["test@latest", "test@latest"]) self.assertEqual(_post.call_count, 2) self.assertEqual(_restart.call_count, 0) @mock.patch.object(Plugins, "update_center_dict") @mock.patch.object(Plugins, "_poll") @mock.patch.object(Plugins, "plugin_version_already_installed") @mock.patch.object( Plugins, "restart_required", new_callable=mock.mock.PropertyMock ) @mock.patch.object(Plugins, "_wait_until_plugin_installed") @mock.patch.object(Requester, "post_xml_and_confirm_status") @mock.patch.object(Jenkins, "safe_restart") def test_install_plugins_good_input_with_restart_required( self, _restart, _post, _wait, restart_required, already_installed, _poll_plugins, _center_dict, ): _poll_plugins.return_value = self.DATA restart_required.return_value = True already_installed.return_value = False self.J.install_plugins(["test@latest", "test@latest"]) self.assertEqual(_post.call_count, 2) self.assertEqual(_restart.call_count, 1) @mock.patch.object(Plugins, "_poll") def test_get_plugin_dependencies(self, _poll_plugins): manifest = ( "Manifest-Version: 1.0\n" "bla: somestuff\n" "Plugin-Dependencies: aws-java-sdk:1.10.45,aws-credentials:1.15" ) downloaded_plugin = StringIO() zipfile.ZipFile(downloaded_plugin, mode="w").writestr( "META-INF/MANIFEST.MF", manifest ) _poll_plugins.return_value = self.DATA dependencies = self.J.plugins._get_plugin_dependencies( downloaded_plugin ) self.assertEqual(len(dependencies), 2) for dep in dependencies: self.assertIsInstance(dep, Plugin) @mock.patch.object(Plugins, "update_center_dict") @mock.patch.object(Plugins, "_poll") def test_plugin_version_already_installed(self, _poll_plugins, _update): _poll_plugins.return_value = self.DATA already_installed = Plugin( {"shortName": "subversion", "version": "1.45"} ) self.assertTrue( self.J.plugins.plugin_version_already_installed(already_installed) ) not_installed = Plugin({"shortName": "subversion", "version": "1.46"}) self.assertFalse( self.J.plugins.plugin_version_already_installed(not_installed) ) latest = Plugin({"shortName": "subversion", "version": "latest"}) self.assertFalse( self.J.plugins.plugin_version_already_installed(latest) ) @mock.patch.object(Plugins, "_poll") @mock.patch.object( Plugins, "update_center_install_status", new_callable=mock.mock.PropertyMock, ) def test_restart_required_after_plugin_installation( self, status, _poll_plugins ): _poll_plugins.return_value = self.DATA status.return_value = { "data": { "jobs": [ { "installStatus": "SuccessButRequiresRestart", "name": "credentials", "requiresRestart": "true", "title": None, "version": "0", } ], "state": "RUNNING", }, "status": "ok", } self.assertTrue(self.J.plugins.restart_required) @mock.patch.object(Plugins, "_poll") @mock.patch.object( Plugins, "update_center_install_status", new_callable=mock.mock.PropertyMock, ) def test_restart_not_required_after_plugin_installation( self, status, _poll_plugins ): _poll_plugins.return_value = self.DATA status.return_value = { "data": {"jobs": [], "state": "RUNNING"}, "status": "ok", } self.assertFalse(self.J.plugins.restart_required) def test_plugin_repr(self): p = Plugin( { "shortName": "subversion", } ) self.assertEqual(repr(p), "") if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_requester.py0000644000000000000000000002710300000000000023132 0ustar0000000000000000from __future__ import print_function import pytest import requests from jenkinsapi.jenkins import Requester from jenkinsapi.custom_exceptions import JenkinsAPIException from mock import patch def test_no_parameters_uses_default_values(): req = Requester() assert isinstance(req, Requester) assert req.username is None assert req.password is None assert req.ssl_verify assert req.cert is None assert req.base_scheme is None assert req.timeout == 10 def test_all_named_parameters(): req = Requester( username="foo", password="bar", ssl_verify=False, cert="foobar", baseurl="http://dummy", timeout=5, ) assert isinstance(req, Requester) assert req.username == "foo" assert req.password == "bar" assert not req.ssl_verify assert req.cert == "foobar" assert req.base_scheme == "http", "dummy" assert req.timeout == 5 def test_mix_one_unnamed_named_parameters(): req = Requester( "foo", password="bar", ssl_verify=False, cert="foobar", baseurl="http://dummy", timeout=5, ) assert isinstance(req, Requester) assert req.username == "foo" assert req.password == "bar" assert not req.ssl_verify assert req.cert == "foobar" assert req.base_scheme == "http", "dummy" assert req.timeout == 5 def test_mix_two_unnamed_named_parameters(): req = Requester( "foo", "bar", ssl_verify=False, cert="foobar", baseurl="http://dummy", timeout=5, ) assert isinstance(req, Requester) assert req.username == "foo" assert req.password == "bar" assert not req.ssl_verify assert req.cert == "foobar" assert req.base_scheme == "http", "dummy" assert req.timeout == 5 def test_mix_three_unnamed_named_parameters(): req = Requester( "foo", "bar", False, cert="foobar", baseurl="http://dummy", timeout=5 ) assert isinstance(req, Requester) assert req.username == "foo" assert req.password == "bar" assert not req.ssl_verify assert req.cert == "foobar" assert req.base_scheme == "http", "dummy" assert req.timeout == 5 def test_mix_four_unnamed_named_parameters(): req = Requester( "foo", "bar", False, "foobar", baseurl="http://dummy", timeout=5 ) assert isinstance(req, Requester) assert req.username == "foo" assert req.password == "bar" assert not req.ssl_verify assert req.cert == "foobar" assert req.base_scheme == "http", "dummy" assert req.timeout == 5 def test_mix_five_unnamed_named_parameters(): req = Requester("foo", "bar", False, "foobar", "http://dummy", timeout=5) assert isinstance(req, Requester) assert req.username == "foo" assert req.password == "bar" assert not req.ssl_verify assert req.cert == "foobar" assert req.base_scheme == "http", "dummy" assert req.timeout == 5 def test_all_unnamed_parameters(): req = Requester("foo", "bar", False, "foobar", "http://dummy", 5) assert isinstance(req, Requester) assert req.username == "foo" assert req.password == "bar" assert not req.ssl_verify assert req.cert == "foobar" assert req.base_scheme == "http", "dummy" assert req.timeout == 5 def test_to_much_unnamed_parameters_raises_error(): with pytest.raises(Exception): Requester("foo", "bar", False, "foobar", "http://dummy", 5, "test") def test_username_without_password_raises_error(): with pytest.raises(Exception): Requester(username="foo") Requester("foo") def test_password_without_username_raises_error(): with pytest.raises(AssertionError): Requester(password="bar") def test_get_request_dict_auth(): req = Requester("foo", "bar") req_return = req.get_request_dict(params={}, data=None, headers=None) assert isinstance(req_return, dict) assert req_return.get("auth") assert req_return["auth"] == ("foo", "bar") @patch("jenkinsapi.jenkins.Requester.AUTH_COOKIE", "FAKE") def test_get_request_dict_cookie(): req = Requester("foo", "bar") req_return = req.get_request_dict(params={}, data=None, headers=None) assert isinstance(req_return, dict) assert req_return.get("headers") assert req_return.get("headers").get("Cookie") assert req_return.get("headers").get("Cookie") == "FAKE" @patch("jenkinsapi.jenkins.Requester.AUTH_COOKIE", "FAKE") def test_get_request_dict_updatecookie(): req = Requester("foo", "bar") req_return = req.get_request_dict( params={}, data=None, headers={"key": "value"} ) assert isinstance(req_return, dict) assert req_return.get("headers") assert req_return.get("headers").get("key") assert req_return.get("headers").get("key") == "value" assert req_return.get("headers").get("Cookie") assert req_return.get("headers").get("Cookie") == "FAKE" def test_get_request_dict_nocookie(): req = Requester("foo", "bar") req_return = req.get_request_dict(params={}, data=None, headers=None) assert isinstance(req_return, dict) assert not req_return.get("headers") def test_get_request_dict_wrong_params(): req = Requester("foo", "bar") with pytest.raises(AssertionError) as na: req.get_request_dict(params="wrong", data=None, headers=None) assert "Params must be a dict, got 'wrong'" in str(na.value) def test_get_request_dict_correct_params(): req = Requester("foo", "bar") req_return = req.get_request_dict( params={"param": "value"}, data=None, headers=None ) assert isinstance(req_return, dict) assert req_return.get("params") assert req_return["params"] == {"param": "value"} def test_get_request_dict_wrong_headers(): req = Requester("foo", "bar") with pytest.raises(AssertionError) as na: req.get_request_dict(params={}, data=None, headers="wrong") assert "headers must be a dict, got 'wrong'" in str(na.value) def test_get_request_dict_correct_headers(): req = Requester("foo", "bar") req_return = req.get_request_dict( params={"param": "value"}, data=None, headers={"header": "value"} ) assert isinstance(req_return, dict) assert req_return.get("headers") assert req_return["headers"] == {"header": "value"} def test_get_request_dict_data_passed(): req = Requester("foo", "bar") req_return = req.get_request_dict( params={"param": "value"}, data="some data", headers={"header": "value"}, ) assert isinstance(req_return, dict) assert req_return.get("data") assert req_return["data"] == "some data" def test_get_request_dict_data_not_passed(): req = Requester("foo", "bar") req_return = req.get_request_dict( params={"param": "value"}, data=None, headers={"header": "value"} ) assert isinstance(req_return, dict) assert req_return.get("data") is None def test_get_url_get(monkeypatch): def fake_get(*args, **kwargs): # pylint: disable=unused-argument return "SUCCESS" monkeypatch.setattr(requests.Session, "get", fake_get) req = Requester("foo", "bar") response = req.get_url( "http://dummy", params={"param": "value"}, headers=None ) assert response == "SUCCESS" def test_get_url_post(monkeypatch): def fake_post(*args, **kwargs): # pylint: disable=unused-argument return "SUCCESS" monkeypatch.setattr(requests.Session, "post", fake_post) req = Requester("foo", "bar") response = req.post_url( "http://dummy", params={"param": "value"}, headers=None ) assert response == "SUCCESS" def test_post_xml_empty_xml(monkeypatch): def fake_post(*args, **kwargs): # pylint: disable=unused-argument return "SUCCESS" monkeypatch.setattr(requests.Session, "post", fake_post) req = Requester("foo", "bar") with pytest.raises(AssertionError): req.post_xml_and_confirm_status( url="http://dummy", params={"param": "value"}, data=None ) def test_post_xml_and_confirm_status_some_xml(monkeypatch): class FakeResponse(requests.Response): def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self.status_code = 200 def fake_post(*args, **kwargs): # pylint: disable=unused-argument return FakeResponse() monkeypatch.setattr(requests.Session, "post", fake_post) req = Requester("foo", "bar") ret = req.post_xml_and_confirm_status( url="http://dummy", params={"param": "value"}, data="" ) assert isinstance(ret, requests.Response) def test_post_and_confirm_status_empty_data(monkeypatch): def fake_post(*args, **kwargs): # pylint: disable=unused-argument return "SUCCESS" monkeypatch.setattr(requests.Session, "post", fake_post) req = Requester("foo", "bar") with pytest.raises(AssertionError): req.post_and_confirm_status( url="http://dummy", params={"param": "value"}, data=None ) def test_post_and_confirm_status_some_data(monkeypatch): class FakeResponse(requests.Response): def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self.status_code = 200 def fake_post(*args, **kwargs): # pylint: disable=unused-argument return FakeResponse() monkeypatch.setattr(requests.Session, "post", fake_post) req = Requester("foo", "bar") ret = req.post_and_confirm_status( url="http://dummy", params={"param": "value"}, data="some data" ) assert isinstance(ret, requests.Response) def test_post_and_confirm_status_bad_result(monkeypatch): class FakeResponse(object): def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self.status_code = 500 self.url = "http://dummy" self.text = "something" def fake_post(*args, **kwargs): # pylint: disable=unused-argument return FakeResponse() monkeypatch.setattr(requests.Session, "post", fake_post) req = Requester("foo", "bar") with pytest.raises(JenkinsAPIException) as error: req.post_and_confirm_status( url="http://dummy", params={"param": "value"}, data="some data" ) assert "status=500" in str(error) def test_get_and_confirm_status(monkeypatch): class FakeResponse(requests.Response): def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self.status_code = 200 def fake_get(*args, **kwargs): # pylint: disable=unused-argument return FakeResponse() monkeypatch.setattr(requests.Session, "get", fake_get) req = Requester("foo", "bar") ret = req.get_and_confirm_status( url="http://dummy", params={"param": "value"} ) assert isinstance(ret, requests.Response) def test_get_and_confirm_status_bad_result(monkeypatch): class FakeResponse(object): def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self.status_code = 500 self.url = "http://dummy" self.text = "something" def fake_get(*args, **kwargs): # pylint: disable=unused-argument return FakeResponse() monkeypatch.setattr(requests.Session, "get", fake_get) req = Requester("foo", "bar", baseurl="http://dummy") with pytest.raises(JenkinsAPIException) as error: req.get_and_confirm_status( url="http://dummy", params={"param": "value"} ) assert "status=500" in str(error) def test_configure_max_retries(): req = Requester( "username", "password", baseurl="http://dummy", max_retries=3 ) for adapter in req.session.adapters.values(): assert adapter.max_retries.total == 3 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_result_set.py0000644000000000000000000001105600000000000023304 0ustar0000000000000000import mock # To run unittests on python 2.6 please use unittest2 library try: import unittest2 as unittest except ImportError: import unittest from jenkinsapi.result_set import ResultSet from jenkinsapi.result import Result class TestResultSet(unittest.TestCase): DATA = { "duration": 0.0, "failCount": 2, "passCount": 0, "skipCount": 0, "suites": [ { "cases": [ { "age": 1, "className": ":setup", "skipped": False, "status": "FAILED", "stderr": None, "stdout": None, }, { "age": 1, "className": "nose.failure.Failure", "duration": 0.0, "errorDetails": "No module named mock", "errorStackTrace": 'Traceback (most recent call last):\n File "/usr/lib/python2.7/unittest/case.py", line 332, in run\n testMethod()\n File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName\n addr.filename, addr.module)\n File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath\n return self.importFromDir(dir_path, fqname)\n File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir\n mod = load_module(part_fqname, fh, filename, desc)\n File "/var/lib/jenkins/jobs/test_jenkinsapi/workspace/jenkinsapi/src/jenkinsapi_tests/unittests/test_build.py", line 1, in \n import mock\nImportError: No module named mock\n', # noqa "failedSince": 88, "name": "runTest", "skipped": False, "status": "FAILED", "stderr": None, "stdout": None, }, ], "duration": 0.0, "id": None, "name": "nosetests", "stderr": None, "stdout": None, "timestamp": None, } ], "childReports": [ {"child": {"number": 1915, "url": "url1"}, "result": None}, ], } @mock.patch.object(ResultSet, "_poll") def setUp(self, _poll): _poll.return_value = self.DATA # def __init__(self, url, build ): self.b = mock.MagicMock() # Build object self.b.__str__.return_value = "FooBuild" self.rs = ResultSet("http://", self.b) def testRepr(self): # Can we produce a repr string for this object repr(self.rs) def testName(self): with self.assertRaises(AttributeError): self.rs.id() self.assertEqual(self.rs.name, "Test Result for FooBuild") def testBuildComponents(self): self.assertTrue(self.rs.items()) for k, v in self.rs.items(): self.assertIsInstance(k, str) self.assertIsInstance(v, Result) self.assertIsInstance(v.identifier(), str) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/jenkinsapi_tests/unittests/test_view.py0000644000000000000000000001551600000000000022072 0ustar0000000000000000import unittest.mock as mock import pytest from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.view import View from jenkinsapi.job import Job from jenkinsapi.custom_exceptions import NotFound DATA = { "description": "Important Shizz", "jobs": [ {"color": "blue", "name": "foo", "url": "http://halob:8080/job/foo/"}, { "color": "red", "name": "test_jenkinsapi", "url": "http://halob:8080/job/test_jenkinsapi/", }, ], "name": "FodFanFo", "property": [], "url": "http://halob:8080/view/FodFanFo/", } JOB_DATA = { "actions": [], "description": "test job", "displayName": "foo", "displayNameOrNull": None, "name": "foo", "url": "http://halob:8080/job/foo/", "buildable": True, "builds": [ {"number": 3, "url": "http://halob:8080/job/foo/3/"}, {"number": 2, "url": "http://halob:8080/job/foo/2/"}, {"number": 1, "url": "http://halob:8080/job/foo/1/"}, ], "color": "blue", "firstBuild": {"number": 1, "url": "http://halob:8080/job/foo/1/"}, "healthReport": [ { "description": "Build stability: No recent builds failed.", "iconUrl": "health-80plus.png", "score": 100, } ], "inQueue": False, "keepDependencies": False, "lastBuild": {"number": 3, "url": "http://halob:8080/job/foo/3/"}, "lastCompletedBuild": {"number": 3, "url": "http://halob:8080/job/foo/3/"}, "lastFailedBuild": None, "lastStableBuild": {"number": 3, "url": "http://halob:8080/job/foo/3/"}, "lastSuccessfulBuild": { "number": 3, "url": "http://halob:8080/job/foo/3/", }, "lastUnstableBuild": None, "lastUnsuccessfulBuild": None, "nextBuildNumber": 4, "property": [], "queueItem": None, "concurrentBuild": False, "downstreamProjects": [], "scm": {}, "upstreamProjects": [], } @pytest.fixture def jenkins(): jenkins = mock.MagicMock(autospec=True) jenkins.has_job.return_value = False return jenkins @pytest.fixture @mock.patch.object(Job, "_poll", autospec=True) @mock.patch.object(View, "_poll", autospec=True) def view(_view_poll, _job_poll, jenkins): _view_poll.return_value = DATA _job_poll.return_value = JOB_DATA return View("http://localhost:800/view/FodFanFo", "FodFanFo", jenkins) @pytest.fixture def jenkins_patch(): class Jenkins: def has_job(self, job_name): return False def get_jenkins_obj_from_url(self, url): return self return Jenkins @pytest.fixture def busy_patch(): class Jenkins: def has_job(self, job_name): return True def get_jenkins_obj_from_url(self, url): return self return Jenkins class TestView: def test_returns_name_when_repr_is_called(self, view): assert repr(view) == "FodFanFo" def test_returns_name_when_str_method_called(self, view): assert str(view) == "FodFanFo" def test_raises_error_when_is_called(self, view): with pytest.raises(AttributeError): view.id() def test_returns_name_when_name_property_is_called(self, view): assert view.name == "FodFanFo" @mock.patch.object(JenkinsBase, "_poll") def test_iteritems(self, _poll, view): _poll.return_value = JOB_DATA for job_name, job_obj in view.iteritems(): assert isinstance(job_obj, Job) assert job_name in ["foo", "test_jenkinsapi"] def test_returns_dict_of_job_info_when_job_dict_method_called(self, view): jobs = view.get_job_dict() assert jobs == { "foo": "http://halob:8080/job/foo/", "test_jenkinsapi": "http://halob:8080/job/test_jenkinsapi/", } def test_returns_len_when_len_is_called(self, view): assert len(view) == 2 @mock.patch.object(JenkinsBase, "_poll") def test_getitem(self, _poll, view): _poll.return_value = JOB_DATA assert isinstance(view["foo"], Job) def test_sets_delete_to_true_when_deleted(self, view): view.delete() assert view.deleted def test_returns_url_when_get_job_url_is_called(self, view): url = view.get_job_url("foo") assert url == "http://halob:8080/job/foo/" def test_raises_not_found_when_get_job_url_is_invalid(self, view): with pytest.raises(NotFound): view.get_job_url("bar") @mock.patch.object(View, "get_jenkins_obj") def test_returns_false_when_adding_wrong_job( self, _get_jenkins, view, jenkins_patch ): _get_jenkins.return_value = jenkins_patch() result = view.add_job("bar") assert result is False def test_returns_false_when_add_existing_job(self, view): result = view.add_job("foo") assert result is False def test_get_nested_view_dict(self, view): result = view.get_nested_view_dict() assert isinstance(result, dict) def test_returns_jenkins_obj_when_get_jenkins_obj_is_called(self, view): obj = view.get_jenkins_obj() assert obj == view.jenkins_obj class TestKeys: def test_returns_key_when_called(self, view): keys = view.keys() assert "foo" in list(keys) assert "test_jenkinsapi" in list(keys) class TestAddJob: @mock.patch.object(JenkinsBase, "_poll") def test_returns_true_when_no_job_provided(self, _poll, view): _poll.return_value = DATA result = view.add_job("bar") assert result is True @mock.patch.object(JenkinsBase, "_poll") def test_returns_false_when_already_registered(self, _poll, view): _poll.return_value = DATA result = view.add_job("foo") assert result is False @mock.patch.object(View, "get_jenkins_obj") def test_returns_false_when_jenkins_has_job( self, _get_jenkins, view, jenkins_patch ): _get_jenkins.return_value = jenkins_patch() result = view.add_job("Foo") _get_jenkins.assert_called() assert result is False @mock.patch.object(View, "get_jenkins_obj") @mock.patch.object(JenkinsBase, "_poll") def test_returns_true_when_jenkins_has_job( self, _poll, _get_jenkins, view, jenkins ): _get_jenkins.return_value = jenkins() _poll.return_value = DATA result = view.add_job("Foo") _get_jenkins.assert_called() assert result is True class TestRemove: @mock.patch.object(JenkinsBase, "_poll") def test_returns_true_when_job_has_been_removed(self, _poll, view): _poll.return_value = DATA result = view.remove_job("foo") assert result is True @mock.patch.object(JenkinsBase, "_poll") def test_returns_false_when_job_does_not_exist(self, _poll, view): _poll.return_value = DATA result = view.remove_job("Non-existant Foo") assert result is False ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/license.txt0000644000000000000000000000221200000000000014240 0ustar0000000000000000Copyright (c) 2012 Salim Fadhley For additional contributors please see the README.rst file The MIT License (MIT) ===================== Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/misc/jenkinsapi.sublime-project0000644000000000000000000000313100000000000020172 0ustar0000000000000000{ "folders": [ { "path": "src", "file_exclude_patterns": ["*.pyc"] } ], "settings": { "python_test_runner": { "before_test": "source .env/bin/activate", "after_test": "deactivate", "test_root": "src/pythonmoo/tests", "test_delimeter": ":", "test_command": "nosetests" }, "pylinter": { "ignore":["C"], "use_icons":true } }, "build_systems": [ { "name":"Virtualenv 2.7", "cmd": [ "${project_path}/bin/python2.7", "$file" ] }, { "name":"Nose 2.7 Unittests", "working_dir": "${project_path:${folder}}/src", "cmd": [ "${project_path}/bin/nosetests", "${project_path}/src/jenkinsapi_tests/unittests" ] }, { "name":"Nose 2.7 All tests", "working_dir": "${project_path:${folder}}/src", "cmd": [ "${project_path}/bin/nosetests", "${project_path}/src/jenkinsapi_tests" ] }, { "name":"Virtualenv 3.3", "working_dir": "${project_path:${folder}}/src", "cmd": [ "source", "${project_path}/bin/activate" ], "cmd": [ "${project_path}/bin/python3.3", "-u", "$file" ] } ] } ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/misc/make_venv.sh0000755000000000000000000000024500000000000015326 0ustar0000000000000000#! /bin/bash virtualenv venv --python=`which python3` --prompt="(jenkinsapi)" --clear source venv/bin/activate pip install --upgrade pip pip install --upgrade wheel ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/misc/readme.txt0000644000000000000000000000032200000000000015006 0ustar0000000000000000This folder contains configuration files which may be useful for developers. Almost certainly, none of these files will work from their current location. You may need to symlink them to a more useful location. ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/pylintrc0000644000000000000000000002130400000000000013647 0ustar0000000000000000[MASTER] # Specify a configuration file. #rcfile= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Add to the black list. It should be a base name, not a # path. You may set this option multiple times. ignore=CVS # Pickle collected data for later comparisons. persistent=yes # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= [MESSAGES CONTROL] # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. #enable= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). # F0401: *Unable to import %r* # E0611: *No name %r in module %r* # E1101: *%s %r has no %r member* # W0142: *Used * or ** magic* # W0212: *Access to a protected member %s of a client class* # :R0201: *Method could be a function* # w0703: Allow catching Exception # R0801: 1: Similar lines in 2 files, badamson: had trouble disabling this locally # FIXME: should be re-enabled after it's fixed # hbrown: I don't think R0801 can be disabled locally # http://www.logilab.org/ticket/6905 # pylint #6905: R0801 message cannot be disabled locally [open] # R0901: Too many ancestors # C0411: wrong-import-order # C0412: ungrouped-imports # # Amplify/Disco customizations: # W0511: TODO - we want to have TODOs during prototyping # E1103: %s %r has no %r member (but some types could not be inferred) - fails to infer real members of types, e.g. in Celery # W0231: method from base class is not called - complains about not invoking empty __init__s in parents, which is annoying # R0921: abstract class not referenced, when in fact referenced from another egg disable=F0401,E0611,E1101,W0142,W0212,R0201,W0703,R0801,R0901,W0511,E1103,W0231,R0921,W0402,I0011,wrong-import-position,wrong-import-order,ungrouped-imports,redefined-variable-type,missing-docstring,redefined-outer-name,redefined-builtin,relative-import,c-extension-no-member,useless-object-inheritance,no-else-return,consider-using-in,consider-using-dict-comprehension,unnecessary-pass,unnecessary-comprehension [REPORTS] # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html output-format=parseable # colorized # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells whether to display a full report or only the messages reports=no # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (R0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (R0004). [BASIC] # List of builtins function names that should not be used, separated by a comma # Amplify: Allowing the use of 'map' and 'filter' bad-functions=apply,input # Regular expression which should only match correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression which should only match correct module level names const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__)|([a-z_][a-z0-9_]*)) # Regular expression which should only match correct class names class-rgx=[A-Z_][a-zA-Z0-9]+$ # Regular expression which should only match correct function names # Amplify: Up to 40 characters long function-rgx=[a-z_][a-z0-9_]+$ # Regular expression which should only match correct method names # Amplify: Up to 40 characters long method-rgx=[a-z_][a-z0-9_]+$ # Regular expression which should only match correct instance attribute names # Amplify: Up to 40 characters long attr-rgx=[a-z_][a-z0-9_]{2,40}$ # Regular expression which should only match correct argument names # Amplify: Up to 40 characters long # argument-rgx=[a-z_][a-z0-9_]{2,40}$ argument-rgx=[A-Za-z_][A-Za-z0-9_]{1,40}$ # Regular expression which should only match correct variable names # Amplify: Up to 40 characters long # variable-rgx=[a-z_][a-z0-9_]{2,40}$ variable-rgx=[A-Za-z_][A-Za-z0-9_]{1,40}$ # Regular expression which should only match correct list comprehension / # generator expression variable names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ # Good variable names which should always be accepted, separated by a comma good-names=i,j,k,ex,Run,_,setUp,setUpClass,tearDown,f # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata # Regular expression which should only match functions or classes name which do # not require a docstring # Amplify: Do not require docstrings in test functions or classes no-docstring-rgx=(__.*__)|([a-z_][a-z0-9_]{2,30}$)|(test_.*)|(.*_test)|(Tests?[A-Z].*)|(.*Tests?) [FORMAT] # Maximum number of characters on a single line. # WGen: Line length 120 max-line-length=120 # Maximum number of lines in a module max-module-lines=1000 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=XXX,TODO [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=4 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes=SQLObject # When zope mode is activated, add a predefined set of Zope acquired attributes # to generated-members. # zope=no # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. generated-members=REQUEST,acl_users,aq_parent [VARIABLES] # Tells whether we should check for unused import in __init__ files. init-import=no # A regular expression matching names used for dummy variables (i.e. not used). dummy-variables-rgx=_|dummy # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= [CLASSES] # List of interface methods to ignore, separated by a comma. This is used for # instance to not check methods defines in Zope's Interface base class. # ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp [DESIGN] # Maximum number of arguments for function / method max-args=10 # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Maximum number of locals for function / method body max-locals=25 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body max-branchs=12 # Maximum number of statements in function / method body max-statements=50 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=14 # Minimum number of public methods for a class (see R0903). min-public-methods=0 # Maximum number of public methods for a class (see R0904). max-public-methods=100 [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=regsub,string,TERMIOS,Bastion,rexec # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674710100.5420542 jenkinsapi-0.3.13/pyproject.toml0000644000000000000000000000406100000000000014775 0ustar0000000000000000[build-system] requires = ["flit_core >=3.2,<4"] build-backend = "flit_core.buildapi" [project] name = "jenkinsapi" authors = [ {name = "Salim Fadhley", email = "salimfadhley@gmail.com"}, {name = "Aleksey Maksimov", email = "ctpeko3a@gmail.com"}, ] maintainers = [ {name = "Aleksey Maksimov", email = "ctpeko3a@gmail.com"} ] description = "A Python API for accessing resources on a Jenkins continuous-integration server." readme = "README.rst" license = {text = "MIT license"} classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Topic :: Software Development :: Testing", "Topic :: Utilities", ] requires_python = ">=2.7" dynamic = ["version"] dependencies = [ "pytz>=2014.4", "requests>=2.3.0", "six>=1.10.0" ] [tool.files] packages = """ jenkinsapi jenkinsapi_utils jenkinsapi_tests""" [tool.pbr] warnerrors = "True" [project.entry_points.cli] console_scripts = """ jenkins_invoke=jenkinsapi.command_line.jenkins_invoke:main jenkinsapi_version=jenkinsapi.command_line.jenkinsapi_version:main""" [tool.build_sphinx] source-dir = "doc/source" build-dir = "doc/build" all_files = "1" [tool.upload_sphinx] upload-dir = "doc/build/html" [tool.distutils.bdist_wheel] universal = 1 [tool.pycodestyle] exclude = ".tox,doc/source/conf.py,build,.venv,.eggs" max-line-length = "99" [tool.setuptools] include-package-data = false ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/requirements.txt0000644000000000000000000000005100000000000015340 0ustar0000000000000000pytz>=2014.4 requests>=2.3.0 six>=1.10.0 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674710100.5420542 jenkinsapi-0.3.13/setup.cfg0000644000000000000000000000311100000000000013675 0ustar0000000000000000[metadata] name = jenkinsapi author = Salim Fadhley, Aleksey Maksimov author_email = salimfadhley@gmail.com, ctpeko3a@gmail.com summary = A Python API for accessing resources on a Jenkins continuous-integration server. description-file = README.rst license = MIT classifier = Development Status :: 4 - Beta Environment :: Console Intended Audience :: Developers Intended Audience :: Information Technology Intended Audience :: System Administrators License :: OSI Approved :: MIT License Natural Language :: English Operating System :: OS Independent Operating System :: OS Independent Programming Language :: Python Programming Language :: Python :: 2 Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Topic :: Software Development :: Testing Topic :: Utilities [files] packages = jenkinsapi jenkinsapi_utils jenkinsapi_tests [pbr] warnerrors = True [entry_points] console_scripts = jenkins_invoke=jenkinsapi.command_line.jenkins_invoke:main jenkinsapi_version=jenkinsapi.command_line.jenkinsapi_version:main [build_sphinx] source-dir = doc/source build-dir = doc/build all_files = 1 [upload_sphinx] upload-dir = doc/build/html [bdist_wheel] universal = 1 [pycodestyle] exclude = .tox,doc/source/conf.py,build,.venv,.eggs max-line-length = 99 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/setup.py0000644000000000000000000000010700000000000013570 0ustar0000000000000000from setuptools import setup setup(setup_requires=["pbr"], pbr=True) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/test-requirements.txt0000644000000000000000000000017700000000000016326 0ustar0000000000000000pytest pytest-mock pytest-cov pycodestyle>=2.3.1 astroid>=1.4.8 pylint>=1.7.1 tox>=2.3.1 mock codecov requests_kerberos flake8 ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1674709558.6346684 jenkinsapi-0.3.13/tox.ini.todelete0000644000000000000000000000142700000000000015203 0ustar0000000000000000# # jenkinsapi tox.ini # # This file helps for developers to simulate locally # what travis will execute when testing merges. See # http://tox.readthedocs.org for configuration info # # Usage: # $ pip install tox # $ tox -e py27 # lint/test for python2.7 OR, # $ tox -e py34 # lint/tests for python3.4 OR, # $ tox # lint/tests for both # [tox] envlist = py27,py38,py39,py310 [testenv] deps=-rtest-requirements.txt passenv = CI TRAVIS TRAVIS_* usedevelop= True commands= py.test -sv --cov=jenkinsapi --cov-report=term-missing --cov-report=xml jenkinsapi_tests {posargs} codecov [testenv:args] deps = -rtest-requirements.txt usedevelop = True commands = {posargs} [gh-actions] python = 2.7: py27 3.8: py38 3.9: py39 3.10: py310 jenkinsapi-0.3.13/PKG-INFO0000644000000000000000000001773600000000000013173 0ustar0000000000000000Metadata-Version: 2.1 Name: jenkinsapi Version: 0.3.13 Summary: A Python API for accessing resources on a Jenkins continuous-integration server. Author-email: Salim Fadhley , Aleksey Maksimov Maintainer-email: Aleksey Maksimov Description-Content-Type: text/x-rst Classifier: Development Status :: 4 - Beta Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: MIT License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Topic :: Software Development :: Testing Classifier: Topic :: Utilities Requires-Dist: pytz>=2014.4 Requires-Dist: requests>=2.3.0 Requires-Dist: six>=1.10.0 jenkinsapi ========== .. image:: https://badge.fury.io/py/jenkinsapi.png :target: http://badge.fury.io/py/jenkinsapi .. image:: https://travis-ci.com/pycontribs/jenkinsapi.png?branch=master :target: https://travis-ci.com/pycontribs/jenkinsapi .. image:: https://codecov.io/gh/pycontribs/jenkinsapi/branch/master/graph/badge.svg :target: https://codecov.io/gh/pycontribs/jenkinsapi .. image:: https://requires.io/github/pycontribs/jenkinsapi/requirements.png?branch=master :target: https://requires.io/github/pycontribs/jenkinsapi/requirements/?branch=master :alt: Requirements Status About this library ------------------- Jenkins is the market leading continuous integration system, originally created by Kohsuke Kawaguchi. Jenkins (and It's predecessor Hudson) are useful projects for automating common development tasks (e.g. unit-testing, production batches) - but they are somewhat Java-centric. Thankfully the designers have provided an excellent and complete REST interface. This library wraps up that interface as more conventional python objects in order to make many Jenkins oriented tasks easier to automate. This library allows you to automate most common Jenkins operations using Python, such as: * Ability to add/remove/query Jenkins jobs * Ability to execute jobs and: * Query the results of a completed build * Block until jobs are complete or run jobs asyncronously * Get objects representing the latest builds of a job * Work with build artifacts: * Search for artifacts by simple criteria * Install artifacts to custom-specified directory structures * Ability to search for builds by source code revision * Ability to add/remove/query: * Slaves (Webstart and SSH slaves) * Views (including nested views using NestedViews Jenkins plugin) * Credentials (username/password and ssh key) * Username/password auth support for jenkins instances with auth turned on * Ability to script jenkins installation including plugins For a full documentation spec of what this library supports see: http://jenkinsapi.readthedocs.io/en/latest/index.html Python versions --------------- The project has been tested against Python versions: * 2.7 * 3.4 * 3.5 * 3.6 * 3.7 Jenkins versions ---------------- Project tested on both stable (LTS) and latest Jenkins versions. Known issues ------------ * Job deletion operations fail unless Cross-Site scripting protection is disabled. For other issues, please refer to the support URL below. Important Links --------------- Support and bug-reports: https://github.com/pycontribs/jenkinsapi/issues?direction=desc&sort=comments&state=open Project source code: github: https://github.com/pycontribs/jenkinsapi Project documentation: https://jenkinsapi.readthedocs.org/en/latest/ Releases: http://pypi.python.org/pypi/jenkinsapi Installation ------------- Egg-files for this project are hosted on PyPi. Most Python users should be able to use pip or setuptools to automatically install this project. Using Pip or Setuptools ^^^^^^^^^^^^^^^^^^^^^^^ Most users can do the following: .. code-block:: bash pip install jenkinsapi Or: .. code-block:: bash easy_install jenkinsapi Both of these techniques can be combined with virtualenv to create an application-specific installation. Using your operating-system's package manager ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ubuntu users can now use apt to install this package: .. code-block:: bash apt-get install python-jenkinsapi Beware that this technique will get a somewhat older version of Jenkinsapi. Example ------- JenkinsAPI is intended to map the objects in Jenkins (e.g. Builds, Views, Jobs) into easily managed Python objects: .. code-block:: python >>> import jenkinsapi >>> from jenkinsapi.jenkins import Jenkins >>> J = Jenkins('http://localhost:8080') >>> J.version 1.542 >>> J.keys() # Jenkins objects appear to be dict-like, mapping keys (job-names) to ['foo', 'test_jenkinsapi'] >>> J['test_jenkinsapi'] >>> J['test_jenkinsapi'].get_last_good_build() ... More examples available on Github: https://github.com/pycontribs/jenkinsapi/tree/master/examples Testing ------- If you have installed the test dependencies on your system already, you can run the testsuite with the following command: .. code-block:: bash python setup.py test Otherwise using a virtualenv is recommended. Setuptools will automatically fetch missing test dependencies: .. code-block:: bash virtualenv source .venv/bin/active (venv) python setup.py test Development ----------- * Make sure that you have Java_ installed. * Create virtual environment for development * Install package in development mode .. code-block:: bash (venv) pip install -e . (venv) pip install -r test-requirements.txt * Make your changes, write tests and check your code .. code-block:: bash (venv) tox Project Contributors -------------------- * Aleksey Maksimov (ctpeko3a@gmail.com) * Salim Fadhley (sal@stodge.org) * Ramon van Alteren (ramon@vanalteren.nl) * Ruslan Lutsenko (ruslan.lutcenko@gmail.com) * Cleber J Santos (cleber@simplesconsultoria.com.br) * William Zhang (jollychang@douban.com) * Victor Garcia (bravejolie@gmail.com) * Bradley Harris (bradley@ninelb.com) * Kyle Rockman (kyle.rockman@mac.com) * Sascha Peilicke (saschpe@gmx.de) * David Johansen (david@makewhat.is) * Misha Behersky (bmwant@gmail.com) Please do not contact these contributors directly for support questions! Use the GitHub tracker instead. License -------- The MIT License (MIT): Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. .. _Java: http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html