pax_global_header00006660000000000000000000000064145071013540014512gustar00rootroot0000000000000052 comment=fe628e9ac6cf1751f593ab38caf7b85f1bf474fd openQA-python-client-4.2.3/000077500000000000000000000000001450710135400154765ustar00rootroot00000000000000openQA-python-client-4.2.3/.github/000077500000000000000000000000001450710135400170365ustar00rootroot00000000000000openQA-python-client-4.2.3/.github/dependabot.yml000066400000000000000000000001711450710135400216650ustar00rootroot00000000000000--- version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" openQA-python-client-4.2.3/.github/workflows/000077500000000000000000000000001450710135400210735ustar00rootroot00000000000000openQA-python-client-4.2.3/.github/workflows/tox.yml000066400000000000000000000015741450710135400224370ustar00rootroot00000000000000--- name: Python package with Tox on: [pull_request] jobs: build: runs-on: ${{ matrix.os }} strategy: max-parallel: 4 fail-fast: false matrix: python-version: - "3.6" - "3.7" - "3.8" - "3.9" - "3.10" - "3.11" - "3.12.0-alpha - 3.12.0" include: - os: "ubuntu-latest" - os: "ubuntu-20.04" python-version: "3.6" steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4.7.1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install tox tox-gh-actions - name: Test with tox run: tox openQA-python-client-4.2.3/.gitignore000066400000000000000000000001271450710135400174660ustar00rootroot00000000000000**/*.pyc **/*.pyo build/ dist/ openqa_client.egg-info/ /coverage.xml /.tox/ /.coverage openQA-python-client-4.2.3/CHANGELOG.md000066400000000000000000000056261450710135400173200ustar00rootroot00000000000000## Changelog ### 4.2.3 - 2023-10-03 1. Add py.typed marker to the package ### 4.2.2 - 2023-09-05 1. Include the response text in RequestError (kalikiana) 2. Support `REQUESTS_CA_BUNDLE` and `CURL_CA_BUNDLE` environment variables (ricardobranco777) ### 4.2.1 - 2022-11-09 1. Make Exceptions proper objects with members (perlpunk) 2. Only retry requests on certain status codes ### 4.2.0 - 2022-09-13 1. Add class global retries and wait values to allow configuration (dcermak) 2. Add type hints (dcermak) 3. Stop encoding X-API-Microtime as bytes (dcermak) 4. Build and CI system modernizations and improvements ### 4.1.2 - 2021-04-27 1. Improve handling of quirky API behaviour regarding settings parameters ### 4.1.1 - 2020-08-07 1. Fix `latest` param when querying jobs to use value `1` not `true` ### 4.1.0 - 2020-03-13 1. Handle server sending us YAML (though we didn't ask for it) 2. Add `parse` kwarg to `do_request` to allow skipping parsing This adds a dependency on pyyaml, unfortunately; can't see any way around that short of just not parsing these responses at all. ### 4.0.0 - 2020-02-28 1. Drop Python 2 support, remove various Python 2-specific workarounds 2. Move module source under `src/` 3. Make tox build and test an sdist, not test the working directory 4. Run [black](https://github.com/psf/black) on the source, add it to CI 5. Add `pyproject.toml` compliant with PEP-517 and PEP-518 6. Update `release.sh` to use `pep517` This is a modernization release to drop Python 2 support and align with various shiny modern Best Practices. There should be no actual functional changes to the code at all, but I'm gonna call it 4.0.0 due to the dropping of Python 2 support and the code being moved within the git repo, which may disrupt some folks. ### 3.0.4 - 2020-02-27 1. OK, this time fix tests on ancient EPEL 7 for realz 2. Tweak py27 tox environment to match EPEL 7 ### 3.0.3 - 2020-02-27 1. Fix tests to run on ancient pytest in EPEL 7 (I hope) ### 3.0.2 - 2020-02-27 1. Fix more broken stuff in setup.py ### 3.0.1 - 2020-02-27 1. Drop duplicated description line in setup.py 2. Fix release.sh for no spaces in setup.py setup() ### 3.0.0 - 2020-02-27 1. **API**: remove `WaitError` exception 2. Update release script to use Python 3, publish to PyPI 3. Update setup.py for current best practices 4. Don't modify original request in `_add_auth_headers` 5. Don't edit list while iterating it in `find_clones` 6. Add a test suite, tox config and GitHub Actions-based CI ### 2.0.1 - 2020-02-26 1. Fix long description for PyPI ### 2.0.0 - 2020-01-06 1. Update constants to reflect upstream changes again, including some additions and **REMOVAL** of JOB_INCOMPLETE_RESULTS ### 1.3.2 - 2019-05-21 1. Update constants to reflect upstream changes (again) ### 1.3.1 - 2017-10-10 1. Update constants to reflect upstream changes ### 1.3.0 - 2017-02-15 1. First proper release openQA-python-client-4.2.3/COPYING000066400000000000000000000432541450710135400165410ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. openQA-python-client-4.2.3/MANIFEST.in000066400000000000000000000001031450710135400172260ustar00rootroot00000000000000exclude .gitignore exclude MANIFEST.in recursive-exclude .github * openQA-python-client-4.2.3/README.md000066400000000000000000000061661450710135400167660ustar00rootroot00000000000000# openqa_client This is a client for the [openQA](https://os-autoinst.github.io/openQA/) API, based on [requests](https://python-requests.org). It requires Python 3.6 or later. ## Usage Here's a simple example of reading the status of a job: from openqa_client.client import OpenQA_Client client = OpenQA_Client(server='openqa.opensuse.org') print(client.openqa_request('GET', 'jobs/1')) Here's an example of triggering jobs for an ISO: # This is a Fedora server. client = OpenQA_Client(server='openqa.happyassassin.net') params = {} params['ISO'] = '22_Beta_TC2_server_x86_64_boot.iso' params['DISTRI'] = 'fedora' params['VERSION'] = '22' params['FLAVOR'] = 'server_boot' params['ARCH'] = 'x86_64' params['BUILD'] = '22_Beta_TC2' print(cl.openqa_request('POST', 'isos', params)) All methods other than `GET` require authentication. This client uses the same configuration file format as the reference (perl) client in openQA itself. Configuration will be read from `/etc/openqa/client.conf` or `~/.config/openqa/client.conf`. A configuration file looks like this: [openqa.happyassassin.net] key = APIKEY secret = APISECRET You can get the API key and secret from the web UI after logging in. Your configuration file may include credentials for multiple servers; each section contains the credentials for the server named in the section title. If you create an `OpenQA_Client` instance without passing the `server` argument, it will use the first server listed in the configuration file if there is one, otherwise it will use 'localhost'. Note: this is a difference in behaviour from the perl client, which *always* uses 'localhost' unless a server name is passed. TLS/SSL connections are the default (except for localhost). You can pass the argument `scheme` to `OpenQA_Client` to force the use of unencrypted HTTP, e.g. `OpenQA_Client(server='openqa.happyassassin.net', scheme='http')`. The API always returns JSON responses; this client's request functions parse the response before returning it. If you need for some reason to make a request which does not fall into the `openqa_request()` method's expected pattern, you can construct a `requests.Request` and pass it to `do_request()`, which will attach the required headers, execute the request, and return the parsed JSON response. The `const` module provides several constants that are shadowed from the upstream openQA code, including job states, results, and the 'scenario keys'. ## Development You can file pull requests at [Github](https://github.com/os-autoinst/openQA-python-client). There is an extensive test suite with CI integration. You can run the test suite locally by running `tox`. If your system has a tox version earlier than 3.3.0, you must have the `setuptools_scm` Python module installed for this to work correctly, or else you will get errors about a missing `install.requires` file. ## Licensing This software is available under the GPL, version 2 or any later version. A copy is included as COPYING. Contributions submitted as pull requests are assumed to be submitted under the same license terms unless otherwise specified. openQA-python-client-4.2.3/ci.requires000066400000000000000000000001071450710135400176500ustar00rootroot00000000000000black coverage diff-cover mypy pylint toml types-requests types-PyYAML openQA-python-client-4.2.3/install.requires000066400000000000000000000000201450710135400207150ustar00rootroot00000000000000pyyaml requests openQA-python-client-4.2.3/pyproject.toml000066400000000000000000000024731450710135400204200ustar00rootroot00000000000000[project] name = "openqa_client" version = "4.2.3" authors = [ { name="Adam Williamson", email="awilliam@redhat.com" }, ] description = "Python client library for openQA API" readme = "README.md" license = { file="COPYING" } requires-python = ">=3.6" classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Topic :: Utilities", ] keywords = ["openqa", "opensuse", "fedora", "client"] dynamic = ["dependencies"] [project.urls] "Homepage" = "https://github.com/os-autoinst/openQA-python-client" "Bug Tracker" = "https://github.com/os-autoinst/openQA-python-client/issues" [build-system] requires = ["setuptools>=40.6.0", "setuptools-scm", "wheel"] build-backend = "setuptools.build_meta" [tool.coverage.run] parallel = true branch = true source = ["openqa_client"] [tool.coverage.paths] source = ["src", ".tox/**/site-packages"] [tool.coverage.report] show_missing = true [tool.black] # don't @ me, Hynek line-length = 100 [tool.setuptools.dynamic] dependencies = { file = ["install.requires"] } [tool.setuptools.package-data] "openqa_client" = ["py.typed"] [tool.setuptools.packages.find] where = ["src"] openQA-python-client-4.2.3/release.sh000077500000000000000000000013611450710135400174560ustar00rootroot00000000000000#!/bin/bash baddeps="" # check deps python3 -m build.__init__ || baddeps="python3-build" if [ -n "${baddeps}" ]; then echo "${baddeps} must be installed!" exit 1 fi if [ "$#" != "1" ]; then echo "Must pass release version!" exit 1 fi version=$1 name=openqa_client sed -i -e "s,version=\".*\",version=\"${version}\", g" setup.py sed -i -e "s,version = \".*\",version = \"${version}\", g" pyproject.toml sed -i -e "s,__version__ = \".*\",__version__ = \"${version}\", g" src/${name}/__init__.py git add setup.py pyproject.toml src/${name}/__init__.py git commit -s -m "Release ${version}" git push git tag -a -m "Release ${version}" ${version} git push origin ${version} python3 -m build . twine upload -r pypi dist/${name}-${version}* openQA-python-client-4.2.3/setup.py000066400000000000000000000040321450710135400172070ustar00rootroot00000000000000# Copyright Red Hat # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Author: Adam Williamson from setuptools import setup from os import path HERE = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(HERE, 'README.md'), encoding='utf-8') as f: LONGDESC = f.read() setup( name="openqa_client", version="4.2.3", description="Python client library for openQA API", author="Adam Williamson", author_email="awilliam@redhat.com", license="GPLv2+", keywords="openqa opensuse fedora client", url="https://github.com/os-autoinst/openQA-python-client", packages=["openqa_client"], package_data={"openqa_client": ["py.typed"]}, package_dir={"": "src"}, install_requires=open('install.requires').read().splitlines(), python_requires="!=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4", long_description=LONGDESC, long_description_content_type='text/markdown', classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Utilities", "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", ], ) openQA-python-client-4.2.3/src/000077500000000000000000000000001450710135400162655ustar00rootroot00000000000000openQA-python-client-4.2.3/src/openqa_client/000077500000000000000000000000001450710135400211065ustar00rootroot00000000000000openQA-python-client-4.2.3/src/openqa_client/__init__.py000066400000000000000000000014051450710135400232170ustar00rootroot00000000000000# Copyright Red Hat # # openqa_client is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Author: Adam Williamson """Python client library for openQA.""" __version__ = "4.2.3" openQA-python-client-4.2.3/src/openqa_client/client.py000066400000000000000000000364021450710135400227430ustar00rootroot00000000000000# Copyright Red Hat # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authors: Adam Williamson # Ludwig Nussel # Jan Sedlak """Main client functionality.""" import hashlib import hmac import os import logging import time import sys from typing import Any, Dict, List, MutableMapping, NoReturn, Optional, Union, overload from urllib.parse import urlparse, urlunparse import configparser import requests import yaml import openqa_client.exceptions if sys.version_info >= (3, 8): from typing import Literal, TypedDict else: # pragma: no cover from typing_extensions import Literal, TypedDict # pragma: no cover logger = logging.getLogger(__name__) RequestMethod = Literal["get", "put", "post", "delete", "GET", "PUT", "POST", "DELETE"] class Job(TypedDict): """Response from openQA about a job.""" #: settings of this job as reported in the webui settings: Dict[str, str] #: this jobs unique identifier id: int #: the unique identifier of the job as which this job has been cloned clone_id: int ## MAIN CLIENT CLASS class OpenQA_Client: """A client for the OpenQA REST API; just handles API auth if needed and provides a couple of custom methods for convenience. Args: server: The URL or hostname of the openqa server. If not provided, will default to the first server in openqa's config files or localhost if none are present. scheme: The scheme used by the server. Extracted from the hostname by default. retries: A default value for the number of retries that will be performed per request. This value is used if retries is not provided to the respective method calls. wait: A default value for the time to wait between attempted requests in seconds. The value provided to the respective method calls takes precedence over this. """ def __init__( self, server: str = "", scheme: str = "", retries: int = 5, wait: int = 10 ) -> None: self.retries = retries self.wait = wait # Read in config files. config = configparser.ConfigParser() paths = ("/etc/openqa", f"{os.path.expanduser('~')}/.config/openqa") config.read(f"{path}/client.conf" for path in paths) # If server not specified, default to the first one in the # configuration file. If no configuration file, default to # localhost. NOTE: this is different from the perl client, it # *always* defaults to localhost. if not server: try: server = config.sections()[0] except (configparser.MissingSectionHeaderError, IndexError): server = "localhost" if server.startswith("http"): # Handle entries like [http://foo] or [https://foo]. The, # perl client does NOT handle these, so you shouldn't use # them. This client started out supporting this, though, # so it should continue to. if not scheme: scheme = urlparse(server).scheme server = urlparse(server).netloc if not scheme: if server in ("localhost", "127.0.0.1", "::1"): # Default to non-TLS for localhost; cert is unlikely to # be valid for 'localhost' and there's no MITM... scheme = "http" else: scheme = "https" self.baseurl = urlunparse((scheme, server, "", "", "", "")) # Get the API secrets from the config file. try: apikey = config.get(server, "key") self.apisecret = config.get(server, "secret") except configparser.Error: try: apikey = config.get(self.baseurl, "key") self.apisecret = config.get(self.baseurl, "secret") except configparser.Error: logger.debug("No API key for %s: only GET requests will be allowed", server) apikey = "" self.apisecret = "" # Create a Requests session and ensure some standard headers # will be used for all requests run through the session. self.session: requests.Session = requests.Session() headers = {} headers["Accept"] = "json" if apikey: headers["X-API-Key"] = apikey self.session.headers.update(headers) def _add_auth_headers(self, request: requests.PreparedRequest) -> requests.PreparedRequest: """Add authentication headers to a PreparedRequest. See openQA/lib/OpenQA/client.pm for the authentication design. """ if not self.apisecret: # Can't auth without an API key. return request # don't modify the original request = request.copy() timestamp = time.time() path = request.path_url.replace("%20", "+").replace("~", "%7E") apihash = hmac.new(self.apisecret.encode(), f"{path}{timestamp}".encode(), hashlib.sha1) headers: MutableMapping[str, str] = {} headers["X-API-Microtime"] = str(timestamp) headers["X-API-Hash"] = apihash.hexdigest() request.headers.update(headers) return request @overload def do_request( self, request: requests.Request, retries: Optional[int] = None, wait: Optional[Union[int, float]] = None, parse: Literal[False] = False, ) -> requests.Response: ... # pragma: no cover @overload def do_request( self, request: requests.Request, retries: Optional[int] = None, wait: Optional[Union[int, float]] = None, parse: Literal[True] = True, ) -> Any: ... # pragma: no cover def do_request( self, request: requests.Request, retries: Optional[int] = None, wait: Optional[Union[int, float]] = None, parse: bool = True, ) -> Union[Any, requests.Response]: """Passed a requests.Request, prepare it with the necessary headers, submit it, and return the parsed output (unless parse is False, in which case return the response for the caller to do whatever it likes with). You can use this directly instead of openqa_request() if you need to do something unusual. May raise ConnectionError or RequestError if the connection or the request fail in some way after 'retries' attempts. 'wait' determines how long we wait between retries: on the *first* retry we wait exactly 'wait' seconds, on each subsequent retry the wait time is doubled, up to a max of 60 seconds between attempts. If wait or retries are None, then the global values of this class are used or the defaults apply. """ prepared = self.session.prepare_request(request) authed = self._add_auth_headers(prepared) settings = self.session.merge_environment_settings( url=self.baseurl, proxies=None, stream=None, verify=None, cert=None ) if retries is None: retries = self.retries if wait is None: wait = self.wait try: resp = self.session.send(authed, **settings) if not resp.ok: raise openqa_client.exceptions.RequestError( request.method, resp.url, resp.status_code, resp.text ) if not parse or resp.status_code == 204: return resp # check if the server sent us YAML when we asked for JSON contype = resp.headers.get("content-type", "") if contype.startswith("text/yaml"): # FullLoader should also be fine as we trust the devs, # but I doubt they're gonna put anything beyond # SafeLoader's capacity in the responses return yaml.load(resp.text, Loader=yaml.SafeLoader) return resp.json() except (requests.exceptions.ConnectionError, openqa_client.exceptions.RequestError) as err: # We could use urllib3.util.Retry here, but that actually # results in more lines of code than doing it ourselves to_retry = (408, 413, 429, 444, 500, 502, 503, 504, 509, 521, 522, 599) if retries and ( isinstance(err, requests.exceptions.ConnectionError) or err.status_code in to_retry ): logger.debug("do_request: request failed! Retrying in %s seconds...", wait) logger.debug("Error: %s", err) time.sleep(wait) newwait = min(wait + wait, 60) return self.do_request(request, retries=retries - 1, wait=newwait) if isinstance(err, openqa_client.exceptions.RequestError): raise err if isinstance(err, requests.exceptions.ConnectionError): raise openqa_client.exceptions.ConnectionError(err) assert False, "This code path must be unreachable" def openqa_request( self, method: RequestMethod, path: str, params: Any = None, retries: Optional[int] = None, wait: Optional[int] = None, data: Any = None, ): """Perform a typical openQA request, with an API path and some optional parameters. Use the data parameter instead of params if you need to pass lots of settings. It will post application/x-www-form-urlencoded data. If either params or data is a dictionary and contains the key "settings" (which is a list of dictionaries), then the entries of "settings" converted as follows before being sent: params = { "name": "something", "settings": [{"key": "varname", "value": "var_value"}] } becomes: params = { "name": "something", "settings[varname]": "var_value" } """ if not params: params = {} # we have to work around a limitation in the API: when modifying job # groups, products, etc. that take a settings parameter, then this # settings parameter gets returned to us as a list like this: # [{"key": "varname", "value": "var_value"}] # But when we sent the reply back, we must send these settings in the # "top level" payload object like this: # "settings[varname]": "var_value" for payload in (params, data): if ( payload is not None and isinstance(payload, dict) and "settings" in payload and isinstance(payload["settings"], list) ): settings = payload.pop("settings") for setting in settings: payload[f"settings[{setting.get('key')}]"] = setting["value"] # As with the reference client, we assume relative paths are # relative to /api/v1. if not path.startswith("/"): path = f"/api/v1/{path}" url = f"{self.baseurl}{path}" req = requests.Request(method=method.upper(), url=url, params=params, data=data) return self.do_request(req, retries=retries, wait=wait, parse=True) def find_clones(self, jobs: List[Job]) -> List[Job]: """Given an iterable of job dicts, this will see if any of the jobs were cloned, and replace any that were cloned with the dicts of their clones, returning a list. It recurses - so if 3 was cloned as 4 and 4 was cloned as 5, you'll wind up with 5. If both a job and its clone are already in the iterable, the original will be removed. """ jobs = list(jobs) while any(job["clone_id"] for job in jobs): toget = [] ids = [job["id"] for job in jobs] # copy the list to iterate over it for job in list(jobs): if job["clone_id"]: logger.debug("Replacing job %s with clone %s", job["id"], job["clone_id"]) if job["clone_id"] not in ids: toget.append(str(job["clone_id"])) jobs.remove(job) if toget: # Get clones and add them to the list clones = self.openqa_request("GET", "jobs", params={"ids": ",".join(toget)})["jobs"] jobs.extend(clones) return jobs @overload def get_jobs(self, jobs: Literal[None], build: Literal[None], filter_dupes: bool) -> NoReturn: ... # pragma: no cover @overload def get_jobs( self, jobs: Optional[List[Union[str, int]]], build: Optional[str], filter_dupes: bool ): ... # pragma: no cover def get_jobs( self, jobs: Optional[List[Union[str, int]]] = None, build: Optional[str] = None, filter_dupes: bool = True, ): """Get job dicts. Either 'jobs' or 'build' must be specified. 'jobs' should be iterable of job IDs (string or int). 'build' should be an openQA BUILD to get all the jobs for. If both are specified, 'jobs' will be used and 'build' ignored. If filter_dupes is True, cloned jobs will be replaced by their clones (see find_clones docstring) and duplicate jobs will be filtered out (using the upstream 'latest' query param). Unlike all previous 'job get' methods in this module, this one will happily return results for running jobs. All it does is get the specified dicts, filter them if filter_dupes is set, and return. If you only want completed jobs, filter the result yourself, or just use fedmsg to make sure you only call this when all the jobs you want are done. This method requires the server to be at least version 4.3 to work correctly. """ if not build and not jobs: raise TypeError("iterate_jobs: either 'jobs' or 'build' must be specified") if jobs: # this gets all jobdicts with a single API query params = {"ids": ",".join(str(j) for j in jobs)} else: assert build is not None params = {"build": build} if filter_dupes: params["latest"] = "1" jobdicts = self.openqa_request("GET", "jobs", params=params)["jobs"] if filter_dupes: # sub out clones. when run on a BUILD this is superfluous # as 'latest' will always wind up finding the latest clone # but this is still useful if run on a jobs iterable and # the jobs in question have clones; 'latest' doesn't help # there as it only considers the jobs queried. jobdicts = self.find_clones(jobdicts) return jobdicts openQA-python-client-4.2.3/src/openqa_client/const.py000066400000000000000000000103331450710135400226060ustar00rootroot00000000000000# Copyright Red Hat # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authors: Adam Williamson """Important constants duplicated from openQA. We need to keep this in sync with upstream, but it's better to have it done just once here rather than every consumer of this library duplicating things like 'these are the "running" states' on the fly. It is explicitly allowed to use 'from openqa_client.const import *'; this will only import sanely named 'constants'. You may prefer to do `from openqa_client import const as oqc` or similar. For details on what each of these means, please refer to the openQA source, it has comments that explain them; it seems unnecessary to duplicate those here. """ # we use 'bad' whitespace to align the definitions nicely. # pylint: disable=bad-whitespace # lib/OpenQA/Schema/Result/Jobs.pm # States JOB_STATE_SCHEDULED = "scheduled" JOB_STATE_ASSIGNED = "assigned" JOB_STATE_SETUP = "setup" JOB_STATE_RUNNING = "running" JOB_STATE_UPLOADING = "uploading" JOB_STATE_CANCELLED = "cancelled" JOB_STATE_DONE = "done" JOB_STATES = (JOB_STATE_SCHEDULED, JOB_STATE_SETUP, JOB_STATE_RUNNING, JOB_STATE_CANCELLED, JOB_STATE_DONE, JOB_STATE_UPLOADING, JOB_STATE_ASSIGNED) JOB_PENDING_STATES = (JOB_STATE_SCHEDULED, JOB_STATE_ASSIGNED, JOB_STATE_SETUP, JOB_STATE_RUNNING, JOB_STATE_UPLOADING) JOB_EXECUTION_STATES = (JOB_STATE_ASSIGNED, JOB_STATE_SETUP, JOB_STATE_RUNNING, JOB_STATE_UPLOADING) JOB_PRE_EXECUTION_STATES = (JOB_STATE_SCHEDULED,) JOB_FINAL_STATES = (JOB_STATE_DONE, JOB_STATE_CANCELLED) # These are referred to as 'meta' states upstream JOB_STATE_PRE_EXECUTION = "pre_execution" JOB_STATE_EXECUTION = "execution" JOB_STATE_FINAL = "final" # Results JOB_RESULT_NONE = "none" JOB_RESULT_PASSED = "passed" JOB_RESULT_SOFTFAILED = "softfailed" JOB_RESULT_FAILED = "failed" JOB_RESULT_INCOMPLETE = "incomplete" JOB_RESULT_SKIPPED = "skipped" JOB_RESULT_OBSOLETED = "obsoleted" JOB_RESULT_PARALLEL_FAILED = "parallel_failed" JOB_RESULT_PARALLEL_RESTARTED = "parallel_restarted" JOB_RESULT_USER_CANCELLED = "user_cancelled" JOB_RESULT_USER_RESTARTED = "user_restarted" JOB_RESULT_TIMEOUT_EXCEEDED = "timeout_exceeded" JOB_RESULTS = (JOB_RESULT_NONE, JOB_RESULT_PASSED, JOB_RESULT_SOFTFAILED, JOB_RESULT_FAILED, JOB_RESULT_INCOMPLETE, JOB_RESULT_SKIPPED, JOB_RESULT_OBSOLETED, JOB_RESULT_PARALLEL_FAILED, JOB_RESULT_PARALLEL_RESTARTED, JOB_RESULT_USER_CANCELLED, JOB_RESULT_USER_RESTARTED, JOB_RESULT_TIMEOUT_EXCEEDED) JOB_COMPLETE_RESULTS = (JOB_RESULT_PASSED, JOB_RESULT_SOFTFAILED, JOB_RESULT_FAILED) JOB_OK_RESULTS = (JOB_RESULT_PASSED, JOB_RESULT_SOFTFAILED) JOB_NOT_COMPLETE_RESULTS = (JOB_RESULT_INCOMPLETE, JOB_RESULT_TIMEOUT_EXCEEDED) JOB_ABORTED_RESULTS = (JOB_RESULT_SKIPPED, JOB_RESULT_OBSOLETED, JOB_RESULT_PARALLEL_FAILED, JOB_RESULT_PARALLEL_RESTARTED, JOB_RESULT_USER_CANCELLED, JOB_RESULT_USER_RESTARTED) JOB_NOT_OK_RESULTS = (JOB_RESULT_FAILED,) + JOB_NOT_COMPLETE_RESULTS + JOB_ABORTED_RESULTS # 'meta' results JOB_RESULT_COMPLETE = "complete" JOB_RESULT_NOT_COMPLETE = "not_complete" JOB_RESULT_ABORTED = "aborted" # Scenarios JOB_SCENARIO_KEYS = ('DISTRI', 'VERSION', 'FLAVOR', 'ARCH', 'TEST') JOB_SCENARIO_WITH_MACHINE_KEYS = JOB_SCENARIO_KEYS + ('MACHINE',) openQA-python-client-4.2.3/src/openqa_client/exceptions.py000066400000000000000000000027511450710135400236460ustar00rootroot00000000000000# Copyright Red Hat # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Author: Adam Williamson """Custom exceptions used by openqa_client.""" from requests.exceptions import ConnectionError as RConnectionError class OpenQAClientError(Exception): """Base class for openQA client errors.""" pass class ConnectionError(OpenQAClientError): """Error raised when server connection fails. Just passed through requests.exceptions.ConnectionError. """ def __init__(self, err: RConnectionError) -> None: self.err = err class RequestError(OpenQAClientError): """Error raised when a request fails (after retries). 3-tuple of method, URL, and status code. """ def __init__(self, method: str, url: str, status_code: int, text: str) -> None: self.method = method self.url = url self.status_code = status_code self.text = text openQA-python-client-4.2.3/src/openqa_client/py.typed000066400000000000000000000000001450710135400225730ustar00rootroot00000000000000openQA-python-client-4.2.3/tests.requires000066400000000000000000000000731450710135400204210ustar00rootroot00000000000000coverage freezegun pytest mypy types-requests types-PyYAML openQA-python-client-4.2.3/tests/000077500000000000000000000000001450710135400166405ustar00rootroot00000000000000openQA-python-client-4.2.3/tests/conftest.py000066400000000000000000000064521450710135400210460ustar00rootroot00000000000000# Copyright Red Hat # # This file is part of openQA-python-client. # # openQA-python-client is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Author: Adam Williamson # these are all kinda inappropriate for pytest patterns # pylint: disable=no-init, protected-access, no-self-use, unused-argument """Test configuration and fixtures.""" import os import shutil from unittest import mock import pytest def _config_teardown(datadir): if os.path.exists(datadir): shutil.rmtree(datadir) def _config_setup(hosts): """Creates a config file in a fake user home directory, at data/home/ under the tests directory. For each host in hosts we write an entry with the same key and secret, unless the host has 'nokey' in it, in which case we write an entry with no key or secret. Before doing this, re-create the home dir. """ datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") home = os.path.join(datadir, "home") _config_teardown(datadir) confpath = os.path.join(home, ".config", "openqa") os.makedirs(confpath) confpath = os.path.join(confpath, "client.conf") content = [] for host in hosts: if "nokey" in host: # don't write a key and secret for this host content.extend([f"[{host}]"]) else: content.extend([f"[{host}]", "key = aaaaaaaaaaaaaaaa", "secret = bbbbbbbbbbbbbbbb"]) content = "\n".join(content) with open(confpath, "w") as conffh: conffh.write(content) return (datadir, home) @pytest.fixture(scope="function") def config(config_hosts): """Create config file via _config_setup, using list of hosts passed in via arg (intended for parametrization). Patch os.path.expanduser to return the home dir, then teardown on test completion. """ (datadir, home) = _config_setup(config_hosts) with mock.patch("os.path.expanduser", return_value=home, autospec=True): yield _config_teardown(datadir) @pytest.fixture(scope="function") def simple_config(): """Create config file via _config_setup, with a single host. Patch os.path.expanduser to return the home dir, then teardown on test completion. """ (datadir, home) = _config_setup(["openqa.fedoraproject.org"]) with mock.patch("os.path.expanduser", return_value=home, autospec=True): yield _config_teardown(datadir) @pytest.fixture(scope="function") def empty_config(): """Create empty config file via _config_setup. Patch os.path.expanduser to return the home dir, then teardown on test completion. """ (datadir, home) = _config_setup([]) with mock.patch("os.path.expanduser", return_value=home, autospec=True): yield _config_teardown(datadir) openQA-python-client-4.2.3/tests/test_client.py000066400000000000000000000435561450710135400215440ustar00rootroot00000000000000# Copyright Red Hat # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authors: Adam Williamson # these are all kinda inappropriate for pytest patterns # pylint: disable=old-style-class, no-init, protected-access, no-self-use, unused-argument # pylint: disable=invalid-name, too-few-public-methods, too-many-public-methods, too-many-lines """Tests for the main client code.""" from unittest import mock import freezegun import pytest import requests import openqa_client.client as oqc import openqa_client.exceptions as oqe class TestClient: """Tests for the client library.""" @pytest.mark.parametrize( "config_hosts", [ ["localhost"], ["openqa.fedoraproject.org"], ["localhost", "openqa.fedoraproject.org"], ["openqa.fedoraproject.org", "localhost"], ["openqa.nokey.org", "localhost", "openqa.fedoraproject.org"], ["http://openqa.fedoraproject.org", "openqa.fedoraproject.org"], ["https://openqa.fedoraproject.org", "localhost"], ], ) def test_config_hosts(self, config, config_hosts): """Test handling config files with various different hosts specified (sometimes one, sometimes more). """ client = oqc.OpenQA_Client() # we expect default scheme 'http' for localhost, specified # scheme if there is one, 'https' for all else if config_hosts[0] == "localhost": scheme = "http://" elif config_hosts[0].startswith("http"): scheme = "" else: scheme = "https://" assert client.baseurl == f"{scheme}{config_hosts[0]}" assert client.session.headers["Accept"] == "json" # this should be set for all but the 'nokey' case if "nokey" in config_hosts[0]: assert "X-API-Key" not in client.session.headers else: assert client.session.headers["X-API-Key"] == "aaaaaaaaaaaaaaaa" assert client.apisecret == "bbbbbbbbbbbbbbbb" # check we override the config file priority but use the key # if server and scheme specified client = oqc.OpenQA_Client(server="openqa.fedoraproject.org", scheme="http") assert client.baseurl == "http://openqa.fedoraproject.org" if "openqa.fedoraproject.org" in config_hosts: assert client.session.headers["X-API-Key"] == "aaaaaaaaaaaaaaaa" assert client.apisecret == "bbbbbbbbbbbbbbbb" else: assert "X-API-Key" not in client.session.headers def test_noconfig_host(self, empty_config): """Test with empty config file (should use localhost).""" client = oqc.OpenQA_Client() assert client.baseurl == "http://localhost" assert "X-API-Key" not in client.session.headers @freezegun.freeze_time("2020-02-27") def test_add_auth_headers(self, simple_config): """Test _add_auth_headers.""" client = oqc.OpenQA_Client() # this weird build value tests tilde substitution in hash params = {"build": "foo~", "latest": "1"} # this (incorrect) URL tests space substitution in hash request = requests.Request( url=client.baseurl + "/api/v1/jobs ", method="GET", params=params ) prepared = client.session.prepare_request(request) authed = client._add_auth_headers(prepared) assert prepared.headers != authed.headers assert authed.headers["X-API-Hash"] == "71373f0a57118b120d1915ccc0a24ae2cc112ad3" assert authed.headers["X-API-Microtime"] == "1582761600.0" # with no key/secret, request should be returned unmodified client = oqc.OpenQA_Client("localhost") request = requests.Request( url=client.baseurl + "/api/v1/jobs ", method="GET", params=params ) prepared = client.session.prepare_request(request) authed = client._add_auth_headers(prepared) assert prepared.headers == authed.headers @mock.patch("requests.sessions.Session.send", autospec=True) def test_do_request_ok(self, fakesend, simple_config): """Test do_request (normal, success case).""" # we have to set up a proper headers dict or mock gets lost in # infinite recursion and eats all our RAM... fakeresp = fakesend.return_value fakeresp.headers = {"content-type": "text/json,encoding=utf-8"} client = oqc.OpenQA_Client() params = {"id": "1"} request = requests.Request(url=client.baseurl + "/api/v1/jobs", method="GET", params=params) client.do_request(request) # check request was authed. Note: [0][0] is self assert "X-API-Key" in fakesend.call_args[0][1].headers assert "X-API-Hash" in fakesend.call_args[0][1].headers assert "X-API-Microtime" in fakesend.call_args[0][1].headers # check URL looks right assert fakesend.call_args[0][1].url == "https://openqa.fedoraproject.org/api/v1/jobs?id=1" # check we called .json() on the response fakeresp = fakesend.return_value assert len(fakeresp.method_calls) == 1 (callname, callargs, callkwargs) = fakeresp.method_calls[0] assert callname == "json" assert not callargs assert not callkwargs @mock.patch("requests.sessions.Session.send", autospec=True) def test_do_request_ok_no_parse(self, fakesend, simple_config): """Test do_request (normal, success case, with parse=False).""" client = oqc.OpenQA_Client() params = {"id": "1"} request = requests.Request(url=client.baseurl + "/api/v1/jobs", method="GET", params=params) client.do_request(request, parse=False) # check request was authed. Note: [0][0] is self assert "X-API-Key" in fakesend.call_args[0][1].headers assert "X-API-Hash" in fakesend.call_args[0][1].headers assert "X-API-Microtime" in fakesend.call_args[0][1].headers # check URL looks right assert fakesend.call_args[0][1].url == "https://openqa.fedoraproject.org/api/v1/jobs?id=1" # check we did not call .json() (or anything else) on response fakeresp = fakesend.return_value assert len(fakeresp.method_calls) == 0 @mock.patch("requests.sessions.Session.send", autospec=True) def test_do_request_ok_yaml(self, fakesend, simple_config): """Test do_request (with YAML response).""" # set up the response to return YAML and correct # content-type header fakeresp = fakesend.return_value fakeresp.headers = {"content-type": "text/yaml,encoding=utf-8"} fakeresp.text = "defaults:\n arm:\n machine: ARM" client = oqc.OpenQA_Client() request = requests.Request( url=client.baseurl + "/api/v1/job_templates_scheduling/1", method="GET" ) ret = client.do_request(request) # check we did not call .json() on response assert len(fakeresp.method_calls) == 0 # check we parsed the response assert ret == {"defaults": {"arm": {"machine": "ARM"}}} @mock.patch("requests.sessions.Session.send", autospec=True) def test_do_request_not_changed(self, fakesend, simple_config): """Test do_request when receiving a 204 Not Changed reply""" fakeresp = fakesend.return_value fakeresp.status_code = 204 fakeresp.text = "" client = oqc.OpenQA_Client() request = requests.Request( url=client.baseurl + "/api/v1/job_templates_scheduling/1", method="PUT" ) ret = client.do_request(request) assert len(fakeresp.method_calls) == 0, "no methods must be called on response" assert ret == fakesend.return_value, "do_request should have returned the response itself" @mock.patch("time.sleep", autospec=True) @mock.patch("requests.sessions.Session.send", autospec=True) def test_do_request_502(self, fakesend, fakesleep, simple_config): """Test do_request (response not OK and in the retry list, default retries). """ fakeresp = fakesend.return_value fakeresp.ok = False fakeresp.status_code = 502 client = oqc.OpenQA_Client() params = {"id": "1"} request = requests.Request(url=client.baseurl + "/api/v1/jobs", method="GET", params=params) # if response is not OK, we should raise RequestError with pytest.raises(oqe.RequestError): client.do_request(request) # we should also have retried 5 times, with a wait based on 10 assert fakesend.call_count == 6 assert fakesleep.call_count == 5 sleeps = [call[0][0] for call in fakesleep.call_args_list] assert sleeps == [10, 20, 40, 60, 60] @mock.patch("time.sleep", autospec=True) @mock.patch("requests.sessions.Session.send", autospec=True) def test_do_request_404(self, fakesend, fakesleep, simple_config): """Test do_request (response not OK but not in the retry list, default retries). """ fakeresp = fakesend.return_value fakeresp.ok = False fakeresp.status_code = 404 client = oqc.OpenQA_Client() params = {"id": "1"} request = requests.Request(url=client.baseurl + "/api/v1/jobs", method="GET", params=params) # if response is not OK, we should raise RequestError with pytest.raises(oqe.RequestError): client.do_request(request) # we should not have retried assert fakesend.call_count == 1 assert fakesleep.call_count == 0 @mock.patch("time.sleep", autospec=True) @mock.patch( "requests.sessions.Session.send", autospec=True, side_effect=requests.exceptions.ConnectionError("foo"), ) def test_do_request_error(self, fakesend, fakesleep, simple_config): """Test do_request (send raises exception, custom retries).""" client = oqc.OpenQA_Client() params = {"id": "1"} request = requests.Request(url=client.baseurl + "/api/v1/jobs", method="GET", params=params) # if send raises ConnectionError, we should raise ours with pytest.raises(oqe.ConnectionError): client.do_request(request, retries=2, wait=5) # we should also have retried 2 times, with a wait based on 5 assert fakesend.call_count == 3 assert fakesleep.call_count == 2 sleeps = [call[0][0] for call in fakesleep.call_args_list] assert sleeps == [5, 10] @mock.patch("openqa_client.client.OpenQA_Client.do_request", autospec=True) def test_openqa_request(self, fakedo, simple_config): """Test openqa_request.""" client = oqc.OpenQA_Client() params = {"id": "1"} client.openqa_request("get", "jobs", params=params, retries=2, wait=5) # check we called do_request right. Note: [0][0] is self assert fakedo.call_args[0][1].url == "https://openqa.fedoraproject.org/api/v1/jobs" assert fakedo.call_args[0][1].params == {"id": "1"} assert fakedo.call_args[1]["retries"] == 2 assert fakedo.call_args[1]["wait"] == 5 # check requests with no params work fakedo.reset_mock() client.openqa_request("get", "jobs", retries=2, wait=5) assert fakedo.call_args[0][1].url == "https://openqa.fedoraproject.org/api/v1/jobs" assert fakedo.call_args[0][1].params == {} assert fakedo.call_args[1]["retries"] == 2 assert fakedo.call_args[1]["wait"] == 5 @mock.patch("time.sleep", autospec=True) @mock.patch( "requests.sessions.Session.send", autospec=True, side_effect=requests.exceptions.ConnectionError("foo"), ) def test_openqa_request_retries(self, fakesend, fakesleep, simple_config): """Test the handling of wait & retries when using openqa_request.""" client = oqc.OpenQA_Client(retries=3) with pytest.raises(oqe.ConnectionError): client.openqa_request("get", "jobs", wait=42) assert fakesend.call_count == 4, "expected the class global retries to be used" assert fakesleep.call_count == 3 sleeps = [call[0][0] for call in fakesleep.call_args_list] # sleep time is capped at 60s assert sleeps == [42, 60, 60] fakesend.reset_mock() fakesleep.reset_mock() with pytest.raises(oqe.ConnectionError): client.openqa_request("get", "jobs", retries=1) assert ( fakesend.call_count == 2 ), "expected the retries value from the method to take precedence" assert fakesleep.call_count == 1 sleeps = [call[0][0] for call in fakesleep.call_args_list] assert sleeps == [10], "expected class default for wait to be used" @mock.patch("openqa_client.client.OpenQA_Client.do_request", autospec=True) def test_openqa_request_settings_addition(self, fakedo, simple_config): """Test openqa_request's handling of the 'settings' parameter.""" client = oqc.OpenQA_Client() test_suite_params = { "id": "1", "name": "some_suite", "settings": [ { "key": "PUBLISH_HDD_1", "value": "%DISTRI%-%VERSION%-%ARCH%-%BUILD%.qcow2", }, {"key": "START_AFTER_TEST", "value": "fedora_rawhide_qcow2"}, ], } client.openqa_request("POST", "test_suites", params=test_suite_params) # check we called do_request right. Note: [0][0] is self assert fakedo.call_args[0][1].url == "https://openqa.fedoraproject.org/api/v1/test_suites" assert fakedo.call_args[0][1].params == { "id": "1", "name": "some_suite", "settings[PUBLISH_HDD_1]": "%DISTRI%-%VERSION%-%ARCH%-%BUILD%.qcow2", "settings[START_AFTER_TEST]": "fedora_rawhide_qcow2", } # check requests with a string payload fakedo.reset_mock() client.openqa_request("put", "test_suites", data="settings") assert fakedo.call_args[0][1].params == {} assert fakedo.call_args[0][1].data == "settings" @mock.patch("openqa_client.client.OpenQA_Client.do_request", autospec=True) def test_not_prepend_api_route(self, fakedo, simple_config): """Test openqa_request not prepending the /api/v1 string for absolute routes.""" client = oqc.OpenQA_Client() client.openqa_request("GET", "/absolute_url") assert fakedo.call_args[0][1].url == "https://openqa.fedoraproject.org/absolute_url" @mock.patch("openqa_client.client.OpenQA_Client.openqa_request", autospec=True) def test_find_clones(self, fakerequest, simple_config): """Test find_clones.""" client = oqc.OpenQA_Client() # test data: three jobs with clones, one included in the data, # two not jobs = [ {"id": 1, "name": "foo", "result": "failed", "clone_id": 2}, {"id": 2, "name": "foo", "result": "passed", "clone_id": None}, {"id": 3, "name": "bar", "result": "failed", "clone_id": 4}, {"id": 5, "name": "moo", "result": "failed", "clone_id": 6}, ] # set the mock to return the additional jobs when we ask fakerequest.return_value = { "jobs": [ {"id": 4, "name": "bar", "result": "passed", "clone_id": None}, {"id": 6, "name": "moo", "result": "passed", "clone_id": None}, ] } ret = client.find_clones(jobs) assert ret == [ {"id": 2, "name": "foo", "result": "passed", "clone_id": None}, {"id": 4, "name": "bar", "result": "passed", "clone_id": None}, {"id": 6, "name": "moo", "result": "passed", "clone_id": None}, ] # check we actually requested the additional job correctly assert fakerequest.call_count == 1 assert fakerequest.call_args[0][1] == "GET" assert fakerequest.call_args[0][2] == "jobs" assert fakerequest.call_args[1]["params"] == {"ids": "4,6"} @mock.patch("openqa_client.client.OpenQA_Client.find_clones", autospec=True) @mock.patch("openqa_client.client.OpenQA_Client.openqa_request", autospec=True) def test_get_jobs(self, fakerequest, fakeclones, simple_config): """Test get_jobs.""" client = oqc.OpenQA_Client() with pytest.raises(TypeError): client.get_jobs() client.get_jobs(jobs=[1, 2]) assert fakerequest.call_args[0][1] == "GET" assert fakerequest.call_args[0][2] == "jobs" assert fakerequest.call_args[1]["params"] == {"ids": "1,2", "latest": "1"} assert fakeclones.call_count == 1 client.get_jobs(build="foo", filter_dupes=False) assert fakerequest.call_args[0][1] == "GET" assert fakerequest.call_args[0][2] == "jobs" assert fakerequest.call_args[1]["params"] == {"build": "foo"} assert fakeclones.call_count == 1 def test_client_errors(self): """Test creation of exceptions""" template_error = '{"error":"fail"}' err = oqe.RequestError("GET", "http://localhost", 404, template_error) assert err.args[0] == "GET" assert err.args[1] == "http://localhost" assert err.args[2] == 404 assert err.method == "GET" assert err.url == "http://localhost" assert err.status_code == 404 assert err.text == template_error err = oqe.ConnectionError("oh no") assert err.args[0] == "oh no" assert err.err == "oh no" openQA-python-client-4.2.3/tox.ini000066400000000000000000000014111450710135400170060ustar00rootroot00000000000000[tox] envlist = py37,py38,py39,py310,py311,py312,ci skip_missing_interpreters = true isolated_build = true [gh-actions] python = 3.6: py36 3.7: py37 3.8: py38 3.9: py39 3.10: py310, ci 3.11: py311 3.12: py312 [testenv] deps = -r{toxinidir}/install.requires -r{toxinidir}/tests.requires commands = coverage run -m pytest {posargs} [testenv:ci] deps = -r{toxinidir}/ci.requires commands = coverage combine coverage report coverage xml diff-cover coverage.xml --fail-under=90 --compare-branch=origin/main diff-quality --violations=pylint --fail-under=90 --compare-branch=origin/main black src/ tests/ --check --exclude const.py mypy src/openqa_client [testenv:venv] passenv = * commands = {posargs} []