././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.043975 python-bugzilla-3.0.2/0000775000175000017500000000000000000000000015065 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1593217225.0 python-bugzilla-3.0.2/CONTRIBUTING.md0000664000175000017500000000364200000000000017323 0ustar00crobinsocrobinso# Setting up the environment If you already have system installed versions of python-bugzilla dependencies, running the command line from git is as simple as doing: cd python-bugzilla.git ./bugzilla-cli [arguments] # Running tests Our test suite uses pytest. If your system has dependencies already, the quick unit test suite is invoked simply with: pytest ## Read-Only Functional tests There are more comprehensive, readonly functional tests that run against several public bugzilla instances, but they are not run by default. No login account is required. Run them with: pytest --ro-functional ## Read/Write Functional Tests. Read/Write functional tests use partner-bugzilla.redhat.com, which is a bugzilla instance specifically for this type of testing. Data is occasionally hard synced with regular bugzilla.redhat.com, and all local edits are removed. Login accounts are also synced. If you want access to partner-bugzilla.redhat.com, sign up for a regular bugzilla.redhat.com login and wait for the next sync period. Before running these tests, you'll need to cache login credentials. Example: ./bugzilla-cli --bugzilla=partner-bugzilla.redhat.com --username=$USER login pytest --rw-functional ## Testing across python versions To test all supported python versions, run tox using any of the following. tox tox -- --ro-functional tox -- --rw-functional # pylint and pycodestyle To test for pylint or pycodestyle violations, you can run: ./setup.py pylint Note: This expects that you already have pylint and pycodestyle installed. # Patch Submission If you are submitting a patch, ensure the following: [REQ] verify that no new pylint or pycodestyle violations [REQ] run basic unit test suite across all python versions as described above. Running any of the functional tests is not a requirement for patch submission, but please give them a go if you are interested. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578255853.0 python-bugzilla-3.0.2/COPYING0000664000175000017500000004325400000000000016130 0ustar00crobinsocrobinso 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578946689.0 python-bugzilla-3.0.2/MANIFEST.in0000664000175000017500000000036400000000000016626 0ustar00crobinsocrobinsoinclude COPYING CONTRIBUTING.md MANIFEST.in README.md NEWS.md include xmlrpc-api-notes.txt include python-bugzilla.spec include *requirements.txt include man/bugzilla.rst recursive-include examples *.py recursive-include tests *.py *.txt *.cfg ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230895.0 python-bugzilla-3.0.2/NEWS.md0000664000175000017500000001104400000000000016163 0ustar00crobinsocrobinso# python-bugzilla release news ## Release 3.0.2 (November 12, 2020) - Fix API key leaking into requests exceptions ## Release 3.0.1 (October 07, 2020) - Skip man page generation to fix build on Windows (Alexander Todorov) ## Release 3.0.0 (October 03, 2020) - Drop python2 support - New option `bugzilla modify --minor-update option` - requests: use PYTHONBUGZILLA_REQUESTS_TIMEOUT env variable - xmlrpc: Don't add api key to passed in user dictionary ## Release 2.5.0 (July 04, 2020) - cli: Add query --extrafield, --includefield, --excludefield - Revive bugzilla.rhbugzilla.RHBugzilla import path ## Release 2.4.0 (June 29, 2020) - Bugzilla REST API support - Add --json command line output option - Add APIs for Bugzilla Groups (Pierre-Yves Chibon) - Add `Bugzilla.get_requests_session()` API to access raw requests Session - Add `Bugzilla.get_xmlrpc_proxy()` API to access raw ServerProxy - Add `Bugzilla requests_session=` init parameter to pass in auth, etc. - Add `bugzilla attach --ignore-obsolete` (Čestmír Kalina) - Add `bugzilla login --api-key` for API key prompting (Danilo C. L. de Paula) - Add `bugzilla new --private` ## Release 2.3.0 (August 26, 2019) - restrict-login suppot (Viliam Krizan) - cli: Add support for private attachments (Brian 'Redbeard' Harrington) - Fix python3 deprecation warnings - Drop python 3.3 support, minimum python3 is python 3.4 now ## Release 2.2.0 (August 11, 2018) - Port tests to pytest - cli: --cert Client side certificate support (Tobias Wolter) - cli: add ability to post comment while sending attachment (Jeff Mahoney) - cli: Add --comment-tag option - cli: Add info --active-components - Add a raw Product.get wrapper API ## Release 2.1.0 (March 30, 2017) - Support for bugzilla 5 API Keys (Dustin J. Mitchell) - bugzillarc can be used to set default URL for the cli tool - Revive update_flags wrapper - Bug fixes and minor improvements ## Release 2.0.0 (Feb 08 2017) This release contains several small to medium API breaks. I expect most users won't notice any difference. I previously outlined the changes here: https://lists.fedorahosted.org/archives/list/python-bugzilla@lists.fedorahosted.org/thread/WCYPOKJZFYOW7RRT44FCM5GQU26O56K4/ The major changes are: - Several fixes for use with bugzilla 5 - Bugzilla.bug_autorefresh now defaults to False - Credentials are now cached in ~/.cache/python-bugzilla/ - bin/bugzilla was converted to argparse - bugzilla query --boolean_chart option is removed - Unify command line flags across sub commands ## Release 1.2.2 (Sep 23 2015) - Switch hosting to http://github.com/python-bugzilla/python-bugzilla - Fix requests usage when ndg-httpsclient is installed (Arun Babu Neelicattu) - Add non-rhbz support for getting bug comments (AJ Lewis) - Misc bugfixes and improvements ## Release 1.2.1 (May 22 2015) - bin/bugzilla: Add --ensure-logged-in option - Fix get_products with bugzilla.redhat.com - A few other minor improvements ## Release 1.2.0 (Apr 08 2015) - Add bugzilla new/query/modify --field flag (Arun Babu Neelicattu) - API support for ExternalBugs (Arun Babu Neelicattu, Brian Bouterse) - Add new/modify --alias support (Adam Williamson) - Bugzilla.logged_in now returns live state (Arun Babu Neelicattu) - Fix getbugs API with latest Bugzilla releases ## Release 1.1.0 (Jun 01 2014) - Support for bugzilla tokens (Arun Babu Nelicattu) - bugzilla: Add query/modify --tags - bugzilla --login: Allow to login and run a command in one shot - bugzilla --no-cache-credentials: Don't use or save cached credentials when using the CLI - Show bugzilla errors when login fails - Don't pull down attachments in bug.refresh(), need to get bug.attachments manually - Add Bugzilla bug_autorefresh parameter. ## Release 1.0.0 (Mar 25 2014) - Python 3 support (Arun Babu Neelicattu) - Port to python-requests (Arun Babu Neelicattu) - bugzilla: new: Add --keywords, --assigned_to, --qa_contact (Lon Hohberger) - bugzilla: query: Add --quicksearch, --savedsearch - bugzilla: query: Support saved searches with --from-url - bugzilla: --sub-component support for all relevant commands ## Release 0.9.0 (Jun 19 2013) - CVE-2013-2191: Switch to pycurl to get SSL host and cert validation - bugzilla: modify: add --dependson (Don Zickus) - bugzilla: new: add --groups option (Paul Frields) - bugzilla: modify: Allow setting nearly every bug parameter - NovellBugzilla implementation removed, can't get it to work ## Release 0.8.0 (Feb 16 2013) - Replace usage of non-upstream Red Hat bugzilla APIs with upstream replacements - Test suite improvements, nearly complete code coverage - Fix all open bug reports and RFEs ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.043975 python-bugzilla-3.0.2/PKG-INFO0000664000175000017500000000163400000000000016166 0ustar00crobinsocrobinsoMetadata-Version: 1.1 Name: python-bugzilla Version: 3.0.2 Summary: Library and command line tool for interacting with Bugzilla Home-page: https://github.com/python-bugzilla/python-bugzilla Author: UNKNOWN Author-email: UNKNOWN License: GPLv2 Description: UNKNOWN Platform: UNKNOWN Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python 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.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1594299448.0 python-bugzilla-3.0.2/README.md0000664000175000017500000000154500000000000016351 0ustar00crobinsocrobinso[![CI](https://github.com/python-bugzilla/python-bugzilla/workflows/CI/badge.svg)](https://github.com/python-bugzilla/python-bugzilla/actions?query=workflow%3ACI) [![PyPI](https://img.shields.io/pypi/v/python-bugzilla)](https://pypi.org/project/python-bugzilla/) # python-bugzilla This package provides two bits: * 'bugzilla' python module for talking to a [Bugzilla](https://www.bugzilla.org/) instance over XMLRPC or REST * /usr/bin/bugzilla command line tool for performing actions from the command line: create or edit bugs, various queries, etc. This was originally written specifically for Red Hat's Bugzilla instance and is used heavily at Red Hat and in Fedora, but it should still be generically useful. You can find some code examples in the [examples](examples) directory. For questions about submitting patches, see [CONTRIBUTING.md](CONTRIBUTING.md) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.032975 python-bugzilla-3.0.2/bugzilla/0000775000175000017500000000000000000000000016676 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1593804279.0 python-bugzilla-3.0.2/bugzilla/__init__.py0000664000175000017500000000217700000000000021016 0ustar00crobinsocrobinso# python-bugzilla - a Python interface to bugzilla using xmlrpclib. # # Copyright (C) 2007, 2008 Red Hat Inc. # Author: Will Woods # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. from .apiversion import version, __version__ from .base import Bugzilla from .exceptions import BugzillaError from .oldclasses import (Bugzilla3, Bugzilla32, Bugzilla34, Bugzilla36, Bugzilla4, Bugzilla42, Bugzilla44, NovellBugzilla, RHBugzilla, RHBugzilla3, RHBugzilla4) # This is the public API. If you are explicitly instantiating any other # class, using some function, or poking into internal files, don't complain # if things break on you. __all__ = [ "Bugzilla3", "Bugzilla32", "Bugzilla34", "Bugzilla36", "Bugzilla4", "Bugzilla42", "Bugzilla44", "NovellBugzilla", "RHBugzilla3", "RHBugzilla4", "RHBugzilla", 'BugzillaError', 'Bugzilla', "version", ] # Clear all other locals() from the public API for __sym in locals().copy(): if __sym.startswith("__") or __sym in __all__: continue locals().pop(__sym) locals().pop("__sym") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605227121.0 python-bugzilla-3.0.2/bugzilla/_authfiles.py0000664000175000017500000001513300000000000021376 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import configparser import http.cookiejar import os from logging import getLogger import urllib.parse from .exceptions import BugzillaError from ._util import listify log = getLogger(__name__) def _parse_hostname(url): # If http://example.com is passed, netloc=example.com path="" # If just example.com is passed, netloc="" path=example.com parsedbits = urllib.parse.urlparse(url) return parsedbits.netloc or parsedbits.path def _makedirs(path): if os.path.exists(os.path.dirname(path)): return os.makedirs(os.path.dirname(path), 0o700) def _default_location(filename, kind): """ Determine default location for passed filename and xdg kind, example: ~/.cache/python-bugzilla/bugzillacookies """ xdgpath = os.path.expanduser("~/.%s/python-bugzilla/%s" % (kind, filename)) return xdgpath def _default_cache_location(filename): return _default_location(filename, 'cache') class _BugzillaRCFile(object): """ Helper class for interacting with bugzillarc files """ @staticmethod def get_default_configpaths(): paths = [ '/etc/bugzillarc', '~/.bugzillarc', '~/.config/python-bugzilla/bugzillarc', ] return paths def __init__(self): self._cfg = None self._configpaths = None self.set_configpaths(None) def set_configpaths(self, configpaths): configpaths = [os.path.expanduser(p) for p in listify(configpaths or [])] cfg = configparser.ConfigParser() read_files = cfg.read(configpaths) if read_files: log.info("Found bugzillarc files: %s", read_files) self._cfg = cfg self._configpaths = configpaths or [] def get_configpaths(self): return self._configpaths[:] def get_default_url(self): """ Grab a default URL from bugzillarc [DEFAULT] url=X """ cfgurl = self._cfg.defaults().get("url", None) if cfgurl is not None: log.debug("bugzillarc: found cli url=%s", cfgurl) return cfgurl def parse(self, url): """ Find the section for the passed URL domain, and return all the fields """ section = "" log.debug("bugzillarc: Searching for config section matching %s", url) urlhost = _parse_hostname(url) for sectionhost in sorted(self._cfg.sections()): # If the section is just a hostname, make it match # If the section has a / in it, do a substring match if "/" not in sectionhost: if sectionhost == urlhost: section = sectionhost elif sectionhost in url: section = sectionhost if section: log.debug("bugzillarc: Found matching section: %s", section) break if not section: log.debug("bugzillarc: No section found") return {} return dict(self._cfg.items(section)) def save_api_key(self, url, api_key): """ Save the API_KEY in the config file. We use the last file in the configpaths list, which is the one with the highest precedence. """ configpaths = self.get_configpaths() if not configpaths: return None config_filename = configpaths[-1] section = _parse_hostname(url) cfg = configparser.ConfigParser() cfg.read(config_filename) if section not in cfg.sections(): cfg.add_section(section) cfg.set(section, 'api_key', api_key.strip()) _makedirs(config_filename) with open(config_filename, 'w') as configfile: cfg.write(configfile) return config_filename class _BugzillaTokenCache(object): """ Class for interacting with a .bugzillatoken cache file """ @staticmethod def get_default_path(): return _default_cache_location("bugzillatoken") def __init__(self): self._filename = None self._cfg = None def _get_domain(self, url): domain = urllib.parse.urlparse(url)[1] if domain and domain not in self._cfg.sections(): self._cfg.add_section(domain) return domain def get_value(self, url): domain = self._get_domain(url) if self._cfg.has_option(domain, 'token'): return self._cfg.get(domain, 'token') return None def set_value(self, url, value): if self.get_value(url) == value: return domain = self._get_domain(url) if value is None: self._cfg.remove_option(domain, 'token') else: self._cfg.set(domain, 'token', value) if self._filename: _makedirs(self._filename) with open(self._filename, 'w') as _cfg: log.debug("Saving to _cfg") self._cfg.write(_cfg) def get_filename(self): return self._filename def set_filename(self, filename): log.debug("Using tokenfile=%s", filename) cfg = configparser.ConfigParser() if filename: cfg.read(filename) self._filename = filename self._cfg = cfg class _BugzillaCookieCache(object): @staticmethod def get_default_path(): return _default_cache_location("bugzillacookies") def __init__(self): self._cookiejar = None def _build_cookiejar(self, cookiefile): cj = http.cookiejar.MozillaCookieJar(cookiefile) if (cookiefile is None or not os.path.exists(cookiefile)): return cj try: cj.load() return cj except http.cookiejar.LoadError: msg = "cookiefile=%s not in Mozilla format" % cookiefile raise BugzillaError(msg) from None def set_filename(self, cookiefile): log.debug("Using cookiefile=%s", cookiefile) self._cookiejar = self._build_cookiejar(cookiefile) def get_filename(self): return self._cookiejar.filename def get_cookiejar(self): return self._cookiejar def set_cookies(self, cookies): for cookie in cookies: self._cookiejar.set_cookie(cookie) cookiefile = self._cookiejar.filename if not cookiefile: return if not os.path.exists(cookiefile): _makedirs(cookiefile) # Make sure a new file has correct permissions open(cookiefile, 'a').close() os.chmod(cookiefile, 0o600) self._cookiejar.save() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1593804280.0 python-bugzilla-3.0.2/bugzilla/_backendbase.py0000664000175000017500000002003700000000000021633 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. from logging import getLogger import requests log = getLogger(__name__) class _BackendBase(object): """ Backends are thin wrappers around the different bugzilla API paradigms (XMLRPC, REST). This base class defines the public API for the rest of the code, but this is all internal to the library. """ def __init__(self, url, bugzillasession): self._url = url self._bugzillasession = bugzillasession @staticmethod def probe(url): try: requests.head(url).raise_for_status() return True # pragma: no cover except Exception as e: log.debug("Failed to probe url=%s : %s", url, str(e)) return False ################# # Internal APIs # ################# def get_xmlrpc_proxy(self): """ Provides the raw XMLRPC proxy to API users of Bugzilla._proxy """ raise NotImplementedError() def is_rest(self): """ :returns: True if this is the REST backend """ return False def is_xmlrpc(self): """ :returns: True if this is the XMLRPC backend """ return False ###################### # Bugzilla info APIs # ###################### def bugzilla_version(self): """ Fetch bugzilla version string http://bugzilla.readthedocs.io/en/latest/api/core/v1/bugzilla.html#version """ raise NotImplementedError() ####################### # Bug attachment APIs # ####################### def bug_attachment_get(self, attachment_ids, paramdict): """ Fetch bug attachments IDs. One part of: http://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#get-attachment """ raise NotImplementedError() def bug_attachment_get_all(self, bug_ids, paramdict): """ Fetch all bug attachments IDs. One part of http://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#get-attachment """ raise NotImplementedError() def bug_attachment_create(self, bug_ids, data, paramdict): """ Create a bug attachment http://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#create-attachment :param data: raw Bytes data of the attachment to attach. API will encode this correctly if you pass it in and 'data' is not in paramdict. """ raise NotImplementedError() def bug_attachment_update(self, attachment_ids, paramdict): """ Update a bug attachment http://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#update-attachment """ raise NotImplementedError() ############ # bug APIs # ############ def bug_comments(self, bug_ids, paramdict): """ Fetch bug comments http://bugzilla.readthedocs.io/en/latest/api/core/v1/comment.html#get-comments """ raise NotImplementedError() def bug_create(self, paramdict): """ Create a new bug http://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#create-bug """ raise NotImplementedError() def bug_fields(self, paramdict): """ Query available bug field values http://bugzilla.readthedocs.io/en/latest/api/core/v1/field.html#fields """ raise NotImplementedError() def bug_get(self, bug_ids, aliases, paramdict): """ Lookup bug data by ID http://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#get-bug """ raise NotImplementedError() def bug_history(self, bug_ids, paramdict): """ Lookup bug history http://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#bug-history """ raise NotImplementedError() def bug_search(self, paramdict): """ Search/query bugs http://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#search-bugs """ raise NotImplementedError() def bug_update(self, bug_ids, paramdict): """ Update bugs http://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#update-bug """ raise NotImplementedError() def bug_update_tags(self, bug_ids, paramdict): """ Update bug tags https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/Bug.html#update_tags """ raise NotImplementedError() ################## # Component APIs # ################## def component_create(self, paramdict): """ Create component https://bugzilla.readthedocs.io/en/latest/api/core/v1/component.html#create-component """ raise NotImplementedError() def component_update(self, paramdict): """ Update component https://bugzilla.readthedocs.io/en/latest/api/core/v1/component.html#update-component """ raise NotImplementedError() ############################### # ExternalBugs extension APIs # ############################### def externalbugs_add(self, paramdict): """ https://bugzilla.redhat.com/docs/en/html/integrating/api/Bugzilla/Extension/ExternalBugs/WebService.html#add-external-bug """ raise NotImplementedError() def externalbugs_update(self, paramdict): """ https://bugzilla.redhat.com/docs/en/html/integrating/api/Bugzilla/Extension/ExternalBugs/WebService.html#update-external-bug """ raise NotImplementedError() def externalbugs_remove(self, paramdict): """ https://bugzilla.redhat.com/docs/en/html/integrating/api/Bugzilla/Extension/ExternalBugs/WebService.html#remove-external-bug """ raise NotImplementedError() ############## # Group APIs # ############## def group_get(self, paramdict): """ https://bugzilla.readthedocs.io/en/latest/api/core/v1/group.html#get-group """ raise NotImplementedError() ################ # Product APIs # ################ def product_get(self, paramdict): """ Fetch product details http://bugzilla.readthedocs.io/en/latest/api/core/v1/product.html#get-product """ raise NotImplementedError() def product_get_accessible(self): """ List accessible products http://bugzilla.readthedocs.io/en/latest/api/core/v1/product.html#list-products """ raise NotImplementedError() def product_get_enterable(self): """ List enterable products http://bugzilla.readthedocs.io/en/latest/api/core/v1/product.html#list-products """ raise NotImplementedError() def product_get_selectable(self): """ List selectable products http://bugzilla.readthedocs.io/en/latest/api/core/v1/product.html#list-products """ raise NotImplementedError() ############# # User APIs # ############# def user_create(self, paramdict): """ Create user http://bugzilla.readthedocs.io/en/latest/api/core/v1/user.html#create-user """ raise NotImplementedError() def user_get(self, paramdict): """ Get user info http://bugzilla.readthedocs.io/en/latest/api/core/v1/user.html#get-user """ raise NotImplementedError() def user_login(self, paramdict): """ Log in to bugzilla http://bugzilla.readthedocs.io/en/latest/api/core/v1/user.html#login """ raise NotImplementedError() def user_logout(self): """ Log out of bugzilla http://bugzilla.readthedocs.io/en/latest/api/core/v1/user.html#logout """ raise NotImplementedError() def user_update(self, paramdict): """ Update user http://bugzilla.readthedocs.io/en/latest/api/core/v1/user.html#update-user """ raise NotImplementedError() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605223204.0 python-bugzilla-3.0.2/bugzilla/_backendrest.py0000664000175000017500000001511700000000000021701 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import base64 import json import logging import os from ._backendbase import _BackendBase from .exceptions import BugzillaError from ._util import listify log = logging.getLogger(__name__) def _update_key(indict, updict, key): if key not in indict: indict[key] = {} indict[key].update(updict.get(key, {})) class _BackendREST(_BackendBase): """ Internal interface for direct calls to bugzilla's REST API """ def __init__(self, url, bugzillasession): _BackendBase.__init__(self, url, bugzillasession) self._bugzillasession.set_rest_defaults() ######################### # Internal REST helpers # ######################### def _handle_response(self, text): try: ret = dict(json.loads(text)) except Exception: log.debug("Failed to parse REST response. Output is:\n%s", text) raise if ret.get("error", False): raise BugzillaError(ret["message"], code=ret["code"]) return ret def _op(self, method, apiurl, paramdict=None): fullurl = os.path.join(self._url, apiurl.lstrip("/")) log.debug("Bugzilla REST %s %s params=%s", method, fullurl, paramdict) data = None params = None if method == "GET": params = paramdict else: data = json.dumps(paramdict or {}) response = self._bugzillasession.request(method, fullurl, data=data, params=params) return self._handle_response(response.text) def _get(self, *args, **kwargs): return self._op("GET", *args, **kwargs) def _put(self, *args, **kwargs): return self._op("PUT", *args, **kwargs) def _post(self, *args, **kwargs): return self._op("POST", *args, **kwargs) ####################### # API implementations # ####################### def get_xmlrpc_proxy(self): raise BugzillaError("You are using the bugzilla REST API, " "so raw XMLRPC access is not provided.") def is_rest(self): return True def bugzilla_version(self): return self._get("/version") def bug_create(self, paramdict): return self._post("/bug", paramdict) def bug_fields(self, paramdict): return self._get("/field/bug", paramdict) def bug_get(self, bug_ids, aliases, paramdict): data = paramdict.copy() data["id"] = listify(bug_ids) data["alias"] = listify(aliases) ret = self._get("/bug", data) return ret def bug_attachment_get(self, attachment_ids, paramdict): # XMLRPC supported mutiple fetch at once, but not REST ret = {} for attid in listify(attachment_ids): out = self._get("/bug/attachment/%s" % attid, paramdict) _update_key(ret, out, "attachments") _update_key(ret, out, "bugs") return ret def bug_attachment_get_all(self, bug_ids, paramdict): # XMLRPC supported mutiple fetch at once, but not REST ret = {} for bugid in listify(bug_ids): out = self._get("/bug/%s/attachment" % bugid, paramdict) _update_key(ret, out, "attachments") _update_key(ret, out, "bugs") return ret def bug_attachment_create(self, bug_ids, data, paramdict): if data is not None and "data" not in paramdict: paramdict["data"] = base64.b64encode(data).decode("utf-8") paramdict["ids"] = listify(bug_ids) return self._post("/bug/%s/attachment" % paramdict["ids"][0], paramdict) def bug_attachment_update(self, attachment_ids, paramdict): paramdict["ids"] = listify(attachment_ids) return self._put("/bug/attachment/%s" % paramdict["ids"][0], paramdict) def bug_comments(self, bug_ids, paramdict): # XMLRPC supported mutiple fetch at once, but not REST ret = {} for bugid in bug_ids: out = self._get("/bug/%s/comment" % bugid, paramdict) _update_key(ret, out, "bugs") return ret def bug_history(self, bug_ids, paramdict): # XMLRPC supported mutiple fetch at once, but not REST ret = {"bugs": []} for bugid in bug_ids: out = self._get("/bug/%s/history" % bugid, paramdict) ret["bugs"].extend(out.get("bugs", [])) return ret def bug_search(self, paramdict): return self._get("/bug", paramdict) def bug_update(self, bug_ids, paramdict): data = paramdict.copy() data["ids"] = listify(bug_ids) return self._put("/bug/%s" % data["ids"][0], data) def bug_update_tags(self, bug_ids, paramdict): raise BugzillaError("No REST API available for bug_update_tags") def component_create(self, paramdict): return self._post("/component", paramdict) def component_update(self, paramdict): if "ids" in paramdict: apiurl = str(listify(paramdict["ids"])[0]) if "names" in paramdict: apiurl = ("%(product)s/%(component)s" % listify(paramdict["names"])[0]) return self._put("/component/%s" % apiurl, paramdict) def externalbugs_add(self, paramdict): raise BugzillaError( "No REST API available yet for externalbugs_add") def externalbugs_remove(self, paramdict): raise BugzillaError( "No REST API available yet for externalbugs_remove") def externalbugs_update(self, paramdict): raise BugzillaError( "No REST API available yet for externalbugs_update") def group_get(self, paramdict): return self._get("/group", paramdict) def product_get(self, paramdict): return self._get("/product/get", paramdict) def product_get_accessible(self): return self._get("/product_accessible") def product_get_enterable(self): return self._get("/product_enterable") def product_get_selectable(self): return self._get("/product_selectable") def user_create(self, paramdict): return self._post("/user", paramdict) def user_get(self, paramdict): return self._get("/user", paramdict) def user_login(self, paramdict): return self._get("/login", paramdict) def user_logout(self): return self._get("/logout") def user_update(self, paramdict): urlid = None if "ids" in paramdict: urlid = listify(paramdict["ids"])[0] if "names" in paramdict: urlid = listify(paramdict["names"])[0] return self._put("/user/%s" % urlid, paramdict) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605227443.0 python-bugzilla-3.0.2/bugzilla/_backendxmlrpc.py0000664000175000017500000002071600000000000022232 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. from logging import getLogger import sys from xmlrpc.client import (Binary, Fault, ProtocolError, ServerProxy, Transport) from requests import RequestException from ._backendbase import _BackendBase from .exceptions import BugzillaError from ._util import listify log = getLogger(__name__) class _BugzillaXMLRPCTransport(Transport): def __init__(self, bugzillasession): if hasattr(Transport, "__init__"): Transport.__init__(self, use_datetime=False) self.__bugzillasession = bugzillasession self.__bugzillasession.set_xmlrpc_defaults() self.__seen_valid_xml = False # Override Transport.user_agent self.user_agent = self.__bugzillasession.get_user_agent() ############################ # Bugzilla private helpers # ############################ def __request_helper(self, url, request_body): """ A helper method to assist in making a request and parsing the response. """ response = None # pylint: disable=try-except-raise # pylint: disable=raise-missing-from try: response = self.__bugzillasession.request( "POST", url, data=request_body) return self.parse_response(response) except RequestException as e: if not response: raise raise ProtocolError( url, response.status_code, str(e), response.headers) except Fault: raise except Exception: msg = str(sys.exc_info()[1]) if not self.__seen_valid_xml: msg += "\nThe URL may not be an XMLRPC URL: %s" % url e = BugzillaError(msg) # pylint: disable=attribute-defined-outside-init e.__traceback__ = sys.exc_info()[2] # pylint: enable=attribute-defined-outside-init raise e ###################### # Tranport overrides # ###################### def parse_response(self, response): """ Override Transport.parse_response """ parser, unmarshaller = self.getparser() msg = response.text.encode('utf-8') try: parser.feed(msg) except Exception: log.debug("Failed to parse this XMLRPC response:\n%s", msg) raise self.__seen_valid_xml = True parser.close() return unmarshaller.close() def request(self, host, handler, request_body, verbose=0): """ Override Transport.request """ # Setting self.verbose here matches overrided request() behavior # pylint: disable=attribute-defined-outside-init self.verbose = verbose url = "%s://%s%s" % (self.__bugzillasession.get_scheme(), host, handler) # xmlrpclib fails to escape \r request_body = request_body.replace(b'\r', b' ') return self.__request_helper(url, request_body) class _BugzillaXMLRPCProxy(ServerProxy, object): """ Override of xmlrpc ServerProxy, to insert bugzilla API auth into the XMLRPC request data """ def __init__(self, uri, bugzillasession, *args, **kwargs): self.__bugzillasession = bugzillasession transport = _BugzillaXMLRPCTransport(self.__bugzillasession) ServerProxy.__init__(self, uri, transport, *args, **kwargs) def _ServerProxy__request(self, methodname, params): """ Overrides ServerProxy _request method """ # params is a singleton tuple, enforced by xmlrpc.client.dumps newparams = params and params[0].copy() or {} log.debug("XMLRPC call: %s(%s)", methodname, newparams) api_key = self.__bugzillasession.get_api_key() token_value = self.__bugzillasession.get_token_value() if api_key is not None: if 'Bugzilla_api_key' not in newparams: newparams['Bugzilla_api_key'] = api_key elif token_value is not None: if 'Bugzilla_token' not in newparams: newparams['Bugzilla_token'] = token_value # pylint: disable=no-member ret = ServerProxy._ServerProxy__request(self, methodname, (newparams,)) # pylint: enable=no-member if isinstance(ret, dict) and 'token' in ret.keys(): self.__bugzillasession.set_token_value(ret.get('token')) return ret class _BackendXMLRPC(_BackendBase): """ Internal interface for direct calls to bugzilla's XMLRPC API """ def __init__(self, url, bugzillasession): _BackendBase.__init__(self, url, bugzillasession) self._xmlrpc_proxy = _BugzillaXMLRPCProxy(url, self._bugzillasession) def get_xmlrpc_proxy(self): return self._xmlrpc_proxy def is_xmlrpc(self): return True def bugzilla_version(self): return self._xmlrpc_proxy.Bugzilla.version() def bug_attachment_get(self, attachment_ids, paramdict): data = paramdict.copy() data["attachment_ids"] = listify(attachment_ids) return self._xmlrpc_proxy.Bug.attachments(data) def bug_attachment_get_all(self, bug_ids, paramdict): data = paramdict.copy() data["ids"] = listify(bug_ids) return self._xmlrpc_proxy.Bug.attachments(data) def bug_attachment_create(self, bug_ids, data, paramdict): pdata = paramdict.copy() pdata["ids"] = listify(bug_ids) if data is not None and "data" not in paramdict: pdata["data"] = Binary(data) return self._xmlrpc_proxy.Bug.add_attachment(pdata) def bug_attachment_update(self, attachment_ids, paramdict): data = paramdict.copy() data["ids"] = listify(attachment_ids) return self._xmlrpc_proxy.Bug.update_attachment(data) def bug_comments(self, bug_ids, paramdict): data = paramdict.copy() data["ids"] = listify(bug_ids) return self._xmlrpc_proxy.Bug.comments(data) def bug_create(self, paramdict): return self._xmlrpc_proxy.Bug.create(paramdict) def bug_fields(self, paramdict): return self._xmlrpc_proxy.Bug.fields(paramdict) def bug_get(self, bug_ids, aliases, paramdict): data = paramdict.copy() data["ids"] = listify(bug_ids) or [] data["ids"] += listify(aliases) or [] return self._xmlrpc_proxy.Bug.get(data) def bug_history(self, bug_ids, paramdict): data = paramdict.copy() data["ids"] = listify(bug_ids) return self._xmlrpc_proxy.Bug.history(data) def bug_search(self, paramdict): return self._xmlrpc_proxy.Bug.search(paramdict) def bug_update(self, bug_ids, paramdict): data = paramdict.copy() data["ids"] = listify(bug_ids) return self._xmlrpc_proxy.Bug.update(data) def bug_update_tags(self, bug_ids, paramdict): data = paramdict.copy() data["ids"] = listify(bug_ids) return self._xmlrpc_proxy.Bug.update_tags(data) def component_create(self, paramdict): return self._xmlrpc_proxy.Component.create(paramdict) def component_update(self, paramdict): return self._xmlrpc_proxy.Component.update(paramdict) def externalbugs_add(self, paramdict): return self._xmlrpc_proxy.ExternalBugs.add_external_bug(paramdict) def externalbugs_update(self, paramdict): return self._xmlrpc_proxy.ExternalBugs.update_external_bug(paramdict) def externalbugs_remove(self, paramdict): return self._xmlrpc_proxy.ExternalBugs.remove_external_bug(paramdict) def group_get(self, paramdict): return self._xmlrpc_proxy.Group.get(paramdict) def product_get(self, paramdict): return self._xmlrpc_proxy.Product.get(paramdict) def product_get_accessible(self): return self._xmlrpc_proxy.Product.get_accessible_products() def product_get_enterable(self): return self._xmlrpc_proxy.Product.get_enterable_products() def product_get_selectable(self): return self._xmlrpc_proxy.Product.get_selectable_products() def user_create(self, paramdict): return self._xmlrpc_proxy.User.create(paramdict) def user_get(self, paramdict): return self._xmlrpc_proxy.User.get(paramdict) def user_login(self, paramdict): return self._xmlrpc_proxy.User.login(paramdict) def user_logout(self): return self._xmlrpc_proxy.User.logout() def user_update(self, paramdict): return self._xmlrpc_proxy.User.update(paramdict) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605227366.0 python-bugzilla-3.0.2/bugzilla/_cli.py0000775000175000017500000013367600000000000020201 0ustar00crobinsocrobinso#!/usr/bin/env python3 # # bugzilla - a commandline frontend for the python bugzilla module # # Copyright (C) 2007-2017 Red Hat Inc. # Author: Will Woods # Author: Cole Robinson # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import argparse import base64 import datetime import errno import json import locale from logging import getLogger, DEBUG, INFO, WARN, StreamHandler, Formatter import os import re import socket import sys import tempfile import urllib.parse import xmlrpc.client import requests.exceptions import bugzilla DEFAULT_BZ = 'https://bugzilla.redhat.com' format_field_re = re.compile("%{([a-z0-9_]+)(?::([^}]*))?}") log = getLogger(bugzilla.__name__) ################ # Util helpers # ################ def _is_unittest_debug(): return bool(os.getenv("__BUGZILLA_UNITTEST_DEBUG")) def open_without_clobber(name, *args): """ Try to open the given file with the given mode; if that filename exists, try "name.1", "name.2", etc. until we find an unused filename. """ fd = None count = 1 orig_name = name while fd is None: try: fd = os.open(name, os.O_CREAT | os.O_EXCL, 0o666) except OSError as err: if err.errno == errno.EEXIST: name = "%s.%i" % (orig_name, count) count += 1 else: # pragma: no cover raise IOError(err.errno, err.strerror, err.filename) from None fobj = open(name, *args) if fd != fobj.fileno(): os.close(fd) return fobj def setup_logging(debug, verbose): handler = StreamHandler(sys.stderr) handler.setFormatter(Formatter( "[%(asctime)s] %(levelname)s (%(module)s:%(lineno)d) %(message)s", "%H:%M:%S")) log.addHandler(handler) if debug: log.setLevel(DEBUG) elif verbose: log.setLevel(INFO) else: log.setLevel(WARN) if _is_unittest_debug(): log.setLevel(DEBUG) # pragma: no cover ################## # Option parsing # ################## def _setup_root_parser(): epilog = 'Try "bugzilla COMMAND --help" for command-specific help.' p = argparse.ArgumentParser(epilog=epilog) default_url = bugzilla.Bugzilla.get_rcfile_default_url() if not default_url: default_url = DEFAULT_BZ # General bugzilla connection options p.add_argument('--bugzilla', default=default_url, help="bugzilla URI. default: %s" % default_url) p.add_argument("--nosslverify", dest="sslverify", action="store_false", default=True, help="Don't error on invalid bugzilla SSL certificate") p.add_argument('--cert', help="client side certificate file needed by the webserver") p.add_argument('--login', action="store_true", help='Run interactive "login" before performing the ' 'specified command.') p.add_argument('--username', help="Log in with this username") p.add_argument('--password', help="Log in with this password") p.add_argument('--restrict-login', action="store_true", help="The session (login token) will be restricted to " "the current IP address.") p.add_argument('--ensure-logged-in', action="store_true", help="Raise an error if we aren't logged in to bugzilla. " "Consider using this if you are depending on " "cached credentials, to ensure that when they expire the " "tool errors, rather than subtly change output.") p.add_argument('--no-cache-credentials', action='store_false', default=True, dest='cache_credentials', help="Don't save any bugzilla cookies or tokens to disk, and " "don't use any pre-existing credentials.") p.add_argument('--cookiefile', default=None, help="cookie file to use for bugzilla authentication") p.add_argument('--tokenfile', default=None, help="token file to use for bugzilla authentication") p.add_argument('--verbose', action='store_true', help="give more info about what's going on") p.add_argument('--debug', action='store_true', help="output bunches of debugging info") p.add_argument('--version', action='version', version=bugzilla.__version__) # Allow user to specify BZClass to initialize. Kinda weird for the # CLI, I'd rather people file bugs about this so we can fix our detection. # So hide it from the help output but keep it for back compat p.add_argument('--bztype', default='auto', help=argparse.SUPPRESS) return p def _parser_add_output_options(p): outg = p.add_argument_group("Output format options") outg.add_argument('--full', action='store_const', dest='output', const='full', default='normal', help="output detailed bug info") outg.add_argument('-i', '--ids', action='store_const', dest='output', const='ids', help="output only bug IDs") outg.add_argument('-e', '--extra', action='store_const', dest='output', const='extra', help="output additional bug information " "(keywords, Whiteboards, etc.)") outg.add_argument('--oneline', action='store_const', dest='output', const='oneline', help="one line summary of the bug (useful for scripts)") outg.add_argument('--json', action='store_const', dest='output', const='json', help="output contents in json format") outg.add_argument("--includefield", action="append", help="Pass the field name to bugzilla include_fields list. " "Only the fields passed to include_fields are returned " "by the bugzilla server. " "This can be specified multiple times.") outg.add_argument("--extrafield", action="append", help="Pass the field name to bugzilla extra_fields list. " "When used with --json this can be used to request " "bugzilla to return values for non-default fields. " "This can be specified multiple times.") outg.add_argument("--excludefield", action="append", help="Pass the field name to bugzilla exclude_fields list. " "When used with --json this can be used to request " "bugzilla to not return values for a field. " "This can be specified multiple times.") outg.add_argument('--raw', action='store_const', dest='output', const='raw', help="raw output of the bugzilla contents. This " "format is unstable and difficult to parse. Use --json instead.") outg.add_argument('--outputformat', help="Print output in the form given. " "You can use RPM-style tags that match bug " "fields, e.g.: '%%{id}: %%{summary}'. See the man page " "section 'Output options' for more details.") def _parser_add_bz_fields(rootp, command): cmd_new = (command == "new") cmd_query = (command == "query") cmd_modify = (command == "modify") if cmd_new: comment_help = "Set initial bug comment/description" elif cmd_query: comment_help = "Search all bug comments" else: comment_help = "Add new bug comment" p = rootp.add_argument_group("Standard bugzilla options") p.add_argument('-p', '--product', help="Product name") p.add_argument('-v', '--version', help="Product version") p.add_argument('-c', '--component', help="Component name") p.add_argument('-t', '--summary', '--short_desc', help="Bug summary") p.add_argument('-l', '--comment', '--long_desc', help=comment_help) if not cmd_query: p.add_argument("--comment-tag", action="append", help="Comment tag for the new comment") p.add_argument("--sub-component", action="append", help="RHBZ sub component field") p.add_argument('-o', '--os', help="Operating system") p.add_argument('--arch', help="Arch this bug occurs on") p.add_argument('-x', '--severity', help="Bug severity") p.add_argument('-z', '--priority', help="Bug priority") p.add_argument('--alias', help='Bug alias (name)') p.add_argument('-s', '--status', '--bug_status', help='Bug status (NEW, ASSIGNED, etc.)') p.add_argument('-u', '--url', help="URL field") p.add_argument('-m', '--target_milestone', help="Target milestone") p.add_argument('--target_release', help="RHBZ Target release") p.add_argument('--blocked', action="append", help="Bug IDs that this bug blocks") p.add_argument('--dependson', action="append", help="Bug IDs that this bug depends on") p.add_argument('--keywords', action="append", help="Bug keywords") p.add_argument('--groups', action="append", help="Which user groups can view this bug") p.add_argument('--cc', action="append", help="CC list") p.add_argument('-a', '--assigned_to', '--assignee', help="Bug assignee") p.add_argument('-q', '--qa_contact', help='QA contact') if cmd_modify: p.add_argument("--minor-update", action="store_true", help="Request bugzilla to not send any " "email about this change") if not cmd_new: p.add_argument('-f', '--flag', action='append', help="Bug flags state. Ex:\n" " --flag needinfo?\n" " --flag dev_ack+ \n" " clear with --flag needinfoX") p.add_argument("--tags", action="append", help="Tags/Personal Tags field.") p.add_argument('-w', "--whiteboard", '--status_whiteboard', action="append", help='Whiteboard field') p.add_argument("--devel_whiteboard", action="append", help='RHBZ devel whiteboard field') p.add_argument("--internal_whiteboard", action="append", help='RHBZ internal whiteboard field') p.add_argument("--qa_whiteboard", action="append", help='RHBZ QA whiteboard field') p.add_argument('-F', '--fixed_in', help="RHBZ 'Fixed in version' field") # Put this at the end, so it sticks out more p.add_argument('--field', metavar="FIELD=VALUE", action="append", dest="fields", help="Manually specify a bugzilla API field. FIELD is " "the raw name used by the bugzilla instance. For example, if your " "bugzilla instance has a custom field cf_my_field, do:\n" " --field cf_my_field=VALUE") if not cmd_modify: _parser_add_output_options(rootp) def _setup_action_new_parser(subparsers): description = ("Create a new bug report. " "--product, --component, --version, --summary, and --comment " "must be specified. " "Options that take multiple values accept comma separated lists, " "including --cc, --blocks, --dependson, --groups, and --keywords.") p = subparsers.add_parser("new", description=description) _parser_add_bz_fields(p, "new") g = p.add_argument_group("'new' specific options") g.add_argument('--private', action='store_true', default=False, help='Mark new comment as private') def _setup_action_query_parser(subparsers): description = ("List bug reports that match the given criteria. " "Certain options can accept a comma separated list to query multiple " "values, including --status, --component, --product, --version, --id.") epilog = ("Note: querying via explicit command line options will only " "get you so far. See the --from-url option for a way to use powerful " "Web UI queries from the command line.") p = subparsers.add_parser("query", description=description, epilog=epilog) _parser_add_bz_fields(p, "query") g = p.add_argument_group("'query' specific options") g.add_argument('-b', '--id', '--bug_id', help="specify individual bugs by IDs, separated with commas") g.add_argument('-r', '--reporter', help="Email: search reporter email for given address") g.add_argument('--quicksearch', help="Search using bugzilla's quicksearch functionality.") g.add_argument('--savedsearch', help="Name of a bugzilla saved search. If you don't own this " "saved search, you must passed --savedsearch_sharer_id.") g.add_argument('--savedsearch-sharer-id', help="Owner ID of the --savedsearch. You can get this ID from " "the URL bugzilla generates when running the saved search " "from the web UI.") # Keep this at the end so it sticks out more g.add_argument('--from-url', metavar="WEB_QUERY_URL", help="Make a working query via bugzilla's 'Advanced search' web UI, " "grab the url from your browser (the string with query.cgi or " "buglist.cgi in it), and --from-url will run it via the " "bugzilla API. Don't forget to quote the string! " "This only works for Bugzilla 5 and Red Hat bugzilla") # Deprecated options p.add_argument('-E', '--emailtype', help=argparse.SUPPRESS) p.add_argument('--components_file', help=argparse.SUPPRESS) p.add_argument('-U', '--url_type', help=argparse.SUPPRESS) p.add_argument('-K', '--keywords_type', help=argparse.SUPPRESS) p.add_argument('-W', '--status_whiteboard_type', help=argparse.SUPPRESS) p.add_argument('--fixed_in_type', help=argparse.SUPPRESS) def _setup_action_info_parser(subparsers): description = ("List products or component information about the " "bugzilla server.") p = subparsers.add_parser("info", description=description) x = p.add_mutually_exclusive_group(required=True) x.add_argument('-p', '--products', action='store_true', help='Get a list of products') x.add_argument('-c', '--components', metavar="PRODUCT", help='List the components in the given product') x.add_argument('-o', '--component_owners', metavar="PRODUCT", help='List components (and their owners)') x.add_argument('-v', '--versions', metavar="PRODUCT", help='List the versions for the given product') p.add_argument('--active-components', action="store_true", help='Only show active components. Combine with --components*') def _setup_action_modify_parser(subparsers): usage = ("bugzilla modify [options] BUGID [BUGID...]\n" "Fields that take multiple values have a special input format.\n" "Append: --cc=foo@example.com\n" "Overwrite: --cc==foo@example.com\n" "Remove: --cc=-foo@example.com\n" "Options that accept this format: --cc, --blocked, --dependson,\n" " --groups, --tags, whiteboard fields.") p = subparsers.add_parser("modify", usage=usage) _parser_add_bz_fields(p, "modify") g = p.add_argument_group("'modify' specific options") g.add_argument("ids", nargs="+", help="Bug IDs to modify") g.add_argument('-k', '--close', metavar="RESOLUTION", help='Close with the given resolution (WONTFIX, NOTABUG, etc.)') g.add_argument('-d', '--dupeid', metavar="ORIGINAL", help='ID of original bug. Implies --close DUPLICATE') g.add_argument('--private', action='store_true', default=False, help='Mark new comment as private') g.add_argument('--reset-assignee', action="store_true", help='Reset assignee to component default') g.add_argument('--reset-qa-contact', action="store_true", help='Reset QA contact to component default') def _setup_action_attach_parser(subparsers): usage = """ bugzilla attach --file=FILE --desc=DESC [--type=TYPE] BUGID [BUGID...] bugzilla attach --get=ATTACHID --getall=BUGID [--ignore-obsolete] [...] bugzilla attach --type=TYPE BUGID [BUGID...]""" description = "Attach files or download attachments." p = subparsers.add_parser("attach", description=description, usage=usage) p.add_argument("ids", nargs="*", help="BUGID references") p.add_argument('-f', '--file', metavar="FILENAME", help='File to attach, or filename for data provided on stdin') p.add_argument('-d', '--description', '--summary', metavar="SUMMARY", dest='desc', help="A short summary of the file being attached") p.add_argument('-t', '--type', metavar="MIMETYPE", help="Mime-type for the file being attached") p.add_argument('-g', '--get', metavar="ATTACHID", action="append", default=[], help="Download the attachment with the given ID") p.add_argument("--getall", "--get-all", metavar="BUGID", action="append", default=[], help="Download all attachments on the given bug") p.add_argument('--ignore-obsolete', action="store_true", help='Do not download attachments marked as obsolete.') p.add_argument('-l', '--comment', '--long_desc', help="Add comment with attachment") p.add_argument('--private', action='store_true', default=False, help='Mark new comment as private') def _setup_action_login_parser(subparsers): usage = 'bugzilla login [--api-key] [username [password]]' description = """Log into bugzilla and save a login cookie or token. Note: These tokens are short-lived, and future Bugzilla versions will no longer support token authentication at all. Please use a ~/.config/python-bugzilla/bugzillarc file with an API key instead, or use 'bugzilla login --api-key' and we will save it for you.""" p = subparsers.add_parser("login", description=description, usage=usage) p.add_argument('--api-key', action='store_true', default=False, help='Prompt for and save an API key into bugzillarc, ' 'rather than prompt for username and password.') p.add_argument("pos_username", nargs="?", help="Optional username ", metavar="username") p.add_argument("pos_password", nargs="?", help="Optional password ", metavar="password") def setup_parser(): rootparser = _setup_root_parser() subparsers = rootparser.add_subparsers(dest="command") subparsers.required = True _setup_action_new_parser(subparsers) _setup_action_query_parser(subparsers) _setup_action_info_parser(subparsers) _setup_action_modify_parser(subparsers) _setup_action_attach_parser(subparsers) _setup_action_login_parser(subparsers) return rootparser #################### # Command routines # #################### def _merge_field_opts(query, fields, parser): # Add any custom fields if specified for f in fields: try: f, v = f.split('=', 1) query[f] = v except Exception: parser.error("Invalid field argument provided: %s" % (f)) def _do_query(bz, opt, parser): q = {} # Parse preconstructed queries. u = opt.from_url if u: q = bz.url_to_query(u) if opt.components_file: # Components slurped in from file (one component per line) # This can be made more robust clist = [] f = open(opt.components_file, 'r') for line in f.readlines(): line = line.rstrip("\n") clist.append(line) opt.component = clist if opt.status: val = opt.status stat = val if val == 'ALL': # leaving this out should return bugs of any status stat = None elif val == 'DEV': # Alias for all development bug statuses stat = ['NEW', 'ASSIGNED', 'NEEDINFO', 'ON_DEV', 'MODIFIED', 'POST', 'REOPENED'] elif val == 'QE': # Alias for all QE relevant bug statuses stat = ['ASSIGNED', 'ON_QA', 'FAILS_QA', 'PASSES_QA'] elif val == 'EOL': # Alias for EndOfLife bug statuses stat = ['VERIFIED', 'RELEASE_PENDING', 'CLOSED'] elif val == 'OPEN': # non-Closed statuses stat = ['NEW', 'ASSIGNED', 'MODIFIED', 'ON_DEV', 'ON_QA', 'VERIFIED', 'RELEASE_PENDING', 'POST'] opt.status = stat # Convert all comma separated list parameters to actual lists, # which is what bugzilla wants # According to bugzilla docs, any parameter can be a list, but # let's only do this for options we explicitly mention can be # comma separated. for optname in ["severity", "id", "status", "component", "priority", "product", "version"]: val = getattr(opt, optname, None) if not isinstance(val, str): continue setattr(opt, optname, val.split(",")) include_fields = None if opt.output in ['raw', 'json']: # 'raw' always does a getbug() call anyways, so just ask for ID back include_fields = ['id'] elif opt.outputformat: include_fields = [] for fieldname, rest in format_field_re.findall(opt.outputformat): if fieldname == "whiteboard" and rest: fieldname = rest + "_" + fieldname elif fieldname == "flag": fieldname = "flags" elif fieldname == "cve": fieldname = ["keywords", "blocks"] elif fieldname == "__unicode__": # Needs to be in sync with bug.__unicode__ fieldname = ["id", "status", "assigned_to", "summary"] flist = isinstance(fieldname, list) and fieldname or [fieldname] for f in flist: if f not in include_fields: include_fields.append(f) if include_fields is not None: include_fields.sort() kwopts = {} if opt.product: kwopts["product"] = opt.product if opt.component: kwopts["component"] = opt.component if opt.sub_component: kwopts["sub_component"] = opt.sub_component if opt.version: kwopts["version"] = opt.version if opt.reporter: kwopts["reporter"] = opt.reporter if opt.id: kwopts["bug_id"] = opt.id if opt.summary: kwopts["short_desc"] = opt.summary if opt.comment: kwopts["long_desc"] = opt.comment if opt.cc: kwopts["cc"] = opt.cc if opt.assigned_to: kwopts["assigned_to"] = opt.assigned_to if opt.qa_contact: kwopts["qa_contact"] = opt.qa_contact if opt.status: kwopts["status"] = opt.status if opt.blocked: kwopts["blocked"] = opt.blocked if opt.dependson: kwopts["dependson"] = opt.dependson if opt.keywords: kwopts["keywords"] = opt.keywords if opt.keywords_type: kwopts["keywords_type"] = opt.keywords_type if opt.url: kwopts["url"] = opt.url if opt.url_type: kwopts["url_type"] = opt.url_type if opt.whiteboard: kwopts["status_whiteboard"] = opt.whiteboard if opt.status_whiteboard_type: kwopts["status_whiteboard_type"] = opt.status_whiteboard_type if opt.fixed_in: kwopts["fixed_in"] = opt.fixed_in if opt.fixed_in_type: kwopts["fixed_in_type"] = opt.fixed_in_type if opt.flag: kwopts["flag"] = opt.flag if opt.alias: kwopts["alias"] = opt.alias if opt.qa_whiteboard: kwopts["qa_whiteboard"] = opt.qa_whiteboard if opt.devel_whiteboard: kwopts["devel_whiteboard"] = opt.devel_whiteboard if opt.severity: kwopts["bug_severity"] = opt.severity if opt.priority: kwopts["priority"] = opt.priority if opt.target_release: kwopts["target_release"] = opt.target_release if opt.target_milestone: kwopts["target_milestone"] = opt.target_milestone if opt.emailtype: kwopts["emailtype"] = opt.emailtype if include_fields: kwopts["include_fields"] = include_fields if opt.quicksearch: kwopts["quicksearch"] = opt.quicksearch if opt.savedsearch: kwopts["savedsearch"] = opt.savedsearch if opt.savedsearch_sharer_id: kwopts["savedsearch_sharer_id"] = opt.savedsearch_sharer_id if opt.tags: kwopts["tags"] = opt.tags built_query = bz.build_query(**kwopts) if opt.fields: _merge_field_opts(built_query, opt.fields, parser) built_query.update(q) q = built_query if not q: # pragma: no cover parser.error("'query' command requires additional arguments") return bz.query(q) def _do_info(bz, opt): """ Handle the 'info' subcommand """ # All these commands call getproducts internally, so do it up front # with minimal include_fields for speed def _filter_components(compdetails): ret = {} for k, v in compdetails.items(): if v.get("is_active", True): ret[k] = v return ret productname = (opt.components or opt.component_owners or opt.versions) fastcomponents = (opt.components and not opt.active_components) include_fields = ["name", "id"] if opt.components or opt.component_owners: include_fields += ["components.name"] if opt.component_owners: include_fields += ["components.default_assigned_to"] if opt.active_components: include_fields += ["components.is_active"] if opt.versions: include_fields += ["versions"] bz.refresh_products(names=productname and [productname] or None, include_fields=include_fields) if opt.products: for name in sorted([p["name"] for p in bz.getproducts()]): print(name) elif fastcomponents: for name in sorted(bz.getcomponents(productname)): print(name) elif opt.components: details = bz.getcomponentsdetails(productname) for name in sorted(_filter_components(details)): print(name) elif opt.versions: proddict = bz.getproducts()[0] for v in proddict['versions']: print(str(v["name"] or '')) elif opt.component_owners: details = bz.getcomponentsdetails(productname) for c in sorted(_filter_components(details)): print(u"%s: %s" % (c, details[c]['default_assigned_to'])) def _convert_to_outputformat(output): fmt = "" if output == "normal": fmt = "%{__unicode__}" elif output == "ids": fmt = "%{id}" elif output == 'full': fmt += "%{__unicode__}\n" fmt += "Component: %{component}\n" fmt += "CC: %{cc}\n" fmt += "Blocked: %{blocks}\n" fmt += "Depends: %{depends_on}\n" fmt += "%{comments}\n" elif output == 'extra': fmt += "%{__unicode__}\n" fmt += " +Keywords: %{keywords}\n" fmt += " +QA Whiteboard: %{qa_whiteboard}\n" fmt += " +Status Whiteboard: %{status_whiteboard}\n" fmt += " +Devel Whiteboard: %{devel_whiteboard}\n" elif output == 'oneline': fmt += "#%{bug_id} %{status} %{assigned_to} %{component}\t" fmt += "[%{target_milestone}] %{flags} %{cve}" else: # pragma: no cover raise RuntimeError("Unknown output type '%s'" % output) return fmt def _xmlrpc_converter(obj): if "DateTime" in str(obj.__class__): # xmlrpc DateTime object. Convert to date format that # bugzilla REST API outputs dobj = datetime.datetime.strptime(str(obj), '%Y%m%dT%H:%M:%S') return dobj.isoformat() + "Z" if "Binary" in str(obj.__class__): # xmlrpc Binary object. Convert to base64 return base64.b64encode(obj.data).decode("utf-8") raise RuntimeError( "Unexpected JSON conversion class=%s" % obj.__class__) def _format_output_json(buglist): out = {"bugs": [b.get_raw_data() for b in buglist]} s = json.dumps(out, default=_xmlrpc_converter, indent=2, sort_keys=True) print(s) def _format_output_raw(buglist): for b in buglist: print("Bugzilla %s: " % b.bug_id) SKIP_NAMES = ["bugzilla"] for attrname in sorted(b.__dict__): if attrname in SKIP_NAMES: continue if attrname.startswith("_"): continue print("ATTRIBUTE[%s]: %s" % (attrname, b.__dict__[attrname])) print("\n\n") def _bug_field_repl_cb(bz, b, matchobj): # whiteboard and flag allow doing # %{whiteboard:devel} and %{flag:needinfo} # That's what 'rest' matches (fieldname, rest) = matchobj.groups() if fieldname == "whiteboard" and rest: fieldname = rest + "_" + fieldname if fieldname == "flag" and rest: val = b.get_flag_status(rest) elif fieldname in ["flags", "flags_requestee"]: tmpstr = [] for f in getattr(b, "flags", []): requestee = f.get('requestee', "") if fieldname == "flags": requestee = "" if fieldname == "flags_requestee": if requestee == "": continue tmpstr.append("%s" % requestee) else: tmpstr.append("%s%s%s" % (f['name'], f['status'], requestee)) val = ",".join(tmpstr) elif fieldname == "cve": cves = [] for key in getattr(b, "keywords", []): # grab CVE from keywords and blockers if key.find("Security") == -1: continue for bl in b.blocks: cvebug = bz.getbug(bl) for cb in cvebug.alias: if (cb.find("CVE") != -1 and cb.strip() not in cves): cves.append(cb) val = ",".join(cves) elif fieldname == "comments": val = "" for c in getattr(b, "comments", []): val += ("\n* %s - %s:\n%s\n" % (c['time'], c.get("creator", c.get("author", "")), c['text'])) elif fieldname == "external_bugs": val = "" for e in getattr(b, "external_bugs", []): url = e["type"]["full_url"].replace("%id%", e["ext_bz_bug_id"]) if not val: val += "\n" val += "External bug: %s\n" % url elif fieldname == "__unicode__": val = b.__unicode__() else: val = getattr(b, fieldname, "") vallist = isinstance(val, list) and val or [val] val = ','.join([str(v or '') for v in vallist]) return val def _format_output(bz, opt, buglist): if opt.output in ['raw', 'json']: include_fields = None exclude_fields = None extra_fields = None if opt.includefield: include_fields = opt.includefield if opt.excludefield: exclude_fields = opt.excludefield if opt.extrafield: extra_fields = opt.extrafield buglist = bz.getbugs([b.bug_id for b in buglist], include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields) if opt.output == 'json': _format_output_json(buglist) if opt.output == 'raw': _format_output_raw(buglist) return for b in buglist: # pylint: disable=cell-var-from-loop def cb(matchobj): return _bug_field_repl_cb(bz, b, matchobj) print(format_field_re.sub(cb, opt.outputformat)) def _parse_triset(vallist, checkplus=True, checkminus=True, checkequal=True, splitcomma=False): add_val = [] rm_val = [] set_val = None def make_list(v): if not v: return [] if splitcomma: return v.split(",") return [v] for val in isinstance(vallist, list) and vallist or [vallist]: val = val or "" if val.startswith("+") and checkplus: add_val += make_list(val[1:]) elif val.startswith("-") and checkminus: rm_val += make_list(val[1:]) elif val.startswith("=") and checkequal: # Intentionally overwrite this set_val = make_list(val[1:]) else: add_val += make_list(val) return add_val, rm_val, set_val def _do_new(bz, opt, parser): # Parse options that accept comma separated list def parse_multi(val): return _parse_triset(val, checkplus=False, checkminus=False, checkequal=False, splitcomma=True)[0] kwopts = {} if opt.blocked: kwopts["blocks"] = parse_multi(opt.blocked) if opt.cc: kwopts["cc"] = parse_multi(opt.cc) if opt.component: kwopts["component"] = opt.component if opt.dependson: kwopts["depends_on"] = parse_multi(opt.dependson) if opt.comment: kwopts["description"] = opt.comment if opt.groups: kwopts["groups"] = parse_multi(opt.groups) if opt.keywords: kwopts["keywords"] = parse_multi(opt.keywords) if opt.os: kwopts["op_sys"] = opt.os if opt.arch: kwopts["platform"] = opt.arch if opt.priority: kwopts["priority"] = opt.priority if opt.product: kwopts["product"] = opt.product if opt.severity: kwopts["severity"] = opt.severity if opt.summary: kwopts["summary"] = opt.summary if opt.url: kwopts["url"] = opt.url if opt.version: kwopts["version"] = opt.version if opt.assigned_to: kwopts["assigned_to"] = opt.assigned_to if opt.qa_contact: kwopts["qa_contact"] = opt.qa_contact if opt.sub_component: kwopts["sub_component"] = opt.sub_component if opt.alias: kwopts["alias"] = opt.alias if opt.comment_tag: kwopts["comment_tags"] = opt.comment_tag if opt.private: kwopts["comment_private"] = opt.private ret = bz.build_createbug(**kwopts) if opt.fields: _merge_field_opts(ret, opt.fields, parser) b = bz.createbug(ret) b.refresh() return [b] def _do_modify(bz, parser, opt): bugid_list = [bugid for a in opt.ids for bugid in a.split(',')] add_wb, rm_wb, set_wb = _parse_triset(opt.whiteboard) add_devwb, rm_devwb, set_devwb = _parse_triset(opt.devel_whiteboard) add_intwb, rm_intwb, set_intwb = _parse_triset(opt.internal_whiteboard) add_qawb, rm_qawb, set_qawb = _parse_triset(opt.qa_whiteboard) add_blk, rm_blk, set_blk = _parse_triset(opt.blocked, splitcomma=True) add_deps, rm_deps, set_deps = _parse_triset(opt.dependson, splitcomma=True) add_key, rm_key, set_key = _parse_triset(opt.keywords) add_cc, rm_cc, ignore = _parse_triset(opt.cc, checkplus=False, checkequal=False) add_groups, rm_groups, ignore = _parse_triset(opt.groups, checkequal=False, splitcomma=True) add_tags, rm_tags, ignore = _parse_triset(opt.tags, checkequal=False) status = opt.status or None if opt.dupeid is not None: opt.close = "DUPLICATE" if opt.close: status = "CLOSED" flags = [] if opt.flag: # Convert "foo+" to tuple ("foo", "+") for f in opt.flag: flags.append({"name": f[:-1], "status": f[-1]}) update_opts = {} if opt.assigned_to: update_opts["assigned_to"] = opt.assigned_to if opt.comment: update_opts["comment"] = opt.comment if opt.private: update_opts["comment_private"] = opt.private if opt.component: update_opts["component"] = opt.component if opt.product: update_opts["product"] = opt.product if add_blk: update_opts["blocks_add"] = add_blk if rm_blk: update_opts["blocks_remove"] = rm_blk if set_blk is not None: update_opts["blocks_set"] = set_blk if opt.url: update_opts["url"] = opt.url if add_cc: update_opts["cc_add"] = add_cc if rm_cc: update_opts["cc_remove"] = rm_cc if add_deps: update_opts["depends_on_add"] = add_deps if rm_deps: update_opts["depends_on_remove"] = rm_deps if set_deps is not None: update_opts["depends_on_set"] = set_deps if add_groups: update_opts["groups_add"] = add_groups if rm_groups: update_opts["groups_remove"] = rm_groups if add_key: update_opts["keywords_add"] = add_key if rm_key: update_opts["keywords_remove"] = rm_key if set_key is not None: update_opts["keywords_set"] = set_key if opt.os: update_opts["op_sys"] = opt.os if opt.arch: update_opts["platform"] = opt.arch if opt.priority: update_opts["priority"] = opt.priority if opt.qa_contact: update_opts["qa_contact"] = opt.qa_contact if opt.severity: update_opts["severity"] = opt.severity if status: update_opts["status"] = status if opt.summary: update_opts["summary"] = opt.summary if opt.version: update_opts["version"] = opt.version if opt.reset_assignee: update_opts["reset_assigned_to"] = opt.reset_assignee if opt.reset_qa_contact: update_opts["reset_qa_contact"] = opt.reset_qa_contact if opt.close: update_opts["resolution"] = opt.close if opt.target_release: update_opts["target_release"] = opt.target_release if opt.target_milestone: update_opts["target_milestone"] = opt.target_milestone if opt.dupeid: update_opts["dupe_of"] = opt.dupeid if opt.fixed_in: update_opts["fixed_in"] = opt.fixed_in if set_wb and set_wb[0]: update_opts["whiteboard"] = set_wb and set_wb[0] if set_devwb and set_devwb[0]: update_opts["devel_whiteboard"] = set_devwb and set_devwb[0] if set_intwb and set_intwb[0]: update_opts["internal_whiteboard"] = set_intwb and set_intwb[0] if set_qawb and set_qawb[0]: update_opts["qa_whiteboard"] = set_qawb and set_qawb[0] if opt.sub_component: update_opts["sub_component"] = opt.sub_component if opt.alias: update_opts["alias"] = opt.alias if flags: update_opts["flags"] = flags if opt.comment_tag: update_opts["comment_tags"] = opt.comment_tag if opt.minor_update: update_opts["minor_update"] = opt.minor_update update = bz.build_update(**update_opts) # We make this a little convoluted to facilitate unit testing wbmap = { "whiteboard": (add_wb, rm_wb), "internal_whiteboard": (add_intwb, rm_intwb), "qa_whiteboard": (add_qawb, rm_qawb), "devel_whiteboard": (add_devwb, rm_devwb), } for k, v in wbmap.copy().items(): if not v[0] and not v[1]: del(wbmap[k]) if opt.fields: _merge_field_opts(update, opt.fields, parser) log.debug("update bug dict=%s", update) log.debug("update whiteboard dict=%s", wbmap) if not any([update, wbmap, add_tags, rm_tags]): parser.error("'modify' command requires additional arguments") if add_tags or rm_tags: ret = bz.update_tags(bugid_list, tags_add=add_tags, tags_remove=rm_tags) log.debug("bz.update_tags returned=%s", ret) if update: ret = bz.update_bugs(bugid_list, update) log.debug("bz.update_bugs returned=%s", ret) if not wbmap: return # Now for the things we can't blindly batch. # Being able to prepend/append to whiteboards, which are just # plain string values, is an old rhbz semantic that we try to maintain # here. This is a bit weird for traditional bugzilla API log.debug("Adjusting whiteboard fields one by one") for bug in bz.getbugs(bugid_list): update_kwargs = {} for wbkey, (add_list, rm_list) in wbmap.items(): bugval = getattr(bug, wbkey) or "" for tag in add_list: if bugval: bugval += " " bugval += tag for tag in rm_list: bugsplit = bugval.split() for t in bugsplit[:]: if t == tag: bugsplit.remove(t) bugval = " ".join(bugsplit) update_kwargs[wbkey] = bugval bz.update_bugs([bug.id], bz.build_update(**update_kwargs)) def _do_get_attach(bz, opt): data = {} def _process_attachment_data(_attlist): for _att in _attlist: data[_att["id"]] = _att if opt.getall: for attlist in bz.get_attachments(opt.getall, None)["bugs"].values(): _process_attachment_data(attlist) if opt.get: _process_attachment_data( bz.get_attachments(None, opt.get)["attachments"].values()) for attdata in data.values(): is_obsolete = attdata.get("is_obsolete", None) == 1 if opt.ignore_obsolete and is_obsolete: continue att = bz.openattachment_data(attdata) outfile = open_without_clobber(att.name, "wb") data = att.read(4096) while data: outfile.write(data) data = att.read(4096) print("Wrote %s" % outfile.name) def _do_set_attach(bz, opt, parser): if not opt.ids: parser.error("Bug ID must be specified for setting attachments") if sys.stdin.isatty(): if not opt.file: parser.error("--file must be specified") fileobj = open(opt.file, "rb") else: # piped input on stdin if not opt.desc: parser.error("--description must be specified if passing " "file on stdin") fileobj = tempfile.NamedTemporaryFile(prefix="bugzilla-attach.") data = sys.stdin.read(4096) while data: fileobj.write(data.encode(locale.getpreferredencoding())) data = sys.stdin.read(4096) fileobj.seek(0) kwargs = {} if opt.file: kwargs["filename"] = os.path.basename(opt.file) if opt.type: kwargs["contenttype"] = opt.type if opt.type in ["text/x-patch"]: kwargs["ispatch"] = True if opt.comment: kwargs["comment"] = opt.comment if opt.private: kwargs["is_private"] = True desc = opt.desc or os.path.basename(fileobj.name) # Upload attachments for bugid in opt.ids: attid = bz.attachfile(bugid, fileobj, desc, **kwargs) print("Created attachment %i on bug %s" % (attid, bugid)) ################# # Main handling # ################# def _make_bz_instance(opt): """ Build the Bugzilla instance we will use """ if opt.bztype != 'auto': log.info("Explicit --bztype is no longer supported, ignoring") cookiefile = None tokenfile = None use_creds = False if opt.cache_credentials: cookiefile = opt.cookiefile or -1 tokenfile = opt.tokenfile or -1 use_creds = True return bugzilla.Bugzilla( url=opt.bugzilla, cookiefile=cookiefile, tokenfile=tokenfile, sslverify=opt.sslverify, use_creds=use_creds, cert=opt.cert) def _handle_login(opt, action, bz): """ Handle all login related bits """ is_login_command = (action == 'login') do_interactive_login = (is_login_command or opt.login or opt.username or opt.password) username = getattr(opt, "pos_username", None) or opt.username password = getattr(opt, "pos_password", None) or opt.password use_key = getattr(opt, "api_key", False) try: if use_key: bz.interactive_save_api_key() elif do_interactive_login: if bz.api_key: print("You already have an API key configured for %s" % bz.url) print("There is no need to cache a login token. Exiting.") sys.exit(0) print("Logging into %s" % urllib.parse.urlparse(bz.url)[1]) bz.interactive_login(username, password, restrict_login=opt.restrict_login) except bugzilla.BugzillaError as e: print(str(e)) sys.exit(1) if opt.ensure_logged_in and not bz.logged_in: print("--ensure-logged-in passed but you aren't logged in to %s" % bz.url) sys.exit(1) if is_login_command: sys.exit(0) def _main(unittest_bz_instance): parser = setup_parser() opt = parser.parse_args() action = opt.command setup_logging(opt.debug, opt.verbose) log.debug("Launched with command line: %s", " ".join(sys.argv)) log.debug("Bugzilla module: %s", bugzilla) if unittest_bz_instance: bz = unittest_bz_instance else: bz = _make_bz_instance(opt) # Handle login options _handle_login(opt, action, bz) ########################### # Run the actual commands # ########################### if hasattr(opt, "outputformat"): if not opt.outputformat and opt.output not in ['raw', 'json', None]: opt.outputformat = _convert_to_outputformat(opt.output) buglist = [] if action == 'info': _do_info(bz, opt) elif action == 'query': buglist = _do_query(bz, opt, parser) elif action == 'new': buglist = _do_new(bz, opt, parser) elif action == 'attach': if opt.get or opt.getall: if opt.ids: parser.error("Bug IDs '%s' not used for " "getting attachments" % opt.ids) _do_get_attach(bz, opt) else: _do_set_attach(bz, opt, parser) elif action == 'modify': _do_modify(bz, parser, opt) else: # pragma: no cover raise RuntimeError("Unexpected action '%s'" % action) # If we're doing new/query/modify, output our results if action in ['new', 'query']: _format_output(bz, opt, buglist) def main(unittest_bz_instance=None): try: try: return _main(unittest_bz_instance) except (Exception, KeyboardInterrupt): log.debug("", exc_info=True) raise except KeyboardInterrupt: print("\nExited at user request.") sys.exit(1) except (xmlrpc.client.Fault, bugzilla.BugzillaError) as e: print("\nServer error: %s" % str(e)) sys.exit(3) except requests.exceptions.SSLError as e: # Give SSL recommendations print("SSL error: %s" % e) print("\nIf you trust the remote server, you can work " "around this error with:\n" " bugzilla --nosslverify ...") sys.exit(4) except (socket.error, requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.InvalidURL, xmlrpc.client.ProtocolError) as e: print("\nConnection lost/failed: %s" % str(e)) sys.exit(2) def cli(): main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1593814261.0 python-bugzilla-3.0.2/bugzilla/_rhconverters.py0000664000175000017500000001040300000000000022131 0ustar00crobinsocrobinso# rhbugzilla.py - a Python interface to Red Hat Bugzilla using xmlrpclib. # # Copyright (C) 2008-2012 Red Hat Inc. # Author: Will Woods # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. from logging import getLogger from ._util import listify log = getLogger(__name__) class _RHBugzillaConverters(object): """ Static class that holds functional Red Hat back compat converters. Called inline in Bugzilla """ @staticmethod def convert_build_update( component=None, fixed_in=None, qa_whiteboard=None, devel_whiteboard=None, internal_whiteboard=None, sub_component=None): adddict = {} def get_alias(): # RHBZ has a custom extension to allow a bug to have multiple # aliases, so the format of aliases is # {"add": [...], "remove": [...]} # But that means in order to approximate upstream, behavior # which just overwrites the existing alias, we need to read # the bug's state first to know what string to remove. Which # we can't do, since we don't know the bug numbers at this point. # So fail for now. # # The API should provide {"set": [...]} # https://bugzilla.redhat.com/show_bug.cgi?id=1173114 # # Implementation will go here when it's available pass if fixed_in is not None: adddict["cf_fixed_in"] = fixed_in if qa_whiteboard is not None: adddict["cf_qa_whiteboard"] = qa_whiteboard if devel_whiteboard is not None: adddict["cf_devel_whiteboard"] = devel_whiteboard if internal_whiteboard is not None: adddict["cf_internal_whiteboard"] = internal_whiteboard if sub_component: if not isinstance(sub_component, dict): component = listify(component) if not component: raise ValueError("component must be specified if " "specifying sub_component") sub_component = {component[0]: sub_component} adddict["sub_components"] = sub_component get_alias() return adddict ################# # Query methods # ################# @staticmethod def pre_translation(query): """ Translates the query for possible aliases """ old = query.copy() def split_comma(_v): if isinstance(_v, list): return _v return _v.split(",") if 'bug_id' in query: query['id'] = split_comma(query.pop('bug_id')) if 'component' in query: query['component'] = split_comma(query['component']) if 'include_fields' not in query and 'column_list' in query: query['include_fields'] = query.pop('column_list') if old != query: log.debug("RHBugzilla pretranslated query to: %s", query) @staticmethod def post_translation(query, bug): """ Convert the results of getbug back to the ancient RHBZ value formats """ ignore = query # RHBZ _still_ returns component and version as lists, which # deviates from upstream. Copy the list values to components # and versions respectively. if 'component' in bug and "components" not in bug: val = bug['component'] bug['components'] = isinstance(val, list) and val or [val] bug['component'] = bug['components'][0] if 'version' in bug and "versions" not in bug: val = bug['version'] bug['versions'] = isinstance(val, list) and val or [val] bug['version'] = bug['versions'][0] # sub_components isn't too friendly of a format, add a simpler # sub_component value if 'sub_components' in bug and 'sub_component' not in bug: val = bug['sub_components'] bug['sub_component'] = "" if isinstance(val, dict): values = [] for vallist in val.values(): values += vallist bug['sub_component'] = " ".join(values) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605227015.0 python-bugzilla-3.0.2/bugzilla/_session.py0000664000175000017500000000777700000000000021114 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. from logging import getLogger import os import sys import urllib.parse import requests log = getLogger(__name__) class _BugzillaSession(object): """ Class to handle the backend agnostic 'requests' setup """ def __init__(self, url, user_agent, cookiecache, sslverify, cert, tokencache, api_key, requests_session=None): self._url = url self._user_agent = user_agent self._scheme = urllib.parse.urlparse(url)[0] self._cookiecache = cookiecache self._tokencache = tokencache self._api_key = api_key self._is_xmlrpc = False if self._scheme not in ["http", "https"]: raise Exception("Invalid URL scheme: %s (%s)" % ( self._scheme, url)) self._session = requests_session if not self._session: self._session = requests.Session() if cert: self._session.cert = cert if self._cookiecache: self._session.cookies = self._cookiecache.get_cookiejar() if sslverify is False: self._session.verify = False self._session.headers["User-Agent"] = self._user_agent self._set_tokencache_param() def _get_timeout(self): # Default to 5 minutes. This is longer than bugzilla.redhat.com's # apparent 3 minute timeout so shouldn't affect legitimate usage, # but saves us from indefinite hangs DEFAULT_TIMEOUT = 300 envtimeout = os.environ.get("PYTHONBUGZILLA_REQUESTS_TIMEOUT") return float(envtimeout or DEFAULT_TIMEOUT) def set_rest_defaults(self): self._session.headers["Content-Type"] = "application/json" # Bugzilla 5.0 only supports api_key as a query parameter. # Bugzilla 5.1+ takes it as a X-BUGZILLA-API-KEY header as well, # with query param taking preference. self._session.params["Bugzilla_api_key"] = self._api_key def set_xmlrpc_defaults(self): self._is_xmlrpc = True self._session.headers["Content-Type"] = "text/xml" def get_user_agent(self): return self._user_agent def get_scheme(self): return self._scheme def get_api_key(self): return self._api_key def get_token_value(self): return self._tokencache.get_value(self._url) def set_token_value(self, value): self._tokencache.set_value(self._url, value) self._set_tokencache_param() def _set_tokencache_param(self): if self._api_key: # Don't add a token to the params list if an API key is set. # Keeping API key solo means bugzilla will definitely fail # if the key expires. Passing in a token could hide that # fact, which could make it confusing to pinpoint the issue. return token = self.get_token_value() self._session.params["Bugzilla_token"] = token def set_response_cookies(self, response): """ Save any cookies received from the passed requests response """ self._cookiecache.set_cookies(response.cookies) def get_requests_session(self): return self._session def request(self, *args, **kwargs): timeout = self._get_timeout() if "timeout" not in kwargs: kwargs["timeout"] = timeout response = self._session.request(*args, **kwargs) if self._is_xmlrpc: # Yes this still appears to matter for properly decoding unicode # code points in bugzilla.redhat.com content response.encoding = "UTF-8" # Set response cookies self.set_response_cookies(response) try: response.raise_for_status() except Exception as e: # Scrape the api key out of the returned exception string message = str(e).replace(self._api_key or "", "") raise type(e)(message).with_traceback(sys.exc_info()[2]) return response ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/bugzilla/_util.py0000664000175000017500000000051600000000000020366 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. def listify(val): """Ensure that value is either None or a list, converting single values into 1-element lists""" if val is None: return val if isinstance(val, list): return val return [val] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230895.0 python-bugzilla-3.0.2/bugzilla/apiversion.py0000664000175000017500000000027000000000000021426 0ustar00crobinsocrobinso# # Copyright (C) 2014 Red Hat Inc. # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. version = "3.0.2" __version__ = version ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230249.0 python-bugzilla-3.0.2/bugzilla/base.py0000664000175000017500000022750300000000000020173 0ustar00crobinsocrobinso# base.py - the base classes etc. for a Python interface to bugzilla # # Copyright (C) 2007, 2008, 2009, 2010 Red Hat Inc. # Author: Will Woods # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import collections import getpass import locale from logging import getLogger import mimetypes import os import sys import urllib.parse from io import BytesIO from ._authfiles import (_BugzillaRCFile, _BugzillaCookieCache, _BugzillaTokenCache) from .apiversion import __version__ from ._backendrest import _BackendREST from ._backendxmlrpc import _BackendXMLRPC from .bug import Bug, Group, User from .exceptions import BugzillaError from ._rhconverters import _RHBugzillaConverters from ._session import _BugzillaSession from ._util import listify log = getLogger(__name__) def _nested_update(d, u): # Helper for nested dict update() for k, v in list(u.items()): if isinstance(v, collections.abc.Mapping): d[k] = _nested_update(d.get(k, {}), v) else: d[k] = v return d class _FieldAlias(object): """ Track API attribute names that differ from what we expose in users. For example, originally 'short_desc' was the name of the property that maps to 'summary' on modern bugzilla. We want pre-existing API users to be able to continue to use Bug.short_desc, and query({"short_desc": "foo"}). This class tracks that mapping. @oldname: The old attribute name @newname: The modern attribute name @is_api: If True, use this mapping for values sent to the xmlrpc API (like the query example) @is_bug: If True, use this mapping for Bug attribute names. """ def __init__(self, newname, oldname, is_api=True, is_bug=True): self.newname = newname self.oldname = oldname self.is_api = is_api self.is_bug = is_bug class _BugzillaAPICache(object): """ Helper class that holds cached API results for things like products, components, etc. """ def __init__(self): self.products = [] self.component_names = {} self.bugfields = [] self.version_raw = None self.version_parsed = (0, 0) class Bugzilla(object): """ The main API object. Connects to a bugzilla instance over XMLRPC, and provides wrapper functions to simplify dealing with API calls. The most common invocation here will just be with just a URL: bzapi = Bugzilla("http://bugzilla.example.com") If you have previously logged into that URL, and have cached login cookies/tokens, you will automatically be logged in. Otherwise to log in, you can either pass auth options to __init__, or call a login helper like interactive_login(). If you are not logged in, you won't be able to access restricted data like user email, or perform write actions like bug create/update. But simple querys will work correctly. If you are unsure if you are logged in, you can check the .logged_in property. Another way to specify auth credentials is via a 'bugzillarc' file. See readconfig() documentation for details. """ @staticmethod def url_to_query(url): """ Given a big huge bugzilla query URL, returns a query dict that can be passed along to the Bugzilla.query() method. """ q = {} # pylint: disable=unpacking-non-sequence (ignore1, ignore2, path, ignore, query, ignore3) = urllib.parse.urlparse(url) base = os.path.basename(path) if base not in ('buglist.cgi', 'query.cgi'): return {} for (k, v) in urllib.parse.parse_qsl(query): if k not in q: q[k] = v elif isinstance(q[k], list): q[k].append(v) else: oldv = q[k] q[k] = [oldv, v] # Handle saved searches if base == "buglist.cgi" and "namedcmd" in q and "sharer_id" in q: q = { "sharer_id": q["sharer_id"], "savedsearch": q["namedcmd"], } return q @staticmethod def fix_url(url, force_rest=False): """ Turn passed url into a bugzilla XMLRPC web url :param force_rest: If True, generate a REST API url """ (scheme, netloc, path, params, query, fragment) = urllib.parse.urlparse(url) if not scheme: scheme = 'https' if path and not netloc: netloc = path.split("/", 1)[0] path = "/".join(path.split("/")[1:]) or None if not path: path = 'xmlrpc.cgi' if force_rest: path = "rest/" newurl = urllib.parse.urlunparse( (scheme, netloc, path, params, query, fragment)) return newurl @staticmethod def get_rcfile_default_url(): """ Helper to check all the default bugzillarc file paths for a [DEFAULT] url=X section, and if found, return it. """ configpaths = _BugzillaRCFile.get_default_configpaths() rcfile = _BugzillaRCFile() rcfile.set_configpaths(configpaths) return rcfile.get_default_url() def __init__(self, url=-1, user=None, password=None, cookiefile=-1, sslverify=True, tokenfile=-1, use_creds=True, api_key=None, cert=None, configpaths=-1, force_rest=False, force_xmlrpc=False, requests_session=None): """ :param url: The bugzilla instance URL, which we will connect to immediately. Most users will want to specify this at __init__ time, but you can defer connecting by passing url=None and calling connect(URL) manually :param user: optional username to connect with :param password: optional password for the connecting user :param cert: optional certificate file for client side certificate authentication :param cookiefile: Location to cache the login session cookies so you don't have to keep specifying username/password. Bugzilla 5+ will use tokens instead of cookies. If -1, use the default path. If None, don't use or save any cookiefile. :param sslverify: Set this to False to skip SSL hostname and CA validation checks, like out of date certificate :param tokenfile: Location to cache the API login token so youi don't have to keep specifying username/password. If -1, use the default path. If None, don't use or save any tokenfile. :param use_creds: If False, this disables cookiefile, tokenfile, and configpaths by default. This is a convenience option to unset those values at init time. If those values are later changed, they may be used for future operations. :param sslverify: Maps to 'requests' sslverify parameter. Set to False to disable SSL verification, but it can also be a path to file or directory for custom certs. :param api_key: A bugzilla5+ API key :param configpaths: A list of possible bugzillarc locations. :param force_rest: Force use of the REST API :param force_xmlrpc: Force use of the XMLRPC API. If neither force_X parameter are specified, heuristics will be used to determine which API to use, with XMLRPC preferred for back compatability. :param requests_session: An optional requests.Session object the API will use to contact the remote bugzilla instance. This way the API user can set up whatever auth bits they may need. """ if url == -1: raise TypeError("Specify a valid bugzilla url, or pass url=None") # Settings the user might want to tweak self.user = user or '' self.password = password or '' self.api_key = api_key self.cert = cert or None self.url = '' self._backend = None self._session = None self._user_requests_session = requests_session self._sslverify = sslverify self._cache = _BugzillaAPICache() self._bug_autorefresh = False self._is_redhat_bugzilla = False self._rcfile = _BugzillaRCFile() self._cookiecache = _BugzillaCookieCache() self._tokencache = _BugzillaTokenCache() self._force_rest = force_rest self._force_xmlrpc = force_xmlrpc if not use_creds: cookiefile = None tokenfile = None configpaths = [] if cookiefile == -1: cookiefile = self._cookiecache.get_default_path() if tokenfile == -1: tokenfile = self._tokencache.get_default_path() if configpaths == -1: configpaths = _BugzillaRCFile.get_default_configpaths() self._setcookiefile(cookiefile) self._settokenfile(tokenfile) self._setconfigpath(configpaths) if url: self.connect(url) def _detect_is_redhat_bugzilla(self): if self._is_redhat_bugzilla: return True if "bugzilla.redhat.com" in self.url: log.info("Using RHBugzilla for URL containing bugzilla.redhat.com") return True return False def _init_class_from_url(self): """ Detect if we should use RHBugzilla class, and if so, set it """ from .oldclasses import RHBugzilla # pylint: disable=cyclic-import if not self._detect_is_redhat_bugzilla(): return self._is_redhat_bugzilla = True if self.__class__ == Bugzilla: # Overriding the class doesn't have any functional effect, # but we continue to do it for API back compat incase anyone # is doing any class comparison. We should drop this in the future self.__class__ = RHBugzilla def _get_field_aliases(self): # List of field aliases. Maps old style RHBZ parameter # names to actual upstream values. Used for createbug() and # query include_fields at least. ret = [] def _add(*args, **kwargs): ret.append(_FieldAlias(*args, **kwargs)) def _add_both(newname, origname): _add(newname, origname, is_api=False) _add(origname, newname, is_bug=False) _add('summary', 'short_desc') _add('description', 'comment') _add('platform', 'rep_platform') _add('severity', 'bug_severity') _add('status', 'bug_status') _add('id', 'bug_id') _add('blocks', 'blockedby') _add('blocks', 'blocked') _add('depends_on', 'dependson') _add('creator', 'reporter') _add('url', 'bug_file_loc') _add('dupe_of', 'dupe_id') _add('dupe_of', 'dup_id') _add('comments', 'longdescs') _add('creation_time', 'opendate') _add('creation_time', 'creation_ts') _add('whiteboard', 'status_whiteboard') _add('last_change_time', 'delta_ts') if self._is_redhat_bugzilla: _add_both('fixed_in', 'cf_fixed_in') _add_both('qa_whiteboard', 'cf_qa_whiteboard') _add_both('devel_whiteboard', 'cf_devel_whiteboard') _add_both('internal_whiteboard', 'cf_internal_whiteboard') _add('component', 'components', is_bug=False) _add('version', 'versions', is_bug=False) # Yes, sub_components is the field name the API expects _add('sub_components', 'sub_component', is_bug=False) # flags format isn't exactly the same but it's the closest approx _add('flags', 'flag_types') return ret def _get_user_agent(self): return 'python-bugzilla/%s' % __version__ user_agent = property(_get_user_agent) @property def bz_ver_major(self): return self._cache.version_parsed[0] @property def bz_ver_minor(self): return self._cache.version_parsed[1] ################### # Private helpers # ################### def _get_version(self): """ Return version number as a float """ return float("%d.%d" % (self.bz_ver_major, self.bz_ver_minor)) def _get_bug_aliases(self): return [(f.newname, f.oldname) for f in self._get_field_aliases() if f.is_bug] def _get_api_aliases(self): return [(f.newname, f.oldname) for f in self._get_field_aliases() if f.is_api] ################# # Auth handling # ################# def _getcookiefile(self): return self._cookiecache.get_filename() def _delcookiefile(self): self._setcookiefile(None) def _setcookiefile(self, cookiefile): self._cookiecache.set_filename(cookiefile) cookiefile = property(_getcookiefile, _setcookiefile, _delcookiefile) def _gettokenfile(self): return self._tokencache.get_filename() def _settokenfile(self, filename): self._tokencache.set_filename(filename) def _deltokenfile(self): self._settokenfile(None) tokenfile = property(_gettokenfile, _settokenfile, _deltokenfile) def _getconfigpath(self): return self._rcfile.get_configpaths() def _setconfigpath(self, configpaths): return self._rcfile.set_configpaths(configpaths) def _delconfigpath(self): return self._rcfile.set_configpaths(None) configpath = property(_getconfigpath, _setconfigpath, _delconfigpath) ############################# # Login/connection handling # ############################# def readconfig(self, configpath=None, overwrite=True): """ :param configpath: Optional bugzillarc path to read, instead of the default list. This function is called automatically from Bugzilla connect(), which is called at __init__ if a URL is passed. Calling it manually is just for passing in a non-standard configpath. The locations for the bugzillarc file are preferred in this order: ~/.config/python-bugzilla/bugzillarc ~/.bugzillarc /etc/bugzillarc It has content like: [bugzilla.yoursite.com] user = username password = password Or [bugzilla.yoursite.com] api_key = key The file can have multiple sections for different bugzilla instances. A 'url' field in the [DEFAULT] section can be used to set a default URL for the bugzilla command line tool. Be sure to set appropriate permissions on bugzillarc if you choose to store your password in it! :param overwrite: If True, bugzillarc will clobber any already set self.user/password/api_key/cert value. """ if configpath: self._setconfigpath(configpath) data = self._rcfile.parse(self.url) for key, val in data.items(): if key == "api_key" and (overwrite or not self.api_key): log.debug("bugzillarc: setting api_key") self.api_key = val elif key == "user" and (overwrite or not self.user): log.debug("bugzillarc: setting user=%s", val) self.user = val elif key == "password" and (overwrite or not self.password): log.debug("bugzillarc: setting password") self.password = val elif key == "cert" and (overwrite or not self.cert): log.debug("bugzillarc: setting cert") self.cert = val else: log.debug("bugzillarc: unknown key=%s", key) def _set_bz_version(self, version): self._cache.version_raw = version try: major, minor = [int(i) for i in version.split(".")[0:2]] except Exception: log.debug("version doesn't match expected format X.Y.Z, " "assuming 5.0", exc_info=True) major = 5 minor = 0 self._cache.version_parsed = (major, minor) def _get_backend_class(self, url): # pragma: no cover # This is a hook for the test suite to do some mock hackery if self._force_rest and self._force_xmlrpc: raise BugzillaError( "Cannot specify both force_rest and force_xmlrpc") xmlurl = self.fix_url(url) if self._force_xmlrpc: return _BackendXMLRPC, xmlurl resturl = self.fix_url(url, force_rest=self._force_rest) if self._force_rest: return _BackendREST, resturl # Simple heuristic if the original url has a path in it if "/xmlrpc" in url: return _BackendXMLRPC, xmlurl if "/rest" in url: return _BackendREST, resturl # We were passed something like bugzilla.example.com but we # aren't sure which method to use, try probing if _BackendXMLRPC.probe(xmlurl): return _BackendXMLRPC, xmlurl if _BackendREST.probe(resturl): return _BackendREST, resturl # Otherwise fallback to XMLRPC default and let it fail return _BackendXMLRPC, xmlurl def connect(self, url=None): """ Connect to the bugzilla instance with the given url. This is called by __init__ if a URL is passed. Or it can be called manually at any time with a passed URL. This will also read any available config files (see readconfig()), which may set 'user' and 'password', and others. If 'user' and 'password' are both set, we'll run login(). Otherwise you'll have to login() yourself before some methods will work. """ if self._session: self.disconnect() url = url or self.url backendclass, newurl = self._get_backend_class(url) if url != newurl: log.debug("Converted url=%s to fixed url=%s", url, newurl) self.url = newurl log.debug("Connecting with URL %s", self.url) # we've changed URLs - reload config self.readconfig(overwrite=False) self._session = _BugzillaSession(self.url, self.user_agent, cookiecache=self._cookiecache, sslverify=self._sslverify, cert=self.cert, tokencache=self._tokencache, api_key=self.api_key, requests_session=self._user_requests_session) self._backend = backendclass(self.url, self._session) if (self.user and self.password): log.info("user and password present - doing login()") self.login() if self.api_key: log.debug("using API key") version = self._backend.bugzilla_version()["version"] log.debug("Bugzilla version string: %s", version) self._set_bz_version(version) self._init_class_from_url() @property def _proxy(self): """ Return an xmlrpc ServerProxy instance that will work seamlessly with bugzilla Some apps have historically accessed _proxy directly, like fedora infrastrucutre pieces. So we consider it part of the API """ return self._backend.get_xmlrpc_proxy() def is_xmlrpc(self): """ :returns: True if using the XMLRPC API """ return self._backend.is_xmlrpc() def is_rest(self): """ :returns: True if using the REST API """ return self._backend.is_rest() def get_requests_session(self): """ Give API users access to the Requests.session object we use for talking to the remote bugzilla instance. :returns: The Requests.session object backing the open connection. """ return self._session.get_requests_session() def disconnect(self): """ Disconnect from the given bugzilla instance. """ self._backend = None self._session = None self._cache = _BugzillaAPICache() def login(self, user=None, password=None, restrict_login=None): """ Attempt to log in using the given username and password. Subsequent method calls will use this username and password. Returns False if login fails, otherwise returns some kind of login info - typically either a numeric userid, or a dict of user info. If user is not set, the value of Bugzilla.user will be used. If *that* is not set, ValueError will be raised. If login fails, BugzillaError will be raised. The login session can be restricted to current user IP address with restrict_login argument. (Bugzilla 4.4+) This method will be called implicitly at the end of connect() if user and password are both set. So under most circumstances you won't need to call this yourself. """ if self.api_key: raise ValueError("cannot login when using an API key") if user: self.user = user if password: self.password = password if not self.user: raise ValueError("missing username") if not self.password: raise ValueError("missing password") payload = {"login": self.user} if restrict_login: payload['restrict_login'] = True log.debug("logging in with options %s", str(payload)) payload['password'] = self.password try: ret = self._backend.user_login(payload) self.password = '' log.info("login succeeded for user=%s", self.user) return ret except Exception as e: log.debug("Login exception: %s", str(e), exc_info=True) raise BugzillaError("Login failed: %s" % BugzillaError.get_bugzilla_error_string(e)) from None def interactive_save_api_key(self): """ Helper method to interactively ask for an API key, verify it is valid, and save it to a bugzillarc file referenced via self.configpaths """ sys.stdout.write('API Key: ') sys.stdout.flush() api_key = sys.stdin.readline().strip() self.disconnect() self.api_key = api_key log.info('Checking API key... ') self.connect() if not self.logged_in: # pragma: no cover raise BugzillaError("Login with API_KEY failed") log.info('API Key accepted') wrote_filename = self._rcfile.save_api_key(self.url, self.api_key) log.info("API key written to filename=%s", wrote_filename) msg = "Login successful." if wrote_filename: msg += " API key written to %s" % wrote_filename print(msg) def interactive_login(self, user=None, password=None, force=False, restrict_login=None): """ Helper method to handle login for this bugzilla instance. :param user: bugzilla username. If not specified, prompt for it. :param password: bugzilla password. If not specified, prompt for it. :param force: Unused :param restrict_login: restricts session to IP address """ ignore = force log.debug('Calling interactive_login') if not user: sys.stdout.write('Bugzilla Username: ') sys.stdout.flush() user = sys.stdin.readline().strip() if not password: password = getpass.getpass('Bugzilla Password: ') log.info('Logging in... ') out = self.login(user, password, restrict_login) msg = "Login successful." if "token" in out and self.tokenfile: msg += " Token cache saved to %s" % self.tokenfile if self._get_version() >= 5.0: msg += "\nToken usage is deprecated. " msg += "Consider using bugzilla API keys instead." print(msg) def logout(self): """ Log out of bugzilla. Drops server connection and user info, and destroys authentication cookies. """ self._backend.user_logout() self.disconnect() self.user = '' self.password = '' @property def logged_in(self): """ This is True if this instance is logged in else False. We test if this session is authenticated by calling the User.get() XMLRPC method with ids set. Logged-out users cannot pass the 'ids' parameter and will result in a 505 error. If we tried to login with a token, but the token was incorrect or expired, the server returns a 32000 error. For Bugzilla 5 and later, a new method, User.valid_login is available to test the validity of the token. However, this will require that the username be cached along with the token in order to work effectively in all scenarios and is not currently used. For more information, refer to the following url. http://bugzilla.readthedocs.org/en/latest/api/core/v1/user.html#valid-login """ try: self._backend.user_get({"ids": [1]}) return True except Exception as e: code = BugzillaError.get_bugzilla_error_code(e) if code in [505, 32000]: return False raise e ###################### # Bugfields querying # ###################### def getbugfields(self, force_refresh=False, names=None): """ Calls getBugFields, which returns a list of fields in each bug for this bugzilla instance. This can be used to set the list of attrs on the Bug object. :param force_refresh: If True, overwrite the bugfield cache with these newly checked values. :param names: Only check for the passed bug field names """ def _fieldnames(): data = {"include_fields": ["name"]} if names: data["names"] = names r = self._backend.bug_fields(data) return [f['name'] for f in r['fields']] if force_refresh or not self._cache.bugfields: log.debug("Refreshing bugfields") self._cache.bugfields = _fieldnames() self._cache.bugfields.sort() log.debug("bugfields = %s", self._cache.bugfields) return self._cache.bugfields bugfields = property(fget=lambda self: self.getbugfields(), fdel=lambda self: setattr(self, '_bugfields', None)) #################### # Product querying # #################### def product_get(self, ids=None, names=None, include_fields=None, exclude_fields=None, ptype=None): """ Raw wrapper around Product.get https://bugzilla.readthedocs.io/en/latest/api/core/v1/product.html#get-product This does not perform any caching like other product API calls. If ids, names, or ptype is not specified, we default to ptype=accessible for historical reasons @ids: List of product IDs to lookup @names: List of product names to lookup @ptype: Either 'accessible', 'selectable', or 'enterable'. If specified, we return data for all those @include_fields: Only include these fields in the output @exclude_fields: Do not include these fields in the output """ if ids is None and names is None and ptype is None: ptype = "accessible" if ptype: raw = None if ptype == "accessible": raw = self._backend.product_get_accessible() elif ptype == "enterable": raw = self._backend.product_get_enterable() elif ptype == "selectable": raw = self._backend.product_get_selectable() if raw is None: raise RuntimeError("Unknown ptype=%s" % ptype) ids = raw['ids'] log.debug("For ptype=%s found ids=%s", ptype, ids) kwargs = {} if ids: kwargs["ids"] = listify(ids) if names: kwargs["names"] = listify(names) if include_fields: kwargs["include_fields"] = include_fields if exclude_fields: kwargs["exclude_fields"] = exclude_fields ret = self._backend.product_get(kwargs) return ret['products'] def refresh_products(self, **kwargs): """ Refresh a product's cached info. Basically calls product_get with the passed arguments, and tries to intelligently update our product cache. For example, if we already have cached info for product=foo, and you pass in names=["bar", "baz"], the new cache will have info for products foo, bar, baz. Individual product fields are also updated. """ for product in self.product_get(**kwargs): updated = False for current in self._cache.products[:]: if (current.get("id", -1) != product.get("id", -2) and current.get("name", -1) != product.get("name", -2)): continue _nested_update(current, product) updated = True break if not updated: self._cache.products.append(product) def getproducts(self, force_refresh=False, **kwargs): """ Query all products and return the raw dict info. Takes all the same arguments as product_get. On first invocation this will contact bugzilla and internally cache the results. Subsequent getproducts calls or accesses to self.products will return this cached data only. :param force_refresh: force refreshing via refresh_products() """ if force_refresh or not self._cache.products: self.refresh_products(**kwargs) return self._cache.products products = property( fget=lambda self: self.getproducts(), fdel=lambda self: setattr(self, '_products', None), doc="Helper for accessing the products cache. If nothing " "has been cached yet, this calls getproducts()") ####################### # components querying # ####################### def _lookup_product_in_cache(self, productname): prodstr = isinstance(productname, str) and productname or None prodint = isinstance(productname, int) and productname or None for proddict in self._cache.products: if prodstr == proddict.get("name", -1): return proddict if prodint == proddict.get("id", "nope"): return proddict return {} def getcomponentsdetails(self, product, force_refresh=False): """ Wrapper around Product.get(include_fields=["components"]), returning only the "components" data for the requested product, slightly reworked to a dict mapping of components.name: components, for historical reasons. This uses the product cache, but will update it if the product isn't found or "components" isn't cached for the product. In cases like bugzilla.redhat.com where there are tons of components for some products, this API will time out. You should use product_get instead. """ proddict = self._lookup_product_in_cache(product) if (force_refresh or not proddict or "components" not in proddict): self.refresh_products(names=[product], include_fields=["name", "id", "components"]) proddict = self._lookup_product_in_cache(product) ret = {} for compdict in proddict["components"]: ret[compdict["name"]] = compdict return ret def getcomponentdetails(self, product, component, force_refresh=False): """ Helper for accessing a single component's info. This is a wrapper around getcomponentsdetails, see that for explanation """ d = self.getcomponentsdetails(product, force_refresh) return d[component] def getcomponents(self, product, force_refresh=False): """ Return a list of component names for the passed product. On first invocation the value is cached, and subsequent calls will return the cached data. :param force_refresh: Force refreshing the cache, and return the new data """ proddict = self._lookup_product_in_cache(product) product_id = proddict.get("id", None) if (force_refresh or product_id is None or "components" not in proddict): self.refresh_products( names=[product], include_fields=["name", "id", "components.name"]) proddict = self._lookup_product_in_cache(product) if "id" not in proddict: raise BugzillaError("Product '%s' not found" % product) product_id = proddict["id"] if product_id not in self._cache.component_names: names = [] for comp in proddict.get("components", []): name = comp.get("name") if name: names.append(name) self._cache.component_names[product_id] = names return self._cache.component_names[product_id] ############################ # component adding/editing # ############################ def _component_data_convert(self, data, update=False): # Back compat for the old RH interface convert_fields = [ ("initialowner", "default_assignee"), ("initialqacontact", "default_qa_contact"), ("initialcclist", "default_cc"), ] for old, new in convert_fields: if old in data: data[new] = data.pop(old) if update: names = {"product": data.pop("product"), "component": data.pop("component")} updates = {} for k in list(data.keys()): updates[k] = data.pop(k) data["names"] = [names] data["updates"] = updates def addcomponent(self, data): """ A method to create a component in Bugzilla. Takes a dict, with the following elements: product: The product to create the component in component: The name of the component to create description: A one sentence summary of the component default_assignee: The bugzilla login (email address) of the initial owner of the component default_qa_contact (optional): The bugzilla login of the initial QA contact default_cc: (optional) The initial list of users to be CC'ed on new bugs for the component. is_active: (optional) If False, the component is hidden from the component list when filing new bugs. """ data = data.copy() self._component_data_convert(data) return self._backend.component_create(data) def editcomponent(self, data): """ A method to edit a component in Bugzilla. Takes a dict, with mandatory elements of product. component, and initialowner. All other elements are optional and use the same names as the addcomponent() method. """ data = data.copy() self._component_data_convert(data, update=True) return self._backend.component_update(data) ################### # getbug* methods # ################### def _process_include_fields(self, include_fields, exclude_fields, extra_fields): """ Internal helper to process include_fields lists """ def _convert_fields(_in): for newname, oldname in self._get_api_aliases(): if oldname in _in: _in.remove(oldname) if newname not in _in: _in.append(newname) return _in ret = {} if include_fields: include_fields = _convert_fields(include_fields) if "id" not in include_fields: include_fields.append("id") ret["include_fields"] = include_fields if exclude_fields: exclude_fields = _convert_fields(exclude_fields) ret["exclude_fields"] = exclude_fields if self._supports_getbug_extra_fields(): if extra_fields: ret["extra_fields"] = _convert_fields(extra_fields) return ret def _get_bug_autorefresh(self): """ This value is passed to Bug.autorefresh for all fetched bugs. If True, and an uncached attribute is requested from a Bug, the Bug will update its contents and try again. """ return self._bug_autorefresh def _set_bug_autorefresh(self, val): self._bug_autorefresh = bool(val) bug_autorefresh = property(_get_bug_autorefresh, _set_bug_autorefresh) def _getbug_extra_fields(self): """ Extra fields that need to be explicitly requested from Bug.get in order for the data to be returned. """ rhbz_extra_fields = [ "comments", "description", "external_bugs", "flags", "sub_components", "tags", ] if self._is_redhat_bugzilla: return rhbz_extra_fields return [] def _supports_getbug_extra_fields(self): """ Return True if the bugzilla instance supports passing extra_fields to getbug As of Dec 2012 it seems like only RH bugzilla actually has behavior like this, for upstream bz it returns all info for every Bug.get() """ return self._is_redhat_bugzilla def _getbugs(self, idlist, permissive, include_fields=None, exclude_fields=None, extra_fields=None): """ Return a list of dicts of full bug info for each given bug id. bug ids that couldn't be found will return None instead of a dict. """ ids = [] aliases = [] def _alias_or_int(_v): if str(_v).isdigit(): return int(_v), None return None, str(_v) for idstr in idlist: idint, alias = _alias_or_int(idstr) if alias: aliases.append(alias) else: ids.append(idstr) extra_fields = listify(extra_fields or []) extra_fields += self._getbug_extra_fields() getbugdata = {} if permissive: getbugdata["permissive"] = 1 getbugdata.update(self._process_include_fields( include_fields, exclude_fields, extra_fields)) r = self._backend.bug_get(ids, aliases, getbugdata) # Do some wrangling to ensure we return bugs in the same order # the were passed in, for historical reasons ret = [] for idval in idlist: idint, alias = _alias_or_int(idval) for bugdict in r["bugs"]: if idint and idint != bugdict.get("id", None): continue aliaslist = listify(bugdict.get("alias", None) or []) if alias and alias not in aliaslist: continue ret.append(bugdict) break return ret def _getbug(self, objid, **kwargs): """ Thin wrapper around _getbugs to handle the slight argument tweaks for fetching a single bug. The main bit is permissive=False, which will tell bugzilla to raise an explicit error if we can't fetch that bug. This logic is called from Bug() too """ return self._getbugs([objid], permissive=False, **kwargs)[0] def getbug(self, objid, include_fields=None, exclude_fields=None, extra_fields=None): """ Return a Bug object with the full complement of bug data already loaded. """ data = self._getbug(objid, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields) return Bug(self, dict=data, autorefresh=self.bug_autorefresh) def getbugs(self, idlist, include_fields=None, exclude_fields=None, extra_fields=None, permissive=True): """ Return a list of Bug objects with the full complement of bug data already loaded. If there's a problem getting the data for a given id, the corresponding item in the returned list will be None. """ data = self._getbugs(idlist, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields, permissive=permissive) return [(b and Bug(self, dict=b, autorefresh=self.bug_autorefresh)) or None for b in data] def get_comments(self, idlist): """ Returns a dictionary of bugs and comments. The comments key will be empty. See bugzilla docs for details """ return self._backend.bug_comments(idlist, {}) ################# # query methods # ################# def build_query(self, product=None, component=None, version=None, long_desc=None, bug_id=None, short_desc=None, cc=None, assigned_to=None, reporter=None, qa_contact=None, status=None, blocked=None, dependson=None, keywords=None, keywords_type=None, url=None, url_type=None, status_whiteboard=None, status_whiteboard_type=None, fixed_in=None, fixed_in_type=None, flag=None, alias=None, qa_whiteboard=None, devel_whiteboard=None, bug_severity=None, priority=None, target_release=None, target_milestone=None, emailtype=None, include_fields=None, quicksearch=None, savedsearch=None, savedsearch_sharer_id=None, sub_component=None, tags=None, exclude_fields=None, extra_fields=None): """ Build a query string from passed arguments. Will handle query parameter differences between various bugzilla versions. Most of the parameters should be self-explanatory. However, if you want to perform a complex query, and easy way is to create it with the bugzilla web UI, copy the entire URL it generates, and pass it to the static method Bugzilla.url_to_query Then pass the output to Bugzilla.query() For details about the specific argument formats, see the bugzilla docs: https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#search-bugs """ query = { "alias": alias, "product": listify(product), "component": listify(component), "version": version, "id": bug_id, "short_desc": short_desc, "bug_status": status, "bug_severity": bug_severity, "priority": priority, "target_release": target_release, "target_milestone": target_milestone, "tag": listify(tags), "quicksearch": quicksearch, "savedsearch": savedsearch, "sharer_id": savedsearch_sharer_id, # RH extensions... don't add any more. See comment below "sub_components": listify(sub_component), } def add_bool(bzkey, value, bool_id, booltype=None): value = listify(value) if value is None: return bool_id query["query_format"] = "advanced" for boolval in value: def make_bool_str(prefix): # pylint: disable=cell-var-from-loop return "%s%i-0-0" % (prefix, bool_id) query[make_bool_str("field")] = bzkey query[make_bool_str("value")] = boolval query[make_bool_str("type")] = booltype or "substring" bool_id += 1 return bool_id # RH extensions that we have to maintain here for back compat, # but all future custom fields should be specified via # cli --field option, or via extending the query dict() manually. # No more supporting custom fields in this API bool_id = 0 bool_id = add_bool("keywords", keywords, bool_id, keywords_type) bool_id = add_bool("blocked", blocked, bool_id) bool_id = add_bool("dependson", dependson, bool_id) bool_id = add_bool("bug_file_loc", url, bool_id, url_type) bool_id = add_bool("cf_fixed_in", fixed_in, bool_id, fixed_in_type) bool_id = add_bool("flagtypes.name", flag, bool_id) bool_id = add_bool("status_whiteboard", status_whiteboard, bool_id, status_whiteboard_type) bool_id = add_bool("cf_qa_whiteboard", qa_whiteboard, bool_id) bool_id = add_bool("cf_devel_whiteboard", devel_whiteboard, bool_id) def add_email(key, value, count): if value is None: return count if not emailtype: query[key] = value return count query["query_format"] = "advanced" query['email%i' % count] = value query['email%s%i' % (key, count)] = True query['emailtype%i' % count] = emailtype return count + 1 email_count = 1 email_count = add_email("cc", cc, email_count) email_count = add_email("assigned_to", assigned_to, email_count) email_count = add_email("reporter", reporter, email_count) email_count = add_email("qa_contact", qa_contact, email_count) if long_desc is not None: query["query_format"] = "advanced" query["longdesc"] = long_desc query["longdesc_type"] = "allwordssubstr" # 'include_fields' only available for Bugzilla4+ # 'extra_fields' is an RHBZ extension query.update(self._process_include_fields( include_fields, exclude_fields, extra_fields)) # Strip out None elements in the dict for k, v in query.copy().items(): if v is None: del(query[k]) self.pre_translation(query) return query def query(self, query): """ Query bugzilla and return a list of matching bugs. query must be a dict with fields like those in in querydata['fields']. Returns a list of Bug objects. Also see the _query() method for details about the underlying implementation. """ try: r = self._backend.bug_search(query) log.debug("bug_search returned:\n%s", str(r)) except Exception as e: # Try to give a hint in the error message if url_to_query # isn't supported by this bugzilla instance if ("query_format" not in str(e) or not BugzillaError.get_bugzilla_error_code(e) or self._get_version() >= 5.0): raise raise BugzillaError("%s\nYour bugzilla instance does not " "appear to support API queries derived from bugzilla " "web URL queries." % e) from None log.debug("Query returned %s bugs", len(r['bugs'])) return [Bug(self, dict=b, autorefresh=self.bug_autorefresh) for b in r['bugs']] def pre_translation(self, query): """ In order to keep the API the same, Bugzilla4 needs to process the query and the result. This also applies to the refresh() function """ if self._is_redhat_bugzilla: _RHBugzillaConverters.pre_translation(query) query.update(self._process_include_fields( query.get("include_fields", []), None, None)) def post_translation(self, query, bug): """ In order to keep the API the same, Bugzilla4 needs to process the query and the result. This also applies to the refresh() function """ if self._is_redhat_bugzilla: _RHBugzillaConverters.post_translation(query, bug) def bugs_history_raw(self, bug_ids): """ Experimental. Gets the history of changes for particular bugs in the database. """ return self._backend.bug_history(bug_ids, {}) ####################################### # Methods for modifying existing bugs # ####################################### # Bug() also has individual methods for many ops, like setassignee() def update_bugs(self, ids, updates): """ A thin wrapper around bugzilla Bug.update(). Used to update all values of an existing bug report, as well as add comments. The dictionary passed to this function should be generated with build_update(), otherwise we cannot guarantee back compatibility. """ tmp = updates.copy() return self._backend.bug_update(listify(ids), tmp) def update_tags(self, idlist, tags_add=None, tags_remove=None): """ Updates the 'tags' field for a bug. """ tags = {} if tags_add: tags["add"] = listify(tags_add) if tags_remove: tags["remove"] = listify(tags_remove) d = { "tags": tags, } return self._backend.bug_update_tags(listify(idlist), d) def update_flags(self, idlist, flags): """ A thin back compat wrapper around build_update(flags=X) """ return self.update_bugs(idlist, self.build_update(flags=flags)) def build_update(self, alias=None, assigned_to=None, blocks_add=None, blocks_remove=None, blocks_set=None, depends_on_add=None, depends_on_remove=None, depends_on_set=None, cc_add=None, cc_remove=None, is_cc_accessible=None, comment=None, comment_private=None, component=None, deadline=None, dupe_of=None, estimated_time=None, groups_add=None, groups_remove=None, keywords_add=None, keywords_remove=None, keywords_set=None, op_sys=None, platform=None, priority=None, product=None, qa_contact=None, is_creator_accessible=None, remaining_time=None, reset_assigned_to=None, reset_qa_contact=None, resolution=None, see_also_add=None, see_also_remove=None, severity=None, status=None, summary=None, target_milestone=None, target_release=None, url=None, version=None, whiteboard=None, work_time=None, fixed_in=None, qa_whiteboard=None, devel_whiteboard=None, internal_whiteboard=None, sub_component=None, flags=None, comment_tags=None, minor_update=None): """ Returns a python dict() with properly formatted parameters to pass to update_bugs(). See bugzilla documentation for the format of the individual fields: https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#create-bug """ ret = {} rhbzret = {} # These are only supported for rhbugzilla # # This should not be extended any more. # If people want to handle custom fields, manually extend the # returned dictionary. rhbzargs = { "fixed_in": fixed_in, "devel_whiteboard": devel_whiteboard, "qa_whiteboard": qa_whiteboard, "internal_whiteboard": internal_whiteboard, "sub_component": sub_component, } if self._is_redhat_bugzilla: rhbzret = _RHBugzillaConverters.convert_build_update( component=component, **rhbzargs) else: for key, val in rhbzargs.items(): if val is not None: raise ValueError("bugzilla instance does not support " "updating '%s'" % key) def s(key, val, convert=None): if val is None: return if convert: val = convert(val) ret[key] = val def add_dict(key, add, remove, _set=None, convert=None): if add is remove is _set is None: return def c(val): val = listify(val) if convert: val = [convert(v) for v in val] return val newdict = {} if add is not None: newdict["add"] = c(add) if remove is not None: newdict["remove"] = c(remove) if _set is not None: newdict["set"] = c(_set) ret[key] = newdict s("alias", alias) s("assigned_to", assigned_to) s("is_cc_accessible", is_cc_accessible, bool) s("component", component) s("deadline", deadline) s("dupe_of", dupe_of, int) s("estimated_time", estimated_time, int) s("op_sys", op_sys) s("platform", platform) s("priority", priority) s("product", product) s("qa_contact", qa_contact) s("is_creator_accessible", is_creator_accessible, bool) s("remaining_time", remaining_time, float) s("reset_assigned_to", reset_assigned_to, bool) s("reset_qa_contact", reset_qa_contact, bool) s("resolution", resolution) s("severity", severity) s("status", status) s("summary", summary) s("target_milestone", target_milestone) s("target_release", target_release) s("url", url) s("version", version) s("whiteboard", whiteboard) s("work_time", work_time, float) s("flags", flags) s("comment_tags", comment_tags, listify) s("minor_update", minor_update, bool) add_dict("blocks", blocks_add, blocks_remove, blocks_set, convert=int) add_dict("depends_on", depends_on_add, depends_on_remove, depends_on_set, convert=int) add_dict("cc", cc_add, cc_remove) add_dict("groups", groups_add, groups_remove) add_dict("keywords", keywords_add, keywords_remove, keywords_set) add_dict("see_also", see_also_add, see_also_remove) if comment is not None: ret["comment"] = {"comment": comment} if comment_private: ret["comment"]["is_private"] = comment_private ret.update(rhbzret) return ret ######################################## # Methods for working with attachments # ######################################## def attachfile(self, idlist, attachfile, description, **kwargs): """ Attach a file to the given bug IDs. Returns the ID of the attachment or raises XMLRPC Fault if something goes wrong. attachfile may be a filename (which will be opened) or a file-like object, which must provide a 'read' method. If it's not one of these, this method will raise a TypeError. description is the short description of this attachment. Optional keyword args are as follows: file_name: this will be used as the filename for the attachment. REQUIRED if attachfile is a file-like object with no 'name' attribute, otherwise the filename or .name attribute will be used. comment: An optional comment about this attachment. is_private: Set to True if the attachment should be marked private. is_patch: Set to True if the attachment is a patch. content_type: The mime-type of the attached file. Defaults to application/octet-stream if not set. NOTE that text files will *not* be viewable in bugzilla unless you remember to set this to text/plain. So remember that! Returns the list of attachment ids that were added. If only one attachment was added, we return the single int ID for back compat """ if isinstance(attachfile, str): f = open(attachfile, "rb") elif hasattr(attachfile, 'read'): f = attachfile else: raise TypeError("attachfile must be filename or file-like object") # Back compat if "contenttype" in kwargs: kwargs["content_type"] = kwargs.pop("contenttype") if "ispatch" in kwargs: kwargs["is_patch"] = kwargs.pop("ispatch") if "isprivate" in kwargs: kwargs["is_private"] = kwargs.pop("isprivate") if "filename" in kwargs: kwargs["file_name"] = kwargs.pop("filename") kwargs['summary'] = description data = f.read() if not isinstance(data, bytes): # pragma: no cover data = data.encode(locale.getpreferredencoding()) if 'file_name' not in kwargs and hasattr(f, "name"): kwargs['file_name'] = os.path.basename(f.name) if 'content_type' not in kwargs: ctype = None if kwargs['file_name']: ctype = mimetypes.guess_type( kwargs['file_name'], strict=False)[0] kwargs['content_type'] = ctype or 'application/octet-stream' ret = self._backend.bug_attachment_create( listify(idlist), data, kwargs) if "attachments" in ret: # Up to BZ 4.2 ret = [int(k) for k in ret["attachments"].keys()] elif "ids" in ret: # BZ 4.4+ ret = ret["ids"] if isinstance(ret, list) and len(ret) == 1: ret = ret[0] return ret def openattachment_data(self, attachment_dict): """ Helper for turning passed API attachment dictionary into a filelike object """ ret = BytesIO() data = attachment_dict["data"] if hasattr(data, "data"): # This is for xmlrpc Binary content = data.data # pragma: no cover else: import base64 content = base64.b64decode(data) ret.write(content) ret.name = attachment_dict["file_name"] ret.seek(0) return ret def openattachment(self, attachid): """ Get the contents of the attachment with the given attachment ID. Returns a file-like object. """ attachments = self.get_attachments(None, attachid) data = attachments["attachments"][str(attachid)] return self.openattachment_data(data) def updateattachmentflags(self, bugid, attachid, flagname, **kwargs): """ Updates a flag for the given attachment ID. Optional keyword args are: status: new status for the flag ('-', '+', '?', 'X') requestee: new requestee for the flag """ # Bug ID was used for the original custom redhat API, no longer # needed though ignore = bugid flags = {"name": flagname} flags.update(kwargs) attachment_ids = [int(attachid)] update = {'flags': [flags]} return self._backend.bug_attachment_update(attachment_ids, update) def get_attachments(self, ids, attachment_ids, include_fields=None, exclude_fields=None): """ Wrapper for Bug.attachments. One of ids or attachment_ids is required :param ids: Get attachments for this bug ID :param attachment_ids: Specific attachment ID to get https://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#get-attachment """ params = {} if include_fields: params["include_fields"] = listify(include_fields) if exclude_fields: params["exclude_fields"] = listify(exclude_fields) if attachment_ids: return self._backend.bug_attachment_get(attachment_ids, params) return self._backend.bug_attachment_get_all(ids, params) ##################### # createbug methods # ##################### createbug_required = ('product', 'component', 'summary', 'version', 'description') def build_createbug(self, product=None, component=None, version=None, summary=None, description=None, comment_private=None, blocks=None, cc=None, assigned_to=None, keywords=None, depends_on=None, groups=None, op_sys=None, platform=None, priority=None, qa_contact=None, resolution=None, severity=None, status=None, target_milestone=None, target_release=None, url=None, sub_component=None, alias=None, comment_tags=None): """ Returns a python dict() with properly formatted parameters to pass to createbug(). See bugzilla documentation for the format of the individual fields: https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#update-bug """ localdict = {} if blocks: localdict["blocks"] = listify(blocks) if cc: localdict["cc"] = listify(cc) if depends_on: localdict["depends_on"] = listify(depends_on) if groups: localdict["groups"] = listify(groups) if keywords: localdict["keywords"] = listify(keywords) if description: localdict["description"] = description if comment_private: localdict["comment_is_private"] = True # Most of the machinery and formatting here is the same as # build_update, so reuse that as much as possible ret = self.build_update(product=product, component=component, version=version, summary=summary, op_sys=op_sys, platform=platform, priority=priority, qa_contact=qa_contact, resolution=resolution, severity=severity, status=status, target_milestone=target_milestone, target_release=target_release, url=url, assigned_to=assigned_to, sub_component=sub_component, alias=alias, comment_tags=comment_tags) ret.update(localdict) return ret def _validate_createbug(self, *args, **kwargs): # Previous API required users specifying keyword args that mapped # to the XMLRPC arg names. Maintain that bad compat, but also allow # receiving a single dictionary like query() does if kwargs and args: # pragma: no cover raise BugzillaError("createbug: cannot specify positional " "args=%s with kwargs=%s, must be one or the " "other." % (args, kwargs)) if args: if len(args) > 1 or not isinstance(args[0], dict): raise BugzillaError( # pragma: no cover "createbug: positional arguments only " "accept a single dictionary.") data = args[0] else: data = kwargs # If we're getting a call that uses an old fieldname, convert it to the # new fieldname instead. for newname, oldname in self._get_api_aliases(): if (newname in self.createbug_required and newname not in data and oldname in data): data[newname] = data.pop(oldname) # Back compat handling for check_args if "check_args" in data: del(data["check_args"]) return data def createbug(self, *args, **kwargs): """ Create a bug with the given info. Returns a new Bug object. Check bugzilla API documentation for valid values, at least product, component, summary, version, and description need to be passed. """ data = self._validate_createbug(*args, **kwargs) rawbug = self._backend.bug_create(data) return Bug(self, bug_id=rawbug["id"], autorefresh=self.bug_autorefresh) ############################## # Methods for handling Users # ############################## def getuser(self, username): """ Return a bugzilla User for the given username :arg username: The username used in bugzilla. :raises XMLRPC Fault: Code 51 if the username does not exist :returns: User record for the username """ ret = self.getusers(username) return ret and ret[0] def getusers(self, userlist): """ Return a list of Users from . :userlist: List of usernames to lookup :returns: List of User records """ userlist = listify(userlist) rawusers = self._backend.user_get({"names": userlist}) userobjs = [User(self, **rawuser) for rawuser in rawusers.get('users', [])] # Return users in same order they were passed in ret = [] for u in userlist: for uobj in userobjs[:]: if uobj.email == u: userobjs.remove(uobj) ret.append(uobj) break ret += userobjs return ret def searchusers(self, pattern): """ Return a bugzilla User for the given list of patterns :arg pattern: List of patterns to match against. :returns: List of User records """ rawusers = self._backend.user_get({"match": listify(pattern)}) return [User(self, **rawuser) for rawuser in rawusers.get('users', [])] def createuser(self, email, name='', password=''): """ Return a bugzilla User for the given username :arg email: The email address to use in bugzilla :kwarg name: Real name to associate with the account :kwarg password: Password to set for the bugzilla account :raises XMLRPC Fault: Code 501 if the username already exists Code 500 if the email address isn't valid Code 502 if the password is too short Code 503 if the password is too long :return: User record for the username """ args = {"email": email} if name: args["name"] = name if password: args["password"] = password self._backend.user_create(args) return self.getuser(email) def updateperms(self, user, action, groups): """ A method to update the permissions (group membership) of a bugzilla user. :arg user: The e-mail address of the user to be acted upon. Can also be a list of emails. :arg action: add, remove, or set :arg groups: list of groups to be added to (i.e. ['fedora_contrib']) """ groups = listify(groups) if action == "rem": action = "remove" if action not in ["add", "remove", "set"]: raise BugzillaError("Unknown user permission action '%s'" % action) update = { "names": listify(user), "groups": { action: groups, } } return self._backend.user_update(update) ############################### # Methods for handling Groups # ############################### def _getgroups(self, names, membership=False): """ Return a list of groups that match criteria. :kwarg ids: list of group ids to return data on :kwarg membership: boolean specifying wether to query the members of the group or not. :raises XMLRPC Fault: Code 51: if a Bad Login Name was sent to the names array. Code 304: if the user was not authorized to see user they requested. Code 505: user is logged out and can't use the match or ids parameter. Code 805: logged in user do not have enough priviledges to view groups. """ params = {"membership": membership} params['names'] = listify(names) return self._backend.group_get(params) def getgroup(self, name, membership=False): """ Return a bugzilla Group for the given name :arg name: The group name used in bugzilla. :raises XMLRPC Fault: Code 51 if the name does not exist :raises XMLRPC Fault: Code 805 if the user does not have enough permissions to view groups :returns: Group record for the name """ ret = self.getgroups(name, membership=membership) return ret and ret[0] def getgroups(self, grouplist, membership=False): """ Return a list of Groups from . :userlist: List of group names to lookup :returns: List of Group records """ grouplist = listify(grouplist) groupobjs = [ Group(self, **rawgroup) for rawgroup in self._getgroups( names=grouplist, membership=membership).get('groups', []) ] # Return in same order they were passed in ret = [] for g in grouplist: for gobj in groupobjs[:]: if gobj.name == g: groupobjs.remove(gobj) ret.append(gobj) break ret += groupobjs return ret ############################# # ExternalBugs API wrappers # ############################# def add_external_tracker(self, bug_ids, ext_bz_bug_id, ext_type_id=None, ext_type_description=None, ext_type_url=None, ext_status=None, ext_description=None, ext_priority=None): """ Wrapper method to allow adding of external tracking bugs using the ExternalBugs::WebService::add_external_bug method. This is documented at https://bugzilla.redhat.com/docs/en/html/api/extensions/ExternalBugs/lib/WebService.html#add_external_bug bug_ids: A single bug id or list of bug ids to have external trackers added. ext_bz_bug_id: The external bug id (ie: the bug number in the external tracker). ext_type_id: The external tracker id as used by Bugzilla. ext_type_description: The external tracker description as used by Bugzilla. ext_type_url: The external tracker url as used by Bugzilla. ext_status: The status of the external bug. ext_description: The description of the external bug. ext_priority: The priority of the external bug. """ param_dict = {'ext_bz_bug_id': ext_bz_bug_id} if ext_type_id is not None: param_dict['ext_type_id'] = ext_type_id if ext_type_description is not None: param_dict['ext_type_description'] = ext_type_description if ext_type_url is not None: param_dict['ext_type_url'] = ext_type_url if ext_status is not None: param_dict['ext_status'] = ext_status if ext_description is not None: param_dict['ext_description'] = ext_description if ext_priority is not None: param_dict['ext_priority'] = ext_priority params = { 'bug_ids': listify(bug_ids), 'external_bugs': [param_dict], } return self._backend.externalbugs_add(params) def update_external_tracker(self, ids=None, ext_type_id=None, ext_type_description=None, ext_type_url=None, ext_bz_bug_id=None, bug_ids=None, ext_status=None, ext_description=None, ext_priority=None): """ Wrapper method to allow adding of external tracking bugs using the ExternalBugs::WebService::update_external_bug method. This is documented at https://bugzilla.redhat.com/docs/en/html/api/extensions/ExternalBugs/lib/WebService.html#update_external_bug ids: A single external tracker bug id or list of external tracker bug ids. ext_type_id: The external tracker id as used by Bugzilla. ext_type_description: The external tracker description as used by Bugzilla. ext_type_url: The external tracker url as used by Bugzilla. ext_bz_bug_id: A single external bug id or list of external bug ids (ie: the bug number in the external tracker). bug_ids: A single bug id or list of bug ids to have external tracker info updated. ext_status: The status of the external bug. ext_description: The description of the external bug. ext_priority: The priority of the external bug. """ params = {} if ids is not None: params['ids'] = listify(ids) if ext_type_id is not None: params['ext_type_id'] = ext_type_id if ext_type_description is not None: params['ext_type_description'] = ext_type_description if ext_type_url is not None: params['ext_type_url'] = ext_type_url if ext_bz_bug_id is not None: params['ext_bz_bug_id'] = listify(ext_bz_bug_id) if bug_ids is not None: params['bug_ids'] = listify(bug_ids) if ext_status is not None: params['ext_status'] = ext_status if ext_description is not None: params['ext_description'] = ext_description if ext_priority is not None: params['ext_priority'] = ext_priority return self._backend.externalbugs_update(params) def remove_external_tracker(self, ids=None, ext_type_id=None, ext_type_description=None, ext_type_url=None, ext_bz_bug_id=None, bug_ids=None): """ Wrapper method to allow removal of external tracking bugs using the ExternalBugs::WebService::remove_external_bug method. This is documented at https://bugzilla.redhat.com/docs/en/html/api/extensions/ExternalBugs/lib/WebService.html#remove_external_bug ids: A single external tracker bug id or list of external tracker bug ids. ext_type_id: The external tracker id as used by Bugzilla. ext_type_description: The external tracker description as used by Bugzilla. ext_type_url: The external tracker url as used by Bugzilla. ext_bz_bug_id: A single external bug id or list of external bug ids (ie: the bug number in the external tracker). bug_ids: A single bug id or list of bug ids to have external tracker info updated. """ params = {} if ids is not None: params['ids'] = listify(ids) if ext_type_id is not None: params['ext_type_id'] = ext_type_id if ext_type_description is not None: params['ext_type_description'] = ext_type_description if ext_type_url is not None: params['ext_type_url'] = ext_type_url if ext_bz_bug_id is not None: params['ext_bz_bug_id'] = listify(ext_bz_bug_id) if bug_ids is not None: params['bug_ids'] = listify(bug_ids) return self._backend.externalbugs_remove(params) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605204051.0 python-bugzilla-3.0.2/bugzilla/bug.py0000664000175000017500000004154600000000000020037 0ustar00crobinsocrobinso# Copyright (C) 2007, 2008, 2009, 2010 Red Hat Inc. # Author: Will Woods # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import copy from logging import getLogger log = getLogger(__name__) class Bug(object): """ A container object for a bug report. Requires a Bugzilla instance - every Bug is on a Bugzilla, obviously. Optional keyword args: dict=DICT - populate attributes with the result of a getBug() call bug_id=ID - if dict does not contain bug_id, this is required before you can read any attributes or make modifications to this bug. """ def __init__(self, bugzilla, bug_id=None, dict=None, autorefresh=False): # pylint: disable=redefined-builtin # API had pre-existing issue that we can't change ('dict' usage) self.bugzilla = bugzilla self._rawdata = {} self.autorefresh = autorefresh # pylint: disable=protected-access self._aliases = self.bugzilla._get_bug_aliases() # pylint: enable=protected-access if not dict: dict = {} if bug_id: dict["id"] = bug_id self._update_dict(dict) self.weburl = bugzilla.url.replace('xmlrpc.cgi', 'show_bug.cgi?id=%i' % self.bug_id) def __str__(self): """ Return a simple string representation of this bug """ return self.__unicode__() def __unicode__(self): """ Return a simple unicode string representation of this bug """ return "#%-6s %-10s - %s - %s" % (self.bug_id, self.bug_status, self.assigned_to, self.summary) def __repr__(self): url = "" if self.bugzilla: url = self.bugzilla.url return '' % (self.bug_id, url, id(self)) def __getattr__(self, name): refreshed = False while True: if refreshed and name in self.__dict__: # If name was in __dict__ to begin with, __getattr__ would # have never been called. return self.__dict__[name] for newname, oldname in self._aliases: if name == oldname and newname in self.__dict__: return self.__dict__[newname] # Doing dir(bugobj) does getattr __members__/__methods__, # don't refresh for those if name.startswith("__") and name.endswith("__"): break if refreshed or not self.autorefresh: break log.info("Bug %i missing attribute '%s' - doing implicit " "refresh(). This will be slow, if you want to avoid " "this, properly use query/getbug include_fields, and " "set bugzilla.bug_autorefresh = False to force failure.", self.bug_id, name) # We pass the attribute name to getbug, since for something like # 'attachments' which downloads lots of data we really want the # user to opt in. self.refresh(extra_fields=[name]) refreshed = True msg = ("Bug object has no attribute '%s'." % name) if not self.autorefresh: msg += ("\nIf '%s' is a bugzilla attribute, it may not have " "been cached when the bug was fetched. You may want " "to adjust your include_fields for getbug/query." % name) raise AttributeError(msg) def get_raw_data(self): """ Return the raw API dictionary data that has been used to populate this bug """ return copy.deepcopy(self._rawdata) def refresh(self, include_fields=None, exclude_fields=None, extra_fields=None): """ Refresh the bug with the latest data from bugzilla """ # pylint: disable=protected-access extra_fields = list(self._rawdata.keys()) + (extra_fields or []) r = self.bugzilla._getbug(self.bug_id, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields) # pylint: enable=protected-access self._update_dict(r) reload = refresh def _translate_dict(self, newdict): if self.bugzilla: self.bugzilla.post_translation({}, newdict) for newname, oldname in self._aliases: if oldname not in newdict: continue if newname not in newdict: newdict[newname] = newdict[oldname] elif newdict[newname] != newdict[oldname]: log.debug("Update dict contained differing alias values " "d[%s]=%s and d[%s]=%s , dropping the value " "d[%s]", newname, newdict[newname], oldname, newdict[oldname], oldname) del(newdict[oldname]) def _update_dict(self, newdict): """ Update internal dictionary, in a way that ensures no duplicate entries are stored WRT field aliases """ self._translate_dict(newdict) self._rawdata.update(newdict) self.__dict__.update(newdict) if 'id' not in self.__dict__ and 'bug_id' not in self.__dict__: raise TypeError("Bug object needs a bug_id") ################## # pickle helpers # ################## def __getstate__(self): ret = self._rawdata.copy() ret["_aliases"] = self._aliases return ret def __setstate__(self, vals): self._rawdata = {} self.bugzilla = None self._aliases = vals.get("_aliases", []) self.autorefresh = False self._update_dict(vals) ##################### # Modify bug status # ##################### def setstatus(self, status, comment=None, private=False): """ Update the status for this bug report. Commonly-used values are ASSIGNED, MODIFIED, and NEEDINFO. To change bugs to CLOSED, use .close() instead. """ # Note: fedora bodhi uses this function vals = self.bugzilla.build_update(status=status, comment=comment, comment_private=private) log.debug("setstatus: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals) def close(self, resolution, dupeid=None, fixedin=None, comment=None, isprivate=False): """ Close this bug. Valid values for resolution are in bz.querydefaults['resolution_list'] For bugzilla.redhat.com that's: ['NOTABUG', 'WONTFIX', 'DEFERRED', 'WORKSFORME', 'CURRENTRELEASE', 'RAWHIDE', 'ERRATA', 'DUPLICATE', 'UPSTREAM', 'NEXTRELEASE', 'CANTFIX', 'INSUFFICIENT_DATA'] If using DUPLICATE, you need to set dupeid to the ID of the other bug. If using WORKSFORME/CURRENTRELEASE/RAWHIDE/ERRATA/UPSTREAM/NEXTRELEASE you can (and should) set 'new_fixed_in' to a string representing the version that fixes the bug. You can optionally add a comment while closing the bug. Set 'isprivate' to True if you want that comment to be private. """ # Note: fedora bodhi uses this function vals = self.bugzilla.build_update(comment=comment, comment_private=isprivate, resolution=resolution, dupe_of=dupeid, fixed_in=fixedin, status=str("CLOSED")) log.debug("close: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals) ##################### # Modify bug emails # ##################### def setassignee(self, assigned_to=None, qa_contact=None, comment=None): """ Set any of the assigned_to or qa_contact fields to a new bugzilla account, with an optional comment, e.g. setassignee(assigned_to='wwoods@redhat.com') setassignee(qa_contact='wwoods@redhat.com', comment='wwoods QA ftw') You must set at least one of the two assignee fields, or this method will throw a ValueError. Returns [bug_id, mailresults]. """ if not (assigned_to or qa_contact): raise ValueError("You must set one of assigned_to " " or qa_contact") vals = self.bugzilla.build_update(assigned_to=assigned_to, qa_contact=qa_contact, comment=comment) log.debug("setassignee: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals) def addcc(self, cclist, comment=None): """ Adds the given email addresses to the CC list for this bug. cclist: list of email addresses (strings) comment: optional comment to add to the bug """ vals = self.bugzilla.build_update(comment=comment, cc_add=cclist) log.debug("addcc: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals) def deletecc(self, cclist, comment=None): """ Removes the given email addresses from the CC list for this bug. """ vals = self.bugzilla.build_update(comment=comment, cc_remove=cclist) log.debug("deletecc: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals) #################### # comment handling # #################### def addcomment(self, comment, private=False): """ Add the given comment to this bug. Set private to True to mark this comment as private. """ # Note: fedora bodhi uses this function vals = self.bugzilla.build_update(comment=comment, comment_private=private) log.debug("addcomment: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals) def getcomments(self): """ Returns an array of comment dictionaries for this bug """ comment_list = self.bugzilla.get_comments([self.bug_id]) return comment_list['bugs'][str(self.bug_id)]['comments'] ##################### # Get/Set bug flags # ##################### def get_flag_type(self, name): """ Return flag_type information for a specific flag Older RHBugzilla returned a lot more info here, but it was non-upstream and is now gone. """ for t in self.flags: if t['name'] == name: return t return None def get_flags(self, name): """ Return flag value information for a specific flag """ ft = self.get_flag_type(name) if not ft: return None return [ft] def get_flag_status(self, name): """ Return a flag 'status' field This method works only for simple flags that have only a 'status' field with no "requestee" info, and no multiple values. For more complex flags, use get_flags() to get extended flag value information. """ f = self.get_flags(name) if not f: return None # This method works only for simple flags that have only one # value set. assert len(f) <= 1 return f[0]['status'] def updateflags(self, flags): """ Thin wrapper around build_update(flags=X). This only handles simple status changes, anything like needinfo requestee needs to call build_update + update_bugs directly :param flags: Dictionary of the form {"flagname": "status"}, example {"needinfo": "?", "devel_ack": "+"} """ flaglist = [] for key, value in flags.items(): flaglist.append({"name": key, "status": value}) return self.bugzilla.update_bugs([self.bug_id], self.bugzilla.build_update(flags=flaglist)) ######################## # Experimental methods # ######################## def get_attachments(self, include_fields=None, exclude_fields=None): """ Helper call to Bugzilla.get_attachments. If you want to fetch specific attachment IDs, use that function instead """ if "attachments" in self.__dict__: return self.attachments data = self.bugzilla.get_attachments([self.bug_id], None, include_fields, exclude_fields) return data["bugs"][str(self.bug_id)] def get_attachment_ids(self): """ Helper function to return only the attachment IDs for this bug """ return [a["id"] for a in self.get_attachments(exclude_fields=["data"])] def get_history_raw(self): """ Experimental. Get the history of changes for this bug. """ return self.bugzilla.bugs_history_raw([self.bug_id]) class User(object): """ Container object for a bugzilla User. :arg bugzilla: Bugzilla instance that this User belongs to. Rest of the params come straight from User.get() """ def __init__(self, bugzilla, **kwargs): self.bugzilla = bugzilla self.__userid = kwargs.get('id') self.__name = kwargs.get('name') self.__email = kwargs.get('email', self.__name) self.__can_login = kwargs.get('can_login', False) self.real_name = kwargs.get('real_name', None) self.password = None self.groups = kwargs.get('groups', {}) self.groupnames = [] for g in self.groups: if "name" in g: self.groupnames.append(g["name"]) self.groupnames.sort() ######################## # Read-only attributes # ######################## # We make these properties so that the user cannot set them. They are # unaffected by the update() method so it would be misleading to let them # be changed. @property def userid(self): return self.__userid @property def email(self): return self.__email @property def can_login(self): return self.__can_login # name is a key in some methods. Mark it dirty when we change it # @property def name(self): return self.__name def refresh(self): """ Update User object with latest info from bugzilla """ newuser = self.bugzilla.getuser(self.email) self.__dict__.update(newuser.__dict__) def updateperms(self, action, groups): """ A method to update the permissions (group membership) of a bugzilla user. :arg action: add, remove, or set :arg groups: list of groups to be added to (i.e. ['fedora_contrib']) """ self.bugzilla.updateperms(self.name, action, groups) class Group(object): """ Container object for a bugzilla Group. :arg bugzilla: Bugzilla instance that this Group belongs to. Rest of the params come straight from Group.get() """ def __init__(self, bugzilla, **kwargs): self.bugzilla = bugzilla self.__groupid = kwargs.get('id') self.name = kwargs.get('name') self.description = kwargs.get('description', self.name) self.is_active = kwargs.get('is_active', False) self.icon_url = kwargs.get('icon_url', None) self.is_active_bug_group = kwargs.get('is_active_bug_group', None) self.membership = kwargs.get('membership', []) self.__member_emails = set() self._refresh_member_emails_list() ######################## # Read-only attributes # ######################## # We make these properties so that the user cannot set them. They are # unaffected by the update() method so it would be misleading to let them # be changed. @property def groupid(self): return self.__groupid @property def member_emails(self): return sorted(self.__member_emails) def _refresh_member_emails_list(self): """ Refresh the list of emails of the members of the group. """ if self.membership: for m in self.membership: if "email" in m: self.__member_emails.add(m["email"]) def refresh(self, membership=False): """ Update Group object with latest info from bugzilla """ newgroup = self.bugzilla.getgroup( self.name, membership=membership) self.__dict__.update(newgroup.__dict__) self._refresh_member_emails_list() def members(self): """ Retrieve the members of this Group from bugzilla """ if not self.membership: self.refresh(membership=True) return self.membership ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1593804281.0 python-bugzilla-3.0.2/bugzilla/exceptions.py0000664000175000017500000000234200000000000021432 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. class BugzillaError(Exception): """ Error raised in the Bugzilla client code. """ @staticmethod def get_bugzilla_error_string(exc): """ Helper to return the bugzilla instance error message from an XMLRPC Fault, or any other exception type that's raised from bugzilla interaction """ return getattr(exc, "faultString", str(exc)) @staticmethod def get_bugzilla_error_code(exc): """ Helper to return the bugzilla instance error code from an XMLRPC Fault, or any other exception type that's raised from bugzilla interaction """ for propname in ["faultCode", "code"]: if hasattr(exc, propname): return getattr(exc, propname) return None def __init__(self, message, code=None): """ :param code: The error code from the remote bugzilla instance. Only set if the error came directly from the remove bugzilla """ self.code = code if self.code: message += " (code=%s)" % self.code Exception.__init__(self, message) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1593813798.0 python-bugzilla-3.0.2/bugzilla/oldclasses.py0000664000175000017500000000227300000000000021410 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. from .base import Bugzilla # These are old compat classes. Nothing new should be added here, # and these should not be altered class Bugzilla3(Bugzilla): pass class Bugzilla32(Bugzilla): pass class Bugzilla34(Bugzilla): pass class Bugzilla36(Bugzilla): pass class Bugzilla4(Bugzilla): pass class Bugzilla42(Bugzilla): pass class Bugzilla44(Bugzilla): pass class NovellBugzilla(Bugzilla): pass class RHBugzilla(Bugzilla): """ Helper class for historical bugzilla.redhat.com back compat Historically this class used many more non-upstream methods, but in 2012 RH started dropping most of its custom bits. By that time, upstream BZ had most of the important functionality. Much of the remaining code here is just trying to keep things operating in python-bugzilla back compatible manner. This class was written using bugzilla.redhat.com's API docs: https://bugzilla.redhat.com/docs/en/html/api/ """ _is_redhat_bugzilla = True class RHBugzilla3(RHBugzilla): pass class RHBugzilla4(RHBugzilla): pass ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1593814261.0 python-bugzilla-3.0.2/bugzilla/rhbugzilla.py0000664000175000017500000000043000000000000021410 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # This class needs to live in rhbugzilla.py to preserve historical # 'bugzilla.rhbugzilla' import compat from .oldclasses import RHBugzilla # pylint: disable=unused-import ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.033975 python-bugzilla-3.0.2/examples/0000775000175000017500000000000000000000000016703 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/examples/apikey.py0000664000175000017500000000166000000000000020542 0ustar00crobinsocrobinso#!/usr/bin/env python # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # apikey.py: Demostrate prompting for API key and passing it to Bugzilla # pylint: disable=undefined-variable import bugzilla # Don't worry, changing things here is fine, and won't send any email to # users or anything. It's what landfill.bugzilla.org is for! URL = "https://landfill.bugzilla.org/bugzilla-5.0-branch/xmlrpc.cgi" print("You can get an API key at:\n " " https://landfill.bugzilla.org/bugzilla-5.0-branch/userprefs.cgi") print("This is a test site, so no harm will come!\n") api_key = input("Enter Bugzilla API Key: ") # API key usage assumes the API caller is storing the API key; if you would # like to use one of the login options that stores credentials on-disk for # command-line usage, use tokens or cookies. bzapi = bugzilla.Bugzilla(URL, api_key=api_key) assert bzapi.logged_in ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/examples/bug_autorefresh.py0000664000175000017500000000462100000000000022444 0ustar00crobinsocrobinso#!/usr/bin/env python # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # bug_autorefresh.py: Show what bug_autorefresh is all about, and explain # how to handle the default change via python-bugzilla in 2016 import bugzilla # public test instance of bugzilla.redhat.com. It's okay to make changes URL = "partner-bugzilla.redhat.com" bzapi = bugzilla.Bugzilla(URL) # The Bugzilla.bug_autorefresh setting controls whether bugs will # automatically go out and try to update their cached contents when code # tries to access a bug attribute that isn't already cached. # # Note this is likely only relevant if some part of your code is using # include_fields, or exclude_fields, or you are depending on access # to bugzilla.redhat.com 'extra_fields' type data like 'attachments' # without explicitly asking the API for them. If you aren't using any # of those bits, you can ignore this. # # Though if you aren't using include_fields and you are running regular # queries in a script, check examples/query.py for a simple usecase that # shows how much include_fields usage can speed up your scripts. # The default as of mid 2016 is bug_autorefresh=off, so set it True here # to demonstrate bzapi.bug_autorefresh = True bug = bzapi.getbug(427301, include_fields=["id", "summary"]) # The limited include_fields here means that only "id" and "summary" fields # of the bug are cached in the bug object. What happens when we try to # get component for example? print("Bug component=%s" % bug.component) # Because bug_autorefresh is True, the bug object basically did a # a bug.refresh() for us, grabbed all its data, and now the component field # is there. Let's try it again, but this time without bug_autorefresh bzapi.bug_autorefresh = False bug = bzapi.getbug(427301, include_fields=["id", "summary"]) try: print("Shouldn't see this! bug component=%s" % bug.component) except AttributeError: print("With bug_autorefresh=False, we received AttributeError as expected") # Why does this matter? Some scripts are implicitly depending on this # auto-refresh behavior, because their include_fields specification doesn't # cover all attributes they actually use. Your script will work, sure, but # it's likely doing many more API calls than needed, possibly 1 per bug. # So if after upgrading python-bugzilla you start hitting issues, the # recommendation is to fix your include_fields. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/examples/create.py0000664000175000017500000000272300000000000020524 0ustar00crobinsocrobinso#!/usr/bin/env python # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # create.py: Create a new bug report import time import bugzilla # public test instance of bugzilla.redhat.com. # # Don't worry, changing things here is fine, and won't send any email to # users or anything. It's what partner-bugzilla.redhat.com is for! URL = "partner-bugzilla.redhat.com" bzapi = bugzilla.Bugzilla(URL) if not bzapi.logged_in: print("This example requires cached login credentials for %s" % URL) bzapi.interactive_login() # Similar to build_query, build_createbug is a helper function that handles # some bugzilla version incompatibility issues. All it does is return a # properly formatted dict(), and provide friendly parameter names. # The argument names map to those accepted by Bugzilla Bug.create: # https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#create-bug # # The arguments specified here are mandatory, but there are many other # optional ones like op_sys, platform, etc. See the docs createinfo = bzapi.build_createbug( product="Fedora", version="rawhide", component="python-bugzilla", summary="new example python-bugzilla bug %s" % time.time(), description="This is comment #0 of an example bug created by " "the python-bugzilla.git examples/create.py script.") newbug = bzapi.createbug(createinfo) print("Created new bug id=%s url=%s" % (newbug.id, newbug.weburl)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/examples/getbug.py0000664000175000017500000000252200000000000020533 0ustar00crobinsocrobinso#!/usr/bin/env python # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # getbug.py: Simple demonstration of connecting to bugzilla, fetching # a bug, and printing some details. import pprint import bugzilla # public test instance of bugzilla.redhat.com. It's okay to make changes URL = "partner-bugzilla.redhat.com" bzapi = bugzilla.Bugzilla(URL) # getbug() is just a simple wrapper around getbugs(), which takes a list # IDs, if you need to fetch multiple # # Example bug: https://partner-bugzilla.redhat.com/show_bug.cgi?id=427301 bug = bzapi.getbug(427301) print("Fetched bug #%s:" % bug.id) print(" Product = %s" % bug.product) print(" Component = %s" % bug.component) print(" Status = %s" % bug.status) print(" Resolution= %s" % bug.resolution) print(" Summary = %s" % bug.summary) # Just check dir(bug) for other attributes, or check upstream bugzilla # Bug.get docs for field names: # https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#get-bug # comments must be fetched separately on stock bugzilla. this just returns # a raw dict with all the info. comments = bug.getcomments() print("\nLast comment data:\n%s" % pprint.pformat(comments[-1])) # getcomments is just a wrapper around bzapi.get_comments(), which can be # used for bulk comments fetching ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/examples/getbug_restapi.py0000664000175000017500000000203200000000000022256 0ustar00crobinsocrobinso#!/usr/bin/env python # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # getbug_restapi.py: # Simple demonstration of connecting to bugzilla over the REST # API and printing some bug details. import bugzilla # public test instance of bugzilla.redhat.com. It's okay to make changes URL = "partner-bugzilla.redhat.com" # By default, if plain Bugzilla(URL) is invoked, the Bugzilla class will # attempt to determine if XMLRPC or REST API is available, with a preference # for XMLRPC for back compatability. But you can use the REST API # with force_rest=True bzapi = bugzilla.Bugzilla(URL, force_rest=True) # After that, the bugzilla API can be used as normal. See getbug.py for # some more info here. bug = bzapi.getbug(427301) print("Fetched bug #%s:" % bug.id) print(" Product = %s" % bug.product) print(" Component = %s" % bug.component) print(" Status = %s" % bug.status) print(" Resolution= %s" % bug.resolution) print(" Summary = %s" % bug.summary) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/examples/query.py0000664000175000017500000000615700000000000020433 0ustar00crobinsocrobinso#!/usr/bin/env python # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # query.py: Perform a few varieties of queries import time import bugzilla # public test instance of bugzilla.redhat.com. It's okay to make changes URL = "partner-bugzilla.redhat.com" bzapi = bugzilla.Bugzilla(URL) # build_query is a helper function that handles some bugzilla version # incompatibility issues. All it does is return a properly formatted # dict(), and provide friendly parameter names. The param names map # to those accepted by Bugzilla Bug.search: # https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#search-bugs query = bzapi.build_query( product="Fedora", component="python-bugzilla") # Since 'query' is just a dict, you could set your own parameters too, like # if your bugzilla had a custom field. This will set 'status' for example, # but for common opts it's better to use build_query query["status"] = "CLOSED" # query() is what actually performs the query. it's a wrapper around Bug.search t1 = time.time() bugs = bzapi.query(query) t2 = time.time() print("Found %d bugs with our query" % len(bugs)) print("Query processing time: %s" % (t2 - t1)) # Depending on the size of your query, you can massively speed things up # by telling bugzilla to only return the fields you care about, since a # large chunk of the return time is transmitting the extra bug data. You # tweak this with include_fields: # https://wiki.mozilla.org/Bugzilla:BzAPI#Field_Control # Bugzilla will only return those fields listed in include_fields. query = bzapi.build_query( product="Fedora", component="python-bugzilla", include_fields=["id", "summary"]) t1 = time.time() bugs = bzapi.query(query) t2 = time.time() print("Quicker query processing time: %s" % (t2 - t1)) # bugzilla.redhat.com, and bugzilla >= 5.0 support queries using the same # format as is used for 'advanced' search URLs via the Web UI. For example, # I go to partner-bugzilla.redhat.com -> Search -> Advanced Search, select # Classification=Fedora # Product=Fedora # Component=python-bugzilla # Unselect all bug statuses (so, all status values) # Under Custom Search # Creation date -- is less than or equal to -- 2010-01-01 # # Run that, copy the URL and bring it here, pass it to url_to_query to # convert it to a dict(), and query as usual query = bzapi.url_to_query("https://partner-bugzilla.redhat.com/" "buglist.cgi?classification=Fedora&component=python-bugzilla&" "f1=creation_ts&o1=lessthaneq&order=Importance&product=Fedora&" "query_format=advanced&v1=2010-01-01") query["include_fields"] = ["id", "summary"] bugs = bzapi.query(query) print("The URL query returned 22 bugs... " "I know that without even checking because it shouldn't change!... " "(count is %d)" % len(bugs)) # One note about querying... you can get subtley different results if # you are not logged in. Depending on your bugzilla setup it may not matter, # but if you are dealing with private bugs, check bzapi.logged_in setting # to ensure your cached credentials are up to date. See update.py for # an example usage ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/examples/update.py0000664000175000017500000000430200000000000020536 0ustar00crobinsocrobinso#!/usr/bin/env python # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # update.py: Make changes to an existing bug import time import bugzilla # public test instance of bugzilla.redhat.com. It's okay to make changes URL = "partner-bugzilla.redhat.com" bzapi = bugzilla.Bugzilla(URL) if not bzapi.logged_in: print("This example requires cached login credentials for %s" % URL) bzapi.interactive_login() # Similar to build_query, build_update is a helper function that handles # some bugzilla version incompatibility issues. All it does is return a # properly formatted dict(), and provide friendly parameter names. # The param names map to those accepted by Bugzilla Bug.update: # https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#update-bug # # Example bug: https://partner-bugzilla.redhat.com/show_bug.cgi?id=427301 # Don't worry, changing things here is fine, and won't send any email to # users or anything. It's what partner-bugzilla.redhat.com is for! bug = bzapi.getbug(427301) print("Bug id=%s original summary=%s" % (bug.id, bug.summary)) update = bzapi.build_update(summary="new example summary %s" % time.time()) bzapi.update_bugs([bug.id], update) # Call bug.refresh() to update its cached state bug.refresh() print("Bug id=%s new summary=%s" % (bug.id, bug.summary)) # Now let's add a comment comments = bug.getcomments() print("Bug originally has %d comments" % len(comments)) update = bzapi.build_update(comment="new example comment %s" % time.time()) bzapi.update_bugs([bug.id], update) # refresh() actually isn't required here because comments are fetched # on demand comments = bug.getcomments() print("Bug now has %d comments. Last comment=%s" % (len(comments), comments[-1]["text"])) # The 'bug' object actually has some old convenience APIs for specific # actions like commenting, and closing. However these aren't recommended: # they encourage splitting up bug edits when really batching should be done # as much as possible, not only to make your code quicker and save strain # on the bugzilla instance, but also to avoid spamming bugzilla users with # redundant email from two modifications that could have been batched. ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.033975 python-bugzilla-3.0.2/man/0000775000175000017500000000000000000000000015640 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1604419208.0 python-bugzilla-3.0.2/man/bugzilla.10000664000175000017500000004024500000000000017540 0ustar00crobinsocrobinso.\" Man page generated from reStructuredText. . .TH BUGZILLA 1 "" "" "User Commands" .SH NAME bugzilla \- command line tool for interacting with Bugzilla . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .SH SYNOPSIS .sp \fBbugzilla\fP [\fIoptions\fP] [\fIcommand\fP] [\fIcommand\-options\fP] .SH DESCRIPTION .sp \fBbugzilla\fP is a command line tool for interacting with a Bugzilla instance over REST or XMLRPC. .nf \fIcommand\fP is one of: * login \- log into the given bugzilla instance * new \- create a new bug * query \- search for bugs matching given criteria * modify \- modify existing bugs * attach \- attach files to existing bugs, or get attachments * info \- get info about the given bugzilla instance .fi .sp .SH GLOBAL OPTIONS .SS \fB\-\-help, \-h\fP .sp \fBSyntax:\fP \fB\-h\fP .sp show this help message and exit .SS \fB\-\-bugzilla\fP .sp \fBSyntax:\fP \fB\-\-bugzilla\fP BUGZILLA .sp The bugzilla URL. Full API URLs are typically like: .nf * \fI\%https://bugzilla.example.com/xmlrpc.cgi\fP # XMLRPC API * \fI\%https://bugzilla.example.com/rest/\fP # REST API .fi .sp .sp If a non\-specific URL is passed, like \(aqbugzilla.redhat.com\(aq, \fBbugzilla\fP will try to probe whether the expected XMLRPC or REST path is available, preferring XMLRPC for backwards compatibility. .sp The default URL \fI\%https://bugzilla.redhat.com\fP .SS \fB\-\-nosslverify\fP .sp \fBSyntax:\fP \fB\-\-nosslverify\fP .sp Don\(aqt error on invalid bugzilla SSL certificate .SS \fB\-\-cert\fP .sp \fBSyntax:\fP \fB\-\-cert\fP CERTFILE .sp client side certificate file needed by the webserver. .SS \fB\-\-login\fP .sp \fBSyntax:\fP \fB\-\-login\fP .sp Run interactive "login" before performing the specified command. .SS \fB\-\-username\fP .sp \fBSyntax:\fP \fB\-\-username\fP USERNAME .sp Log in with this username .SS \fB\-\-password\fP .sp \fBSyntax:\fP \fB\-\-password\fP PASSWORD .sp Log in with this password .SS \fB\-\-restrict\-login\fP .sp \fBSyntax:\fP \fB\-\-restrict\-login\fP .sp The session (login token) will be restricted to the current IP address. .SS \fB\-\-ensure\-logged\-in\fP .sp \fBSyntax:\fP \fB\-\-ensure\-logged\-in\fP .sp Raise an error if we aren\(aqt logged in to bugzilla. Consider using this if you are depending on cached credentials, to ensure that when they expire the tool errors, rather than subtly change output. .SS \fB\-\-no\-cache\-credentials\fP .sp \fBSyntax:\fP \fB\-\-no\-cache\-credentials\fP .sp Don\(aqt save any bugzilla cookies or tokens to disk, and don\(aqt use any pre\-existing credentials. .SS \fB\-\-cookiefile\fP .sp \fBSyntax:\fP \fB\-\-cookiefile\fP COOKIEFILE .sp cookie file to use for bugzilla authentication .SS \fB\-\-tokenfile\fP .sp \fBSyntax:\fP \fB\-\-tokenfile\fP TOKENFILE .sp token file to use for bugzilla authentication .SS \fB\-\-verbose\fP .sp \fBSyntax:\fP \fB\-\-verbose\fP .sp give more info about what\(aqs going on .SS \fB\-\-debug\fP .sp \fBSyntax:\fP \fB\-\-debug\fP .sp output bunches of debugging info .SS \fB\-\-version\fP .sp \fBSyntax:\fP \fB\-\-version\fP .sp show program\(aqs version number and exit .SH STANDARD BUGZILLA OPTIONS .sp These options are shared by some combination of the \(aqnew\(aq, \(aqquery\(aq, and \(aqmodify\(aq sub commands. Not every option works for each command though. .SS \fB\-p, \-\-product\fP .sp \fBSyntax:\fP \fB\-\-product\fP PRODUCT .sp Product name .SS \fB\-v, \-\-version\fP .sp \fBSyntax:\fP \fB\-\-version\fP VERSION .sp Product version .SS \fB\-c, \-\-component\fP .sp \fBSyntax:\fP \fB\-\-component\fP COMPONENT .sp Component name .SS \fB\-s, \-\-summary\fP .sp \fBSyntax:\fP \fB\-\-summary\fP SUMMARY .sp Bug summary .SS \fB\-l, \-\-comment\fP .sp \fBSyntax:\fP \fB\-\-comment\fP DESCRIPTION .sp Set initial bug comment/description .SS \fB\-\-comment\-tag\fP .sp \fBSyntax:\fP \fB\-\-comment\-tag\fP TAG .sp Comment tag for the new comment .SS \fB\-\-sub\-component\fP .sp \fBSyntax:\fP \fB\-\-sub\-component\fP SUB_COMPONENT .sp RHBZ sub component name .SS \fB\-o, \-\-os\fP .sp \fBSyntax:\fP \fB\-\-os\fP OS .sp Operating system .SS \fB\-\-arch\fP .sp \fBSyntax:\fP \fB\-\-arch\fP ARCH .sp Arch this bug occurs on .SS \fB\-x, \-\-severity\fP .sp \fBSyntax:\fP \fB\-\-severity\fP SEVERITY .sp Bug severity .SS \fB\-z, \-\-priority\fP .sp \fBSyntax:\fP \fB\-\-priority\fP PRIORITY .sp Bug priority .SS \fB\-\-alias\fP .sp \fBSyntax:\fP \fB\-\-alias\fP ALIAS .sp Bug alias (name) .SS \fB\-s, \-\-status\fP .sp \fBSyntax:\fP \fB\-\-status\fP STATUS .sp Bug status (NEW, ASSIGNED, etc.) .SS \fB\-u, \-\-url\fP .sp \fBSyntax:\fP \fB\-\-url\fP URL .sp URL for further bug info .SS \fB\-m \-\-target_milestone\fP .sp \fBSyntax:\fP \fB\-\-target_milestone\fP TARGET_MILESTONE .sp Target milestone .SS \fB\-\-target_release\fP .sp \fBSyntax:\fP \fB\-\-target_release\fP TARGET_RELEASE .sp RHBZ Target release .SS \fB\-\-blocked\fP .sp \fBSyntax:\fP \fB\&...]\fP .sp Bug IDs that this bug blocks .SS \fB\-\-dependson\fP .sp \fBSyntax:\fP \fB\&...]\fP .sp Bug IDs that this bug depends on .SS \fB\-\-keywords\fP .sp \fBSyntax:\fP \fB\&...]\fP .sp Bug keywords .SS \fB\-\-groups\fP .sp \fBSyntax:\fP \fB\&...]\fP .sp Which user groups can view this bug .SS \fB\-\-cc\fP .sp \fBSyntax:\fP \fB\&...]\fP .sp CC list .SS \fB\-a, \-\-assignee, \-\-assigned_to\fP .sp \fBSyntax:\fP \fB\-\-assigned_to\fP ASSIGNED_TO .sp Bug assignee .SS \fB\-q, \-\-qa_contact\fP .sp \fBSyntax:\fP \fB\-\-qa_contact\fP QA_CONTACT .sp QA contact .SS \fB\-\-flag\fP .sp \fBSyntax:\fP \fB\-\-flag\fP FLAG .sp Set or unset a flag. For example, to set a flag named devel_ack, do \-\-flag devel_ack+ Unset a flag with the \(aqX\(aq value, like \-\-flag needinfoX .SS \fB\-\-tags\fP .sp \fBSyntax:\fP \fB\-\-tags\fP TAG .sp Set (personal) tags field .SS \fB\-w, \-\-whiteboard\fP .sp \fBSyntax:\fP \fB\-\-whiteboard\fP WHITEBOARD .sp Whiteboard field .SS \fB\-\-devel_whiteboard\fP .sp \fBSyntax:\fP \fB\-\-devel_whiteboard\fP DEVEL_WHITEBOARD .sp RHBZ devel whiteboard field .SS \fB\-\-internal_whiteboard\fP .sp \fBSyntax:\fP \fB\-\-internal_whiteboard\fP INTERNAL_WHITEBOARD .sp RHBZ internal whiteboard field .SS \fB\-\-qa_whiteboard\fP .sp \fBSyntax:\fP \fB\-\-qa_whiteboard\fP QA_WHITEBOARD .sp RHBZ QA whiteboard field .SS \fB\-F, \-\-fixed_in\fP .sp \fBSyntax:\fP \fB\-\-fixed_in\fP FIXED_IN .sp RHBZ \(aqFixed in version\(aq field .SS \fB\-\-field\fP .sp \fBSyntax:\fP \fB\-\-field\fP FIELD\(ga\(ga VALUE .sp Manually specify a bugzilla API field. FIELD is the raw name used by the bugzilla instance. For example if your bugzilla instance has a custom field cf_my_field, do: \-\-field cf_my_field=VALUE .SH OUTPUT OPTIONS .sp These options are shared by several commands, for tweaking the text output of the command results. .SS \fB\-f, \-\-full\fP .sp \fBSyntax:\fP \fB\-\-full\fP .sp output detailed bug info .SS \fB\-i, \-\-ids\fP .sp \fBSyntax:\fP \fB\-\-ids\fP .sp output only bug IDs .SS \fB\-e, \-\-extra\fP .sp \fBSyntax:\fP \fB\-\-extra\fP .sp output additional bug information (keywords, Whiteboards, etc.) .SS \fB\-\-oneline\fP .sp \fBSyntax:\fP \fB\-\-oneline\fP .sp one line summary of the bug (useful for scripts) .SS \fB\-\-json\fP .sp \fBSyntax:\fP \fB\-\-json\fP .sp output bug contents in JSON format .SS \fB\-\-includefield\fP .sp \fBSyntax:\fP \fB\-\-includefield\fP .sp Pass the field name to bugzilla include_fields list. Only the fields passed to include_fields are returned by the bugzilla server. This can be specified multiple times. .SS \fB\-\-extrafield\fP .sp \fBSyntax:\fP \fB\-\-extrafield\fP .sp Pass the field name to bugzilla extra_fields list. When used with \-\-json this can be used to request bugzilla to return values for non\-default fields. This can be specified multiple times. .SS \fB\-\-excludefield\fP .sp \fBSyntax:\fP \fB\-\-excludefield\fP .sp Pass the field name to bugzilla exclude_fields list. When used with \-\-json this can be used to request bugzilla to not return values for a field. This can be specified multiple times. .SS \fB\-\-raw\fP .sp \fBSyntax:\fP \fB\-\-raw\fP .sp raw output of the bugzilla contents. This format is unstable and difficult to parse. Please use the \fB\-\-json\fP instead if you want maximum output from the \fIbugzilla\fP .SS \fB\-\-outputformat\fP .sp \fBSyntax:\fP \fB\-\-outputformat\fP OUTPUTFORMAT .sp Print output in the form given. You can use RPM\-style tags that match bug fields, e.g.: \(aq%{id}: %{summary}\(aq. .sp The output of the bugzilla tool should NEVER BE PARSED unless you are using a custom \-\-outputformat. For everything else, just don\(aqt parse it, the formats are not stable and are subject to change. .sp \-\-outputformat allows printing arbitrary bug data in a user preferred format. For example, to print a returned bug ID, component, and product, separated with ::, do: .sp \-\-outputformat "%{id}::%{component}::%{product}" .sp The fields (like \(aqid\(aq, \(aqcomponent\(aq, etc.) are the names of the values returned by bugzilla\(aqs API. To see a list of all fields, check the API documentation in the \(aqSEE ALSO\(aq section. Alternatively, run a \(aqbugzilla \-\-debug query ...\(aq and look at the key names returned in the query results. Also, in most cases, using the name of the associated command line switch should work, like \-\-bug_status becomes %{bug_status}, etc. .SH ‘QUERY’ SPECIFIC OPTIONS .sp Certain options can accept a comma separated list to query multiple values, including \-\-status, \-\-component, \-\-product, \-\-version, \-\-id. .sp Note: querying via explicit command line options will only get you so far. See the \-\-from\-url option for a way to use powerful Web UI queries from the command line. .SS \fB\-b, \-\-bug_id, \-\-id\fP .sp \fBSyntax:\fP \fB\-\-id\fP ID .sp specify individual bugs by IDs, separated with commas .SS \fB\-r, \-\-reporter\fP .sp \fBSyntax:\fP \fB\-\-reporter\fP REPORTER .sp Email: search reporter email for given address .SS \fB\-\-quicksearch\fP .sp \fBSyntax:\fP \fB\-\-quicksearch\fP QUICKSEARCH .sp Search using bugzilla\(aqs quicksearch functionality. .SS \fB\-\-savedsearch\fP .sp \fBSyntax:\fP \fB\-\-savedsearch\fP SAVEDSEARCH .sp Name of a bugzilla saved search. If you don\(aqt own this saved search, you must passed \-\-savedsearch_sharer_id. .SS \fB\-\-savedsearch\-sharer\-id\fP .sp \fBSyntax:\fP \fB\-\-savedsearch\-sharer\-id\fP SAVEDSEARCH_SHARER_ID .sp Owner ID of the \-\-savedsearch. You can get this ID from the URL bugzilla generates when running the saved search from the web UI. .SS \fB\-\-from\-url\fP .sp \fBSyntax:\fP \fB\-\-from\-url\fP WEB_QUERY_URL .sp Make a working query via bugzilla\(aqs \(aqAdvanced search\(aq web UI, grab the url from your browser (the string with query.cgi or buglist.cgi in it), and \-\-from\-url will run it via the bugzilla API. Don\(aqt forget to quote the string! This only works for Bugzilla 5 and Red Hat bugzilla .SH ‘MODIFY’ SPECIFIC OPTIONS .sp Fields that take multiple values have a special input format. .nf Append: \fI\%\-\-cc=foo@example.com\fP Overwrite: \fI\%\-\-cc==foo@example.com\fP Remove: \fI\%\-\-cc=\-foo@example.com\fP .fi .sp .sp Options that accept this format: \-\-cc, \-\-blocked, \-\-dependson, \-\-groups, \-\-tags, whiteboard fields. .SS \fB\-k, \-\-close RESOLUTION\fP .sp \fBSyntax:\fP \fBRESOLUTION\fP .sp Close with the given resolution (WONTFIX, NOTABUG, etc.) .SS \fB\-d, \-\-dupeid\fP .sp \fBSyntax:\fP \fB\-\-dupeid\fP ORIGINAL .sp ID of original bug. Implies \-\-close DUPLICATE .SS \fB\-\-private\fP .sp \fBSyntax:\fP \fB\-\-private\fP .sp Mark new comment as private .SS \fB\-\-reset\-assignee\fP .sp \fBSyntax:\fP \fB\-\-reset\-assignee\fP .sp Reset assignee to component default .SS \fB\-\-reset\-qa\-contact\fP .sp \fBSyntax:\fP \fB\-\-reset\-qa\-contact\fP .sp Reset QA contact to component default .SS \fB\-\-minor\-update\fP .sp \fBSyntax:\fP \fB\-\-minor\-update\fP .sp Request bugzilla to not send any email about this change .SH ‘NEW’ SPECIFIC OPTIONS .SS \fB\-\-private\fP .sp \fBSyntax:\fP \fB\-\-private\fP .sp Mark new comment as private .SH ‘ATTACH’ OPTIONS .SS \fB\-f, \-\-file\fP .sp \fBSyntax:\fP \fB\-\-file\fP FILENAME .sp File to attach, or filename for data provided on stdin .SS \fB\-d, \-\-description\fP .sp \fBSyntax:\fP \fB\-\-description\fP DESCRIPTION .sp A short description of the file being attached .SS \fB\-t, \-\-type\fP .sp \fBSyntax:\fP \fB\-\-type\fP MIMETYPE .sp Mime\-type for the file being attached .SS \fB\-g, \-\-get\fP .sp \fBSyntax:\fP \fB\-\-get\fP ATTACHID .sp Download the attachment with the given ID .SS \fB\-\-getall\fP .sp \fBSyntax:\fP \fB\-\-getall\fP BUGID .sp Download all attachments on the given bug .SS \fB\-\-ignore\-obsolete\fP .sp \fBSyntax:\fP \fB\-\-ignore\-obsolete\fP .sp Do not download attachments marked as obsolete. .SS \fB\-l, \-\-comment\fP .sp \fBSyntax:\fP \fB\-\-comment\fP COMMENT .sp Add comment with attachment .SH ‘INFO’ OPTIONS .SS \fB\-p, \-\-products\fP .sp \fBSyntax:\fP \fB\-\-products\fP .sp Get a list of products .SS \fB\-c, \-\-components\fP .sp \fBSyntax:\fP \fB\-\-components\fP PRODUCT .sp List the components in the given product .SS \fB\-o, \-\-component_owners\fP .sp \fBSyntax:\fP \fB\-\-component_owners\fP PRODUCT .sp List components (and their owners) .SS \fB\-v, \-\-versions\fP .sp \fBSyntax:\fP \fB\-\-versions\fP PRODUCT .sp List the versions for the given product .SS \fB\-\-active\-components\fP .sp \fBSyntax:\fP \fB\-\-active\-components\fP .sp Only show active components. Combine with \-\-components* .SH AUTHENTICATION CACHE AND API KEYS .sp Some command usage will require an active login to the bugzilla instance. For example, if the bugzilla instance has some private bugs, those bugs will be missing from \(aqquery\(aq output if you do not have an active login. .sp If you are connecting to a bugzilla 5.0 or later instance, the best option is to use bugzilla API keys. From the bugzilla web UI, log in, navigate to Preferences\->API Keys, and generate a key (it will be a long string of characters and numbers). Then create a ~/.config/python\-bugzilla/bugzillarc like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cat ~/.config/python\-bugzilla/bugzillarc [bugzilla.example.com] api_key=YOUR_API_KEY .ft P .fi .UNINDENT .UNINDENT .sp Replace \(aqbugzilla.example.com\(aq with your bugzilla host name, and YOUR_API_KEY with the generated API Key from the Web UI. .sp Alternatively, you can use \(aqbugzilla login \-\-api\-key\(aq, which will ask for the API key, and save it to bugzillarc for you. .sp For older bugzilla instances, you will need to cache a login cookie or token with the "login" subcommand or the "\-\-login" argument. .sp Additionally, the \-\-no\-cache\-credentials option will tell the bugzilla tool to \fInot\fP save or use any authentication cache, including the bugzillarc file. .SH EXAMPLES .nf bugzilla query \-\-bug_id 62037 bugzilla query \-\-version 15 \-\-component python\-bugzilla bugzilla login bugzilla new \-p Fedora \-v rawhide \-c python\-bugzilla \e .in +2 \-\-summary "python\-bugzilla causes headaches" \e \-\-comment "python\-bugzilla made my brain hurt when I used it." .in -2 bugzilla attach \-\-file ~/Pictures/cam1.jpg \-\-desc "me, in pain" $BUGID bugzilla attach \-\-getall $BUGID bugzilla modify \-\-close NOTABUG \-\-comment "Actually, you\(aqre hungover." $BUGID .fi .sp .SH EXIT STATUS .sp \fBbugzilla\fP normally returns 0 if the requested command was successful. Otherwise, exit status is 1 if \fBbugzilla\fP is interrupted by the user (or a login attempt fails), 2 if a socket error occurs (e.g. TCP connection timeout), and 3 if the Bugzilla server throws an error. .SH BUGS .sp Please report any bugs as github issues at \fI\%https://github.com/python\-bugzilla/python\-bugzilla\fP .SH SEE ALSO .sp \fI\%https://bugzilla.readthedocs.io/en/latest/api/index.html\fP \fI\%https://bugzilla.redhat.com/docs/en/html/api/Bugzilla/WebService/Bug.html\fP .\" Generated by docutils manpage writer. . ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/man/bugzilla.rst0000664000175000017500000003637600000000000020222 0ustar00crobinsocrobinso======== bugzilla ======== ----------------------------------------------- command line tool for interacting with Bugzilla ----------------------------------------------- :Manual section: 1 :Manual group: User Commands SYNOPSIS ======== **bugzilla** [*options*] [*command*] [*command-options*] DESCRIPTION =========== **bugzilla** is a command line tool for interacting with a Bugzilla instance over REST or XMLRPC. | | *command* is one of: | * login - log into the given bugzilla instance | * new - create a new bug | * query - search for bugs matching given criteria | * modify - modify existing bugs | * attach - attach files to existing bugs, or get attachments | * info - get info about the given bugzilla instance GLOBAL OPTIONS ============== ``--help, -h`` ^^^^^^^^^^^^^^ **Syntax:** ``-h`` show this help message and exit ``--bugzilla`` ^^^^^^^^^^^^^^ **Syntax:** ``--bugzilla`` BUGZILLA The bugzilla URL. Full API URLs are typically like: | | * https://bugzilla.example.com/xmlrpc.cgi # XMLRPC API | * https://bugzilla.example.com/rest/ # REST API | If a non-specific URL is passed, like 'bugzilla.redhat.com', **bugzilla** will try to probe whether the expected XMLRPC or REST path is available, preferring XMLRPC for backwards compatibility. The default URL https://bugzilla.redhat.com ``--nosslverify`` ^^^^^^^^^^^^^^^^^ **Syntax:** ``--nosslverify`` Don't error on invalid bugzilla SSL certificate ``--cert`` ^^^^^^^^^^ **Syntax:** ``--cert`` CERTFILE client side certificate file needed by the webserver. ``--login`` ^^^^^^^^^^^ **Syntax:** ``--login`` Run interactive "login" before performing the specified command. ``--username`` ^^^^^^^^^^^^^^ **Syntax:** ``--username`` USERNAME Log in with this username ``--password`` ^^^^^^^^^^^^^^ **Syntax:** ``--password`` PASSWORD Log in with this password ``--restrict-login`` ^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--restrict-login`` The session (login token) will be restricted to the current IP address. ``--ensure-logged-in`` ^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--ensure-logged-in`` Raise an error if we aren't logged in to bugzilla. Consider using this if you are depending on cached credentials, to ensure that when they expire the tool errors, rather than subtly change output. ``--no-cache-credentials`` ^^^^^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--no-cache-credentials`` Don't save any bugzilla cookies or tokens to disk, and don't use any pre-existing credentials. ``--cookiefile`` ^^^^^^^^^^^^^^^^ **Syntax:** ``--cookiefile`` COOKIEFILE cookie file to use for bugzilla authentication ``--tokenfile`` ^^^^^^^^^^^^^^^ **Syntax:** ``--tokenfile`` TOKENFILE token file to use for bugzilla authentication ``--verbose`` ^^^^^^^^^^^^^ **Syntax:** ``--verbose`` give more info about what's going on ``--debug`` ^^^^^^^^^^^ **Syntax:** ``--debug`` output bunches of debugging info ``--version`` ^^^^^^^^^^^^^ **Syntax:** ``--version`` show program's version number and exit Standard bugzilla options ========================= These options are shared by some combination of the 'new', 'query', and 'modify' sub commands. Not every option works for each command though. ``-p, --product`` ^^^^^^^^^^^^^^^^^ **Syntax:** ``--product`` PRODUCT Product name ``-v, --version`` ^^^^^^^^^^^^^^^^^ **Syntax:** ``--version`` VERSION Product version ``-c, --component`` ^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--component`` COMPONENT Component name ``-s, --summary`` ^^^^^^^^^^^^^^^^^ **Syntax:** ``--summary`` SUMMARY Bug summary ``-l, --comment`` ^^^^^^^^^^^^^^^^^ **Syntax:** ``--comment`` DESCRIPTION Set initial bug comment/description ``--comment-tag`` ^^^^^^^^^^^^^^^^^ **Syntax:** ``--comment-tag`` TAG Comment tag for the new comment ``--sub-component`` ^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--sub-component`` SUB_COMPONENT RHBZ sub component name ``-o, --os`` ^^^^^^^^^^^^ **Syntax:** ``--os`` OS Operating system ``--arch`` ^^^^^^^^^^ **Syntax:** ``--arch`` ARCH Arch this bug occurs on ``-x, --severity`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--severity`` SEVERITY Bug severity ``-z, --priority`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--priority`` PRIORITY Bug priority ``--alias`` ^^^^^^^^^^^ **Syntax:** ``--alias`` ALIAS Bug alias (name) ``-s, --status`` ^^^^^^^^^^^^^^^^ **Syntax:** ``--status`` STATUS Bug status (NEW, ASSIGNED, etc.) ``-u, --url`` ^^^^^^^^^^^^^ **Syntax:** ``--url`` URL URL for further bug info ``-m --target_milestone`` ^^^^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--target_milestone`` TARGET_MILESTONE Target milestone ``--target_release`` ^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--target_release`` TARGET_RELEASE RHBZ Target release ``--blocked`` ^^^^^^^^^^^^^ **Syntax:** ``...]`` Bug IDs that this bug blocks ``--dependson`` ^^^^^^^^^^^^^^^ **Syntax:** ``...]`` Bug IDs that this bug depends on ``--keywords`` ^^^^^^^^^^^^^^ **Syntax:** ``...]`` Bug keywords ``--groups`` ^^^^^^^^^^^^ **Syntax:** ``...]`` Which user groups can view this bug ``--cc`` ^^^^^^^^ **Syntax:** ``...]`` CC list ``-a, --assignee, --assigned_to`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--assigned_to`` ASSIGNED_TO Bug assignee ``-q, --qa_contact`` ^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--qa_contact`` QA_CONTACT QA contact ``--flag`` ^^^^^^^^^^ **Syntax:** ``--flag`` FLAG Set or unset a flag. For example, to set a flag named devel_ack, do --flag devel_ack+ Unset a flag with the 'X' value, like --flag needinfoX ``--tags`` ^^^^^^^^^^ **Syntax:** ``--tags`` TAG Set (personal) tags field ``-w, --whiteboard`` ^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--whiteboard`` WHITEBOARD Whiteboard field ``--devel_whiteboard`` ^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--devel_whiteboard`` DEVEL_WHITEBOARD RHBZ devel whiteboard field ``--internal_whiteboard`` ^^^^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--internal_whiteboard`` INTERNAL_WHITEBOARD RHBZ internal whiteboard field ``--qa_whiteboard`` ^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--qa_whiteboard`` QA_WHITEBOARD RHBZ QA whiteboard field ``-F, --fixed_in`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--fixed_in`` FIXED_IN RHBZ 'Fixed in version' field ``--field`` ^^^^^^^^^^^ **Syntax:** ``--field`` FIELD`` VALUE Manually specify a bugzilla API field. FIELD is the raw name used by the bugzilla instance. For example if your bugzilla instance has a custom field cf_my_field, do: --field cf_my_field=VALUE Output options ============== These options are shared by several commands, for tweaking the text output of the command results. ``-f, --full`` ^^^^^^^^^^^^^^ **Syntax:** ``--full`` output detailed bug info ``-i, --ids`` ^^^^^^^^^^^^^ **Syntax:** ``--ids`` output only bug IDs ``-e, --extra`` ^^^^^^^^^^^^^^^ **Syntax:** ``--extra`` output additional bug information (keywords, Whiteboards, etc.) ``--oneline`` ^^^^^^^^^^^^^ **Syntax:** ``--oneline`` one line summary of the bug (useful for scripts) ``--json`` ^^^^^^^^^^ **Syntax:** ``--json`` output bug contents in JSON format ``--includefield`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--includefield`` Pass the field name to bugzilla include_fields list. Only the fields passed to include_fields are returned by the bugzilla server. This can be specified multiple times. ``--extrafield`` ^^^^^^^^^^^^^^^^ **Syntax:** ``--extrafield`` Pass the field name to bugzilla extra_fields list. When used with --json this can be used to request bugzilla to return values for non-default fields. This can be specified multiple times. ``--excludefield`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--excludefield`` Pass the field name to bugzilla exclude_fields list. When used with --json this can be used to request bugzilla to not return values for a field. This can be specified multiple times. ``--raw`` ^^^^^^^^^ **Syntax:** ``--raw`` raw output of the bugzilla contents. This format is unstable and difficult to parse. Please use the ``--json`` instead if you want maximum output from the `bugzilla` ``--outputformat`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--outputformat`` OUTPUTFORMAT Print output in the form given. You can use RPM-style tags that match bug fields, e.g.: '%{id}: %{summary}'. The output of the bugzilla tool should NEVER BE PARSED unless you are using a custom --outputformat. For everything else, just don't parse it, the formats are not stable and are subject to change. --outputformat allows printing arbitrary bug data in a user preferred format. For example, to print a returned bug ID, component, and product, separated with ::, do: --outputformat "%{id}::%{component}::%{product}" The fields (like 'id', 'component', etc.) are the names of the values returned by bugzilla's API. To see a list of all fields, check the API documentation in the 'SEE ALSO' section. Alternatively, run a 'bugzilla --debug query ...' and look at the key names returned in the query results. Also, in most cases, using the name of the associated command line switch should work, like --bug_status becomes %{bug_status}, etc. ‘query’ specific options ======================== Certain options can accept a comma separated list to query multiple values, including --status, --component, --product, --version, --id. Note: querying via explicit command line options will only get you so far. See the --from-url option for a way to use powerful Web UI queries from the command line. ``-b, --bug_id, --id`` ^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--id`` ID specify individual bugs by IDs, separated with commas ``-r, --reporter`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--reporter`` REPORTER Email: search reporter email for given address ``--quicksearch`` ^^^^^^^^^^^^^^^^^ **Syntax:** ``--quicksearch`` QUICKSEARCH Search using bugzilla's quicksearch functionality. ``--savedsearch`` ^^^^^^^^^^^^^^^^^ **Syntax:** ``--savedsearch`` SAVEDSEARCH Name of a bugzilla saved search. If you don't own this saved search, you must passed --savedsearch_sharer_id. ``--savedsearch-sharer-id`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--savedsearch-sharer-id`` SAVEDSEARCH_SHARER_ID Owner ID of the --savedsearch. You can get this ID from the URL bugzilla generates when running the saved search from the web UI. ``--from-url`` ^^^^^^^^^^^^^^ **Syntax:** ``--from-url`` WEB_QUERY_URL Make a working query via bugzilla's 'Advanced search' web UI, grab the url from your browser (the string with query.cgi or buglist.cgi in it), and --from-url will run it via the bugzilla API. Don't forget to quote the string! This only works for Bugzilla 5 and Red Hat bugzilla ‘modify’ specific options ========================= Fields that take multiple values have a special input format. | Append: --cc=foo@example.com | Overwrite: --cc==foo@example.com | Remove: --cc=-foo@example.com Options that accept this format: --cc, --blocked, --dependson, --groups, --tags, whiteboard fields. ``-k, --close RESOLUTION`` ^^^^^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``RESOLUTION`` Close with the given resolution (WONTFIX, NOTABUG, etc.) ``-d, --dupeid`` ^^^^^^^^^^^^^^^^ **Syntax:** ``--dupeid`` ORIGINAL ID of original bug. Implies --close DUPLICATE ``--private`` ^^^^^^^^^^^^^ **Syntax:** ``--private`` Mark new comment as private ``--reset-assignee`` ^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--reset-assignee`` Reset assignee to component default ``--reset-qa-contact`` ^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--reset-qa-contact`` Reset QA contact to component default ``--minor-update`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--minor-update`` Request bugzilla to not send any email about this change ‘new’ specific options ====================== ``--private`` ^^^^^^^^^^^^^ **Syntax:** ``--private`` Mark new comment as private ‘attach’ options ================ ``-f, --file`` ^^^^^^^^^^^^^^ **Syntax:** ``--file`` FILENAME File to attach, or filename for data provided on stdin ``-d, --description`` ^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--description`` DESCRIPTION A short description of the file being attached ``-t, --type`` ^^^^^^^^^^^^^^ **Syntax:** ``--type`` MIMETYPE Mime-type for the file being attached ``-g, --get`` ^^^^^^^^^^^^^ **Syntax:** ``--get`` ATTACHID Download the attachment with the given ID ``--getall`` ^^^^^^^^^^^^ **Syntax:** ``--getall`` BUGID Download all attachments on the given bug ``--ignore-obsolete`` ^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--ignore-obsolete`` Do not download attachments marked as obsolete. ``-l, --comment`` ^^^^^^^^^^^^^^^^^ **Syntax:** ``--comment`` COMMENT Add comment with attachment ‘info’ options ============== ``-p, --products`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--products`` Get a list of products ``-c, --components`` ^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--components`` PRODUCT List the components in the given product ``-o, --component_owners`` ^^^^^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--component_owners`` PRODUCT List components (and their owners) ``-v, --versions`` ^^^^^^^^^^^^^^^^^^ **Syntax:** ``--versions`` PRODUCT List the versions for the given product ``--active-components`` ^^^^^^^^^^^^^^^^^^^^^^^ **Syntax:** ``--active-components`` Only show active components. Combine with --components* AUTHENTICATION CACHE AND API KEYS ================================= Some command usage will require an active login to the bugzilla instance. For example, if the bugzilla instance has some private bugs, those bugs will be missing from 'query' output if you do not have an active login. If you are connecting to a bugzilla 5.0 or later instance, the best option is to use bugzilla API keys. From the bugzilla web UI, log in, navigate to Preferences->API Keys, and generate a key (it will be a long string of characters and numbers). Then create a ~/.config/python-bugzilla/bugzillarc like this: :: $ cat ~/.config/python-bugzilla/bugzillarc [bugzilla.example.com] api_key=YOUR_API_KEY Replace 'bugzilla.example.com' with your bugzilla host name, and YOUR_API_KEY with the generated API Key from the Web UI. Alternatively, you can use 'bugzilla login --api-key', which will ask for the API key, and save it to bugzillarc for you. For older bugzilla instances, you will need to cache a login cookie or token with the "login" subcommand or the "--login" argument. Additionally, the --no-cache-credentials option will tell the bugzilla tool to *not* save or use any authentication cache, including the bugzillarc file. EXAMPLES ======== | bugzilla query --bug_id 62037 | | bugzilla query --version 15 --component python-bugzilla | | bugzilla login | | bugzilla new -p Fedora -v rawhide -c python-bugzilla \\ | --summary "python-bugzilla causes headaches" \\ | --comment "python-bugzilla made my brain hurt when I used it." | | bugzilla attach --file ~/Pictures/cam1.jpg --desc "me, in pain" | $BUGID | | bugzilla attach --getall $BUGID | | bugzilla modify --close NOTABUG --comment "Actually, you're | hungover." $BUGID EXIT STATUS =========== **bugzilla** normally returns 0 if the requested command was successful. Otherwise, exit status is 1 if **bugzilla** is interrupted by the user (or a login attempt fails), 2 if a socket error occurs (e.g. TCP connection timeout), and 3 if the Bugzilla server throws an error. BUGS ==== Please report any bugs as github issues at https://github.com/python-bugzilla/python-bugzilla SEE ALSO ======== https://bugzilla.readthedocs.io/en/latest/api/index.html https://bugzilla.redhat.com/docs/en/html/api/Bugzilla/WebService/Bug.html ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230895.0 python-bugzilla-3.0.2/python-bugzilla.spec0000664000175000017500000000341400000000000021073 0ustar00crobinsocrobinsoName: python-bugzilla Version: 3.0.2 Release: 1%{?dist} Summary: Python library for interacting with Bugzilla License: GPLv2+ URL: https://github.com/python-bugzilla/python-bugzilla Source0: https://github.com/python-bugzilla/python-bugzilla/archive/v%{version}/%{name}-%{version}.tar.gz BuildArch: noarch BuildRequires: python3-devel BuildRequires: python3-requests BuildRequires: python3-setuptools BuildRequires: python3-pytest %global _description\ python-bugzilla is a python library for interacting with bugzilla instances\ over XMLRPC or REST.\ %description %_description %package -n python3-bugzilla Summary: %summary Requires: python3-requests %{?python_provide:%python_provide python3-bugzilla} Obsoletes: python-bugzilla < %{version}-%{release} Obsoletes: python2-bugzilla < %{version}-%{release} %description -n python3-bugzilla %_description %package cli Summary: Command line tool for interacting with Bugzilla Requires: python3-bugzilla = %{version}-%{release} %description cli This package includes the 'bugzilla' command-line tool for interacting with bugzilla. Uses the python-bugzilla API %prep %setup -q %install %{__python3} setup.py install -O1 --root %{buildroot} # Replace '#!/usr/bin/env python' with '#!/usr/bin/python2' # The format is ideal for upstream, but not a distro. See: # https://fedoraproject.org/wiki/Features/SystemPythonExecutablesUseSystemPython %global python_env_path %{__python3} for f in $(find %{buildroot} -type f -executable -print); do sed -i "1 s|^#!/usr/bin/.*|#!%{python_env_path}|" $f || : done %check pytest-3 %files -n python3-bugzilla %doc COPYING README.md NEWS.md %{python3_sitelib}/* %files cli %{_bindir}/bugzilla %{_mandir}/man1/bugzilla.1.gz ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.033975 python-bugzilla-3.0.2/python_bugzilla.egg-info/0000775000175000017500000000000000000000000021771 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230909.0 python-bugzilla-3.0.2/python_bugzilla.egg-info/PKG-INFO0000664000175000017500000000163400000000000023072 0ustar00crobinsocrobinsoMetadata-Version: 1.1 Name: python-bugzilla Version: 3.0.2 Summary: Library and command line tool for interacting with Bugzilla Home-page: https://github.com/python-bugzilla/python-bugzilla Author: UNKNOWN Author-email: UNKNOWN License: GPLv2 Description: UNKNOWN Platform: UNKNOWN Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python 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.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230909.0 python-bugzilla-3.0.2/python_bugzilla.egg-info/SOURCES.txt0000664000175000017500000001357100000000000023664 0ustar00crobinsocrobinsoCONTRIBUTING.md COPYING MANIFEST.in NEWS.md README.md python-bugzilla.spec requirements.txt setup.py test-requirements.txt bugzilla/__init__.py bugzilla/_authfiles.py bugzilla/_backendbase.py bugzilla/_backendrest.py bugzilla/_backendxmlrpc.py bugzilla/_cli.py bugzilla/_rhconverters.py bugzilla/_session.py bugzilla/_util.py bugzilla/apiversion.py bugzilla/base.py bugzilla/bug.py bugzilla/exceptions.py bugzilla/oldclasses.py bugzilla/rhbugzilla.py examples/apikey.py examples/bug_autorefresh.py examples/create.py examples/getbug.py examples/getbug_restapi.py examples/query.py examples/update.py man/bugzilla.1 man/bugzilla.rst python_bugzilla.egg-info/PKG-INFO python_bugzilla.egg-info/SOURCES.txt python_bugzilla.egg-info/dependency_links.txt python_bugzilla.egg-info/entry_points.txt python_bugzilla.egg-info/requires.txt python_bugzilla.egg-info/top_level.txt tests/__init__.py tests/conftest.py tests/mockbackend.py tests/pycodestyle.cfg tests/test_api_attachments.py tests/test_api_authfiles.py tests/test_api_bug.py tests/test_api_externalbugs.py tests/test_api_groups.py tests/test_api_misc.py tests/test_api_products.py tests/test_api_users.py tests/test_cli_attach.py tests/test_cli_info.py tests/test_cli_login.py tests/test_cli_misc.py tests/test_cli_modify.py tests/test_cli_new.py tests/test_cli_query.py tests/test_ro_functional.py tests/test_rw_functional.py tests/utils.py tests/data/bz-attach-get1.txt tests/data/components_file.txt tests/data/cookies-bad.txt tests/data/cookies-lwp.txt tests/data/cookies-moz.txt tests/data/authfiles/output-bugzillarc.txt tests/data/authfiles/output-cookies.txt tests/data/authfiles/output-token.txt tests/data/clioutput/test_info_components-active.txt tests/data/clioutput/test_info_components-owners.txt tests/data/clioutput/test_info_components.txt tests/data/clioutput/test_info_products.txt tests/data/clioutput/test_info_versions.txt tests/data/clioutput/test_interactive_login_apikey_rcfile.txt tests/data/clioutput/test_json_xmlrpc.txt tests/data/clioutput/test_new1.txt tests/data/clioutput/test_new2.txt tests/data/clioutput/test_query1-ids.txt tests/data/clioutput/test_query1-rhbz.txt tests/data/clioutput/test_query1.txt tests/data/clioutput/test_query10.txt tests/data/clioutput/test_query2-rhbz.txt tests/data/clioutput/test_query2.txt tests/data/clioutput/test_query3.txt tests/data/clioutput/test_query4.txt tests/data/clioutput/test_query5.txt tests/data/clioutput/test_query6.txt tests/data/clioutput/test_query7.txt tests/data/clioutput/test_query8.txt tests/data/clioutput/test_query9.txt tests/data/mockargs/test_api_attachments_create1.txt tests/data/mockargs/test_api_component_create1.txt tests/data/mockargs/test_api_component_update1.txt tests/data/mockargs/test_api_getbugs1.txt tests/data/mockargs/test_api_getbugs2.txt tests/data/mockargs/test_api_groups_get1.txt tests/data/mockargs/test_api_groups_get2.txt tests/data/mockargs/test_api_login1.txt tests/data/mockargs/test_api_login2.txt tests/data/mockargs/test_api_products_get1.txt tests/data/mockargs/test_api_products_get2.txt tests/data/mockargs/test_api_products_get3.txt tests/data/mockargs/test_api_products_get4.txt tests/data/mockargs/test_api_products_get5.txt tests/data/mockargs/test_api_users_create.txt tests/data/mockargs/test_api_users_get1.txt tests/data/mockargs/test_api_users_get2.txt tests/data/mockargs/test_api_users_get3.txt tests/data/mockargs/test_api_users_update1.txt tests/data/mockargs/test_attach1.txt tests/data/mockargs/test_attach2.txt tests/data/mockargs/test_attach_get1.txt tests/data/mockargs/test_attach_get2.txt tests/data/mockargs/test_attachments_get1.txt tests/data/mockargs/test_attachments_getall1.txt tests/data/mockargs/test_attachments_update1.txt tests/data/mockargs/test_bug_api_comments.txt tests/data/mockargs/test_bug_api_get_attachments.txt tests/data/mockargs/test_bug_api_history.txt tests/data/mockargs/test_bug_apis_addcc_update.txt tests/data/mockargs/test_bug_apis_addcomment_update.txt tests/data/mockargs/test_bug_apis_close_update.txt tests/data/mockargs/test_bug_apis_deletecc_update.txt tests/data/mockargs/test_bug_apis_setassignee_update.txt tests/data/mockargs/test_bug_apis_setstatus_update.txt tests/data/mockargs/test_bug_apis_updateflags_update.txt tests/data/mockargs/test_bug_fields.txt tests/data/mockargs/test_externalbugs_add.txt tests/data/mockargs/test_externalbugs_remove.txt tests/data/mockargs/test_externalbugs_update.txt tests/data/mockargs/test_getbug_query9.txt tests/data/mockargs/test_info_components-active.txt tests/data/mockargs/test_info_components-owners.txt tests/data/mockargs/test_info_components.txt tests/data/mockargs/test_info_products.txt tests/data/mockargs/test_info_versions.txt tests/data/mockargs/test_interactive_login.txt tests/data/mockargs/test_login-restrict.txt tests/data/mockargs/test_login.txt tests/data/mockargs/test_modify1.txt tests/data/mockargs/test_modify2.txt tests/data/mockargs/test_modify3-tags.txt tests/data/mockargs/test_modify3.txt tests/data/mockargs/test_modify4.txt tests/data/mockargs/test_modify5.txt tests/data/mockargs/test_new1.txt tests/data/mockargs/test_new2.txt tests/data/mockargs/test_query1-ids.txt tests/data/mockargs/test_query1-rhbz.txt tests/data/mockargs/test_query1.txt tests/data/mockargs/test_query10.txt tests/data/mockargs/test_query2-rhbz.txt tests/data/mockargs/test_query2.txt tests/data/mockargs/test_query3.txt tests/data/mockargs/test_query4.txt tests/data/mockargs/test_query5.txt tests/data/mockargs/test_query6.txt tests/data/mockargs/test_query7.txt tests/data/mockargs/test_query8.txt tests/data/mockargs/test_query9.txt tests/data/mockargs/test_query_cve_getbug.txt tests/data/mockargs/test_update_flags.txt tests/data/mockreturn/test_attach_get1.txt tests/data/mockreturn/test_attach_get2.txt tests/data/mockreturn/test_bug_fields.txt tests/data/mockreturn/test_getbug.txt tests/data/mockreturn/test_getbug_rhel.txt tests/data/mockreturn/test_query1.txt tests/data/mockreturn/test_query_cve_getbug.txt././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230909.0 python-bugzilla-3.0.2/python_bugzilla.egg-info/dependency_links.txt0000664000175000017500000000000100000000000026037 0ustar00crobinsocrobinso ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230909.0 python-bugzilla-3.0.2/python_bugzilla.egg-info/entry_points.txt0000664000175000017500000000006000000000000025263 0ustar00crobinsocrobinso[console_scripts] bugzilla = bugzilla._cli:cli ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230909.0 python-bugzilla-3.0.2/python_bugzilla.egg-info/requires.txt0000664000175000017500000000001100000000000024361 0ustar00crobinsocrobinsorequests ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605230909.0 python-bugzilla-3.0.2/python_bugzilla.egg-info/top_level.txt0000664000175000017500000000001100000000000024513 0ustar00crobinsocrobinsobugzilla ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1604419282.0 python-bugzilla-3.0.2/requirements.txt0000664000175000017500000000001100000000000020341 0ustar00crobinsocrobinsorequests ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.043975 python-bugzilla-3.0.2/setup.cfg0000664000175000017500000000004600000000000016706 0ustar00crobinsocrobinso[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1604419797.0 python-bugzilla-3.0.2/setup.py0000775000175000017500000001046300000000000016606 0ustar00crobinsocrobinso#!/usr/bin/env python3 import glob import os import shutil import subprocess import sys from distutils.core import Command from setuptools import setup def get_version(): f = open("bugzilla/apiversion.py") for line in f: if line.startswith('version = '): return eval(line.split('=')[-1]) # pylint: disable=eval-used class PylintCommand(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import pylint.lint import pycodestyle files = (["bugzilla-cli", "bugzilla", "setup.py"] + glob.glob("examples/*.py") + glob.glob("tests/*.py")) output_format = sys.stdout.isatty() and "colorized" or "text" print("running pycodestyle") style_guide = pycodestyle.StyleGuide( config_file='tox.ini', format="pylint", paths=files, ) report = style_guide.check_files() if style_guide.options.count: sys.stderr.write(str(report.total_errors) + '\n') print("running pylint") pylint_opts = [ "--rcfile", ".pylintrc", "--output-format=%s" % output_format, ] pylint.lint.Run(files + pylint_opts) class RPMCommand(Command): description = ("Build src and binary rpms and output them " "in the source directory") user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): self.run_command('sdist') srcdir = os.path.dirname(__file__) cmd = [ "rpmbuild", "-ta", "--define", "_rpmdir %s" % srcdir, "--define", "_srcrpmdir %s" % srcdir, "--define", "_specdir /tmp", "dist/python-bugzilla-%s.tar.gz" % get_version(), ] subprocess.check_call(cmd) class ManCommand(Command): description = ("Regenerate manpages from rst") user_options = [] def initialize_options(self): pass def finalize_options(self): pass def _make_man_pages(self): rstbin = shutil.which("rst2man") if not rstbin: rstbin = shutil.which("rst2man.py") if not rstbin: raise RuntimeError("Didn't find rst2man or rst2man.py") for path in glob.glob("man/*.rst"): base = os.path.basename(path) appname = os.path.splitext(base)[0] newpath = os.path.join(os.path.dirname(path), appname + ".1") print("Generating %s" % newpath) out = subprocess.check_output([rstbin, path]) open(newpath, "wb").write(out) self.distribution.data_files.append( ('share/man/man1', (newpath,))) def run(self): self._make_man_pages() def _parse_requirements(fname): ret = [] for line in open(fname).readlines(): if not line or line.startswith("#"): continue ret.append(line) return ret setup( name='python-bugzilla', version=get_version(), description='Library and command line tool for interacting with Bugzilla', license="GPLv2", url='https://github.com/python-bugzilla/python-bugzilla', classifiers=[ 'Topic :: Software Development :: Libraries :: Python Modules', 'Intended Audience :: Developers', 'License :: OSI Approved :: ' 'GNU General Public License v2 or later (GPLv2+)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], packages=['bugzilla'], data_files=[('share/man/man1', ['man/bugzilla.1'])], entry_points={'console_scripts': ['bugzilla = bugzilla._cli:cli']}, install_requires=_parse_requirements("requirements.txt"), tests_require=_parse_requirements("test-requirements.txt"), cmdclass={ "regenerate_manpages": ManCommand, "pylint": PylintCommand, "rpm": RPMCommand, }, ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1579014774.0 python-bugzilla-3.0.2/test-requirements.txt0000664000175000017500000000006000000000000021322 0ustar00crobinsocrobinso# additional packages needed for testing pytest ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.035975 python-bugzilla-3.0.2/tests/0000775000175000017500000000000000000000000016227 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/__init__.py0000664000175000017500000000056100000000000020342 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import os class _CLICONFIG(object): def __init__(self): self.REDHAT_URL = None self.REGENERATE_OUTPUT = False self.ONLY_REST = False self.ONLY_XMLRPC = False CLICONFIG = _CLICONFIG() os.environ["__BUGZILLA_UNITTEST"] = "1" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/conftest.py0000664000175000017500000000737500000000000020442 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import locale import logging import os import pytest import tests import tests.utils import bugzilla # pytest plugin adding custom options. Hooks are documented here: # https://docs.pytest.org/en/latest/writing_plugins.html def pytest_addoption(parser): parser.addoption("--ro-functional", action="store_true", default=False, help=("Run readonly functional tests against actual " "bugzilla instances. This will be very slow.")) parser.addoption("--rw-functional", action="store_true", default=False, help=("Run read/write functional tests against actual bugzilla " "instances. As of now this only runs against " "partner-bugzilla.redhat.com, which requires an RH " "bugzilla account with cached login creds. This will " "also be very slow.")) parser.addoption("--redhat-url", help="Redhat bugzilla URL to use for ro/rw_functional tests") parser.addoption("--pybz-debug", action="store_true", default=False, help=("Enable python-bugzilla debug output. This may break " "output comparison tests.")) parser.addoption("--regenerate-output", action="store_true", default=False, help=("Force regeneration of generated test output")) parser.addoption("--only-rest", action="store_true", default=False) parser.addoption("--only-xmlrpc", action="store_true", default=False) def pytest_ignore_collect(path, config): has_ro = config.getoption("--ro-functional") has_rw = config.getoption("--rw-functional") base = os.path.basename(str(path)) is_ro = base == "test_ro_functional.py" is_rw = base == "test_rw_functional.py" if is_ro and not has_ro: return True if is_rw and not has_rw: return True def pytest_configure(config): try: # Needed for test reproducibility on systems not using a UTF-8 locale locale.setlocale(locale.LC_ALL, 'C') locale.setlocale(locale.LC_CTYPE, 'en_US.UTF-8') except Exception as e: print("Error setting locale: %s" % str(e)) if config.getoption("--redhat-url"): tests.CLICONFIG.REDHAT_URL = config.getoption("--redhat-url") if config.getoption("--pybz-debug"): logging.getLogger(bugzilla.__name__).setLevel(logging.DEBUG) os.environ["__BUGZILLA_UNITTEST_DEBUG"] = "1" if config.getoption("--regenerate-output"): tests.CLICONFIG.REGENERATE_OUTPUT = config.getoption( "--regenerate-output") if config.getoption("--only-rest"): tests.CLICONFIG.ONLY_REST = True if config.getoption("--only-xmlrpc"): tests.CLICONFIG.ONLY_XMLRPC = True if (config.getoption("--ro-functional") or config.getoption("--rw-functional")): config.option.verbose = 2 def pytest_generate_tests(metafunc): """ If a test requests the 'backends' fixture, run that test with both force_rest=True and force_xmlrpc=True Bugzilla options """ if 'backends' in metafunc.fixturenames: values = [] ids = [] if not tests.CLICONFIG.ONLY_REST: values.append({"force_xmlrpc": True}) ids.append("XMLRPC") if not tests.CLICONFIG.ONLY_XMLRPC: values.append({"force_rest": True}) ids.append("REST") metafunc.parametrize("backends", values, ids=ids, scope="session") @pytest.fixture def run_cli(capsys, monkeypatch): """ Custom pytest fixture to pass a function for testing a bugzilla cli command. """ def _do_run(*args, **kwargs): return tests.utils.do_run_cli(capsys, monkeypatch, *args, **kwargs) return _do_run ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.035975 python-bugzilla-3.0.2/tests/data/0000775000175000017500000000000000000000000017140 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.035975 python-bugzilla-3.0.2/tests/data/authfiles/0000775000175000017500000000000000000000000021124 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/authfiles/output-bugzillarc.txt0000664000175000017500000000004600000000000025361 0ustar00crobinsocrobinso[example.com] api_key = TEST-API-KEY ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1579376798.0 python-bugzilla-3.0.2/tests/data/authfiles/output-cookies.txt0000664000175000017500000000042600000000000024661 0ustar00crobinsocrobinso# Netscape HTTP Cookie File # http://curl.haxx.se/rfc/cookie_spec.html # This is a generated file! Do not edit. .partner-bugzilla.redhat.com TRUE / FALSE 2145916800 Bugzilla_login notacookie .partner-bugzilla.redhat.com TRUE / FALSE 2145916800 Bugzilla_logincookie notacookie ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/authfiles/output-token.txt0000664000175000017500000000004500000000000024342 0ustar00crobinsocrobinso[example.com] token = MY-FAKE-TOKEN ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1490730675.0 python-bugzilla-3.0.2/tests/data/bz-attach-get1.txt0000664000175000017500000000255600000000000022424 0ustar00crobinsocrobinso--- base.py.old 2010-12-16 12:15:09.932010659 +0100 +++ base.py 2010-12-16 16:04:18.995185933 +0100 @@ -19,6 +19,8 @@ import tempfile import logging import locale +import email.header +import re log = logging.getLogger('bugzilla') @@ -677,10 +679,17 @@ # RFC 2183 defines the content-disposition header, if you're curious disp = att.headers['content-disposition'].split(';') [filename_parm] = [i for i in disp if i.strip().startswith('filename=')] - (dummy,filename) = filename_parm.split('=') - # RFC 2045/822 defines the grammar for the filename value, but - # I think we just need to remove the quoting. I hope. - att.name = filename.strip('"') + (dummy,filename) = filename_parm.split('=',1) + # RFC 2045/822 defines the grammar for the filename value + filename = filename.strip('"') + # email.header.decode_header cannot handle strings not ending with '?=', + # so let's transform one =?...?= part at a time + while True: + match = re.search("=\?.*?\?=", filename) + if match is None: + break + filename = filename[:match.start()] + email.header.decode_header(match.group(0))[0][0] + filename[match.end():] + att.name = filename # Hooray, now we have a file-like object with .read() and .name return att ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1605230910.0379748 python-bugzilla-3.0.2/tests/data/clioutput/0000775000175000017500000000000000000000000021170 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_info_components-active.txt0000664000175000017500000000004100000000000027434 0ustar00crobinsocrobinsobackend/kernel client-interfaces ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_info_components-owners.txt0000664000175000017500000000007600000000000027506 0ustar00crobinsocrobinsoclient-interfaces: Fake Guy configuration: ANother fake dude! ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_info_components.txt0000664000175000017500000000004100000000000026163 0ustar00crobinsocrobinsobackend/kernel client-interfaces ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_info_products.txt0000664000175000017500000000003600000000000025645 0ustar00crobinsocrobinsoProd 1 Test test-fake-product ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_info_versions.txt0000664000175000017500000000002000000000000025643 0ustar00crobinsocrobinso7.1 fooversion! ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_interactive_login_apikey_rcfile.txt0000664000175000017500000000004500000000000031362 0ustar00crobinsocrobinso[example.com] api_key = MY-FAKE-KEY ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_json_xmlrpc.txt0000664000175000017500000000366600000000000025341 0ustar00crobinsocrobinso{ "bugs": [ { "binarytest": "LS0tIGJhc2UucHkub2xkCTIwMTAtMTItMTYgMTI6MTU6MDkuOTMyMDEwNjU5ICswMTAwCisrKyBiYXNlLnB5CTIwMTAtMTItMTYgMTY6MDQ6MTguOTk1MTg1OTMzICswMTAwCkBAIC0xOSw2ICsxOSw4IEBACiBpbXBvcnQgdGVtcGZpbGUKIGltcG9ydCBsb2dnaW5nCiBpbXBvcnQgbG9jYWxlCitpbXBvcnQgZW1haWwuaGVhZGVyCitpbXBvcnQgcmUKIAogbG9nID0gbG9nZ2luZy5nZXRMb2dnZXIoJ2J1Z3ppbGxhJykKIApAQCAtNjc3LDEwICs2NzksMTcgQEAKICAgICAgICAgIyBSRkMgMjE4MyBkZWZpbmVzIHRoZSBjb250ZW50LWRpc3Bvc2l0aW9uIGhlYWRlciwgaWYgeW91J3JlIGN1cmlvdXMKICAgICAgICAgZGlzcCA9IGF0dC5oZWFkZXJzWydjb250ZW50LWRpc3Bvc2l0aW9uJ10uc3BsaXQoJzsnKQogICAgICAgICBbZmlsZW5hbWVfcGFybV0gPSBbaSBmb3IgaSBpbiBkaXNwIGlmIGkuc3RyaXAoKS5zdGFydHN3aXRoKCdmaWxlbmFtZT0nKV0KLSAgICAgICAgKGR1bW15LGZpbGVuYW1lKSA9IGZpbGVuYW1lX3Bhcm0uc3BsaXQoJz0nKQotICAgICAgICAjIFJGQyAyMDQ1LzgyMiBkZWZpbmVzIHRoZSBncmFtbWFyIGZvciB0aGUgZmlsZW5hbWUgdmFsdWUsIGJ1dAotICAgICAgICAjIEkgdGhpbmsgd2UganVzdCBuZWVkIHRvIHJlbW92ZSB0aGUgcXVvdGluZy4gSSBob3BlLgotICAgICAgICBhdHQubmFtZSA9IGZpbGVuYW1lLnN0cmlwKCciJykKKyAgICAgICAgKGR1bW15LGZpbGVuYW1lKSA9IGZpbGVuYW1lX3Bhcm0uc3BsaXQoJz0nLDEpCisgICAgICAgICMgUkZDIDIwNDUvODIyIGRlZmluZXMgdGhlIGdyYW1tYXIgZm9yIHRoZSBmaWxlbmFtZSB2YWx1ZQorICAgICAgICBmaWxlbmFtZSA9IGZpbGVuYW1lLnN0cmlwKCciJykKKyAgICAgICAgIyBlbWFpbC5oZWFkZXIuZGVjb2RlX2hlYWRlciBjYW5ub3QgaGFuZGxlIHN0cmluZ3Mgbm90IGVuZGluZyB3aXRoICc/PScsCisgICAgICAgICMgc28gbGV0J3MgdHJhbnNmb3JtIG9uZSA9Py4uLj89IHBhcnQgYXQgYSB0aW1lCisgICAgICAgIHdoaWxlIFRydWU6CisgICAgICAgICAgICBtYXRjaCA9IHJlLnNlYXJjaCgiPVw/Lio/XD89IiwgZmlsZW5hbWUpCisgICAgICAgICAgICBpZiBtYXRjaCBpcyBOb25lOgorICAgICAgICAgICAgICAgIGJyZWFrCisgICAgICAgICAgICBmaWxlbmFtZSA9IGZpbGVuYW1lWzptYXRjaC5zdGFydCgpXSArIGVtYWlsLmhlYWRlci5kZWNvZGVfaGVhZGVyKG1hdGNoLmdyb3VwKDApKVswXVswXSArIGZpbGVuYW1lW21hdGNoLmVuZCgpOl0KKyAgICAgICAgYXR0Lm5hbWUgPSBmaWxlbmFtZQogICAgICAgICAjIEhvb3JheSwgbm93IHdlIGhhdmUgYSBmaWxlLWxpa2Ugb2JqZWN0IHdpdGggLnJlYWQoKSBhbmQgLm5hbWUKICAgICAgICAgcmV0dXJuIGF0dAogCg==", "id": 1165434, "timetest": "2018-12-09T19:12:12Z" } ] } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_new1.txt0000664000175000017500000000013200000000000023636 0ustar00crobinsocrobinso#1694158 CLOSED - crobinso@redhat.com - python-bugzilla test bug for API minor_update ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/data/clioutput/test_new2.txt0000664000175000017500000000013200000000000023637 0ustar00crobinsocrobinso#1694158 CLOSED - crobinso@redhat.com - python-bugzilla test bug for API minor_update ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query1-ids.txt0000664000175000017500000000001600000000000024770 0ustar00crobinsocrobinso508645 668543 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query1-rhbz.txt0000664000175000017500000000033100000000000025156 0ustar00crobinsocrobinso#508645 NEW - Libvirt Maintainers - RFE: qemu: Support a managed autoconnect mode for host USB devices #668543 NEW - Cole Robinson - RFE: warn users at guest start if networks/storage pools are inactive ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query1.txt0000664000175000017500000000033100000000000024213 0ustar00crobinsocrobinso#508645 NEW - Libvirt Maintainers - RFE: qemu: Support a managed autoconnect mode for host USB devices #668543 NEW - Cole Robinson - RFE: warn users at guest start if networks/storage pools are inactive ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query10.txt0000664000175000017500000000015400000000000024276 0ustar00crobinsocrobinso#1165434 CLOSED - lvm-team@redhat.com - LVM mirrored root can deadlock dmeventd if a mirror leg is lost ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query2-rhbz.txt0000664000175000017500000000033100000000000025157 0ustar00crobinsocrobinso#508645 NEW - Libvirt Maintainers - RFE: qemu: Support a managed autoconnect mode for host USB devices #668543 NEW - Cole Robinson - RFE: warn users at guest start if networks/storage pools are inactive ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query2.txt0000664000175000017500000000413200000000000024217 0ustar00crobinsocrobinsoBugzilla 1165434: ATTRIBUTE[actual_time]: 0.0 ATTRIBUTE[alias]: [] ATTRIBUTE[assigned_to]: lvm-team@redhat.com ATTRIBUTE[assigned_to_detail]: 'DICT SCRUBBED' ATTRIBUTE[autorefresh]: False ATTRIBUTE[blocks]: [123456] ATTRIBUTE[cc]: ['example@redhat.com', 'example2@redhat.com'] ATTRIBUTE[cc_detail]: ['DICT SCRUBBED'] ATTRIBUTE[cf_build_id]: ATTRIBUTE[cf_conditional_nak]: [] ATTRIBUTE[cf_cust_facing]: --- ATTRIBUTE[cf_devel_whiteboard]: somedeveltag,someothertag ATTRIBUTE[cf_doc_type]: Bug Fix ATTRIBUTE[cf_environment]: ATTRIBUTE[cf_fixed_in]: ATTRIBUTE[cf_internal_whiteboard]: someinternal TAG ATTRIBUTE[cf_last_closed]: 2016-03-03T22:15:07 ATTRIBUTE[cf_partner]: [] ATTRIBUTE[cf_pgm_internal]: ATTRIBUTE[cf_pm_score]: 0 ATTRIBUTE[cf_qa_whiteboard]: foo bar baz ATTRIBUTE[cf_qe_conditional_nak]: [] ATTRIBUTE[cf_release_notes]: ATTRIBUTE[cf_target_upstream_version]: ATTRIBUTE[cf_verified]: [] ATTRIBUTE[classification]: Red Hat ATTRIBUTE[comments]: ['DICT SCRUBBED'] ATTRIBUTE[depends_on]: [112233] ATTRIBUTE[docs_contact]: ATTRIBUTE[estimated_time]: 0.0 ATTRIBUTE[external_bugs]: ['DICT SCRUBBED'] ATTRIBUTE[flags]: ['DICT SCRUBBED'] ATTRIBUTE[groups]: ['somegroup'] ATTRIBUTE[id]: 1165434 ATTRIBUTE[is_cc_accessible]: True ATTRIBUTE[is_confirmed]: True ATTRIBUTE[is_creator_accessible]: True ATTRIBUTE[is_open]: False ATTRIBUTE[keywords]: ['key1', 'keyword2', 'Security'] ATTRIBUTE[last_change_time]: 2018-12-09T19:12:12 ATTRIBUTE[op_sys]: Linux ATTRIBUTE[platform]: All ATTRIBUTE[priority]: medium ATTRIBUTE[product]: Red Hat Enterprise Linux 5 ATTRIBUTE[qa_contact]: mspqa-list@redhat.com ATTRIBUTE[qa_contact_detail]: 'DICT SCRUBBED' ATTRIBUTE[remaining_time]: 0.0 ATTRIBUTE[resolution]: WONTFIX ATTRIBUTE[see_also]: [] ATTRIBUTE[severity]: medium ATTRIBUTE[status]: CLOSED ATTRIBUTE[sub_components]: 'DICT SCRUBBED' ATTRIBUTE[summary]: LVM mirrored root can deadlock dmeventd if a mirror leg is lost ATTRIBUTE[tags]: [] ATTRIBUTE[target_milestone]: rc ATTRIBUTE[target_release]: ['---'] ATTRIBUTE[url]: ATTRIBUTE[version]: ['5.8'] ATTRIBUTE[weburl]: https:///TESTSUITEMOCK ATTRIBUTE[whiteboard]: genericwhiteboard ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query3.txt0000664000175000017500000000153400000000000024223 0ustar00crobinsocrobinso:::genericwhiteboard:qe_test_coverage?,release?,pm_ack?,devel_ack?,qa_ack+,needinfo?:hello@example.com::?:: * 2014-11-19T00:26:50 - example@redhat.com: Description of problem: Version-Release number of selected component (if applicable): kernel-2.6.18-308.el5 device-mapper-multipath-0.4.7-48.el5 device-mapper-1.02.67-2.el5 device-mapper-1.02.67-2.el5 device-mapper-event-1.02.67-2.el5 * 2014-11-19T00:47:57 - example@redhat.com: We can see that there is a dmeventd task that has sent data over a socket and is waiting for the peer to respond: crash> bt any interaction with the filesystem until it has issued the suspend command to convert the mirror device to a linear device. * 2014-11-19T01:53:53 - example@redhat.com: Test text :: External bug: https://bugzilla.gnome.org/show_bug.cgi?id=703421 External bug: https://bugs.launchpad.net/bugs/1203576 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query4.txt0000664000175000017500000000147400000000000024227 0ustar00crobinsocrobinso#1165434 CLOSED - lvm-team@redhat.com - LVM mirrored root can deadlock dmeventd if a mirror leg is lost Component: CC: example@redhat.com,example2@redhat.com Blocked: 123456 Depends: 112233 * 2014-11-19T00:26:50 - example@redhat.com: Description of problem: Version-Release number of selected component (if applicable): kernel-2.6.18-308.el5 device-mapper-multipath-0.4.7-48.el5 device-mapper-1.02.67-2.el5 device-mapper-1.02.67-2.el5 device-mapper-event-1.02.67-2.el5 * 2014-11-19T00:47:57 - example@redhat.com: We can see that there is a dmeventd task that has sent data over a socket and is waiting for the peer to respond: crash> bt any interaction with the filesystem until it has issued the suspend command to convert the mirror device to a linear device. * 2014-11-19T01:53:53 - example@redhat.com: Test text ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query5.txt0000664000175000017500000000033600000000000024224 0ustar00crobinsocrobinso#1165434 CLOSED - lvm-team@redhat.com - LVM mirrored root can deadlock dmeventd if a mirror leg is lost +Keywords: key1,keyword2,Security +QA Whiteboard: +Status Whiteboard: genericwhiteboard +Devel Whiteboard: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query6.txt0000664000175000017500000000017000000000000024221 0ustar00crobinsocrobinso#1165434 CLOSED lvm-team@redhat.com [rc] qe_test_coverage?,release?,pm_ack?,devel_ack?,qa_ack+,needinfo? CVE-1234-5678 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query7.txt0000664000175000017500000000015400000000000024224 0ustar00crobinsocrobinso#1165434 CLOSED - lvm-team@redhat.com - LVM mirrored root can deadlock dmeventd if a mirror leg is lost ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query8.txt0000664000175000017500000001631600000000000024234 0ustar00crobinsocrobinso{ "bugs": [ { "actual_time": 0.0, "alias": [], "assigned_to": "lvm-team@redhat.com", "assigned_to_detail": { "email": "lvm-team@redhat.com", "id": 206817, "name": "lvm-team@redhat.com", "real_name": "LVM and device-mapper development team" }, "blocks": [ 123456 ], "cc": [ "example@redhat.com", "example2@redhat.com" ], "cc_detail": [ { "email": "example@redhat.com", "id": 123456, "name": "example@redhat.com", "real_name": "Example user" }, { "email": "example2@redhat.com", "id": 123457, "name": "heinzm@redhat.com", "real_name": "Example2 user" } ], "cf_build_id": "", "cf_conditional_nak": [], "cf_cust_facing": "---", "cf_devel_whiteboard": "somedeveltag,someothertag", "cf_doc_type": "Bug Fix", "cf_environment": "", "cf_fixed_in": "", "cf_internal_whiteboard": "someinternal TAG", "cf_last_closed": "2016-03-03T22:15:07", "cf_partner": [], "cf_pgm_internal": "", "cf_pm_score": "0", "cf_qa_whiteboard": "foo bar baz", "cf_qe_conditional_nak": [], "cf_release_notes": "", "cf_target_upstream_version": "", "cf_verified": [], "classification": "Red Hat", "comments": [ { "bug_id": 1165434, "count": 0, "creation_time": "2014-11-19T00:26:50", "creator": "example@redhat.com", "creator_id": 276776, "id": 7685441, "is_private": false, "tags": [], "text": "Description of problem:\nVersion-Release number of selected component (if applicable):\nkernel-2.6.18-308.el5\ndevice-mapper-multipath-0.4.7-48.el5\ndevice-mapper-1.02.67-2.el5\ndevice-mapper-1.02.67-2.el5\ndevice-mapper-event-1.02.67-2.el5\n", "time": "2014-11-19T00:26:50" }, { "bug_id": 1165434, "count": 1, "creation_time": "2014-11-19T00:47:57", "creator": "example@redhat.com", "creator_id": 276776, "id": 7685467, "is_private": false, "tags": [], "text": "We can see that there is a dmeventd task that has sent data over a socket and is waiting for the peer to respond:\n\ncrash> bt\nany interaction with the filesystem until it has issued the suspend command to convert the mirror device to a linear device.", "time": "2014-11-19T00:47:57" }, { "bug_id": 1165434, "count": 2, "creation_time": "2014-11-19T01:53:53", "creator": "example@redhat.com", "creator_id": 156796, "id": 7685595, "is_private": false, "tags": [], "text": "Test text", "time": "2014-11-19T01:53:53" } ], "depends_on": [ 112233 ], "docs_contact": "", "estimated_time": 0.0, "external_bugs": [ { "bug_id": 989253, "ext_bz_bug_id": "703421", "ext_bz_id": 3, "ext_description": "None", "ext_priority": "None", "ext_status": "None", "id": 115528, "type": { "can_get": true, "can_send": false, "description": "GNOME Bugzilla", "full_url": "https://bugzilla.gnome.org/show_bug.cgi?id=%id%", "id": 3, "must_send": false, "send_once": false, "type": "Bugzilla", "url": "https://bugzilla.gnome.org" } }, { "bug_id": 989253, "ext_bz_bug_id": "1203576", "ext_bz_id": 29, "ext_description": "None", "ext_priority": "None", "ext_status": "None", "id": 115527, "type": { "can_get": false, "can_send": false, "description": "Launchpad", "full_url": "https://bugs.launchpad.net/bugs/%id%", "id": 29, "must_send": false, "send_once": false, "type": "None", "url": "https://bugs.launchpad.net/bugs" } } ], "flags": [ { "creation_date": "2019-11-15T21:57:21Z", "id": 4302313, "is_active": 1, "modification_date": "2019-11-15T21:57:21Z", "name": "qe_test_coverage", "setter": "pm-rhel@redhat.com", "status": "?", "type_id": 318 }, { "creation_date": "2018-12-25T16:47:43Z", "id": 3883137, "is_active": 1, "modification_date": "2018-12-25T16:47:43Z", "name": "release", "setter": "rule-engine@redhat.com", "status": "?", "type_id": 1197 }, { "creation_date": "2018-12-25T16:47:38Z", "id": 3883134, "is_active": 1, "modification_date": "2018-12-25T16:47:38Z", "name": "pm_ack", "setter": "example3@redhat.com", "status": "?", "type_id": 11 }, { "creation_date": "2018-12-25T16:47:38Z", "id": 3883135, "is_active": 1, "modification_date": "2018-12-25T16:47:38Z", "name": "devel_ack", "setter": "example2@redhat.com", "status": "?", "type_id": 10 }, { "creation_date": "2018-12-25T16:47:38Z", "id": 3883136, "is_active": 1, "modification_date": "2019-04-28T02:07:03Z", "name": "qa_ack", "setter": "example@redhat.com", "status": "+", "type_id": 9 }, { "creation_date": "2019-03-29T06:50:01Z", "id": 3999302, "is_active": 1, "modification_date": "2019-03-29T06:50:01Z", "name": "needinfo", "requestee": "hello@example.com", "setter": "example@redhat.com", "status": "?", "type_id": 1164 } ], "groups": [ "somegroup" ], "id": 1165434, "is_cc_accessible": true, "is_confirmed": true, "is_creator_accessible": true, "is_open": false, "keywords": [ "key1", "keyword2", "Security" ], "last_change_time": "2018-12-09T19:12:12", "op_sys": "Linux", "platform": "All", "priority": "medium", "product": "Red Hat Enterprise Linux 5", "qa_contact": "mspqa-list@redhat.com", "qa_contact_detail": { "email": "mspqa-list@redhat.com", "id": 164197, "name": "mspqa-list@redhat.com", "real_name": "Cluster QE" }, "remaining_time": 0.0, "resolution": "WONTFIX", "see_also": [], "severity": "medium", "status": "CLOSED", "sub_components": { "lvm2": [ "dmeventd (RHEL5)" ] }, "summary": "LVM mirrored root can deadlock dmeventd if a mirror leg is lost", "tags": [], "target_milestone": "rc", "target_release": [ "---" ], "url": "", "version": [ "5.8" ], "whiteboard": "genericwhiteboard" } ] } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/clioutput/test_query9.txt0000664000175000017500000001640600000000000024235 0ustar00crobinsocrobinso{ "bugs": [ { "actual_time": 0.0, "alias": [], "assigned_to": "lvm-team@redhat.com", "assigned_to_detail": { "email": "lvm-team@redhat.com", "id": 206817, "name": "lvm-team@redhat.com", "real_name": "LVM and device-mapper development team" }, "blocks": [ 123456 ], "cc": [ "example@redhat.com", "example2@redhat.com" ], "cc_detail": [ { "email": "example@redhat.com", "id": 123456, "name": "example@redhat.com", "real_name": "Example user" }, { "email": "example2@redhat.com", "id": 123457, "name": "heinzm@redhat.com", "real_name": "Example2 user" } ], "cf_build_id": "", "cf_conditional_nak": [], "cf_cust_facing": "---", "cf_doc_type": "Bug Fix", "cf_environment": "", "cf_last_closed": "2016-03-03T22:15:07", "cf_partner": [], "cf_pgm_internal": "", "cf_pm_score": "0", "cf_qe_conditional_nak": [], "cf_release_notes": "", "cf_target_upstream_version": "", "cf_verified": [], "classification": "Red Hat", "comments": [ { "bug_id": 1165434, "count": 0, "creation_time": "2014-11-19T00:26:50", "creator": "example@redhat.com", "creator_id": 276776, "id": 7685441, "is_private": false, "tags": [], "text": "Description of problem:\nVersion-Release number of selected component (if applicable):\nkernel-2.6.18-308.el5\ndevice-mapper-multipath-0.4.7-48.el5\ndevice-mapper-1.02.67-2.el5\ndevice-mapper-1.02.67-2.el5\ndevice-mapper-event-1.02.67-2.el5\n", "time": "2014-11-19T00:26:50" }, { "bug_id": 1165434, "count": 1, "creation_time": "2014-11-19T00:47:57", "creator": "example@redhat.com", "creator_id": 276776, "id": 7685467, "is_private": false, "tags": [], "text": "We can see that there is a dmeventd task that has sent data over a socket and is waiting for the peer to respond:\n\ncrash> bt\nany interaction with the filesystem until it has issued the suspend command to convert the mirror device to a linear device.", "time": "2014-11-19T00:47:57" }, { "bug_id": 1165434, "count": 2, "creation_time": "2014-11-19T01:53:53", "creator": "example@redhat.com", "creator_id": 156796, "id": 7685595, "is_private": false, "tags": [], "text": "Test text", "time": "2014-11-19T01:53:53" } ], "depends_on": [ 112233 ], "devel_whiteboard": "somedeveltag,someothertag", "docs_contact": "", "estimated_time": 0.0, "external_bugs": [ { "bug_id": 989253, "ext_bz_bug_id": "703421", "ext_bz_id": 3, "ext_description": "None", "ext_priority": "None", "ext_status": "None", "id": 115528, "type": { "can_get": true, "can_send": false, "description": "GNOME Bugzilla", "full_url": "https://bugzilla.gnome.org/show_bug.cgi?id=%id%", "id": 3, "must_send": false, "send_once": false, "type": "Bugzilla", "url": "https://bugzilla.gnome.org" } }, { "bug_id": 989253, "ext_bz_bug_id": "1203576", "ext_bz_id": 29, "ext_description": "None", "ext_priority": "None", "ext_status": "None", "id": 115527, "type": { "can_get": false, "can_send": false, "description": "Launchpad", "full_url": "https://bugs.launchpad.net/bugs/%id%", "id": 29, "must_send": false, "send_once": false, "type": "None", "url": "https://bugs.launchpad.net/bugs" } } ], "fixed_in": "", "flags": [ { "creation_date": "2019-11-15T21:57:21Z", "id": 4302313, "is_active": 1, "modification_date": "2019-11-15T21:57:21Z", "name": "qe_test_coverage", "setter": "pm-rhel@redhat.com", "status": "?", "type_id": 318 }, { "creation_date": "2018-12-25T16:47:43Z", "id": 3883137, "is_active": 1, "modification_date": "2018-12-25T16:47:43Z", "name": "release", "setter": "rule-engine@redhat.com", "status": "?", "type_id": 1197 }, { "creation_date": "2018-12-25T16:47:38Z", "id": 3883134, "is_active": 1, "modification_date": "2018-12-25T16:47:38Z", "name": "pm_ack", "setter": "example3@redhat.com", "status": "?", "type_id": 11 }, { "creation_date": "2018-12-25T16:47:38Z", "id": 3883135, "is_active": 1, "modification_date": "2018-12-25T16:47:38Z", "name": "devel_ack", "setter": "example2@redhat.com", "status": "?", "type_id": 10 }, { "creation_date": "2018-12-25T16:47:38Z", "id": 3883136, "is_active": 1, "modification_date": "2019-04-28T02:07:03Z", "name": "qa_ack", "setter": "example@redhat.com", "status": "+", "type_id": 9 }, { "creation_date": "2019-03-29T06:50:01Z", "id": 3999302, "is_active": 1, "modification_date": "2019-03-29T06:50:01Z", "name": "needinfo", "requestee": "hello@example.com", "setter": "example@redhat.com", "status": "?", "type_id": 1164 } ], "groups": [ "somegroup" ], "id": 1165434, "internal_whiteboard": "someinternal TAG", "is_cc_accessible": true, "is_confirmed": true, "is_creator_accessible": true, "is_open": false, "keywords": [ "key1", "keyword2", "Security" ], "last_change_time": "2018-12-09T19:12:12", "op_sys": "Linux", "platform": "All", "priority": "medium", "product": "Red Hat Enterprise Linux 5", "qa_contact": "mspqa-list@redhat.com", "qa_contact_detail": { "email": "mspqa-list@redhat.com", "id": 164197, "name": "mspqa-list@redhat.com", "real_name": "Cluster QE" }, "qa_whiteboard": "foo bar baz", "remaining_time": 0.0, "resolution": "WONTFIX", "see_also": [], "severity": "medium", "status": "CLOSED", "sub_component": "dmeventd (RHEL5)", "sub_components": { "lvm2": [ "dmeventd (RHEL5)" ] }, "summary": "LVM mirrored root can deadlock dmeventd if a mirror leg is lost", "tags": [], "target_milestone": "rc", "target_release": [ "---" ], "url": "", "version": "5.8", "versions": [ "5.8" ], "whiteboard": "genericwhiteboard" } ] } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1490730675.0 python-bugzilla-3.0.2/tests/data/components_file.txt0000664000175000017500000000001400000000000023060 0ustar00crobinsocrobinsofoo bar baz ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1490730675.0 python-bugzilla-3.0.2/tests/data/cookies-bad.txt0000664000175000017500000000003400000000000022056 0ustar00crobinsocrobinsofoo this is invalid cookies ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578161803.0 python-bugzilla-3.0.2/tests/data/cookies-lwp.txt0000664000175000017500000000046500000000000022142 0ustar00crobinsocrobinso#LWP-Cookies-2.0 Set-Cookie3: Bugzilla_login=notacookie; path="/"; domain=".partner-bugzilla.redhat.com"; domain_dot; expires="2038-01-01 00:00:00Z"; version=0 Set-Cookie3: Bugzilla_logincookie=notacookie; path="/"; domain=".partner-bugzilla.redhat.com"; domain_dot; expires="2038-01-01 00:00:00Z"; version=0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578161803.0 python-bugzilla-3.0.2/tests/data/cookies-moz.txt0000664000175000017500000000044200000000000022140 0ustar00crobinsocrobinso# Netscape HTTP Cookie File # http://www.netscape.com/newsref/std/cookie_spec.html # This is a generated file! Do not edit. .partner-bugzilla.redhat.com TRUE / FALSE 2145916800 Bugzilla_login notacookie .partner-bugzilla.redhat.com TRUE / FALSE 2145916800 Bugzilla_logincookie notacookie ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.042975 python-bugzilla-3.0.2/tests/data/mockargs/0000775000175000017500000000000000000000000020746 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_attachments_create1.txt0000664000175000017500000000023300000000000027314 0ustar00crobinsocrobinso([123456], 'STRIPPED-BY-TESTSUITE', {'content_type': 'text/plain', 'file_name': 'bz-attach-get1.txt', 'is_private': True, 'summary': 'some desc'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_component_create1.txt0000664000175000017500000000024100000000000027002 0ustar00crobinsocrobinso{'default_assignee': 'foo@example.com', 'default_cc': 'foo3@example.com', 'default_qa_contact': 'foo2@example.com', 'is_active': 0, 'product': 'fooproduct'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_component_update1.txt0000664000175000017500000000027100000000000027024 0ustar00crobinsocrobinso{'names': [{'component': 'foocomponent', 'product': 'fooproduct'}], 'updates': {'blaharg': 'blahval', 'default_assignee': 'foo@example.com', 'is_active': 0}} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_getbugs1.txt0000664000175000017500000000006300000000000025117 0ustar00crobinsocrobinso([], ['CVE-1234-5678'], {'exclude_fields': 'foo'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_getbugs2.txt0000664000175000017500000000006300000000000025120 0ustar00crobinsocrobinso(['123456'], ['CVE-1234-FAKE'], {'permissive': 1}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_groups_get1.txt0000664000175000017500000000005700000000000025640 0ustar00crobinsocrobinso{'membership': False, 'names': ['TestGroups']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_groups_get2.txt0000664000175000017500000000005500000000000025637 0ustar00crobinsocrobinso{'membership': True, 'names': ['TestGroup']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_login1.txt0000664000175000017500000000004200000000000024564 0ustar00crobinsocrobinso{'login': None, 'password': None} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_login2.txt0000664000175000017500000000004400000000000024567 0ustar00crobinsocrobinso{'login': 'FOO', 'password': 'BAR'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_products_get1.txt0000664000175000017500000000002000000000000026152 0ustar00crobinsocrobinso{'ids': [1, 7]} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_products_get2.txt0000664000175000017500000000012700000000000026163 0ustar00crobinsocrobinso{'include_fields': ['name', 'id', 'components.name'], 'names': ['test-fake-product']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_products_get3.txt0000664000175000017500000000012100000000000026156 0ustar00crobinsocrobinso{'include_fields': ['name', 'id', 'components'], 'names': ['test-fake-product']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_products_get4.txt0000664000175000017500000000006200000000000026163 0ustar00crobinsocrobinso{'exclude_fields': ['product.foo'], 'ids': ['7']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_products_get5.txt0000664000175000017500000000010400000000000026161 0ustar00crobinsocrobinso{'include_fields': ['name', 'id', 'components.name'], 'names': [0]} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_users_create.txt0000664000175000017500000000011400000000000026057 0ustar00crobinsocrobinso{'email': 'example1@example.com', 'name': 'fooname', 'password': 'foopass'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_users_get1.txt0000664000175000017500000000004400000000000025456 0ustar00crobinsocrobinso{'names': ['example2@example.com']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_users_get2.txt0000664000175000017500000000004400000000000025457 0ustar00crobinsocrobinso{'names': ['example1@example.com']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_users_get3.txt0000664000175000017500000000004400000000000025460 0ustar00crobinsocrobinso{'match': ['example1@example.com']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_api_users_update1.txt0000664000175000017500000000010600000000000026160 0ustar00crobinsocrobinso{'groups': {'remove': ['fedora_contrib']}, 'names': ['example name']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_attach1.txt0000664000175000017500000000034700000000000024077 0ustar00crobinsocrobinso(['123456'], 'STRIPPED-BY-TESTSUITE', {'comment': 'some comment to go with it', 'content_type': 'text/x-patch', 'file_name': 'bz-attach-get1.txt', 'is_patch': True, 'is_private': True, 'summary': 'bz-attach-get1.txt'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_attach2.txt0000664000175000017500000000023100000000000024070 0ustar00crobinsocrobinso(['123456'], 'STRIPPED-BY-TESTSUITE', {'content_type': 'text/plain', 'file_name': 'fake-file-name.txt', 'summary': 'Some attachment description'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_attach_get1.txt0000664000175000017500000000002100000000000024723 0ustar00crobinsocrobinso(['112233'], {}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_attach_get2.txt0000664000175000017500000000002100000000000024724 0ustar00crobinsocrobinso(['663674'], {}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_attachments_get1.txt0000664000175000017500000000001500000000000025775 0ustar00crobinsocrobinso(502352, {}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_attachments_getall1.txt0000664000175000017500000000010300000000000026464 0ustar00crobinsocrobinso([123456], {'exclude_fields': ['bar'], 'include_fields': ['foo']}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_attachments_update1.txt0000664000175000017500000000012400000000000026501 0ustar00crobinsocrobinso([112233], {'flags': [{'is_patch': True, 'name': 'needinfo', 'value': 'foobar'}]}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_api_comments.txt0000664000175000017500000000002000000000000026051 0ustar00crobinsocrobinso([1165434], {}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_api_get_attachments.txt0000664000175000017500000000001700000000000027404 0ustar00crobinsocrobinso([663674], {}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_api_history.txt0000664000175000017500000000002000000000000025725 0ustar00crobinsocrobinso([1165434], {}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_apis_addcc_update.txt0000664000175000017500000000013200000000000027013 0ustar00crobinsocrobinso([1165434], {'cc': {'add': ['foo2@example.com']}, 'comment': {'comment': 'foocomment'}}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_apis_addcomment_update.txt0000664000175000017500000000011200000000000030066 0ustar00crobinsocrobinso([1165434], {'comment': {'comment': 'test comment', 'is_private': True}}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_apis_close_update.txt0000664000175000017500000000023300000000000027064 0ustar00crobinsocrobinso([1165434], {'cf_fixed_in': '1.2.3.4.5', 'comment': {'comment': 'foocomment2'}, 'dupe_of': 123456, 'resolution': 'UPSTREAM', 'status': 'CLOSED'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_apis_deletecc_update.txt0000664000175000017500000000013500000000000027530 0ustar00crobinsocrobinso([1165434], {'cc': {'remove': ['foo2@example.com']}, 'comment': {'comment': 'foocomment'}}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_apis_setassignee_update.txt0000664000175000017500000000017400000000000030275 0ustar00crobinsocrobinso([1165434], {'assigned_to': 'foo@example.com', 'comment': {'comment': 'foocomment'}, 'qa_contact': 'bar@example.com'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_apis_setstatus_update.txt0000664000175000017500000000013300000000000030015 0ustar00crobinsocrobinso([1165434], {'comment': {'comment': 'foocomment', 'is_private': True}, 'status': 'POST'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_apis_updateflags_update.txt0000664000175000017500000000010400000000000030253 0ustar00crobinsocrobinso([1165434], {'flags': [{'name': 'someflag', 'status': 'someval'}]}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_bug_fields.txt0000664000175000017500000000006600000000000024653 0ustar00crobinsocrobinso{'include_fields': ['name'], 'names': ['bug_status']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_externalbugs_add.txt0000664000175000017500000000064600000000000026067 0ustar00crobinsocrobinso{'bug_ids': [1234, 5678], 'external_bugs': [{'ext_bz_bug_id': 'externalid', 'ext_description': 'link to launchpad', 'ext_priority': 'bigly', 'ext_status': 'CLOSED', 'ext_type_description': 'some-bug-add-description', 'ext_type_id': 'launchpad', 'ext_type_url': 'https://example.com/launchpad/1234'}]} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_externalbugs_remove.txt0000664000175000017500000000024400000000000026626 0ustar00crobinsocrobinso{'bug_ids': ['blah'], 'ext_bz_bug_id': ['99999'], 'ext_type_description': 'foo-desc', 'ext_type_id': 'footype', 'ext_type_url': 'foo-url', 'ids': ['remove1']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_externalbugs_update.txt0000664000175000017500000000051500000000000026614 0ustar00crobinsocrobinso{'bug_ids': ['some', 'bug', 'id'], 'ext_bz_bug_id': ['externalid-update'], 'ext_description': 'link to mozilla', 'ext_priority': 'like, really bigly', 'ext_status': 'OPEN', 'ext_type_description': 'some-bug-update', 'ext_type_id': 'mozilla', 'ext_type_url': 'https://mozilla.foo/bar/5678', 'ids': ['external1', 'external2']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_getbug_query9.txt0000664000175000017500000000056200000000000025344 0ustar00crobinsocrobinso([1165434], [], {'exclude_fields': ['excludeme'], 'extra_fields': ['extrame1', 'extrame2', 'comments', 'description', 'external_bugs', 'flags', 'sub_components', 'tags'], 'include_fields': ['foo', 'bar', 'id'], 'permissive': 1}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_info_components-active.txt0000664000175000017500000000015700000000000027222 0ustar00crobinsocrobinso{'include_fields': ['name', 'id', 'components.name', 'components.is_active'], 'names': ['test-fake-product']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_info_components-owners.txt0000664000175000017500000000026500000000000027264 0ustar00crobinsocrobinso{'include_fields': ['name', 'id', 'components.name', 'components.default_assigned_to'], 'names': ['test-fake-product']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_info_components.txt0000664000175000017500000000012700000000000025746 0ustar00crobinsocrobinso{'include_fields': ['name', 'id', 'components.name'], 'names': ['test-fake-product']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_info_products.txt0000664000175000017500000000006200000000000025422 0ustar00crobinsocrobinso{'ids': [1, 7], 'include_fields': ['name', 'id']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_info_versions.txt0000664000175000017500000000011700000000000025430 0ustar00crobinsocrobinso{'include_fields': ['name', 'id', 'versions'], 'names': ['test-fake-product']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_interactive_login.txt0000664000175000017500000000005600000000000026254 0ustar00crobinsocrobinso{'login': 'fakeuser', 'password': 'fakepass'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_login-restrict.txt0000664000175000017500000000007400000000000025514 0ustar00crobinsocrobinso{'login': 'FOO', 'password': 'BAR', 'restrict_login': True} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_login.txt0000664000175000017500000000004400000000000023654 0ustar00crobinsocrobinso{'login': 'FOO', 'password': 'BAR'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_modify1.txt0000664000175000017500000000011000000000000024106 0ustar00crobinsocrobinso(['123456', '1234567'], {'component': 'NEWCOMP', 'status': 'ASSIGNED'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_modify2.txt0000664000175000017500000000057200000000000024123 0ustar00crobinsocrobinso(['123456'], {'blocks': {'set': [123456, 445566]}, 'comment': {'comment': 'some example comment', 'is_private': True}, 'component': 'NEWCOMP', 'dupe_of': 555666, 'flags': [{'name': '-needinfo,+somethingels', 'status': 'e'}], 'groups': {'remove': ['BAR']}, 'keywords': {'add': ['FOO']}, 'resolution': 'DUPLICATE', 'status': 'CLOSED', 'whiteboard': 'thisone'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_modify3-tags.txt0000664000175000017500000000010200000000000025045 0ustar00crobinsocrobinso(['1165434'], {'tags': {'add': ['addtag'], 'remove': ['rmtag']}}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_modify3.txt0000664000175000017500000000026500000000000024123 0ustar00crobinsocrobinso([1165434], {'cf_devel_whiteboard': 'somedeveltag,someothertag devel-duh', 'cf_internal_whiteboard': 'someinternal TAG internal-hey bar', 'cf_qa_whiteboard': 'bar baz yo-qa'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_modify4.txt0000664000175000017500000000017300000000000024122 0ustar00crobinsocrobinso(['1165434'], {'cf_fixed_in': 'foofixedin', 'component': 'lvm2', 'sub_components': {'lvm2': ['some-sub-component']}}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/data/mockargs/test_modify5.txt0000664000175000017500000000160700000000000024126 0ustar00crobinsocrobinso(['1165434'], {'alias': 'fooalias', 'assigned_to': 'foo@example.com', 'bar': 'foo', 'blocks': {'add': [1234], 'remove': [1235], 'set': []}, 'cc': {'add': ['+bar@example.com'], 'remove': ['steve@example.com']}, 'cf_devel_whiteboard': 'DEVBOARD', 'cf_internal_whiteboard': 'INTBOARD', 'cf_qa_whiteboard': 'QABOARD', 'comment_tags': ['FOOTAG'], 'depends_on': {'add': [2234], 'remove': [2235], 'set': []}, 'groups': {'add': ['foogroup']}, 'keywords': {'add': ['newkeyword'], 'remove': ['byekeyword'], 'set': []}, 'minor_update': True, 'op_sys': 'windows', 'platform': 'mips', 'priority': 'high', 'product': 'newproduct', 'qa_contact': 'qa@example.com', 'reset_assigned_to': True, 'reset_qa_contact': True, 'severity': 'low', 'summary': 'newsummary', 'target_milestone': 'beta', 'target_release': '1.2.4', 'url': 'https://example.com', 'version': '1.2.3'}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_new1.txt0000664000175000017500000000054000000000000023417 0ustar00crobinsocrobinso{'blocks': ['12345', '6789'], 'cc': ['foo@example.com', 'bar@example.com'], 'comment_is_private': True, 'component': 'FOOCOMP', 'depends_on': ['dependme'], 'description': 'This is the first comment!\nWith newline & stuff.', 'groups': ['FOOGROUP', 'BARGROUP'], 'keywords': ['ADDKEY'], 'product': 'FOOPROD', 'summary': 'Hey this is the title!'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/data/mockargs/test_new2.txt0000664000175000017500000000123400000000000023421 0ustar00crobinsocrobinso{'alias': 'somealias', 'assigned_to': 'foo@example.com', 'blocks': ['12345', '6789'], 'cc': ['foo@example.com', 'bar@example.com'], 'comment_is_private': True, 'comment_tags': ['FOO'], 'component': 'FOOCOMP', 'depends_on': ['dependme'], 'description': 'This is the first comment!\nWith newline & stuff.', 'foo': 'bar', 'groups': ['FOOGROUP', 'BARGROUP'], 'keywords': ['ADDKEY'], 'op_sys': 'linux', 'platform': 'mips', 'priority': 'low', 'product': 'FOOPROD', 'qa_contact': 'qa@example.com', 'severity': 'high', 'sub_components': {'FOOCOMP': ['FOOCOMP']}, 'summary': 'Hey this is the title!', 'url': 'https://some.example.com', 'version': '5.6.7'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query1-ids.txt0000664000175000017500000000014700000000000024553 0ustar00crobinsocrobinso{'component': ['foo', 'bar'], 'id': ['1234', '2480'], 'include_fields': ['id'], 'product': ['foo']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query1-rhbz.txt0000664000175000017500000000107500000000000024742 0ustar00crobinsocrobinso{'cc': ['foo@example.com'], 'component': ['foo', 'bar'], 'field0-0-0': 'keywords', 'field1-0-0': 'cf_fixed_in', 'field2-0-0': 'cf_qa_whiteboard', 'id': ['1234', '2480'], 'include_fields': ['assigned_to', 'id', 'status', 'summary'], 'longdesc': 'some comment string', 'longdesc_type': 'allwordssubstr', 'product': ['foo'], 'qa_contact': 'qa@example.com', 'query_format': 'advanced', 'type0-0-0': 'substring', 'type1-0-0': 'substring', 'type2-0-0': 'substring', 'value0-0-0': 'fribkeyword', 'value1-0-0': 'amifixed', 'value2-0-0': 'some-example-whiteboard'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query1.txt0000664000175000017500000000021300000000000023770 0ustar00crobinsocrobinso{'component': ['foo', 'bar'], 'id': ['1234', '2480'], 'include_fields': ['assigned_to', 'id', 'status', 'summary'], 'product': ['foo']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query10.txt0000664000175000017500000000211300000000000024051 0ustar00crobinsocrobinso{'alias': 'somealias', 'assigned_to': 'bar@example.com', 'field0-0-0': 'keywords', 'field1-0-0': 'blocked', 'field2-0-0': 'dependson', 'field3-0-0': 'bug_file_loc', 'field4-0-0': 'cf_fixed_in', 'field5-0-0': 'flagtypes.name', 'field6-0-0': 'status_whiteboard', 'field7-0-0': 'cf_devel_whiteboard', 'include_fields': ['assigned_to', 'id', 'status', 'summary'], 'priority': ['wibble'], 'query_format': 'advanced', 'quicksearch': '1', 'reporter': 'me@example.com', 'savedsearch': '2', 'sharer_id': '3', 'short_desc': 'search summary', 'sub_components': ['FOOCOMP'], 'tag': ['+foo'], 'target_milestone': 'bar', 'target_release': 'foo', 'type0-0-0': 'substring', 'type1-0-0': 'substring', 'type2-0-0': 'substring', 'type3-0-0': 'sometype', 'type4-0-0': 'substring', 'type5-0-0': 'substring', 'type6-0-0': 'substring', 'type7-0-0': 'substring', 'value0-0-0': 'FOO', 'value1-0-0': '12345', 'value2-0-0': '23456', 'value3-0-0': 'https://example.com', 'value4-0-0': '5.5.5', 'value5-0-0': 'needinfo', 'value6-0-0': 'FOO', 'value7-0-0': 'DEVBOARD', 'version': ['5.6.7']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query2-rhbz.txt0000664000175000017500000000024500000000000024741 0ustar00crobinsocrobinso{'email1': ['foo@example.com'], 'emailcc1': True, 'emailtype1': 'BAR', 'include_fields': ['assigned_to', 'id', 'status', 'summary'], 'query_format': 'advanced'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query2.txt0000664000175000017500000000005600000000000023776 0ustar00crobinsocrobinso{'id': ['1165434'], 'include_fields': ['id']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query3.txt0000664000175000017500000000050700000000000024000 0ustar00crobinsocrobinso{'bug_severity': ['sev1', 'sev2'], 'include_fields': ['bar', 'comments', 'devel_whiteboard', 'external_bugs', 'flags', 'flags_requestee', 'foo', 'whiteboard', 'id']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query4.txt0000664000175000017500000000072000000000000023776 0ustar00crobinsocrobinso{'bug_status': ['NEW', 'ASSIGNED', 'NEEDINFO', 'ON_DEV', 'MODIFIED', 'POST', 'REOPENED'], 'include_fields': ['assigned_to', 'blocks', 'cc', 'comments', 'component', 'depends_on', 'id', 'status', 'summary']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query5.txt0000664000175000017500000000055600000000000024006 0ustar00crobinsocrobinso{'bug_status': ['ASSIGNED', 'ON_QA', 'FAILS_QA', 'PASSES_QA'], 'component': ['foo', 'bar', 'baz'], 'include_fields': ['assigned_to', 'devel_whiteboard', 'id', 'keywords', 'qa_whiteboard', 'status', 'summary', 'whiteboard']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query6.txt0000664000175000017500000000053100000000000024000 0ustar00crobinsocrobinso{'BAR': 'WIBBLE', 'FOO': '1', 'bug_status': ['VERIFIED', 'RELEASE_PENDING', 'CLOSED'], 'include_fields': ['assigned_to', 'blocks', 'component', 'flags', 'keywords', 'status', 'target_milestone', 'id']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query7.txt0000664000175000017500000000070200000000000024001 0ustar00crobinsocrobinso{'bug_status': ['NEW', 'ASSIGNED', 'MODIFIED', 'ON_DEV', 'ON_QA', 'VERIFIED', 'FAILS_QA', 'RELEASE_PENDING', 'POST'], 'classification': 'Fedora', 'component': 'virt-manager', 'include_fields': ['assigned_to', 'id', 'status', 'summary'], 'order': 'bug_status,bug_id', 'product': 'Fedora', 'query_format': 'advanced'} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query8.txt0000664000175000017500000000005600000000000024004 0ustar00crobinsocrobinso{'id': ['1165434'], 'include_fields': ['id']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query9.txt0000664000175000017500000000005600000000000024005 0ustar00crobinsocrobinso{'id': ['1165434'], 'include_fields': ['id']} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668195.0 python-bugzilla-3.0.2/tests/data/mockargs/test_query_cve_getbug.txt0000664000175000017500000000002300000000000026100 0ustar00crobinsocrobinso([123456], [], {}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601668194.0 python-bugzilla-3.0.2/tests/data/mockargs/test_update_flags.txt0000664000175000017500000000010000000000000025173 0ustar00crobinsocrobinso([12345, 6789], {'flags': {'name': 'needinfo', 'status': '?'}}) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1605230910.043975 python-bugzilla-3.0.2/tests/data/mockreturn/0000775000175000017500000000000000000000000021331 5ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/data/mockreturn/test_attach_get1.txt0000664000175000017500000000154200000000000025317 0ustar00crobinsocrobinso{'attachments': {'502352': {'bug_id': 663674, 'content_type': 'text/plain', 'creation_time': '2011-06-01T18:57:50Z', 'creator': 'example', 'data': 'SG9vcmF5IGZvciBNZXRlb3JvbG9naWNrw6kgenByw6F2eSA1XzA0LnBkZiEK', 'file_name': 'Klíč memorial test file.txt', 'flags': [], 'id': 502352, 'is_obsolete': 0, 'is_patch': 0, 'is_private': 0, 'last_change_time': '2011-06-01T18:57:50Z', 'size': 45, 'summary': 'An empty test file with a utf-8 ' 'filename'}}, 'bugs': {}} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/data/mockreturn/test_attach_get2.txt0000664000175000017500000001310700000000000025320 0ustar00crobinsocrobinso{'attachments': {}, 'bugs': {'663674': [{'bug_id': 663674, 'content_type': 'application/octet-stream', 'creation_time': '2010-12-16T15:28:01Z', 'creator': 'example', 'data': 'LS0tIGJhc2UucHkub2xkCTIwMTAtMTItMTYgMTI6MTU6MDkuOTMyMDEwNjU5ICswMTAwCisrKyBiYXNlLnB5CTIwMTAtMTItMTYgMTY6MDQ6MTguOTk1MTg1OTMzICswMTAwCkBAIC0xOSw2ICsxOSw4IEBACiBpbXBvcnQgdGVtcGZpbGUKIGltcG9ydCBsb2dnaW5nCiBpbXBvcnQgbG9jYWxlCitpbXBvcnQgZW1haWwuaGVhZGVyCitpbXBvcnQgcmUKIAogbG9nID0gbG9nZ2luZy5nZXRMb2dnZXIoJ2J1Z3ppbGxhJykKIApAQCAtNjc3LDEwICs2NzksMTcgQEAKICAgICAgICAgIyBSRkMgMjE4MyBkZWZpbmVzIHRoZSBjb250ZW50LWRpc3Bvc2l0aW9uIGhlYWRlciwgaWYgeW91J3JlIGN1cmlvdXMKICAgICAgICAgZGlzcCA9IGF0dC5oZWFkZXJzWydjb250ZW50LWRpc3Bvc2l0aW9uJ10uc3BsaXQoJzsnKQogICAgICAgICBbZmlsZW5hbWVfcGFybV0gPSBbaSBmb3IgaSBpbiBkaXNwIGlmIGkuc3RyaXAoKS5zdGFydHN3aXRoKCdmaWxlbmFtZT0nKV0KLSAgICAgICAgKGR1bW15LGZpbGVuYW1lKSA9IGZpbGVuYW1lX3Bhcm0uc3BsaXQoJz0nKQotICAgICAgICAjIFJGQyAyMDQ1LzgyMiBkZWZpbmVzIHRoZSBncmFtbWFyIGZvciB0aGUgZmlsZW5hbWUgdmFsdWUsIGJ1dAotICAgICAgICAjIEkgdGhpbmsgd2UganVzdCBuZWVkIHRvIHJlbW92ZSB0aGUgcXVvdGluZy4gSSBob3BlLgotICAgICAgICBhdHQubmFtZSA9IGZpbGVuYW1lLnN0cmlwKCciJykKKyAgICAgICAgKGR1bW15LGZpbGVuYW1lKSA9IGZpbGVuYW1lX3Bhcm0uc3BsaXQoJz0nLDEpCisgICAgICAgICMgUkZDIDIwNDUvODIyIGRlZmluZXMgdGhlIGdyYW1tYXIgZm9yIHRoZSBmaWxlbmFtZSB2YWx1ZQorICAgICAgICBmaWxlbmFtZSA9IGZpbGVuYW1lLnN0cmlwKCciJykKKyAgICAgICAgIyBlbWFpbC5oZWFkZXIuZGVjb2RlX2hlYWRlciBjYW5ub3QgaGFuZGxlIHN0cmluZ3Mgbm90IGVuZGluZyB3aXRoICc/PScsCisgICAgICAgICMgc28gbGV0J3MgdHJhbnNmb3JtIG9uZSA9Py4uLj89IHBhcnQgYXQgYSB0aW1lCisgICAgICAgIHdoaWxlIFRydWU6CisgICAgICAgICAgICBtYXRjaCA9IHJlLnNlYXJjaCgiPVw/Lio/XD89IiwgZmlsZW5hbWUpCisgICAgICAgICAgICBpZiBtYXRjaCBpcyBOb25lOgorICAgICAgICAgICAgICAgIGJyZWFrCisgICAgICAgICAgICBmaWxlbmFtZSA9IGZpbGVuYW1lWzptYXRjaC5zdGFydCgpXSArIGVtYWlsLmhlYWRlci5kZWNvZGVfaGVhZGVyKG1hdGNoLmdyb3VwKDApKVswXVswXSArIGZpbGVuYW1lW21hdGNoLmVuZCgpOl0KKyAgICAgICAgYXR0Lm5hbWUgPSBmaWxlbmFtZQogICAgICAgICAjIEhvb3JheSwgbm93IHdlIGhhdmUgYSBmaWxlLWxpa2Ugb2JqZWN0IHdpdGggLnJlYWQoKSBhbmQgLm5hbWUKICAgICAgICAgcmV0dXJuIGF0dAogCg==', 'file_name': 'bugzilla-filename.patch', 'flags': [], 'id': 469147, 'is_obsolete': 1, 'is_patch': 0, 'is_private': 0, 'last_change_time': '2010-12-21T17:57:36Z', 'size': 1390, 'summary': 'Proposed patch'}, {'bug_id': 663674, 'content_type': 'text/plain', 'creation_time': '2010-12-21T17:57:36Z', 'creator': 'example', 'data': 'LS0tIC91c3IvbGliL3B5dGhvbjIuNy9zaXRlLXBhY2thZ2VzL2J1Z3ppbGxhL2Jhc2UucHkub3JpZwkyMDEwLTEyLTIxIDEzOjA1OjI5LjcyNzE4OTE0MSArMDEwMAorKysgL3Vzci9saWIvcHl0aG9uMi43L3NpdGUtcGFja2FnZXMvYnVnemlsbGEvYmFzZS5weQkyMDEwLTEyLTIxIDE4OjQ4OjMxLjU5NDgwMjMwNSArMDEwMApAQCAtMTksNiArMTksOCBAQAogaW1wb3J0IHRlbXBmaWxlCiBpbXBvcnQgbG9nZ2luZwogaW1wb3J0IGxvY2FsZQoraW1wb3J0IHJlCitpbXBvcnQgZW1haWwuaGVhZGVyCiAKIGxvZyA9IGxvZ2dpbmcuZ2V0TG9nZ2VyKCdidWd6aWxsYScpCiAKQEAgLTY3NywxMCArNjc5LDEzIEBACiAgICAgICAgICMgUkZDIDIxODMgZGVmaW5lcyB0aGUgY29udGVudC1kaXNwb3NpdGlvbiBoZWFkZXIsIGlmIHlvdSdyZSBjdXJpb3VzCiAgICAgICAgIGRpc3AgPSBhdHQuaGVhZGVyc1snY29udGVudC1kaXNwb3NpdGlvbiddLnNwbGl0KCc7JykKICAgICAgICAgW2ZpbGVuYW1lX3Bhcm1dID0gW2kgZm9yIGkgaW4gZGlzcCBpZiBpLnN0cmlwKCkuc3RhcnRzd2l0aCgnZmlsZW5hbWU9JyldCi0gICAgICAgIChkdW1teSxmaWxlbmFtZSkgPSBmaWxlbmFtZV9wYXJtLnNwbGl0KCc9JykKLSAgICAgICAgIyBSRkMgMjA0NS84MjIgZGVmaW5lcyB0aGUgZ3JhbW1hciBmb3IgdGhlIGZpbGVuYW1lIHZhbHVlLCBidXQKLSAgICAgICAgIyBJIHRoaW5rIHdlIGp1c3QgbmVlZCB0byByZW1vdmUgdGhlIHF1b3RpbmcuIEkgaG9wZS4KLSAgICAgICAgYXR0Lm5hbWUgPSBmaWxlbmFtZS5zdHJpcCgnIicpCisgICAgICAgIChkdW1teSxmaWxlbmFtZSkgPSBmaWxlbmFtZV9wYXJtLnNwbGl0KCc9JywgMSkKKyAgICAgICAgIyBSRkMgMjA0NS84MjIgZGVmaW5lcyB0aGUgZ3JhbW1hciBmb3IgdGhlIGZpbGVuYW1lIHZhbHVlCisgICAgICAgIGZpbGVuYW1lID0gZmlsZW5hbWUuc3RyaXAoJyInKQorICAgICAgICAjIEluIGNhc2UgdGhlIGZpbGVuYW1lIGlzIG5vdCBjb21wbGlhbnQgd2l0aCB0aGUgc3RhbmRhcmQsIGxldCdzIG1ha2UKKyAgICAgICAgIyBpdCBjb3JyZWN0LgorICAgICAgICBmaWVsZHMgPSBlbWFpbC5oZWFkZXIuZGVjb2RlX2hlYWRlcihyZS5zdWIoJyg9XD8oW15cP10qXD8pezN9PSknLCAnIFxcMSAnLCBmaWxlbmFtZSkpCisgICAgICAgIGF0dC5uYW1lID0gJycuam9pbihmaWVsZFsxXSBhbmQgZmllbGRbMF0uZGVjb2RlKGZpZWxkWzFdKSBvciBmaWVsZFswXSBmb3IgZmllbGQgaW4gZmllbGRzKQogICAgICAgICAjIEhvb3JheSwgbm93IHdlIGhhdmUgYSBmaWxlLWxpa2Ugb2JqZWN0IHdpdGggLnJlYWQoKSBhbmQgLm5hbWUKICAgICAgICAgcmV0dXJuIGF0dAogCg==', 'file_name': 'bugzilla-filename-2.patch', 'flags': [], 'id': 470041, 'is_obsolete': 0, 'is_patch': 1, 'is_private': 0, 'last_change_time': '2010-12-21T17:57:36Z', 'size': 1351, 'summary': 'Better proposed patch'}, {'bug_id': 663674, 'content_type': 'text/plain', 'creation_time': '2011-06-01T18:57:50Z', 'creator': 'example', 'data': 'SG9vcmF5IGZvciBNZXRlb3JvbG9naWNrw6kgenByw6F2eSA1XzA0LnBkZiEK', 'file_name': 'Klíč memorial test file.txt', 'flags': [], 'id': 502352, 'is_obsolete': 0, 'is_patch': 0, 'is_private': 0, 'last_change_time': '2011-06-01T18:57:50Z', 'size': 45, 'summary': 'An empty test file with a utf-8 filename'}]}} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/data/mockreturn/test_bug_fields.txt0000664000175000017500000002253300000000000025241 0ustar00crobinsocrobinso# bugzilla.redhat.com 2020-01-10 with {"names": "bug_status"} { "fields": [ { "display_name": "Status", "id": 2, "is_custom": False, "is_mandatory": False, "is_on_bug_entry": False, "name": "bug_status", "type": 2, "values": [ { "can_change_to": [ { "comment_required": False, "name": "NEW" }, { "comment_required": False, "name": "ASSIGNED" } ], "is_open": True, "sort_key": 0, "sortkey": 0, "visibility_values": [] }, { "can_change_to": [ { "comment_required": False, "name": "ASSIGNED" }, { "comment_required": False, "name": "POST" }, { "comment_required": False, "name": "MODIFIED" }, { "comment_required": False, "name": "ON_DEV" }, { "comment_required": False, "name": "ON_QA" }, { "comment_required": False, "name": "VERIFIED" }, { "comment_required": False, "name": "RELEASE_PENDING" }, { "comment_required": False, "name": "CLOSED" } ], "is_open": True, "name": "NEW", "sort_key": 10, "sortkey": 10, "visibility_values": [] }, { "can_change_to": [ { "comment_required": False, "name": "NEW" }, { "comment_required": False, "name": "POST" }, { "comment_required": False, "name": "MODIFIED" }, { "comment_required": False, "name": "ON_DEV" }, { "comment_required": False, "name": "ON_QA" }, { "comment_required": False, "name": "VERIFIED" }, { "comment_required": False, "name": "RELEASE_PENDING" }, { "comment_required": False, "name": "CLOSED" } ], "is_open": True, "name": "ASSIGNED", "sort_key": 20, "sortkey": 20, "visibility_values": [] }, { "can_change_to": [ { "comment_required": False, "name": "NEW" }, { "comment_required": False, "name": "ASSIGNED" }, { "comment_required": False, "name": "MODIFIED" }, { "comment_required": False, "name": "ON_DEV" }, { "comment_required": False, "name": "ON_QA" }, { "comment_required": False, "name": "VERIFIED" }, { "comment_required": False, "name": "RELEASE_PENDING" }, { "comment_required": False, "name": "CLOSED" } ], "is_open": True, "name": "POST", "sort_key": 30, "sortkey": 30, "visibility_values": [] }, { "can_change_to": [ { "comment_required": False, "name": "NEW" }, { "comment_required": False, "name": "ASSIGNED" }, { "comment_required": False, "name": "POST" }, { "comment_required": False, "name": "ON_DEV" }, { "comment_required": False, "name": "ON_QA" }, { "comment_required": False, "name": "VERIFIED" }, { "comment_required": False, "name": "RELEASE_PENDING" }, { "comment_required": False, "name": "CLOSED" } ], "is_open": True, "name": "MODIFIED", "sort_key": 40, "sortkey": 40, "visibility_values": [] }, { "can_change_to": [ { "comment_required": False, "name": "NEW" }, { "comment_required": False, "name": "ASSIGNED" }, { "comment_required": False, "name": "POST" }, { "comment_required": False, "name": "MODIFIED" }, { "comment_required": False, "name": "ON_QA" }, { "comment_required": False, "name": "VERIFIED" }, { "comment_required": False, "name": "RELEASE_PENDING" }, { "comment_required": False, "name": "CLOSED" } ], "is_open": True, "name": "ON_DEV", "sort_key": 50, "sortkey": 50, "visibility_values": [] }, { "can_change_to": [ { "comment_required": False, "name": "NEW" }, { "comment_required": False, "name": "ASSIGNED" }, { "comment_required": False, "name": "POST" }, { "comment_required": False, "name": "MODIFIED" }, { "comment_required": False, "name": "ON_DEV" }, { "comment_required": False, "name": "VERIFIED" }, { "comment_required": False, "name": "RELEASE_PENDING" }, { "comment_required": False, "name": "CLOSED" } ], "is_open": True, "name": "ON_QA", "sort_key": 60, "sortkey": 60, "visibility_values": [] }, { "can_change_to": [ { "comment_required": False, "name": "NEW" }, { "comment_required": False, "name": "ASSIGNED" }, { "comment_required": False, "name": "POST" }, { "comment_required": False, "name": "MODIFIED" }, { "comment_required": False, "name": "ON_DEV" }, { "comment_required": False, "name": "ON_QA" }, { "comment_required": False, "name": "RELEASE_PENDING" }, { "comment_required": False, "name": "CLOSED" } ], "is_open": True, "name": "VERIFIED", "sort_key": 70, "sortkey": 70, "visibility_values": [] }, { "can_change_to": [ { "comment_required": False, "name": "NEW" }, { "comment_required": False, "name": "ASSIGNED" }, { "comment_required": False, "name": "POST" }, { "comment_required": False, "name": "MODIFIED" }, { "comment_required": False, "name": "ON_DEV" }, { "comment_required": False, "name": "ON_QA" }, { "comment_required": False, "name": "VERIFIED" }, { "comment_required": False, "name": "CLOSED" } ], "is_open": True, "name": "RELEASE_PENDING", "sort_key": 80, "sortkey": 80, "visibility_values": [] }, { "can_change_to": [ { "comment_required": False, "name": "NEW" }, { "comment_required": False, "name": "ASSIGNED" }, { "comment_required": False, "name": "POST" }, { "comment_required": False, "name": "MODIFIED" }, { "comment_required": False, "name": "ON_QA" } ], "is_open": False, "name": "CLOSED", "sort_key": 90, "sortkey": 90, "visibility_values": [] } ], "visibility_values": [] } ] } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/data/mockreturn/test_getbug.txt0000664000175000017500000000463500000000000024416 0ustar00crobinsocrobinso{'bugs': [{ 'actual_time': 0.0, 'alias': [], 'assigned_to': 'crobinso@redhat.com', 'assigned_to_detail': {'email': 'crobinso@redhat.com', 'id': 199727, 'name': 'crobinso@redhat.com', 'real_name': 'Cole Robinson'}, 'blocks': [], 'cc': ['crobinso@redhat.com'], 'cc_detail': [{'email': 'crobinso@redhat.com', 'id': 199727, 'name': 'crobinso@redhat.com', 'real_name': 'Cole Robinson'}], 'cf_build_id': '', 'cf_conditional_nak': [], 'cf_cust_facing': '---', 'cf_devel_whiteboard': '', 'cf_doc_type': 'If docs needed, set a value', 'cf_environment': '', 'cf_fixed_in': '', 'cf_internal_whiteboard': '', 'cf_last_closed': '2019-03-29T16:39:27', 'cf_partner': [], 'cf_pgm_internal': '', 'cf_pm_score': '0', 'cf_qa_whiteboard': '', 'cf_qe_conditional_nak': [], 'cf_release_notes': '', 'cf_verified': [], 'classification': 'Fedora', 'component': ['python-bugzilla'], 'creation_time': '2019-03-29T16:39:01', 'creator': 'crobinso@redhat.com', 'creator_detail': {'email': 'crobinso@redhat.com', 'id': 199727, 'name': 'crobinso@redhat.com', 'real_name': 'Cole Robinson'}, 'depends_on': [], 'docs_contact': '', 'estimated_time': 0.0, 'groups': [], 'id': 1694158, 'is_cc_accessible': True, 'is_confirmed': True, 'is_creator_accessible': True, 'is_open': False, 'keywords': [], 'last_change_time': '2019-03-29T16:57:48', 'op_sys': 'Unspecified', 'platform': 'Unspecified', 'priority': 'unspecified', 'product': 'Fedora', 'qa_contact': 'extras-qa@fedoraproject.org', 'qa_contact_detail': {'email': 'extras-qa@fedoraproject.org', 'id': 171387, 'name': 'extras-qa@fedoraproject.org', 'real_name': 'Fedora Extras Quality ' 'Assurance'}, 'remaining_time': 0.0, 'resolution': 'NOTABUG', 'see_also': [], 'severity': 'unspecified', 'status': 'CLOSED', 'summary': 'python-bugzilla test bug for API minor_update', 'target_milestone': '---', 'target_release': ['---'], 'update_token': '1578493259-h3_XQLcFwQkxxRzj5fTivx_wB8OizN7dPUyU_iJ59Bc', 'url': '', 'version': ['30'], 'whiteboard': ''}], 'faults': []} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/data/mockreturn/test_getbug_rhel.txt0000664000175000017500000001701000000000000025417 0ustar00crobinsocrobinso{'faults': [], "bugs" : [{ 'actual_time': 0.0, 'alias': [], 'assigned_to': 'lvm-team@redhat.com', 'assigned_to_detail': {'email': 'lvm-team@redhat.com', 'id': 206817, 'name': 'lvm-team@redhat.com', 'real_name': 'LVM and device-mapper development team'}, 'blocks': [123456], 'cc': ['example@redhat.com', 'example2@redhat.com'], 'cc_detail': [{'email': 'example@redhat.com', 'id': 123456, 'name': 'example@redhat.com', 'real_name': 'Example user'}, {'email': 'example2@redhat.com', 'id': 123457, 'name': 'heinzm@redhat.com', 'real_name': 'Example2 user'}], 'cf_build_id': '', 'cf_conditional_nak': [], 'cf_cust_facing': '---', 'cf_devel_whiteboard': 'somedeveltag,someothertag', 'cf_doc_type': 'Bug Fix', 'cf_environment': '', 'cf_fixed_in': '', 'cf_internal_whiteboard': 'someinternal TAG', 'cf_last_closed': '2016-03-03T22:15:07', 'cf_partner': [], 'cf_pgm_internal': '', 'cf_pm_score': '0', 'cf_qa_whiteboard': 'foo bar baz', 'cf_qe_conditional_nak': [], 'cf_release_notes': '', 'cf_target_upstream_version': '', 'cf_verified': [], 'classification': 'Red Hat', 'comments': [{'bug_id': 1165434, 'count': 0, 'creation_time': '2014-11-19T00:26:50', 'creator': 'example@redhat.com', 'creator_id': 276776, 'id': 7685441, 'is_private': False, 'tags': [], 'text': 'Description of problem:\n' 'Version-Release number of selected component (if ' 'applicable):\n' 'kernel-2.6.18-308.el5\n' 'device-mapper-multipath-0.4.7-48.el5\n' 'device-mapper-1.02.67-2.el5\n' 'device-mapper-1.02.67-2.el5\n' 'device-mapper-event-1.02.67-2.el5\n', 'time': '2014-11-19T00:26:50'}, {'bug_id': 1165434, 'count': 1, 'creation_time': '2014-11-19T00:47:57', 'creator': 'example@redhat.com', 'creator_id': 276776, 'id': 7685467, 'is_private': False, 'tags': [], 'text': 'We can see that there is a dmeventd task that has sent ' 'data over a socket and is waiting for the peer to ' 'respond:\n' '\n' 'crash> bt\n' 'any interaction with the filesystem until it has ' 'issued the suspend command to convert the mirror ' 'device to a linear device.', 'time': '2014-11-19T00:47:57'}, {'bug_id': 1165434, 'count': 2, 'creation_time': '2014-11-19T01:53:53', 'creator': 'example@redhat.com', 'creator_id': 156796, 'id': 7685595, 'is_private': False, 'tags': [], 'text': 'Test text', 'time': '2014-11-19T01:53:53'}], 'depends_on': [112233], 'docs_contact': '', 'estimated_time': 0.0, 'external_bugs': [{'bug_id': 989253, 'ext_bz_bug_id': '703421', 'ext_bz_id': 3, 'ext_description': 'None', 'ext_priority': 'None', 'ext_status': 'None', 'id': 115528, 'type': {'can_get': True, 'can_send': False, 'description': 'GNOME Bugzilla', 'full_url': 'https://bugzilla.gnome.org/show_bug.cgi?id=%id%', 'id': 3, 'must_send': False, 'send_once': False, 'type': 'Bugzilla', 'url': 'https://bugzilla.gnome.org'}}, {'bug_id': 989253, 'ext_bz_bug_id': '1203576', 'ext_bz_id': 29, 'ext_description': 'None', 'ext_priority': 'None', 'ext_status': 'None', 'id': 115527, 'type': {'can_get': False, 'can_send': False, 'description': 'Launchpad', 'full_url': 'https://bugs.launchpad.net/bugs/%id%', 'id': 29, 'must_send': False, 'send_once': False, 'type': 'None', 'url': 'https://bugs.launchpad.net/bugs'}}], 'flags': [{'creation_date': '2019-11-15T21:57:21Z', 'id': 4302313, 'is_active': 1, 'modification_date': '2019-11-15T21:57:21Z', 'name': 'qe_test_coverage', 'setter': 'pm-rhel@redhat.com', 'status': '?', 'type_id': 318}, {'creation_date': '2018-12-25T16:47:43Z', 'id': 3883137, 'is_active': 1, 'modification_date': '2018-12-25T16:47:43Z', 'name': 'release', 'setter': 'rule-engine@redhat.com', 'status': '?', 'type_id': 1197}, {'creation_date': '2018-12-25T16:47:38Z', 'id': 3883134, 'is_active': 1, 'modification_date': '2018-12-25T16:47:38Z', 'name': 'pm_ack', 'setter': 'example3@redhat.com', 'status': '?', 'type_id': 11}, {'creation_date': '2018-12-25T16:47:38Z', 'id': 3883135, 'is_active': 1, 'modification_date': '2018-12-25T16:47:38Z', 'name': 'devel_ack', 'setter': 'example2@redhat.com', 'status': '?', 'type_id': 10}, {'creation_date': '2018-12-25T16:47:38Z', 'id': 3883136, 'is_active': 1, 'modification_date': '2019-04-28T02:07:03Z', 'name': 'qa_ack', 'setter': 'example@redhat.com', 'status': '+', 'type_id': 9}, {'creation_date': '2019-03-29T06:50:01Z', 'id': 3999302, 'is_active': 1, 'modification_date': '2019-03-29T06:50:01Z', 'name': 'needinfo', 'setter': 'example@redhat.com', 'requestee': 'hello@example.com', 'status': '?', 'type_id': 1164}], 'groups': ["somegroup"], 'id': 1165434, 'is_cc_accessible': True, 'is_confirmed': True, 'is_creator_accessible': True, 'is_open': False, 'keywords': ["key1", "keyword2", "Security"], 'last_change_time': '2018-12-09T19:12:12', 'op_sys': 'Linux', 'platform': 'All', 'priority': 'medium', 'product': 'Red Hat Enterprise Linux 5', 'qa_contact': 'mspqa-list@redhat.com', 'qa_contact_detail': {'email': 'mspqa-list@redhat.com', 'id': 164197, 'name': 'mspqa-list@redhat.com', 'real_name': 'Cluster QE'}, 'remaining_time': 0.0, 'resolution': 'WONTFIX', 'see_also': [], 'severity': 'medium', 'status': 'CLOSED', 'sub_components': {'lvm2': ['dmeventd (RHEL5)']}, 'summary': 'LVM mirrored root can deadlock dmeventd if a mirror leg is lost', 'tags': [], 'target_milestone': 'rc', 'target_release': ['---'], 'url': '', 'version': ['5.8'], 'whiteboard': 'genericwhiteboard'}]} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/data/mockreturn/test_query1.txt0000664000175000017500000000104200000000000024354 0ustar00crobinsocrobinso{'bugs': [{'assigned_to_detail': {'real_name': 'Libvirt Maintainers', 'email': 'libvirt-maint', 'name': 'libvirt-maint', 'id': 311982}, 'summary': 'RFE: qemu: Support a managed autoconnect mode for host USB devices', 'status': 'NEW', 'assigned_to': 'Libvirt Maintainers', 'id': 508645}, {'assigned_to_detail': {'real_name': 'Cole Robinson', 'email': 'crobinso', 'name': 'crobinso', 'id': 199727}, 'summary': 'RFE: warn users at guest start if networks/storage pools are inactive', 'status': 'NEW', 'assigned_to': 'Cole Robinson', 'id': 668543}]} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/data/mockreturn/test_query_cve_getbug.txt0000664000175000017500000000572000000000000026474 0ustar00crobinsocrobinso{'bugs': [{'actual_time': 0.0, 'alias': ["CVE-1234-5678"], 'assigned_to': 'crobinso@redhat.com', 'assigned_to_detail': {'email': 'crobinso@redhat.com', 'id': 199727, 'name': 'crobinso@redhat.com', 'real_name': 'Cole Robinson'}, 'blocks': [], 'cc': ['crobinso@redhat.com'], 'cc_detail': [{'email': 'crobinso@redhat.com', 'id': 199727, 'name': 'crobinso@redhat.com', 'real_name': 'Cole Robinson'}], 'cf_build_id': '', 'cf_conditional_nak': [], 'cf_cust_facing': '---', 'cf_devel_whiteboard': '', 'cf_doc_type': 'If docs needed, set a value', 'cf_environment': '', 'cf_fixed_in': '', 'cf_internal_whiteboard': '', 'cf_last_closed': '2019-03-29T16:39:27', 'cf_partner': [], 'cf_pgm_internal': '', 'cf_pm_score': '0', 'cf_qa_whiteboard': '', 'cf_qe_conditional_nak': [], 'cf_release_notes': '', 'cf_verified': [], 'classification': 'Fedora', 'component': ['python-bugzilla'], 'creation_time': '2019-03-29T16:39:01', 'creator': 'crobinso@redhat.com', 'creator_detail': {'email': 'crobinso@redhat.com', 'id': 199727, 'name': 'crobinso@redhat.com', 'real_name': 'Cole Robinson'}, 'depends_on': [], 'docs_contact': '', 'estimated_time': 0.0, 'groups': [], 'id': 123456, 'is_cc_accessible': True, 'is_confirmed': True, 'is_creator_accessible': True, 'is_open': False, 'keywords': [], 'last_change_time': '2019-03-29T16:57:48', 'op_sys': 'Unspecified', 'platform': 'Unspecified', 'priority': 'unspecified', 'product': 'Fedora', 'qa_contact': 'extras-qa@fedoraproject.org', 'qa_contact_detail': {'email': 'extras-qa@fedoraproject.org', 'id': 171387, 'name': 'extras-qa@fedoraproject.org', 'real_name': 'Fedora Extras Quality ' 'Assurance'}, 'remaining_time': 0.0, 'resolution': 'NOTABUG', 'see_also': [], 'severity': 'unspecified', 'status': 'CLOSED', 'summary': 'python-bugzilla test bug for API minor_update', 'target_milestone': '---', 'target_release': ['---'], 'update_token': '1578493259-h3_XQLcFwQkxxRzj5fTivx_wB8OizN7dPUyU_iJ59Bc', 'url': '', 'version': ['30'], 'whiteboard': ''}], 'faults': []} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/mockbackend.py0000664000175000017500000001106500000000000021045 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import inspect import bugzilla from bugzilla._backendbase import _BackendBase import tests.utils # pylint: disable=abstract-method,arguments-differ class BackendMock(_BackendBase): _version = None def bugzilla_version(self): return {"version": self._version} def __helper(self, args): # Grab the calling function name and use it to generate # input and output variable names for the class. So if this # is called from bug_get, we look for: # self._bug_get_args # self._bug_get_return prevfuncname = inspect.stack()[1][3] func_args = getattr(self, "_%s_args" % prevfuncname) func_return = getattr(self, "_%s_return" % prevfuncname) if isinstance(func_return, BaseException): raise func_return filename = None expect_out = func_args if isinstance(func_args, str): filename = func_args expect_out = None # Hack to strip out attachment content from the generated # test output, because it doesn't play well with the test # suite running on python2 if "content-disposition" in str(args): largs = list(args) largs[1] = "STRIPPED-BY-TESTSUITE" args = tuple(largs) if filename or expect_out: tests.utils.diff_compare(args, filename, expect_out) if isinstance(func_return, dict): return func_return returnstr = open(tests.utils.tests_path(func_return)).read() return eval(returnstr) # pylint: disable=eval-used def bug_attachment_create(self, *args): return self.__helper(args) def bug_attachment_get(self, *args): return self.__helper(args) def bug_attachment_get_all(self, *args): return self.__helper(args) def bug_attachment_update(self, *args): return self.__helper(args) def bug_comments(self, *args): return self.__helper(args) def bug_create(self, *args): return self.__helper(args) def bug_history(self, *args): return self.__helper(args) def bug_get(self, *args): return self.__helper(args) def bug_fields(self, *args): return self.__helper(args) def bug_search(self, *args): return self.__helper(args) def bug_update(self, *args): return self.__helper(args) def bug_update_tags(self, *args): return self.__helper(args) def component_create(self, *args): return self.__helper(args) def component_get(self, *args): return self.__helper(args) def component_update(self, *args): return self.__helper(args) def group_get(self, *args): return self.__helper(args) def externalbugs_add(self, *args): return self.__helper(args) def externalbugs_update(self, *args): return self.__helper(args) def externalbugs_remove(self, *args): return self.__helper(args) def product_get(self, *args): return self.__helper(args) def product_get_accessible(self, *args): return self.__helper(args) def product_get_enterable(self, *args): return self.__helper(args) def product_get_selectable(self, *args): return self.__helper(args) def user_create(self, *args): return self.__helper(args) def user_get(self, *args): return self.__helper(args) def user_login(self, *args): return self.__helper(args) def user_logout(self, *args): return self.__helper(args) def user_update(self, *args): return self.__helper(args) def _make_backend_class(version="6.0.0", **kwargs): class TmpBackendClass(BackendMock): _version = version for key, val in kwargs.items(): setattr(TmpBackendClass, "_%s" % key, val) return TmpBackendClass def make_bz(bz_kwargs=None, rhbz=False, **kwargs): bz_kwargs = (bz_kwargs or {}).copy() if "url" in bz_kwargs: raise RuntimeError("Can't set 'url' in mock make_bz, use connect()") if "use_creds" not in bz_kwargs: bz_kwargs["use_creds"] = False bz = bugzilla.Bugzilla(url=None, **bz_kwargs) backendclass = _make_backend_class(**kwargs) def _get_backend_class(url): return backendclass, bugzilla.Bugzilla.fix_url(url) # pylint: disable=protected-access bz._get_backend_class = _get_backend_class url = "https:///TESTSUITEMOCK" if rhbz: url += "?fakeredhat=bugzilla.redhat.com" bz.connect(url) return bz ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/pycodestyle.cfg0000664000175000017500000000000000000000000021242 0ustar00crobinsocrobinso././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1578859362.0 python-bugzilla-3.0.2/tests/test_api_attachments.py0000664000175000017500000000327600000000000023014 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # import os import pytest import tests import tests.mockbackend def test_api_attachments(): # misc coverage testing for Bugzilla attachment APIs fakebz = tests.mockbackend.make_bz( bug_attachment_get_all_args=( "data/mockargs/test_attachments_getall1.txt"), bug_attachment_get_all_return={}, bug_attachment_update_args=( "data/mockargs/test_attachments_update1.txt"), bug_attachment_update_return={}, bug_attachment_get_args=( "data/mockargs/test_attachments_get1.txt"), bug_attachment_get_return=( "data/mockreturn/test_attach_get1.txt"), bug_attachment_create_args=( "data/mockargs/test_api_attachments_create1.txt"), bug_attachment_create_return={ "attachments": {"123456": {}, "456789": []}}, ) # coverage for include/exclude handling fakebz.get_attachments([123456], None, include_fields=["foo"], exclude_fields="bar") # coverage for updateattachment fakebz.updateattachmentflags(None, "112233", "needinfo", value="foobar", is_patch=True) # coverage for openattachment fobj = fakebz.openattachment(502352) assert "Hooray" in str(fobj.read()) # Error on bad input type with pytest.raises(TypeError): fakebz.attachfile([123456], None, "some desc") # Misc attachfile() pieces attachfile = os.path.dirname(__file__) + "/data/bz-attach-get1.txt" ret = fakebz.attachfile([123456], attachfile, "some desc", isprivate=True) ret.sort() assert ret == [123456, 456789] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/test_api_authfiles.py0000664000175000017500000001621500000000000022462 0ustar00crobinsocrobinso# # Copyright Red Hat, Inc. 2012 # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # """ Test miscellaneous API bits """ import os import shutil import tempfile import pytest import requests import bugzilla import tests import tests.mockbackend import tests.utils def testCookies(monkeypatch): monkeypatch.setitem(os.environ, "HOME", os.path.dirname(__file__) + "/data/homedir") dirname = os.path.dirname(__file__) cookiesbad = dirname + "/data/cookies-bad.txt" cookieslwp = dirname + "/data/cookies-lwp.txt" cookiesmoz = dirname + "/data/cookies-moz.txt" # We used to convert LWP cookies, but it shouldn't matter anymore, # so verify they fail at least with pytest.raises(bugzilla.BugzillaError): tests.mockbackend.make_bz(version="3.0.0", bz_kwargs={"cookiefile": cookieslwp, "use_creds": True}) with pytest.raises(bugzilla.BugzillaError): tests.mockbackend.make_bz(version="3.0.0", bz_kwargs={"cookiefile": cookiesbad, "use_creds": True}) # Mozilla should 'just work' bz = tests.mockbackend.make_bz(version="3.0.0", bz_kwargs={"cookiefile": cookiesmoz, "use_creds": True}) # cookie/token property magic bz = tests.mockbackend.make_bz(bz_kwargs={"use_creds": True}) token = dirname + "/data/homedir/.cache/python-bugzilla/bugzillatoken" cookie = dirname + "/data/homedir/.cache/python-bugzilla/bugzillacookies" assert token == bz.tokenfile assert cookie == bz.cookiefile del(bz.tokenfile) del(bz.cookiefile) assert bz.tokenfile is None assert bz.cookiefile is None def test_readconfig(): # Testing for bugzillarc handling bzapi = tests.mockbackend.make_bz(version="4.4.0", rhbz=True) bzapi.url = "example.com" temp = tempfile.NamedTemporaryFile(mode="w") def _check(user, password, api_key, cert): assert bzapi.user == user assert bzapi.password == password assert bzapi.api_key == api_key assert bzapi.cert == cert def _write(c): temp.seek(0) temp.write(c) temp.flush() return temp.name # Check readconfig normal usage content = """ [example.com] foo=1 user=test1 password=test2 api_key=123abc cert=/a/b/c someunknownkey=someval """ bzapi.readconfig(_write(content)) _check("test1", "test2", "123abc", "/a/b/c") # Check loading a different URL, that values aren't overwritten content = """ [foo.example.com] user=test3 password=test4 api_key=567abc cert=/newpath """ bzapi.readconfig(_write(content)) _check("test1", "test2", "123abc", "/a/b/c") # Change URL, but check readconfig with overwrite=False bzapi.url = "foo.example.com" bzapi.readconfig(temp.name, overwrite=False) _check("test1", "test2", "123abc", "/a/b/c") # With default overwrite=True, values will be updated # Alter the config to have a / in the hostname, which hits different code content = content.replace("example.com", "example.com/xmlrpc.cgi") bzapi.url = "https://foo.example.com/xmlrpc.cgi" bzapi.readconfig(_write(content)) _check("test3", "test4", "567abc", "/newpath") # Confirm nothing overwritten for a totally different URL bzapi.user = None bzapi.password = None bzapi.api_key = None bzapi.cert = None bzapi.url = "bugzilla.redhat.com" bzapi.readconfig(temp.name) _check(None, None, None, None) # Test confipath overwrite assert [temp.name] == bzapi.configpath del(bzapi.configpath) assert [] == bzapi.configpath bzapi.readconfig() _check(None, None, None, None) def _get_cookiejar(): cookiefile = os.path.dirname(__file__) + "/data/cookies-moz.txt" inputbz = tests.mockbackend.make_bz( bz_kwargs={"use_creds": True, "cookiefile": cookiefile}) cookiecache = inputbz._cookiecache # pylint: disable=protected-access return cookiecache.get_cookiejar() def test_authfiles_saving(monkeypatch): tmpdir = tempfile.mkdtemp() try: monkeypatch.setitem(os.environ, "HOME", tmpdir) bzapi = tests.mockbackend.make_bz( bz_kwargs={"use_creds": True, "cert": "foo-fake-cert"}) bzapi.connect("https://example.com/fakebz") bzapi.cert = "foo-fake-path" backend = bzapi._backend # pylint: disable=protected-access bsession = backend._bugzillasession # pylint: disable=protected-access response = requests.Response() response.cookies = _get_cookiejar() # token testing, with repetitions to hit various code paths bsession.set_token_value(None) bsession.set_token_value("MY-FAKE-TOKEN") bsession.set_token_value("MY-FAKE-TOKEN") bsession.set_token_value(None) bsession.set_token_value("MY-FAKE-TOKEN") # cookie testing bsession.set_response_cookies(response) dirname = os.path.dirname(__file__) + "/data/authfiles/" output_token = dirname + "output-token.txt" output_cookies = dirname + "output-cookies.txt" tests.utils.diff_compare(open(bzapi.tokenfile).read(), output_token) # On RHEL7 the cookie comment header is different. Strip off leading # comments def strip_comments(f): return "".join([ line for line in open(f).readlines() if not line.startswith("#")]) tests.utils.diff_compare(strip_comments(bzapi.cookiefile), None, expect_out=strip_comments(output_cookies)) # Make sure file can re-read them and not error bzapi = tests.mockbackend.make_bz( bz_kwargs={"use_creds": True, "cookiefile": output_cookies, "tokenfile": output_token}) assert bzapi.tokenfile == output_token assert bzapi.cookiefile == output_cookies # Test rcfile writing for api_key rcfile = bzapi._rcfile # pylint: disable=protected-access bzapi.url = "https://example.com/fake" rcfile.save_api_key(bzapi.url, "TEST-API-KEY") rcfilepath = tmpdir + "/.config/python-bugzilla/bugzillarc" assert rcfile.get_configpaths()[-1] == rcfilepath tests.utils.diff_compare(open(rcfilepath).read(), dirname + "output-bugzillarc.txt") # Use that generated rcfile to test default URL lookup fakeurl = "http://foo.bar.baz/wibble" open(rcfilepath, "w").write("\n[DEFAULT]\nurl = %s" % fakeurl) assert bzapi.get_rcfile_default_url() == fakeurl finally: shutil.rmtree(tmpdir) def test_authfiles_nowrite(): # Set values when n when cookiefile is None, should be fine bzapi = tests.mockbackend.make_bz(bz_kwargs={"use_creds": False}) bzapi.connect("https://example.com/foo") backend = bzapi._backend # pylint: disable=protected-access bsession = backend._bugzillasession # pylint: disable=protected-access rcfile = bzapi._rcfile # pylint: disable=protected-access response = requests.Response() response.cookies = _get_cookiejar() bsession.set_token_value("NEW-TOKEN-VALUE") bsession.set_response_cookies(response) assert rcfile.save_api_key(bzapi.url, "fookey") is None ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/test_api_bug.py0000664000175000017500000001271400000000000021253 0ustar00crobinsocrobinso# # Copyright Red Hat, Inc. 2014 # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # """ Unit tests for testing some bug.py magic """ import io import pickle import pytest import tests import tests.mockbackend import tests.utils from bugzilla.bug import Bug rhbz = tests.mockbackend.make_bz(version="4.4.0", rhbz=True) def testBasic(): data = { "bug_id": 123456, "status": "NEW", "assigned_to": "foo@bar.com", "component": "foo", "product": "bar", "short_desc": "some short desc", "cf_fixed_in": "nope", "fixed_in": "1.2.3.4", "devel_whiteboard": "some status value", } bug = Bug(bugzilla=rhbz, dict=data) def _assert_bug(): assert hasattr(bug, "component") is True assert getattr(bug, "components") == ["foo"] assert getattr(bug, "product") == "bar" assert hasattr(bug, "short_desc") is True assert getattr(bug, "summary") == "some short desc" assert bool(getattr(bug, "cf_fixed_in")) is True assert getattr(bug, "fixed_in") == "1.2.3.4" assert bool(getattr(bug, "cf_devel_whiteboard")) is True assert getattr(bug, "devel_whiteboard") == "some status value" _assert_bug() assert str(bug) == "#123456 NEW - foo@bar.com - some short desc" assert repr(bug).startswith(" 18 def testCmdHelp(run_cli): out = run_cli("bugzilla query --help", None) assert len(out.splitlines()) > 40 def testVersion(run_cli): out = run_cli("bugzilla --version", None) assert out.strip() == bugzilla.__version__ def testPositionalArgs(run_cli): # Make sure cli correctly rejects ambiguous positional args out = run_cli("bugzilla login --xbadarg foo", None, expectfail=True) assert "unrecognized arguments: --xbadarg" in out out = run_cli("bugzilla modify 123456 --foobar --status NEW", None, expectfail=True) assert "unrecognized arguments: --foobar" in out def testDebug(run_cli): # Coverage testing for debug options run_cli("bugzilla --bugzilla https:///BADURI --verbose login", None, expectfail=True) run_cli("bugzilla --bugzilla https:///BADURI --debug login", None, expectfail=True) def testExceptions(run_cli): """ Test exception handling around main() """ fakebz = tests.mockbackend.make_bz( bug_search_args=None, bug_search_return=KeyboardInterrupt()) out = run_cli("bugzilla query --bug_id 1", fakebz, expectfail=True) assert "user request" in out fakebz = tests.mockbackend.make_bz( bug_search_args=None, bug_search_return=bugzilla.BugzillaError("foo")) out = run_cli("bugzilla query --bug_id 1", fakebz, expectfail=True) assert "Server error:" in out fakebz = tests.mockbackend.make_bz( bug_search_args=None, bug_search_return=requests.exceptions.SSLError()) out = run_cli("bugzilla query --bug_id 1", fakebz, expectfail=True) assert "trust the remote server" in out fakebz = tests.mockbackend.make_bz( bug_search_args=None, bug_search_return=requests.exceptions.ConnectionError()) out = run_cli("bugzilla query --bug_id 1", fakebz, expectfail=True) assert "Connection lost" in out def testManualURL(run_cli): """ Test passing a manual URL, to hit those non-testsuite code paths """ try: cmd = "bugzilla --bztype foobar " cmd += "--bugzilla https:///FAKEURL query --bug_id 1" run_cli(cmd, None) except Exception as e: assert "No host supplied" in str(e) def test_json_xmlrpc(run_cli): # Test --json output with XMLRPC type conversion cmd = "bugzilla query --json --id 1165434" timestr = '20181209T19:12:12' dateobj = datetime.datetime.strptime(timestr, '%Y%m%dT%H:%M:%S') attachfile = tests.utils.tests_path("data/bz-attach-get1.txt") attachdata = open(attachfile, "rb").read() bugid = 1165434 data = {"bugs": [{ 'id': bugid, 'timetest': xmlrpc.client.DateTime(dateobj), 'binarytest': xmlrpc.client.Binary(attachdata), }]} fakebz = tests.mockbackend.make_bz( bug_search_args=None, bug_search_return={"bugs": [{"id": bugid}]}, bug_get_args=None, bug_get_return=data) out = run_cli(cmd, fakebz) tests.utils.diff_compare(tests.utils.sanitize_json(out), "data/clioutput/test_json_xmlrpc.txt") retdata = json.loads(out)["bugs"][0] assert (base64.b64decode(retdata["binarytest"]) == attachdata) assert retdata["timetest"] == dateobj.isoformat() + "Z" # Test an error case, json converter can't handle Exception class data["bugs"][0]["foo"] = Exception("foo") fakebz = tests.mockbackend.make_bz( bug_search_args=None, bug_search_return={"bugs": [{"id": bugid}]}, bug_get_args=None, bug_get_return=data) with pytest.raises(RuntimeError): run_cli(cmd, fakebz, expectfail=True) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/test_cli_modify.py0000664000175000017500000000677500000000000021775 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import tests import tests.mockbackend import tests.utils ################################## # 'bugzilla modify' mock testing # ################################## def test_modify(run_cli): # errors on missing args cmd = "bugzilla modify 123456" fakebz = tests.mockbackend.make_bz() out = run_cli(cmd, fakebz, expectfail=True) assert "additional arguments" in out # Modify basic cmd = "bugzilla modify 123456 1234567 " cmd += "--status ASSIGNED --component NEWCOMP " fakebz = tests.mockbackend.make_bz( bug_update_args="data/mockargs/test_modify1.txt", bug_update_return={}) out = run_cli(cmd, fakebz) assert not out # Modify with lots of opts cmd = "bugzilla modify 123456 --component NEWCOMP " cmd += "--keyword +FOO --groups=-BAR --blocked =123456,445566 " cmd += "--flag=-needinfo,+somethingelse " cmd += "--whiteboard =foo --whiteboard =thisone " cmd += "--dupeid 555666 " cmd += "--comment 'some example comment' --private " fakebz = tests.mockbackend.make_bz( bug_update_args="data/mockargs/test_modify2.txt", bug_update_return={}) out = run_cli(cmd, fakebz) assert not out # Modify with tricky opts hitting other API calls cmd = "bugzilla modify 1165434 " cmd += "--tags +addtag --tags=-rmtag " cmd += "--qa_whiteboard +yo-qa --qa_whiteboard=-foo " cmd += "--internal_whiteboard +internal-hey --internal_whiteboard +bar " cmd += "--devel_whiteboard +devel-duh --devel_whiteboard=-yay " fakebz = tests.mockbackend.make_bz(rhbz=True, bug_update_tags_args="data/mockargs/test_modify3-tags.txt", bug_update_tags_return={}, bug_update_args="data/mockargs/test_modify3.txt", bug_update_return={}, bug_get_args=None, bug_get_return="data/mockreturn/test_getbug_rhel.txt") out = run_cli(cmd, fakebz) assert not out # Modify hitting some rhbz paths cmd = "bugzilla modify 1165434 " cmd += "--fixed_in foofixedin " cmd += "--component lvm2 " cmd += "--sub-component some-sub-component" fakebz = tests.mockbackend.make_bz(rhbz=True, bug_update_args="data/mockargs/test_modify4.txt", bug_update_return={}) out = run_cli(cmd, fakebz) assert not out # Modify with a slew of misc opt coverage cmd = "bugzilla modify 1165434 " cmd += "--assigned_to foo@example.com --qa_contact qa@example.com " cmd += "--product newproduct " cmd += "--blocked +1234 --blocked -1235 --blocked = " cmd += "--url https://example.com " cmd += "--cc=+bar@example.com --cc=-steve@example.com " cmd += "--dependson=+2234 --dependson=-2235 --dependson = " cmd += "--groups +foogroup " cmd += "--keywords +newkeyword --keywords=-byekeyword --keywords = " cmd += "--os windows --arch mips " cmd += "--priority high --severity low " cmd += "--summary newsummary --version 1.2.3 " cmd += "--reset-assignee --reset-qa-contact " cmd += "--alias fooalias " cmd += "--target_release 1.2.4 --target_milestone beta " cmd += "--devel_whiteboard =DEVBOARD --internal_whiteboard =INTBOARD " cmd += "--qa_whiteboard =QABOARD " cmd += "--comment-tag FOOTAG --field bar=foo " cmd += "--minor-update " fakebz = tests.mockbackend.make_bz(rhbz=True, bug_update_args="data/mockargs/test_modify5.txt", bug_update_return={}) out = run_cli(cmd, fakebz) assert not out ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/test_cli_new.py0000664000175000017500000000402700000000000021263 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import tests import tests.mockbackend import tests.utils ############################### # 'bugzilla new' mock testing # ############################### def test_new(run_cli): # Test a simpler creation cmd = "bugzilla new --product FOOPROD --component FOOCOMP " cmd += "--summary 'Hey this is the title!' " cmd += "--comment 'This is the first comment!\nWith newline & stuff.' " cmd += "--keywords ADDKEY --groups FOOGROUP,BARGROUP " cmd += "--blocked 12345,6789 --cc foo@example.com --cc bar@example.com " cmd += "--dependson dependme --private " fakebz = tests.mockbackend.make_bz( bug_create_args="data/mockargs/test_new1.txt", bug_create_return={"id": 1694158}, bug_get_args=None, bug_get_return="data/mockreturn/test_getbug.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_new1.txt") # Test every option cmd = "bugzilla new --product FOOPROD --component FOOCOMP " cmd += "--summary 'Hey this is the title!' " cmd += "--comment 'This is the first comment!\nWith newline & stuff.' " cmd += "--keywords ADDKEY --groups FOOGROUP,BARGROUP " cmd += "--blocked 12345,6789 --cc foo@example.com --cc bar@example.com " cmd += "--dependson dependme --private " cmd += "--os linux --arch mips --severity high --priority low " cmd += "--url https://some.example.com " cmd += "--version 5.6.7 --alias somealias " cmd += "--sub-component FOOCOMP " cmd += "--assignee foo@example.com --qa_contact qa@example.com " cmd += "--comment-tag FOO " cmd += "--field foo=bar " fakebz = tests.mockbackend.make_bz( bug_create_args="data/mockargs/test_new2.txt", bug_create_return={"id": 1694158}, bug_get_args=None, bug_get_return="data/mockreturn/test_getbug.txt", rhbz=True) out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_new2.txt") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/test_cli_query.py0000664000175000017500000001710300000000000021636 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import json import os import re import tests import tests.mockbackend import tests.utils ################################# # 'bugzilla query' mock testing # ################################# def test_query(run_cli): # bad field option fakebz = tests.mockbackend.make_bz() cmd = "bugzilla query --field FOO" out = run_cli(cmd, fakebz, expectfail=True) assert "Invalid field argument" in out # Simple query with some comma opts cmd = "bugzilla query " cmd += "--product foo --component foo,bar --bug_id 1234,2480" fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query1.txt", bug_search_return="data/mockreturn/test_query1.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query1.txt") # RHBZ query with a ton of opts cmd = "bugzilla query " cmd += "--product foo --component foo,bar --bug_id 1234,2480 " cmd += "--keywords fribkeyword --fixed_in amifixed " cmd += "--qa_whiteboard some-example-whiteboard " cmd += "--cc foo@example.com --qa_contact qa@example.com " cmd += "--comment 'some comment string' " fakebz = tests.mockbackend.make_bz(rhbz=True, bug_search_args="data/mockargs/test_query1-rhbz.txt", bug_search_return="data/mockreturn/test_query1.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query1-rhbz.txt") # --emailtype handling cmd = "bugzilla query --cc foo@example.com --emailtype BAR " fakebz = tests.mockbackend.make_bz(rhbz=True, bug_search_args="data/mockargs/test_query2-rhbz.txt", bug_search_return="data/mockreturn/test_query1.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query2-rhbz.txt") # Same but with --ids output cmd = "bugzilla query --ids " cmd += "--product foo --component foo,bar --bug_id 1234,2480" fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query1-ids.txt", bug_search_return="data/mockreturn/test_query1.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query1-ids.txt") # Same but with --raw output cmd = "bugzilla query --raw --bug_id 1165434" fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query2.txt", bug_search_return={"bugs": [{"id": 1165434}]}, bug_get_args=None, bug_get_return="data/mockreturn/test_getbug_rhel.txt") out = run_cli(cmd, fakebz) # Dictionary ordering is random, so scrub it from our output out = re.sub(r"\{.*\}", r"'DICT SCRUBBED'", out, re.MULTILINE) tests.utils.diff_compare(out, "data/clioutput/test_query2.txt") # Test a bunch of different combinations for code coverage cmd = "bugzilla query --status ALL --severity sev1,sev2 " cmd += "--outputformat='%{foo}:%{bar}::%{whiteboard}:" cmd += "%{flags}:%{flags_requestee}%{whiteboard:devel}::" cmd += "%{flag:needinfo}::%{comments}::%{external_bugs}'" fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query3.txt", bug_search_return="data/mockreturn/test_getbug_rhel.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query3.txt") # Test --status DEV and --full cmd = "bugzilla query --status DEV --full" fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query4.txt", bug_search_return="data/mockreturn/test_getbug_rhel.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query4.txt") # Test --status QE and --extra, and components-file compfile = os.path.dirname(__file__) + "/data/components_file.txt" cmd = "bugzilla query --status QE --extra " cmd += "--components_file %s" % compfile fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query5.txt", bug_search_return="data/mockreturn/test_getbug_rhel.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query5.txt") # Test --status EOL and --oneline, and some --field usage cmd = "bugzilla query --status EOL --oneline " cmd += "--field FOO=1 --field=BAR=WIBBLE " fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query6.txt", bug_search_return="data/mockreturn/test_getbug_rhel.txt", bug_get_args="data/mockargs/test_query_cve_getbug.txt", bug_get_return="data/mockreturn/test_query_cve_getbug.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query6.txt") # Test --status OPEN and --from-url url = "https://bugzilla.redhat.com/buglist.cgi?bug_status=NEW&bug_status=ASSIGNED&bug_status=MODIFIED&bug_status=ON_DEV&bug_status=ON_QA&bug_status=VERIFIED&bug_status=FAILS_QA&bug_status=RELEASE_PENDING&bug_status=POST&classification=Fedora&component=virt-manager&order=bug_status%2Cbug_id&product=Fedora&query_format=advanced" # noqa cmd = "bugzilla query --status OPEN --from-url %s" % url fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query7.txt", bug_search_return="data/mockreturn/test_getbug_rhel.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query7.txt") # Test --json output cmd = "bugzilla query --json --id 1165434" fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query8.txt", bug_search_return={"bugs": [{"id": 1165434}]}, bug_get_args=None, bug_get_return="data/mockreturn/test_getbug_rhel.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(tests.utils.sanitize_json(out), "data/clioutput/test_query8.txt") assert json.loads(out) # Test --json output cmd = ("bugzilla query --json --id 1165434 " "--includefield foo --includefield bar " "--excludefield excludeme " "--extrafield extrame1 --extrafield extrame2 ") fakebz = tests.mockbackend.make_bz(rhbz=True, bug_search_args="data/mockargs/test_query9.txt", bug_search_return={"bugs": [{"id": 1165434}]}, bug_get_args="data/mockargs/test_getbug_query9.txt", bug_get_return="data/mockreturn/test_getbug_rhel.txt") out = run_cli(cmd, fakebz) tests.utils.diff_compare(tests.utils.sanitize_json(out), "data/clioutput/test_query9.txt") assert json.loads(out) # Test every remaining option cmd = "bugzilla query " cmd += "--sub-component FOOCOMP " cmd += "--version 5.6.7 --reporter me@example.com " cmd += "--summary 'search summary' " cmd += "--assignee bar@example.com " cmd += "--blocked 12345 --dependson 23456 " cmd += "--keywords FOO --keywords_type substring " cmd += "--url https://example.com --url_type sometype " cmd += "--target_release foo --target_milestone bar " cmd += "--quicksearch 1 --savedsearch 2 --savedsearch-sharer-id 3 " cmd += "--tags +foo --flag needinfo --alias somealias " cmd += "--devel_whiteboard DEVBOARD " cmd += "--priority wibble " cmd += "--fixed_in 5.5.5 --fixed_in_type substring " cmd += "--whiteboard FOO --status_whiteboard_type substring " fakebz = tests.mockbackend.make_bz( bug_search_args="data/mockargs/test_query10.txt", bug_search_return="data/mockreturn/test_getbug_rhel.txt", rhbz=True) out = run_cli(cmd, fakebz) tests.utils.diff_compare(out, "data/clioutput/test_query10.txt") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605226594.0 python-bugzilla-3.0.2/tests/test_ro_functional.py0000664000175000017500000002663600000000000022517 0ustar00crobinsocrobinso# # Copyright Red Hat, Inc. 2012 # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # """ Unit tests that do readonly functional tests against real bugzilla instances. """ import pytest import bugzilla import tests REDHAT_URL = (tests.CLICONFIG.REDHAT_URL or "https://bugzilla.redhat.com") def _open_bz(url, bzclass=None, **kwargs): if "use_creds" not in kwargs: kwargs["use_creds"] = False return tests.utils.open_functional_bz(bzclass or bugzilla.Bugzilla, url, kwargs) def _check(out, mincount, expectstr): # Since we are running these tests against bugzilla instances in # the wild, we can't depend on certain data like product lists # remaining static. Use lax sanity checks in this case if mincount is not None: assert len(out.splitlines()) >= mincount assert expectstr in out def _test_version(bz, bzversion): assert bz.bz_ver_major == bzversion[0] assert bz.bz_ver_minor == bzversion[1] def test_bugzilla_override(): class MyBugzilla(bugzilla.Bugzilla): pass bz = _open_bz("bugzilla.redhat.com", bzclass=MyBugzilla) assert bz.__class__ is MyBugzilla assert bz._is_redhat_bugzilla is True # pylint: disable=protected-access def test_rest_xmlrpc_detection(): # The default: use XMLRPC bz = _open_bz("bugzilla.redhat.com") assert bz.is_xmlrpc() assert "/xmlrpc.cgi" in bz.url assert bz.__class__ is bugzilla.RHBugzilla # See /rest in the URL, so use REST bz = _open_bz("bugzilla.redhat.com/rest") assert bz.is_rest() # See /xmlrpc.cgi in the URL, so use XMLRPC bz = _open_bz("bugzilla.redhat.com/xmlrpc.cgi") assert bz.is_xmlrpc() def test_apikey_error_scraping(): # Ensure the API key does not leak into any requests exceptions fakekey = "FOOBARMYKEY" with pytest.raises(Exception) as e: _open_bz("https://httpstat.us/502&foo", force_xmlrpc=True, api_key=fakekey) assert "400 Client Error" in str(e.value) assert fakekey not in str(e.value) with pytest.raises(Exception) as e: _open_bz("https://httpstat.us/502&foo", force_rest=True, api_key=fakekey) assert "400 Client Error" in str(e.value) assert fakekey not in str(e.value) ################### # mozilla testing # ################### def test_mozilla(backends): url = "bugzilla.mozilla.org" bz = _open_bz(url, **backends) # bugzilla.mozilla.org returns version values in YYYY-MM-DD # format, so just try to confirm that assert bz.__class__ == bugzilla.Bugzilla assert bz.bz_ver_major >= 2016 assert bz.bz_ver_minor in range(1, 13) ################## # gentoo testing # ################## def test_gentoo(backends): url = "bugs.gentoo.org" bzversion = (5, 0) bz = _open_bz(url, **backends) _test_version(bz, bzversion) # This is a bugzilla 5.0 instance, which supports URL queries now query_url = ("https://bugs.gentoo.org/buglist.cgi?" "component=[CS]&product=Doc%20Translations" "&query_format=advanced&resolution=FIXED") ret = bz.query(bz.url_to_query(query_url)) assert len(ret) > 0 ################## # redhat testing # ################## def testInfoProducts(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) out = run_cli("bugzilla info --products", bz) _check(out, 123, "Virtualization Tools") def testInfoComps(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) out = run_cli("bugzilla info --components 'Virtualization Tools'", bz) _check(out, 8, "virtinst") def testInfoVers(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) out = run_cli("bugzilla info --versions Fedora", bz) _check(out, 17, "rawhide") def testInfoCompOwners(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) out = run_cli("bugzilla info " "--component_owners 'Virtualization Tools'", bz) _check(out, None, "libvirt: Libvirt Maintainers") def testQuery(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) args = "--product Fedora --component python-bugzilla --version 14" cli = "bugzilla query %s --bug_status CLOSED" % args mincount = 4 expectbug = "621030" out = run_cli(cli, bz) assert len(out.splitlines()) >= mincount assert bool([l1 for l1 in out.splitlines() if l1.startswith("#" + expectbug)]) # Check --ids output option out2 = run_cli(cli + " --ids", bz) assert len(out.splitlines()) == len(out2.splitlines()) assert bool([l2 for l2 in out2.splitlines() if l2 == expectbug]) def testQueryFull(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) bugid = "621601" out = run_cli("bugzilla query --full --bug_id %s" % bugid, bz) _check(out, 60, "end-of-life (EOL)") def testQueryRaw(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) bugid = "307471" out = run_cli("bugzilla query --raw --bug_id %s" % bugid, bz) _check(out, 70, "ATTRIBUTE[whiteboard]: bzcl34nup") def testQueryOneline(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) bugid = "785016" out = run_cli("bugzilla query --oneline --bug_id %s" % bugid, bz) assert len(out.splitlines()) == 1 assert out.splitlines()[0].startswith("#%s" % bugid) assert "[---] fedora-review+,fedora-cvs+" in out bugid = "720784" out = run_cli("bugzilla query --oneline --bug_id %s" % bugid, bz) assert len(out.splitlines()) == 1 assert out.splitlines()[0].startswith("#%s" % bugid) assert " CVE-2011-2527" in out def testQueryExtra(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) bugid = "307471" out = run_cli("bugzilla query --extra --bug_id %s" % bugid, bz) assert ("#%s" % bugid) in out assert " +Status Whiteboard: bzcl34nup" in out def testQueryFormat(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) args = ("--bug_id 307471 --outputformat=\"id=%{bug_id} " "sw=%{whiteboard:status} needinfo=%{flag:needinfo} " "sum=%{summary}\"") out = run_cli("bugzilla query %s" % args, bz) assert "id=307471 sw= bzcl34nup needinfo= " in out args = ("--bug_id 785016 --outputformat=\"id=%{bug_id} " "sw=%{whiteboard:status} flag=%{flag:fedora-review} " "sum=%{summary}\"") out = run_cli("bugzilla query %s" % args, bz) assert "id=785016 sw= flag=+" in out # Unicode in this bug's summary args = "--bug_id 522796 --outputformat \"%{summary}\"" out = run_cli("bugzilla query %s" % args, bz) assert u"V34 — system" in out def testQueryURL(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) qurl = ("/buglist.cgi?f1=creation_ts" "&list_id=973582&o1=greaterthaneq&classification=Fedora&" "o2=lessthaneq&query_format=advanced&f2=creation_ts" "&v1=2010-01-01&component=python-bugzilla&v2=2011-01-01" "&product=Fedora") url = REDHAT_URL if "/xmlrpc.cgi" in url: url = url.replace("/xmlrpc.cgi", qurl) else: url += qurl out = run_cli("bugzilla query --from-url \"%s\"" % url, bz) _check(out, 22, "#553878 CLOSED") def testQueryFixedIn(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) out = run_cli("bugzilla query --fixed_in anaconda-15.29-1", bz) assert len(out.splitlines()) == 4 assert "#629311 CLOSED" in out def testQueryExtrafieldPool(run_cli, backends): # rhbz has an agile 'pool' extension but doesn't return the field # by default. Check that '-extrafield pool' returns it for --json output bz = _open_bz(REDHAT_URL, **backends) out1 = run_cli("bugzilla query --id 1717616 --json", bz) out2 = run_cli("bugzilla query --id 1717616 --json --extrafield pool", bz) assert "current_sprint_id" not in out1 assert "current_sprint_id" in out2 def testComponentsDetails(backends): """ Fresh call to getcomponentsdetails should properly refresh """ bz = _open_bz(REDHAT_URL, **backends) assert bool(bz.getcomponentsdetails("Red Hat Developer Toolset")) def testGetBugAlias(backends): """ getbug() works if passed an alias """ bz = _open_bz(REDHAT_URL, **backends) bug = bz.getbug("CVE-2011-2527") assert bug.bug_id == 720773 def testQuerySubComponent(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) tests.utils.skip_if_rest(bz, "Not working on REST, not sure why yet") # Test special error wrappers in bugzilla/_cli.py out = run_cli("bugzilla query --product 'Red Hat Enterprise Linux 7' " "--component lvm2 --sub-component 'Thin Provisioning'", bz) assert len(out.splitlines()) >= 3 assert "#1060931 " in out def testBugFields(backends): bz = _open_bz(REDHAT_URL, **backends) fields = bz.getbugfields(names=["product"])[:] assert fields == ["product"] bz.getbugfields(names=["product", "bug_status"], force_refresh=True) assert set(bz.bugfields) == set(["product", "bug_status"]) def testBugAutoRefresh(backends): bz = _open_bz(REDHAT_URL, **backends) bz.bug_autorefresh = True bug = bz.query(bz.build_query(bug_id=720773, include_fields=["summary"]))[0] assert hasattr(bug, "component") assert bool(bug.component) bz.bug_autorefresh = False bug = bz.query(bz.build_query(bug_id=720773, include_fields=["summary"]))[0] assert not hasattr(bug, "component") try: assert bool(bug.component) except Exception as e: assert "adjust your include_fields" in str(e) def testExtraFields(backends): bz = _open_bz(REDHAT_URL, **backends) # Check default extra_fields will pull in comments bug = bz.getbug(720773, exclude_fields=["product"]) assert "comments" in dir(bug) assert "product" not in dir(bug) # Ensure that include_fields overrides default extra_fields bug = bz.getbug(720773, include_fields=["summary"]) assert "summary" in dir(bug) assert "comments" not in dir(bug) def testExternalBugsOutput(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) out = run_cli('bugzilla query --bug_id 989253 ' '--outputformat="%{external_bugs}"', bz) assert "bugzilla.gnome.org/show_bug.cgi?id=703421" in out assert "External bug: https://bugs.launchpad.net/bugs/1203576" in out def testActiveComps(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) out = run_cli("bugzilla info --components 'Virtualization Tools' " "--active-components", bz) assert "virtinst" not in out out = run_cli("bugzilla info --component_owners 'Virtualization Tools' " "--active-components", bz) assert "virtinst" not in out def testFaults(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) # Test special error wrappers in bugzilla/_cli.py out = run_cli("bugzilla query --field=IDONTEXIST=FOO", bz, expectfail=True) assert "Server error:" in out out = run_cli("bugzilla " "--bugzilla https://example.com/xmlrpc.cgi " "query --field=IDONTEXIST=FOO", None, expectfail=True) assert "Connection lost/failed" in out out = run_cli("bugzilla " "--bugzilla https://expired.badssl.com/ " "query --bug_id 1234", None, expectfail=True) assert "trust the remote server" in out assert "--nosslverify" in out def test_redhat_version(backends): bzversion = (5, 0) bz = _open_bz(REDHAT_URL, **backends) if not tests.CLICONFIG.REDHAT_URL: _test_version(bz, bzversion) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/test_rw_functional.py0000664000175000017500000006773200000000000022531 0ustar00crobinsocrobinso# # Copyright Red Hat, Inc. 2012 # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # """ Unit tests that do permanent functional against a real bugzilla instances. """ import datetime import inspect import os import random import sys import bugzilla import tests import tests.mockbackend import tests.utils RHURL = tests.CLICONFIG.REDHAT_URL or "partner-bugzilla.redhat.com" def _split_int(s): return [int(i) for i in s.split(",")] def _open_bz(**kwargs): return tests.utils.open_functional_bz(bugzilla.RHBugzilla, RHURL, kwargs) if not _open_bz().logged_in: print("\nR/W tests require cached login credentials for url=%s\n" % RHURL) sys.exit(1) def _check_have_admin(bz): funcname = inspect.stack()[1][3] # groupnames is empty for any user if our logged in user does not # have admin privs. # Check a known account that likely won't ever go away ret = bool(bz.getuser("anaconda-maint-list@redhat.com").groupnames) if not ret: print("\nNo admin privs, reduced testing of %s" % funcname) return ret def test0LoggedInNoCreds(): bz = _open_bz(use_creds=False) assert not bz.logged_in def test0ClassDetection(): bz = bugzilla.Bugzilla(RHURL, use_creds=False) assert bz.__class__ is bugzilla.RHBugzilla def _makebug(run_cli, bz): component = "python-bugzilla" version = "rawhide" summary = ("python-bugzilla test basic bug %s" % datetime.datetime.today()) newout = run_cli("bugzilla new " "--product Fedora --component %s --version %s " "--summary \"%s\" " "--comment \"Test bug from the python-bugzilla test suite\" " "--outputformat \"%%{bug_id}\"" % (component, version, summary), bz) assert len(newout.splitlines()) == 1 bugid = int(newout.splitlines()[0]) bug = bz.getbug(bugid) print("\nCreated bugid: %s" % bug.id) assert bug.component == component assert bug.version == version assert bug.summary == summary return bug def test03NewBugBasic(run_cli, backends): """ Create a bug with minimal amount of fields, then close it """ bz = _open_bz(**backends) bug = _makebug(run_cli, bz) # Verify hasattr works assert hasattr(bug, "id") assert hasattr(bug, "bug_id") # Close the bug run_cli("bugzilla modify --close NOTABUG %s --minor-update" % bug.id, bz) bug.refresh() assert bug.status == "CLOSED" assert bug.resolution == "NOTABUG" def test04NewBugAllFields(run_cli, backends): """ Create a bug using all 'new' fields, check some values, close it """ bz = _open_bz(**backends) summary = ("python-bugzilla test manyfields bug %s" % datetime.datetime.today()) url = "http://example.com" osval = "Windows" cc = "triage@lists.fedoraproject.org" blocked = "461686,461687" dependson = "427301" comment = "Test bug from python-bugzilla test suite" sub_component = "Command-line tools (RHEL6)" alias = "pybz-%s" % datetime.datetime.today().strftime("%s") newout = run_cli("bugzilla new " "--product 'Red Hat Enterprise Linux 6' --version 6.0 " "--component lvm2 --sub-component '%s' " "--summary \"%s\" " "--comment \"%s\" " "--url %s --severity Urgent --priority Low --os %s " "--arch ppc --cc %s --blocked %s --dependson %s " "--alias %s " "--outputformat \"%%{bug_id}\"" % (sub_component, summary, comment, url, osval, cc, blocked, dependson, alias), bz) assert len(newout.splitlines()) == 1 bugid = int(newout.splitlines()[0]) bug = bz.getbug(bugid, extra_fields=["sub_components"]) print("\nCreated bugid: %s" % bugid) assert bug.summary == summary assert bug.bug_file_loc == url assert bug.op_sys == osval assert bug.blocks == _split_int(blocked) assert bug.depends_on == _split_int(dependson) assert all([e in bug.cc for e in cc.split(",")]) assert bug.longdescs[0]["text"] == comment assert bug.sub_components == {"lvm2": [sub_component]} assert bug.alias == [alias] # Close the bug # RHBZ makes it difficult to provide consistent semantics for # 'alias' update: # https://bugzilla.redhat.com/show_bug.cgi?id=1173114 # alias += "-closed" run_cli("bugzilla modify " "--close WONTFIX %s " % bugid, bz) bug.refresh() assert bug.status == "CLOSED" assert bug.resolution == "WONTFIX" assert bug.alias == [alias] # Check bug's minimal history ret = bug.get_history_raw() assert len(ret["bugs"]) == 1 assert len(ret["bugs"][0]["history"]) def test05ModifyStatus(run_cli, backends): """ Modify status and comment fields for an existing bug """ bz = _open_bz(**backends) bugid = "663674" cmd = "bugzilla modify %s " % bugid bug = bz.getbug(bugid) # We want to start with an open bug, so fix things if bug.status == "CLOSED": run_cli(cmd + "--status ASSIGNED", bz) bug.refresh() assert bug.status == "ASSIGNED" origstatus = bug.status # Set to ON_QA with a private comment status = "ON_QA" comment = ("changing status to %s at %s" % (status, datetime.datetime.today())) run_cli(cmd + "--status %s --comment \"%s\" --private" % (status, comment), bz) bug.refresh() assert bug.status == status assert bug.longdescs[-1]["is_private"] == 1 assert bug.longdescs[-1]["text"] == comment # Close bug as DEFERRED with a private comment resolution = "DEFERRED" comment = ("changing status to CLOSED=%s at %s" % (resolution, datetime.datetime.today())) run_cli(cmd + "--close %s --comment \"%s\" --private" % (resolution, comment), bz) bug.refresh() assert bug.status == "CLOSED" assert bug.resolution == resolution assert bug.comments[-1]["is_private"] == 1 assert bug.comments[-1]["text"] == comment # Close bug as dup with no comment dupeid = "461686" desclen = len(bug.longdescs) run_cli(cmd + "--close DUPLICATE --dupeid %s" % dupeid, bz) bug.refresh() assert bug.dupe_of == int(dupeid) assert len(bug.longdescs) == (desclen + 1) assert "marked as a duplicate" in bug.longdescs[-1]["text"] # bz.setstatus test comment = ("adding lone comment at %s" % datetime.datetime.today()) bug.setstatus("POST", comment=comment, private=True) bug.refresh() assert bug.longdescs[-1]["is_private"] == 1 assert bug.longdescs[-1]["text"] == comment assert bug.status == "POST" # bz.close test fixed_in = str(datetime.datetime.today()) bug.close("ERRATA", fixedin=fixed_in) bug.refresh() assert bug.status == "CLOSED" assert bug.resolution == "ERRATA" assert bug.fixed_in == fixed_in # bz.addcomment test comment = ("yet another test comment %s" % datetime.datetime.today()) bug.addcomment(comment, private=False) bug.refresh() assert bug.longdescs[-1]["text"] == comment assert bug.longdescs[-1]["is_private"] == 0 # Confirm comments is same as getcomments assert bug.comments == bug.getcomments() # Reset state run_cli(cmd + "--status %s" % origstatus, bz) bug.refresh() assert bug.status == origstatus def test06ModifyEmails(run_cli, backends): """ Modify cc, assignee, qa_contact for existing bug """ bz = _open_bz(**backends) bugid = "663674" cmd = "bugzilla modify %s " % bugid bug = bz.getbug(bugid) origcc = bug.cc # Test CC list and reset it email1 = "triage@lists.fedoraproject.org" email2 = "crobinso@redhat.com" bug.deletecc(origcc) run_cli(cmd + "--cc %s --cc %s" % (email1, email2), bz) bug.addcc(email1) bug.refresh() assert email1 in bug.cc assert email2 in bug.cc assert len(bug.cc) == 2 run_cli(cmd + "--cc=-%s" % email1, bz) bug.refresh() assert email1 not in bug.cc # Test assigned target run_cli(cmd + "--assignee %s" % email1, bz) bug.refresh() assert bug.assigned_to == email1 # Test QA target run_cli(cmd + "--qa_contact %s" % email1, bz) bug.refresh() assert bug.qa_contact == email1 # Reset values bug.deletecc(bug.cc) run_cli(cmd + "--reset-qa-contact --reset-assignee", bz) bug.refresh() assert bug.cc == [] assert bug.assigned_to == "crobinso@redhat.com" assert bug.qa_contact == "extras-qa@fedoraproject.org" def test07ModifyMultiFlags(run_cli, backends): """ Modify flags and fixed_in for 2 bugs """ bz = _open_bz(**backends) bugid1 = "461686" bugid2 = "461687" cmd = "bugzilla modify %s %s " % (bugid1, bugid2) def flagstr(b): ret = [] for flag in b.flags: ret.append(flag["name"] + flag["status"]) return " ".join(sorted(ret)) def cleardict_old(b): """ Clear flag dictionary, for format meant for bug.updateflags """ clearflags = {} for flag in b.flags: clearflags[flag["name"]] = "X" return clearflags def cleardict_new(b): """ Clear flag dictionary, for format meant for update_bugs """ clearflags = [] for flag in b.flags: clearflags.append({"name": flag["name"], "status": "X"}) return clearflags bug1 = bz.getbug(bugid1) if cleardict_old(bug1): bug1.updateflags(cleardict_old(bug1)) bug2 = bz.getbug(bugid2) if cleardict_old(bug2): bug2.updateflags(cleardict_old(bug2)) # Set flags and confirm setflags = "needinfo? requires_doc_text-" run_cli(cmd + " ".join([(" --flag " + f) for f in setflags.split()]), bz) bug1.refresh() bug2.refresh() assert flagstr(bug1) == setflags assert flagstr(bug2) == setflags assert bug1.get_flags("needinfo")[0]["status"] == "?" assert bug1.get_flag_status("requires_doc_text") == "-" # Clear flags if cleardict_new(bug1): bz.update_flags(bug1.id, cleardict_new(bug1)) bug1.refresh() if cleardict_new(bug2): bz.update_flags(bug2.id, cleardict_new(bug2)) bug2.refresh() assert cleardict_old(bug1) == {} assert cleardict_old(bug2) == {} # Set "Fixed In" field origfix1 = bug1.fixed_in origfix2 = bug2.fixed_in newfix = origfix1 and (origfix1 + "-new1") or "blippy1" if newfix == origfix2: newfix = origfix2 + "-2" run_cli(cmd + "--fixed_in=%s" % newfix, bz) bug1.refresh() bug2.refresh() assert bug1.fixed_in == newfix assert bug2.fixed_in == newfix # Reset fixed_in run_cli(cmd + "--fixed_in=\"-\"", bz) bug1.refresh() bug2.refresh() assert bug1.fixed_in == "-" assert bug2.fixed_in == "-" def test07ModifyMisc(run_cli, backends): bugid = "461686" cmd = "bugzilla modify %s " % bugid bz = _open_bz(**backends) bug = bz.getbug(bugid) # modify --dependson run_cli(cmd + "--dependson 123456", bz) bug.refresh() assert 123456 in bug.depends_on run_cli(cmd + "--dependson =111222", bz) bug.refresh() assert [111222] == bug.depends_on run_cli(cmd + "--dependson=-111222", bz) bug.refresh() assert [] == bug.depends_on # modify --blocked run_cli(cmd + "--blocked 123,456", bz) bug.refresh() assert [123, 456] == bug.blocks run_cli(cmd + "--blocked =", bz) bug.refresh() assert [] == bug.blocks # modify --keywords run_cli(cmd + "--keywords +Documentation --keywords EasyFix", bz) bug.refresh() assert ["Documentation", "EasyFix"] == bug.keywords run_cli(cmd + "--keywords=-EasyFix --keywords=-Documentation", bz) bug.refresh() assert [] == bug.keywords # modify --target_release # modify --target_milestone targetbugid = 492463 targetbug = bz.getbug(targetbugid) targetcmd = "bugzilla modify %s " % targetbugid run_cli(targetcmd + "--target_milestone beta --target_release 6.2", bz) targetbug.refresh() assert targetbug.target_milestone == "beta" assert targetbug.target_release == ["6.2"] run_cli(targetcmd + "--target_milestone rc --target_release 6.10", bz) targetbug.refresh() assert targetbug.target_milestone == "rc" assert targetbug.target_release == ["6.10"] # modify --priority # modify --severity run_cli(cmd + "--priority low --severity high", bz) bug.refresh() assert bug.priority == "low" assert bug.severity == "high" run_cli(cmd + "--priority medium --severity medium", bz) bug.refresh() assert bug.priority == "medium" assert bug.severity == "medium" # modify --os # modify --platform # modify --version run_cli(cmd + "--version rawhide --os Windows --arch ppc " "--url http://example.com", bz) bug.refresh() assert bug.version == "rawhide" assert bug.op_sys == "Windows" assert bug.platform == "ppc" assert bug.url == "http://example.com" run_cli(cmd + "--version rawhide --os Linux --arch s390 " "--url http://example.com/fribby", bz) bug.refresh() assert bug.version == "rawhide" assert bug.op_sys == "Linux" assert bug.platform == "s390" assert bug.url == "http://example.com/fribby" # modify --field run_cli(cmd + "--field cf_fixed_in=foo-bar-1.2.3 \ --field=cf_release_notes=baz", bz) bug.refresh() assert bug.fixed_in == "foo-bar-1.2.3" assert bug.cf_release_notes == "baz" def test08Attachments(run_cli, backends): tmpdir = "__test_attach_output" if tmpdir in os.listdir("."): os.system("rm -r %s" % tmpdir) os.mkdir(tmpdir) os.chdir(tmpdir) try: _test8Attachments(run_cli, backends) finally: os.chdir("..") os.system("rm -r %s" % tmpdir) def _test8Attachments(run_cli, backends): """ Get and set attachments for a bug """ bz = _open_bz(**backends) cmd = "bugzilla attach " testfile = "../tests/data/bz-attach-get1.txt" # Add attachment as CLI option setbug = _makebug(run_cli, bz) setbug = bz.getbug(setbug.id, extra_fields=["attachments"]) orignumattach = len(setbug.attachments) # Add attachment from CLI with mime guessing desc1 = "python-bugzilla cli upload %s" % datetime.datetime.today() out1 = run_cli(cmd + "%s --description \"%s\" --file %s" % (setbug.id, desc1, testfile), bz) out1 = out1.splitlines()[-1] desc2 = "python-bugzilla cli upload %s" % datetime.datetime.today() out2 = run_cli(cmd + "%s --file test --summary \"%s\"" % (setbug.id, desc2), bz, stdin=open(testfile).read()) # Expected output format: # Created attachment on bug setbug.refresh() assert len(setbug.attachments) == (orignumattach + 2) att1 = setbug.attachments[-2] attachid = att1["id"] assert att1["summary"] == desc1 assert att1["id"] == int(out1.splitlines()[0].split()[2]) assert att1["content_type"] == "text/plain" att2 = setbug.attachments[-1] assert att2["summary"] == desc2 assert att2["id"] == int(out2.splitlines()[0].split()[2]) assert att2["content_type"] == "application/octet-stream" # Set attachment flags assert att1["flags"] == [] bz.updateattachmentflags(setbug.id, att2["id"], "review", status="+") setbug.refresh() assert len(setbug.attachments[-1]["flags"]) == 1 assert setbug.attachments[-1]["flags"][0]["name"] == "review" assert setbug.attachments[-1]["flags"][0]["status"] == "+" bz.updateattachmentflags(setbug.id, setbug.attachments[-1]["id"], "review", status="X") setbug.refresh() assert setbug.attachments[-1]["flags"] == [] # Set attachment obsolete bz._backend.bug_attachment_update( # pylint: disable=protected-access [setbug.attachments[-1]["id"]], {"is_obsolete": 1}) setbug.refresh() assert setbug.attachments[-1]["is_obsolete"] == 1 # Get attachment, verify content out = run_cli(cmd + "--get %s" % attachid, bz).splitlines() # Expect format: # Wrote fname = out[0].split()[1].strip() assert len(out) == 1 assert fname == "bz-attach-get1.txt" assert open(fname).read() == open(testfile).read() os.unlink(fname) # Get all attachments getbug = bz.getbug(setbug.id) getbug.autorefresh = True numattach = len(getbug.attachments) out = run_cli(cmd + "--getall %s" % getbug.id, bz).splitlines() assert len(out) == numattach fnames = [line.split(" ", 1)[1].strip() for line in out] assert len(fnames) == numattach for f in fnames: if not os.path.exists(f): raise AssertionError("filename '%s' not found" % f) os.unlink(f) # Get all attachments, but ignore obsolete ignorecmd = cmd + "--getall %s --ignore-obsolete" % getbug.id out = run_cli(ignorecmd, bz).splitlines() assert len(out) == (numattach - 1) fnames = [line.split(" ", 1)[1].strip() for line in out] assert len(fnames) == (numattach - 1) for f in fnames: if not os.path.exists(f): raise AssertionError("filename '%s' not found" % f) os.unlink(f) def test09Whiteboards(run_cli, backends): bz = _open_bz(**backends) bug_id = "663674" cmd = "bugzilla modify %s " % bug_id bug = bz.getbug(bug_id) # Set all whiteboards initval = str(random.randint(1, 1024)) run_cli(cmd + "--whiteboard =%sstatus " "--devel_whiteboard =%sdevel " "--internal_whiteboard '=%sinternal, security, foo security1' " "--qa_whiteboard =%sqa " % (initval, initval, initval, initval), bz) bug.refresh() assert bug.whiteboard == (initval + "status") assert bug.qa_whiteboard == (initval + "qa") assert bug.devel_whiteboard == (initval + "devel") assert (bug.internal_whiteboard == (initval + "internal, security, foo security1")) # Modify whiteboards run_cli(cmd + "--whiteboard =foobar " "--qa_whiteboard _app " "--devel_whiteboard =pre-%s" % bug.devel_whiteboard, bz) bug.refresh() assert bug.qa_whiteboard == (initval + "qa" + " _app") assert bug.devel_whiteboard == ("pre-" + initval + "devel") assert bug.status_whiteboard == "foobar" # Verify that tag manipulation is smart about separator run_cli(cmd + "--qa_whiteboard=-_app " "--internal_whiteboard=-security,", bz) bug.refresh() assert bug.qa_whiteboard == (initval + "qa") assert bug.internal_whiteboard == (initval + "internal, foo security1") # Clear whiteboards update = bz.build_update( whiteboard="", devel_whiteboard="", internal_whiteboard="", qa_whiteboard="") bz.update_bugs(bug.id, update) bug.refresh() assert bug.whiteboard == "" assert bug.qa_whiteboard == "" assert bug.devel_whiteboard == "" assert bug.internal_whiteboard == "" def test10Login(run_cli, monkeypatch): """ Failed login test, gives us a bit more coverage """ tests.utils.monkeypatch_getpass(monkeypatch) cmd = "bugzilla --no-cache-credentials --bugzilla %s" % RHURL # Implied login with --username and --password ret = run_cli("%s --user foobar@example.com " "--password foobar query -b 123456" % cmd, None, expectfail=True) assert "Login failed: " in ret # 'login' with explicit options ret = run_cli("%s --user foobar@example.com " "--password foobar login" % cmd, None, expectfail=True) assert "Login failed: " in ret # 'login' with positional options ret = run_cli("%s login foobar@example.com foobar" % cmd, None, expectfail=True) assert "Login failed: " in ret # bare 'login' stdinstr = "foobar@example.com\n\rfoobar\n\r" ret = run_cli("%s login" % cmd, None, expectfail=True, stdin=stdinstr) assert "Bugzilla Username:" in ret assert "Bugzilla Password:" in ret assert "Login failed: " in ret def test11UserUpdate(backends): # This won't work if run by the same user we are using bz = _open_bz(**backends) email = "anaconda-maint-list@redhat.com" group = "fedora_contrib" have_admin = _check_have_admin(bz) user = bz.getuser(email) if have_admin: assert group in user.groupnames origgroups = user.groupnames # Test group_get try: group = bz.getgroup("fedora_contrib") group.refresh() except Exception as e: if have_admin: raise assert bugzilla.BugzillaError.get_bugzilla_error_code(e) == 805 # Remove the group try: bz.updateperms(email, "remove", [group]) user.refresh() assert group not in user.groupnames except Exception as e: if have_admin: raise assert "Sorry, you aren't a member" in str(e) # Re add it try: bz.updateperms(email, "add", group) user.refresh() assert group in user.groupnames except Exception as e: if have_admin: raise assert "Sorry, you aren't a member" in str(e) # Set groups try: newgroups = user.groupnames[:] if have_admin: newgroups.remove(group) bz.updateperms(email, "set", newgroups) user.refresh() assert group not in user.groupnames except Exception as e: if have_admin: raise assert "Sorry, you aren't a member" in str(e) # Reset everything try: bz.updateperms(email, "set", origgroups) except Exception as e: if have_admin: raise assert "Sorry, you aren't a member" in str(e) user.refresh() assert user.groupnames == origgroups def test11ComponentEditing(backends): bz = _open_bz(**backends) component = ("python-bugzilla-testcomponent-%s" % str(random.randint(1, 1024 * 1024 * 1024))) basedata = { "product": "Fedora Documentation", "component": component, } have_admin = _check_have_admin(bz) def compare(data, newid): # pylint: disable=protected-access products = bz._proxy.Product.get({"names": [basedata["product"]]}) compdata = None for c in products["products"][0]["components"]: if int(c["id"]) == int(newid): compdata = c break assert bool(compdata) assert data["component"] == compdata["name"] assert data["description"] == compdata["description"] assert data["initialowner"] == compdata["default_assigned_to"] assert data["initialqacontact"] == compdata["default_qa_contact"] assert data["is_active"] == compdata["is_active"] # Create component data = basedata.copy() data.update({ "description": "foo test bar", "initialowner": "crobinso@redhat.com", "initialqacontact": "extras-qa@fedoraproject.org", "initialcclist": ["wwoods@redhat.com", "toshio@fedoraproject.org"], "is_active": True, }) newid = None try: newid = bz.addcomponent(data)['id'] print("Created product=%s component=%s" % ( basedata["product"], basedata["component"])) compare(data, newid) except Exception as e: if have_admin: raise assert (("Sorry, you aren't a member" in str(e)) or # bugzilla 5 error string ("You are not allowed" in str(e))) # bugzilla.redhat.com doesn't have REST editcomponent yet tests.utils.skip_if_rest( bz, "editcomponent not supported for redhat REST API") # Edit component data = basedata.copy() data.update({ "description": "hey new desc!", "initialowner": "extras-qa@fedoraproject.org", "initialqacontact": "virt-mgr-maint@redhat.com", "initialcclist": ["libvirt-maint@redhat.com", "virt-maint@lists.fedoraproject.org"], "is_active": False, }) try: bz.editcomponent(data) if newid is not None: compare(data, newid) except Exception as e: if have_admin: raise assert (("Sorry, you aren't a member" in str(e)) or # bugzilla 5 error string ("You are not allowed" in str(e))) def test13SubComponents(backends): bz = _open_bz(**backends) # Long closed RHEL5 lvm2 bug. This component has sub_components bug = bz.getbug("185526") bug.autorefresh = True assert bug.component == "lvm2" bz.update_bugs(bug.id, bz.build_update( component="lvm2", sub_component="Command-line tools (RHEL5)")) bug.refresh() assert bug.sub_components == {"lvm2": ["Command-line tools (RHEL5)"]} bz.update_bugs(bug.id, bz.build_update( component="lvm2", sub_component="Default / Unclassified (RHEL5)")) bug.refresh() assert bug.sub_components == {"lvm2": [ "Default / Unclassified (RHEL5)"]} def test14ExternalTrackersAddUpdateRemoveQuery(backends): bz = _open_bz(**backends) bugid = 461686 ext_bug_id = 380489 tests.utils.skip_if_rest( bz, "unknown if REST API has externaltrackers support") # Delete any existing external trackers to get to a known state ids = [bug['id'] for bug in bz.getbug(bugid).external_bugs] if ids != []: bz.remove_external_tracker(ids=ids) url = "https://bugzilla.mozilla.org" if bz.bz_ver_major < 5: url = "http://bugzilla.mozilla.org" # test adding tracker kwargs = { 'ext_type_id': 6, 'ext_type_url': url, 'ext_type_description': 'Mozilla Foundation', } bz.add_external_tracker(bugid, ext_bug_id, **kwargs) added_bug = bz.getbug(bugid).external_bugs[0] assert added_bug['type']['id'] == kwargs['ext_type_id'] assert added_bug['type']['url'] == kwargs['ext_type_url'] assert (added_bug['type']['description'] == kwargs['ext_type_description']) # test updating status, description, and priority by id kwargs = { 'ids': bz.getbug(bugid).external_bugs[0]['id'], 'ext_status': 'New Status', 'ext_description': 'New Description', 'ext_priority': 'New Priority' } bz.update_external_tracker(**kwargs) updated_bug = bz.getbug(bugid).external_bugs[0] assert updated_bug['ext_bz_bug_id'] == str(ext_bug_id) assert updated_bug['ext_status'] == kwargs['ext_status'] assert updated_bug['ext_description'] == kwargs['ext_description'] assert updated_bug['ext_priority'] == kwargs['ext_priority'] # test removing tracker ids = [bug['id'] for bug in bz.getbug(bugid).external_bugs] assert len(ids) == 1 bz.remove_external_tracker(ids=ids) ids = [bug['id'] for bug in bz.getbug(bugid).external_bugs] assert len(ids) == 0 def test15EnsureLoggedIn(run_cli, backends): bz = _open_bz(**backends) comm = "bugzilla --ensure-logged-in query --bug_id 979546" run_cli(comm, bz) # Test that we don't pollute the query dict with auth info query = {"id": [1234567]} origquery = query.copy() bz.query(query) assert query == origquery def test16ModifyTags(run_cli, backends): bugid = "461686" cmd = "bugzilla modify %s " % bugid bz = _open_bz(**backends) bug = bz.getbug(bugid) tests.utils.skip_if_rest(bz, "update_tags not supported for REST API") if bug.tags: bz.update_tags(bug.id, tags_remove=bug.tags) bug.refresh() assert bug.tags == [] run_cli(cmd + "--tags foo --tags +bar --tags baz", bz) bug.refresh() assert bug.tags == ["foo", "bar", "baz"] run_cli(cmd + "--tags=-bar", bz) bug.refresh() assert bug.tags == ["foo", "baz"] bz.update_tags(bug.id, tags_remove=bug.tags) bug.refresh() assert bug.tags == [] def test17LoginAPIKey(backends): api_key = "somefakeapikey1234" bz = _open_bz(use_creds=False, api_key=api_key, **backends) try: assert bz.logged_in is False # Use this to trigger a warning about api_key bz.createbug(bz.build_createbug()) except Exception as e: assert "The API key you specified is invalid" in str(e) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601752921.0 python-bugzilla-3.0.2/tests/utils.py0000664000175000017500000000664000000000000017747 0ustar00crobinsocrobinso# This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. import difflib import getpass import inspect import io import os import pprint import shlex import sys import pytest import bugzilla._cli import tests def get_funcname(): # Return calling function name return inspect.stack()[1][3] def tests_path(filename): testdir = os.path.dirname(__file__) if testdir not in filename: return os.path.join(testdir, filename) return filename def monkeypatch_getpass(monkeypatch): monkeypatch.setattr(getpass, "getpass", input) def sanitize_json(rawout): # py2.7 leaves trailing whitespace after commas. strip it so # tests pass on both python versions return "\n".join([line.rstrip() for line in rawout.splitlines()]) def open_functional_bz(bzclass, url, kwargs): bz = bzclass(url, **kwargs) if kwargs.get("force_rest", False): assert bz.is_rest() is True if kwargs.get("force_xmlrpc", False): assert bz.is_xmlrpc() is True # Set a request timeout of 60 seconds os.environ["PYTHONBUGZILLA_REQUESTS_TIMEOUT"] = "60" return bz def skip_if_rest(bz, msg): if bz.is_rest(): pytest.skip(msg) def diff_compare(inputdata, filename, expect_out=None): """Compare passed string output to contents of filename""" def _process(data): if isinstance(data, tuple) and len(data) == 1: data = data[0] if isinstance(data, (dict, tuple)): out = pprint.pformat(data, width=81) else: out = str(data) if not out.endswith("\n"): out += "\n" return out actual_out = _process(inputdata) if filename: filename = tests_path(filename) if not os.path.exists(filename) or tests.CLICONFIG.REGENERATE_OUTPUT: open(filename, "w").write(actual_out) expect_out = open(filename).read() else: expect_out = _process(expect_out) diff = "".join(difflib.unified_diff(expect_out.splitlines(1), actual_out.splitlines(1), fromfile=filename or "Manual input", tofile="Generated Output")) if diff: raise AssertionError("Conversion outputs did not match.\n%s" % diff) def do_run_cli(capsys, monkeypatch, argvstr, bzinstance, expectfail=False, stdin=None): """ Run bin/bugzilla.main() directly with passed argv """ argv = shlex.split(argvstr) monkeypatch.setattr(sys, "argv", argv) if stdin: monkeypatch.setattr(sys, "stdin", io.StringIO(stdin)) else: monkeypatch.setattr(sys.stdin, "isatty", lambda: True) ret = 0 try: # pylint: disable=protected-access if bzinstance is None: bugzilla._cli.cli() else: bugzilla._cli.main(unittest_bz_instance=bzinstance) except SystemExit as sys_e: ret = sys_e.code out, err = capsys.readouterr() outstr = out + err if ret != 0 and not expectfail: raise RuntimeError("Command failed with %d\ncmd=%s\nout=%s" % (ret, argvstr, outstr)) if ret == 0 and expectfail: raise RuntimeError("Command succeeded but we expected success\n" "ret=%d\ncmd=%s\nout=%s" % (ret, argvstr, outstr)) return outstr