├── .github └── workflows │ └── main.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── build.py ├── build.sh ├── pyproject.toml ├── requirements.txt └── src ├── main └── python │ └── github3api │ ├── __init__.py │ └── githubapi.py └── unittest └── python └── test_githubapi.py /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: 3 | schedule: 4 | - cron: "0 8 * * *" 5 | push: 6 | branches: 7 | - '**' 8 | pull_request: 9 | branches: 10 | - main 11 | jobs: 12 | build-images: 13 | strategy: 14 | matrix: 15 | version: ['3.7', '3.8', '3.9', '3.10'] 16 | name: Build Python Docker images 17 | runs-on: ubuntu-20.04 18 | steps: 19 | - uses: actions/checkout@v3 20 | - name: build github3api ${{ matrix.version }} image 21 | run: 22 | docker image build --target build-image --build-arg PYTHON_VERSION=${{ matrix.version }} -t github3api:${{ matrix.version }} . 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | .pybuilder 91 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2020 Intel Corporation 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | ARG PYTHON_VERSION=3.9 17 | FROM python:${PYTHON_VERSION}-slim AS build-image 18 | ENV PYTHONDONTWRITEBYTECODE 1 19 | WORKDIR /code 20 | COPY . /code/ 21 | RUN pip install --upgrade pip && pip install pybuilder 22 | RUN pyb -X && pyb install 23 | 24 | FROM python:${PYTHON_VERSION}-slim 25 | ENV PYTHONDONTWRITEBYTECODE 1 26 | WORKDIR /opt/github3api 27 | COPY --from=build-image /code/target/dist/github3api-*/dist/github3api-*.tar.gz /opt/github3api 28 | RUN pip install github3api-*.tar.gz -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # github3api 2 | [![GitHub Workflow Status](https://github.com/soda480/github3api/workflows/build/badge.svg)](https://github.com/soda480/github3api/actions) 3 | [![coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)](https://pybuilder.io/) 4 | [![complexity](https://img.shields.io/badge/complexity-A-brightgreen)](https://radon.readthedocs.io/en/latest/api.html#module-radon.complexity) 5 | [![vulnerabilities](https://img.shields.io/badge/vulnerabilities-None-brightgreen)](https://pypi.org/project/bandit/) 6 | [![PyPI version](https://badge.fury.io/py/github3api.svg)](https://app.codiga.io/public/project/13337/github3api/dashboard) 7 | [![python](https://img.shields.io/badge/python-3.7%20%7C%203.8%20%7C%203.9%20%7C%203.10-teal)](https://www.python.org/downloads/) 8 | 9 | An advanced REST client for the GitHub API. It is a subclass of [rest3client](https://pypi.org/project/rest3client/) tailored for the GitHub API with special optional directives for GET requests that can return all pages from an endpoint or return a generator that can be iterated over (for paged requests). By default all requests will be retried if ratelimit request limit is reached. 10 | 11 | Support for executing Graphql queries including paging; Graphql queries are also retried if Graphql rate limiting occurs. 12 | 13 | 14 | ### Installation 15 | ```bash 16 | pip install github3api 17 | ``` 18 | 19 | ### Example Usage 20 | 21 | ```python 22 | >>> from github3api import GitHubAPI 23 | ``` 24 | 25 | `GitHubAPI` instantiation 26 | ```python 27 | # instantiate using no-auth 28 | >>> client = GitHubAPI() 29 | 30 | # instantiate using a token 31 | >>> client = GitHubAPI(bearer_token='****************') 32 | ``` 33 | 34 | `GET` request 35 | ```python 36 | # GET request - return JSON response 37 | >>> client.get('/rate_limit')['resources']['core'] 38 | {'limit': 60, 'remaining': 37, 'reset': 1588898701} 39 | 40 | # GET request - return raw resonse 41 | >>> client.get('/rate_limit', raw_response=True) 42 | 43 | ``` 44 | 45 | `POST` request 46 | ```python 47 | >>> client.post('/user/repos', json={'name': 'test-repo1'})['full_name'] 48 | 'soda480/test-repo1' 49 | 50 | >>> client.post('/repos/soda480/test-repo1/labels', json={'name': 'label1'})['url'] 51 | 'https://api.github.com/repos/soda480/test-repo1/labels/label1' 52 | ``` 53 | 54 | `PATCH` request 55 | ```python 56 | >>> client.patch('/repos/soda480/test-repo1/labels/label1', json={'description': 'my label'})['url'] 57 | 'https://api.github.com/repos/soda480/test-repo1/labels/label1' 58 | ``` 59 | 60 | `DELETE` request 61 | ```python 62 | >>> client.delete('/repos/soda480/test-repo1') 63 | ``` 64 | 65 | `GET all` directive - Get all pages from an endpoint and return list containing only matching attributes 66 | ```python 67 | for repo in client.get('/orgs/edgexfoundry/repos', _get='all', _attributes=['full_name']): 68 | print(repo['full_name']) 69 | ``` 70 | 71 | `GET page` directive - Yield a page from endpoint 72 | ```python 73 | for page in client.get('/user/repos', _get='page'): 74 | for repo in page: 75 | print(repo['full_name']) 76 | ``` 77 | 78 | `total` - Get total number of resources at given endpoint 79 | ```python 80 | print(client.total('/user/repos')) 81 | ``` 82 | 83 | `graphql` - execute graphql query 84 | ```python 85 | query = """ 86 | query($query:String!, $page_size:Int!) { 87 | search(query: $query, type: REPOSITORY, first: $page_size) { 88 | repositoryCount 89 | edges { 90 | node { 91 | ... on Repository { 92 | nameWithOwner 93 | } 94 | } 95 | } 96 | } 97 | } 98 | """ 99 | variables = {"query": "org:edgexfoundry", "page_size":100} 100 | client.graphql(query, variables) 101 | ``` 102 | 103 | `graphql paging` - execute paged graphql query 104 | ```python 105 | query = """ 106 | query ($query: String!, $page_size: Int!, $cursor: String!) { 107 | search(query: $query, type: REPOSITORY, first: $page_size, after: $cursor) { 108 | repositoryCount 109 | pageInfo { 110 | endCursor 111 | hasNextPage 112 | } 113 | edges { 114 | cursor 115 | node { 116 | ... on Repository { 117 | nameWithOwner 118 | } 119 | } 120 | } 121 | } 122 | } 123 | """ 124 | variables = {"query": "org:edgexfoundry", "page_size":100} 125 | for page in client.graphql(query, variables, page=True, keys='data.search'): 126 | for repo in page: 127 | print(repo['node']['nameWithOwner']) 128 | ``` 129 | 130 | For Graphql paged queries: 131 | - the query should include the necessary pageInfo and cursor attributes 132 | - the keys method argument is a dot annotated string that is used to access the resulting dictionary response object 133 | - the query is retried every 60 seconds (for up to an hour) if a ratelimit occur 134 | 135 | ### Projects using `github3api` 136 | 137 | * [edgexfoundry/sync-github-labels](https://github.com/edgexfoundry/cd-management/tree/git-label-sync) A script that synchronizes GitHub labels and milestones 138 | 139 | * [edgexfoundry/prune-github-tags](https://github.com/edgexfoundry/cd-management/tree/prune-github-tags) A script that prunes GitHub pre-release tags 140 | 141 | * [edgexfoundry/create-github-release](https://github.com/edgexfoundry/cd-management/tree/create-github-release) A script to facilitate creation of GitHub releases 142 | 143 | * [soda480/prepbadge](https://github.com/soda480/prepbadge) A script that creates multiple pull request workflows to update a target organization repos with badges 144 | 145 | * [soda480/github-contributions](https://github.com/soda480/github-contributions) A script to get contribution metrics for all members of a GitHub organization using the GitHub GraphQL API 146 | 147 | * [edgexfoundry/edgex-dev-badge](https://github.com/edgexfoundry/edgex-dev-badge) Rules based GitHub badge scanner 148 | 149 | ### Development 150 | 151 | Ensure the latest version of Docker is installed on your development server. Fork and clone the repository. 152 | 153 | Build the Docker image: 154 | ```sh 155 | docker image build \ 156 | --target build-image \ 157 | --build-arg http_proxy \ 158 | --build-arg https_proxy \ 159 | -t \ 160 | github3api:latest . 161 | ``` 162 | 163 | Run the Docker container: 164 | ```sh 165 | docker container run \ 166 | --rm \ 167 | -it \ 168 | -e http_proxy \ 169 | -e https_proxy \ 170 | -v $PWD:/code \ 171 | github3api:latest \ 172 | bash 173 | ``` 174 | 175 | Execute the build: 176 | ```sh 177 | pyb -X 178 | ``` 179 | 180 | NOTE: commands above assume working behind a proxy, if not then the proxy arguments to both the docker build and run commands can be removed. 181 | -------------------------------------------------------------------------------- /build.py: -------------------------------------------------------------------------------- 1 | 2 | # Copyright (c) 2020 Intel Corporation 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from pybuilder.core import use_plugin 17 | from pybuilder.core import init 18 | from pybuilder.core import Author 19 | 20 | use_plugin('python.core') 21 | use_plugin('python.unittest') 22 | use_plugin('python.flake8') 23 | use_plugin('python.coverage') 24 | use_plugin('python.distutils') 25 | use_plugin('pypi:pybuilder_radon') 26 | use_plugin('pypi:pybuilder_bandit') 27 | use_plugin('pypi:pybuilder_anybadge') 28 | 29 | name = 'github3api' 30 | authors = [Author('Emilio Reyes', 'emilio.reyes@intel.com')] 31 | summary = 'An advanced REST client for the GitHub API' 32 | url = 'https://github.com/soda480/github3api' 33 | version = '0.3.2' 34 | default_task = [ 35 | 'clean', 36 | 'analyze', 37 | 'publish', 38 | 'radon', 39 | 'bandit', 40 | 'anybadge'] 41 | license = 'Apache License, Version 2.0' 42 | description = summary 43 | 44 | @init 45 | def set_properties(project): 46 | project.set_property('unittest_module_glob', 'test_*.py') 47 | project.set_property('coverage_break_build', False) 48 | project.set_property('flake8_max_line_length', 120) 49 | project.set_property('flake8_verbose_output', True) 50 | project.set_property('flake8_break_build', True) 51 | project.set_property('flake8_include_scripts', True) 52 | project.set_property('flake8_include_test_sources', True) 53 | project.set_property('flake8_ignore', 'E501, W503, F401, E722, W605') 54 | project.build_depends_on('mock') 55 | project.depends_on_requirements('requirements.txt') 56 | project.set_property('distutils_readme_description', True) 57 | project.set_property('distutils_description_overwrite', True) 58 | project.set_property('distutils_upload_skip_existing', True) 59 | project.set_property('distutils_classifiers', [ 60 | 'Development Status :: 4 - Beta', 61 | 'Environment :: Console', 62 | 'Environment :: Other Environment', 63 | 'Intended Audience :: Developers', 64 | 'Intended Audience :: System Administrators', 65 | 'License :: OSI Approved :: Apache Software License', 66 | 'Operating System :: POSIX :: Linux', 67 | 'Programming Language :: Python', 68 | 'Programming Language :: Python :: 3.7', 69 | 'Programming Language :: Python :: 3.8', 70 | 'Programming Language :: Python :: 3.9', 71 | 'Programming Language :: Python :: 3.10', 72 | 'Topic :: Software Development :: Libraries', 73 | 'Topic :: Software Development :: Libraries :: Python Modules', 74 | 'Topic :: System :: Networking', 75 | 'Topic :: System :: Systems Administration']) 76 | project.set_property('radon_break_build_average_complexity_threshold', 3.6) 77 | project.set_property('radon_break_build_complexity_threshold', 14) 78 | project.set_property('bandit_break_build', True) 79 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | versions=( '3.7' '3.8' '3.9' '3.10' ) 2 | for version in "${versions[@]}"; 3 | do 4 | docker image build --build-arg PYTHON_VERSION=$version -t github3api:$version . 5 | done -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["pybuilder>=0.12.0"] 3 | build-backend = "pybuilder.pep517" 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | rest3client -------------------------------------------------------------------------------- /src/main/python/github3api/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | # Copyright (c) 2020 Intel Corporation 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from .githubapi import GitHubAPI 17 | -------------------------------------------------------------------------------- /src/main/python/github3api/githubapi.py: -------------------------------------------------------------------------------- 1 | 2 | # Copyright (c) 2020 Intel Corporation 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import re 17 | import logging 18 | from os import getenv 19 | from datetime import datetime 20 | 21 | from retrying import retry 22 | from rest3client import RESTclient 23 | from requests.exceptions import HTTPError 24 | from requests.exceptions import ChunkedEncodingError 25 | 26 | logger = logging.getLogger(__name__) 27 | 28 | logging.getLogger('urllib3.connectionpool').setLevel(logging.CRITICAL) 29 | 30 | HOSTNAME = 'api.github.com' 31 | VERSION = 'v3' 32 | DEFAULT_PAGE_SIZE = 30 33 | DEFAULT_GRAPHQL_PAGE_SIZE = 100 34 | 35 | 36 | class GraphqlRateLimitError(Exception): 37 | """ GraphQL Rate Limit Error 38 | """ 39 | pass 40 | 41 | 42 | class GraphqlError(Exception): 43 | """ GraphQL Error 44 | """ 45 | pass 46 | 47 | 48 | class GitHubAPI(RESTclient): 49 | """ An advanced REST client for the GitHub API 50 | """ 51 | 52 | def __init__(self, **kwargs): 53 | logger.debug('executing GitHubAPI constructor') 54 | hostname = kwargs.pop('hostname', HOSTNAME) 55 | self.version = kwargs.pop('version', VERSION) 56 | super(GitHubAPI, self).__init__(hostname, **kwargs) 57 | 58 | def get_response(self, response, **kwargs): 59 | """ subclass override to including logging of ratelimits 60 | """ 61 | ratelimit = GitHubAPI.get_ratelimit(response.headers) 62 | if ratelimit: 63 | self.log_ratelimit(ratelimit) 64 | return super(GitHubAPI, self).get_response(response, **kwargs) 65 | 66 | def get_headers(self, **kwargs): 67 | """ return headers to pass to requests method 68 | """ 69 | headers = super(GitHubAPI, self).get_headers(**kwargs) 70 | headers['Accept'] = f'application/vnd.github.{self.version}+json' 71 | return headers 72 | 73 | def total(self, endpoint): 74 | """ return total number of resources 75 | """ 76 | # logger.debug(f'get total number of resources at endpoint {endpoint}') 77 | if 'per_page' in endpoint: 78 | raise ValueError(f'endpoint {endpoint} with per_page argument is not supported') 79 | if '?' in endpoint: 80 | endpoint = f'{endpoint}&per_page=1' 81 | else: 82 | endpoint = f'{endpoint}?per_page=1' 83 | response = self.get(endpoint, raw_response=True) 84 | if response.links: 85 | last_url = response.links['last']['url'] 86 | endpoint = self._get_endpoint_from_url(last_url) 87 | items = self.get(endpoint) 88 | per_page = GitHubAPI.get_per_page_from_url(last_url) 89 | last_page = GitHubAPI.get_page_from_url(last_url) 90 | total = per_page * (last_page - 1) + len(items) 91 | else: 92 | items = response.json() 93 | total = len(items) 94 | return total 95 | 96 | @staticmethod 97 | def get_page_from_url(url): 98 | """ get page query parameter form url 99 | """ 100 | regex = r'^.*page=(?P\d+).*$' 101 | match = re.match(regex, url) 102 | if match: 103 | return int(match.group('value')) 104 | 105 | @staticmethod 106 | def get_per_page_from_url(url): 107 | """ get per_page query parameter from url 108 | """ 109 | per_page = DEFAULT_PAGE_SIZE 110 | regex = r'^.*per_page=(?P\d+).*$' 111 | match = re.match(regex, url) 112 | if match: 113 | per_page = int(match.group('value')) 114 | return per_page 115 | 116 | @classmethod 117 | def get_client(cls): 118 | """ return instance of GitHubAPI 119 | """ 120 | return GitHubAPI( 121 | hostname=getenv('GH_BASE_URL', HOSTNAME), 122 | bearer_token=getenv('GH_TOKEN_PSW')) 123 | 124 | @staticmethod 125 | def get_ratelimit(headers): 126 | """ get rate limit data 127 | """ 128 | reset = headers.get('X-RateLimit-Reset') 129 | if not reset: 130 | return {} 131 | remaining = headers.get('X-RateLimit-Remaining') 132 | limit = headers.get('X-RateLimit-Limit') 133 | delta = datetime.fromtimestamp(int(reset)) - datetime.now() 134 | minutes = str(delta.total_seconds() / 60).split('.')[0] 135 | return { 136 | 'remaining': remaining, 137 | 'limit': limit, 138 | 'minutes': minutes 139 | } 140 | 141 | @staticmethod 142 | def log_ratelimit(ratelimit): 143 | """ log rate limit data 144 | """ 145 | logger.debug(f"{ratelimit['remaining']}/{ratelimit['limit']} resets in {ratelimit['minutes']} min") 146 | 147 | @staticmethod 148 | def retry_ratelimit_error(exception): 149 | """ return True if exception is 403 HTTPError, False otherwise 150 | retry: 151 | wait_fixed:60000 152 | stop_max_attempt_number:60 153 | """ 154 | logger.debug(f"checking if '{type(exception).__name__}' exception is a ratelimit error") 155 | if isinstance(exception, HTTPError): 156 | logger.debug(exception.response.reason) 157 | if exception.response.status_code == 403 and 'rate limit exceeded' in exception.response.reason.lower(): 158 | logger.info('ratelimit error encountered - retrying request in 60 seconds') 159 | return True 160 | logger.debug(f'exception is not a ratelimit error: {exception}') 161 | return False 162 | 163 | @staticmethod 164 | def clear_cursor(query, cursor): 165 | """ return query with all cursor references removed if no cursor 166 | """ 167 | if not cursor: 168 | query = query.replace('after: $cursor', '') 169 | query = query.replace('$cursor: String!', '') 170 | return query 171 | 172 | @staticmethod 173 | def sanitize_query(query): 174 | """ sanitize query 175 | """ 176 | return query.replace('\n', ' ').replace(' ', '').strip() 177 | 178 | @staticmethod 179 | def raise_if_error(response): 180 | """ raise GraphqlRateLimitError if error exists in errors 181 | """ 182 | if 'errors' in response: 183 | logger.debug(f'errors detected in graphql response: {response}') 184 | for error in response['errors']: 185 | if error.get('type', '') == 'RATE_LIMITED': 186 | raise GraphqlRateLimitError(error.get('message', '')) 187 | raise GraphqlError(response['errors'][0]['message']) 188 | 189 | @staticmethod 190 | def get_value(data, keys): 191 | """ return value represented by keys dot notated string from data dictionary 192 | """ 193 | if '.' in keys: 194 | key, rest = keys.split('.', 1) 195 | if key in data: 196 | return GitHubAPI.get_value(data[key], rest) 197 | raise KeyError(f'dictionary does not have key {key}') 198 | else: 199 | return data[keys] 200 | 201 | def _get_graphql_page(self, query, variables, keys): 202 | """ return generator that yields page from graphql response 203 | """ 204 | variables['page_size'] = DEFAULT_GRAPHQL_PAGE_SIZE 205 | variables['cursor'] = '' 206 | while True: 207 | updated_query = GitHubAPI.clear_cursor(query, variables['cursor']) 208 | response = self.post('/graphql', json={'query': updated_query, 'variables': variables}) 209 | GitHubAPI.raise_if_error(response) 210 | yield GitHubAPI.get_value(response, f'{keys}.edges') 211 | 212 | page_info = GitHubAPI.get_value(response, f'{keys}.pageInfo') 213 | has_next_page = page_info['hasNextPage'] 214 | if not has_next_page: 215 | logger.debug('no more pages') 216 | break 217 | variables['cursor'] = page_info['endCursor'] 218 | 219 | def check_graphqlratelimiterror(exception): 220 | """ return True if exception is GraphQL Rate Limit Error, False otherwise 221 | """ 222 | logger.debug(f"checking if '{type(exception).__name__}' exception is a GraphqlRateLimitError") 223 | if isinstance(exception, (GraphqlRateLimitError, TypeError)): 224 | logger.debug('exception is a GraphqlRateLimitError - retrying request in 60 seconds') 225 | return True 226 | logger.debug(f'exception is not a GraphqlRateLimitError: {exception}') 227 | return False 228 | 229 | @retry(retry_on_exception=check_graphqlratelimiterror, wait_fixed=60000, stop_max_attempt_number=60) 230 | def graphql(self, query, variables, page=False, keys=None): 231 | """ execute graphql query and return response or paged response if page is True 232 | """ 233 | query = GitHubAPI.sanitize_query(query) 234 | if page: 235 | response = self._get_graphql_page(query, variables, keys) 236 | else: 237 | updated_query = GitHubAPI.clear_cursor(query, variables.get('cursor')) 238 | response = self.post('/graphql', json={'query': updated_query, 'variables': variables}) 239 | GitHubAPI.raise_if_error(response) 240 | return response 241 | 242 | check_graphqlratelimiterror = staticmethod(check_graphqlratelimiterror) 243 | -------------------------------------------------------------------------------- /src/unittest/python/test_githubapi.py: -------------------------------------------------------------------------------- 1 | 2 | # Copyright (c) 2020 Intel Corporation 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import unittest 17 | from mock import patch 18 | from mock import mock_open 19 | from mock import call 20 | from mock import Mock 21 | 22 | from github3api import GitHubAPI 23 | from github3api.githubapi import DEFAULT_PAGE_SIZE 24 | from github3api.githubapi import GraphqlRateLimitError 25 | from github3api.githubapi import GraphqlError 26 | 27 | from datetime import datetime 28 | 29 | from requests.exceptions import HTTPError 30 | from requests.exceptions import ChunkedEncodingError 31 | 32 | import sys 33 | import logging 34 | logger = logging.getLogger(__name__) 35 | 36 | consoleHandler = logging.StreamHandler(sys.stdout) 37 | logFormatter = logging.Formatter("%(asctime)s %(threadName)s %(name)s [%(funcName)s] %(levelname)s %(message)s") 38 | consoleHandler.setFormatter(logFormatter) 39 | rootLogger = logging.getLogger() 40 | rootLogger.addHandler(consoleHandler) 41 | rootLogger.setLevel(logging.DEBUG) 42 | 43 | 44 | class TestGitHubAPI(unittest.TestCase): 45 | 46 | def setUp(self): 47 | 48 | self.items = [ 49 | { 50 | 'name': 'name1-mid-last1', 51 | 'key1': 'value1', 52 | 'key2': 'value2', 53 | 'key3': 'value3' 54 | }, { 55 | 'name': 'name2-mid-last2', 56 | 'key1': 'value1', 57 | 'key2': 'value2', 58 | 'key3': 'value3.2' 59 | }, { 60 | 'name': 'name3-med-last3', 61 | 'key1': 'value1', 62 | 'key2': 'value2', 63 | 'key3': 'value3' 64 | }, { 65 | 'name': 'name4-mid-last4', 66 | 'key1': 'value1', 67 | 'key2': 'value2', 68 | 'key3': 'value3' 69 | } 70 | ] 71 | 72 | def tearDown(self): 73 | 74 | pass 75 | 76 | def test__get_ratelimit_Should_ReturnExpected_When_NoHeader(self, *patches): 77 | result = GitHubAPI.get_ratelimit({}) 78 | expected_result = {} 79 | self.assertEqual(result, expected_result) 80 | 81 | @patch('github3api.githubapi.datetime') 82 | def test__get_ratelimit_Should_ReturnExpected_When_Header(self, datetime_patch, *patches): 83 | datetime_patch.now.return_value = datetime(2020, 5, 6, 18, 22, 45, 12065) 84 | datetime_patch.fromtimestamp.return_value = datetime(2020, 5, 6, 19, 20, 51) 85 | header = { 86 | 'X-RateLimit-Reset': '1588792851', 87 | 'X-RateLimit-Remaining': '4999', 88 | 'X-RateLimit-Limit': '5000' 89 | } 90 | result = GitHubAPI.get_ratelimit(header) 91 | expected_result = { 92 | 'remaining': '4999', 93 | 'limit': '5000', 94 | 'minutes': '58' 95 | } 96 | self.assertEqual(result, expected_result) 97 | 98 | @patch('github3api.githubapi.logger') 99 | def test__log_ratelimit_Should_CallExpected_When_Called(self, logger_patch, *patches): 100 | ratelimit = { 101 | 'remaining': '4999', 102 | 'limit': '5000', 103 | 'minutes': '58' 104 | } 105 | GitHubAPI.log_ratelimit(ratelimit) 106 | logger_patch.debug.assert_called_with('4999/5000 resets in 58 min') 107 | 108 | def test__retry_ratelimit_error_Should_Return_False_When_NotHttpError(self, *patches): 109 | 110 | self.assertFalse(GitHubAPI.retry_ratelimit_error(Exception('test'))) 111 | 112 | def test__retry_ratelimit_error_Should_Return_False_When_HttpErrorNoStatusCodeMatch(self, *patches): 113 | response_mock = Mock(status_code=404) 114 | http_error_mock = HTTPError(Mock()) 115 | http_error_mock.response = response_mock 116 | self.assertFalse(GitHubAPI.retry_ratelimit_error(http_error_mock)) 117 | 118 | def test__retry_ratelimit_error_Should_Return_True_When_Match(self, *patches): 119 | response_mock = Mock(status_code=403, reason='API Rate Limit Exceeded') 120 | http_error_mock = HTTPError(Mock()) 121 | http_error_mock.response = response_mock 122 | self.assertTrue(GitHubAPI.retry_ratelimit_error(http_error_mock)) 123 | 124 | def test__retry_ratelimit_error_Should_Return_False_When_403NotRateLimit(self, *patches): 125 | response_mock = Mock(status_code=403, reason='Forbidden') 126 | http_error_mock = HTTPError(Mock()) 127 | http_error_mock.response = response_mock 128 | self.assertFalse(GitHubAPI.retry_ratelimit_error(http_error_mock)) 129 | 130 | @patch('github3api.githubapi.GitHubAPI.log_ratelimit') 131 | @patch('github3api.githubapi.GitHubAPI.get_ratelimit') 132 | def test__get_response_Should_CallExpected_When_RateLimit(self, get_ratelimit_patch, log_ratelimit_patch, *patches): 133 | client = GitHubAPI(bearer_token='bearer-token') 134 | response_mock = Mock(headers={'key': 'value'}) 135 | client.get_response(response_mock) 136 | get_ratelimit_patch.assert_called_once_with(response_mock.headers) 137 | log_ratelimit_patch.assert_called_once_with(get_ratelimit_patch.return_value) 138 | 139 | @patch('github3api.githubapi.GitHubAPI.log_ratelimit') 140 | @patch('github3api.githubapi.GitHubAPI.get_ratelimit') 141 | def test__get_response_Should_CallExpected_When_NoRateLimit(self, get_ratelimit_patch, log_ratelimit_patch, *patches): 142 | get_ratelimit_patch.return_value = {} 143 | client = GitHubAPI(bearer_token='bearer-token') 144 | response_mock = Mock(headers={'key': 'value'}) 145 | client.get_response(response_mock) 146 | get_ratelimit_patch.assert_called_once_with(response_mock.headers) 147 | log_ratelimit_patch.assert_not_called() 148 | 149 | def test__get_headers_Should_SetAcceptHeader_When_Called(self, *patches): 150 | client = GitHubAPI(bearer_token='bearer-token') 151 | result = client.get_headers() 152 | self.assertEqual(result['Accept'], 'application/vnd.github.v3+json') 153 | 154 | def test__get_headers_Should_SetAcceptHeader_When_Version(self, *patches): 155 | client = GitHubAPI(bearer_token='bearer-token', version='v2') 156 | result = client.get_headers() 157 | self.assertEqual(result['Accept'], 'application/vnd.github.v2+json') 158 | 159 | def test__get_next_endpoint_Should_ReturnNone_When_NoLinkHeader(self, *patches): 160 | client = GitHubAPI(bearer_token='bearer-token') 161 | self.assertIsNone(client._get_next_endpoint(None)) 162 | 163 | def test__get_next_endpoint_Should_ReturnExpected_When_CalledWithNextEndpoint(self, *patches): 164 | client = GitHubAPI(bearer_token='bearer-token') 165 | link_header = 'https://api.github.com/organizations/27781926/repos?page=4' 166 | result = client._get_next_endpoint(link_header) 167 | expected_result = '/organizations/27781926/repos?page=4' 168 | self.assertEqual(result, expected_result) 169 | 170 | @patch('github3api.githubapi.getenv', return_value='token') 171 | @patch('github3api.githubapi.GitHubAPI') 172 | def test__get_client_Should_CallAndReturnExpected_When_Called(self, githubapi_patch, getenv_patch, *patches): 173 | getenv_patch.side_effect = [ 174 | 'url', 175 | 'token' 176 | ] 177 | result = GitHubAPI.get_client() 178 | githubapi_patch.assert_called_once_with(hostname='url', bearer_token='token') 179 | self.assertEqual(result, githubapi_patch.return_value) 180 | 181 | def test__get_retries_Should_ReturnExpected_When_Called(self, *patches): 182 | client = GitHubAPI(bearer_token='bearer-token') 183 | expected_retries = [ 184 | # { 185 | # 'retry_on_exception': client.retry_chunkedencodingerror_error, 186 | # 'stop_max_attempt_number': 120, 187 | # 'wait_fixed': 10000 188 | # }, 189 | { 190 | 'retry_on_exception': client.retry_ratelimit_error, 191 | 'stop_max_attempt_number': 60, 192 | 'wait_fixed': 60000 193 | } 194 | 195 | ] 196 | self.assertEqual(client.retries, expected_retries) 197 | 198 | def test__get_page_from_url_Should_ReturnExpected_When_Match(self, *patches): 199 | result = GitHubAPI.get_page_from_url('https://api.github.com/user/repos?page=213') 200 | expected_result = 213 201 | self.assertEqual(result, expected_result) 202 | 203 | def test__get_page_from_url_Should_ReturnExpected_When_NoMatch(self, *patches): 204 | result = GitHubAPI.get_page_from_url('https://api.github.com/user/repos') 205 | self.assertIsNone(result) 206 | 207 | def test__get_per_page_from_url_Should_Return_Expected_When_Match(self, *patches): 208 | result = GitHubAPI.get_per_page_from_url('https://api.github.com/user/repos?page=213&per_page=75') 209 | expected_result = 75 210 | self.assertEqual(result, expected_result) 211 | 212 | def test__get_per_page_from_url_Should_Return_Expected_When_NoMatch(self, *patches): 213 | result = GitHubAPI.get_per_page_from_url('https://api.github.com/user/repos?page=213') 214 | expected_result = DEFAULT_PAGE_SIZE 215 | self.assertEqual(result, expected_result) 216 | 217 | @patch('github3api.GitHubAPI.get') 218 | def test__get_total_Should_ReturnExpected_When_NoLinks(self, get_patch, *patches): 219 | response_mock = Mock() 220 | response_mock.links = {} 221 | response_mock.json.return_value = ['', '', ''] 222 | get_patch.return_value = response_mock 223 | client = GitHubAPI(bearer_token='bearer-token') 224 | result = client.total('/user/repos') 225 | expected_result = len(response_mock.json.return_value) 226 | self.assertEqual(result, expected_result) 227 | 228 | @patch('github3api.GitHubAPI.get') 229 | def test__get_total_Should_ReturnExpected_When_Links(self, get_patch, *patches): 230 | response1_mock = Mock() 231 | response1_mock.links = {'next': {'url': 'https://api.github.com/user/repos?page=2', 'rel': 'next'}, 'last': {'url': 'https://api.github.com/user/repos?page=208', 'rel': 'last'}} 232 | get_patch.side_effect = [response1_mock, ['', '', '']] 233 | client = GitHubAPI(bearer_token='bearer-token') 234 | result = client.total('/user/repos') 235 | expected_result = DEFAULT_PAGE_SIZE * 207 + 3 236 | self.assertEqual(result, expected_result) 237 | 238 | def test__get_total_Should_RaiseValueError_When_EndpointHasPerPageParameter(self, *patches): 239 | client = GitHubAPI(bearer_token='bearer-token') 240 | with self.assertRaises(ValueError): 241 | client.total('/user/repos?per_page=100') 242 | 243 | @patch('github3api.GitHubAPI.get_per_page_from_url') 244 | @patch('github3api.GitHubAPI.get_page_from_url') 245 | @patch('github3api.GitHubAPI.get') 246 | def test__get_total_Should_CallExpected_When_EndpointHasQueryArguments(self, get_patch, *patches): 247 | response_mock = Mock() 248 | response_mock.links = {} 249 | response_mock.json.return_value = ['', '', ''] 250 | get_patch.return_value = response_mock 251 | client = GitHubAPI(bearer_token='bearer-token') 252 | client.total('/user/repos?type=private&direction=asc') 253 | self.assertTrue(call('/user/repos?type=private&direction=asc&per_page=1', raw_response=True) in get_patch.mock_calls) 254 | 255 | def test__clear_cursor_Should_ReturnExpected_When_NoCursor(self, *patches): 256 | query = """ 257 | query ($query: String!, $page_size: Int!, $cursor: String!) { 258 | search(query: $query, type: REPOSITORY, first: $page_size, after: $cursor) { 259 | repositoryCount 260 | pageInfo { 261 | endCursor 262 | hasNextPage 263 | } 264 | edges { 265 | cursor 266 | node { 267 | ... on Repository { 268 | nameWithOwner 269 | } 270 | } 271 | } 272 | } 273 | } 274 | """ 275 | result = GitHubAPI.clear_cursor(query, '') 276 | expected_result = """ 277 | query ($query: String!, $page_size: Int!, ) { 278 | search(query: $query, type: REPOSITORY, first: $page_size, ) { 279 | repositoryCount 280 | pageInfo { 281 | endCursor 282 | hasNextPage 283 | } 284 | edges { 285 | cursor 286 | node { 287 | ... on Repository { 288 | nameWithOwner 289 | } 290 | } 291 | } 292 | } 293 | } 294 | """ 295 | self.assertEqual(result, expected_result) 296 | 297 | def test__clear_cursor_Should_ReturnExpected_When_Cursor(self, *patches): 298 | query = """ 299 | query ($query: String!, $page_size: Int!, $cursor: String!) { 300 | search(query: $query, type: REPOSITORY, first: $page_size, after: $cursor) { 301 | repositoryCount 302 | pageInfo { 303 | endCursor 304 | hasNextPage 305 | } 306 | edges { 307 | cursor 308 | node { 309 | ... on Repository { 310 | nameWithOwner 311 | } 312 | } 313 | } 314 | } 315 | } 316 | """ 317 | result = GitHubAPI.clear_cursor(query, '--cursor--') 318 | self.assertEqual(result, query) 319 | 320 | def test__sanitize_query_Should_ReturnExpected_When_Called(self, *patches): 321 | query = """ 322 | one 323 | two 324 | three 325 | """ 326 | result = GitHubAPI.sanitize_query(query) 327 | expected_result = 'one two three' 328 | self.assertEqual(result, expected_result) 329 | 330 | def test__raise_if_error_Should_RaiseGraphqlRateLimitError_When_Expected(self, *patches): 331 | response = { 332 | 'errors': [{'type': 'RATE_LIMITED', 'message': 'ratelimit error'}] 333 | } 334 | with self.assertRaises(GraphqlRateLimitError): 335 | GitHubAPI.raise_if_error(response) 336 | 337 | def test__raise_if_error_Should_RaiseGraphqlError_When_Expected(self, *patches): 338 | response = { 339 | 'errors': [{'type': 'other', 'message': 'other error'}] 340 | } 341 | with self.assertRaises(GraphqlError): 342 | GitHubAPI.raise_if_error(response) 343 | 344 | def test__raise_if_error_Should_DoNothing_When_NoError(self, *patches): 345 | response = { 346 | 'data': {} 347 | } 348 | GitHubAPI.raise_if_error(response) 349 | 350 | def test__get_value_Should_ReturnExpected_When_Called(self, *patches): 351 | data = { 352 | 'python': { 353 | 'is': { 354 | 'cool': 'yep' 355 | } 356 | } 357 | } 358 | keys = 'python.is.cool' 359 | result = GitHubAPI.get_value(data, keys) 360 | expected_result = 'yep' 361 | self.assertEqual(result, expected_result) 362 | 363 | def test__get_value_Should_ReturnKeyError_When_Expected(self, *patches): 364 | data = { 365 | 'python': { 366 | 'is': { 367 | 'cool': 'yep' 368 | } 369 | } 370 | } 371 | keys = 'x.y.z' 372 | with self.assertRaises(KeyError): 373 | GitHubAPI.get_value(data, keys) 374 | 375 | def test__get_value_Should_ReturnExpected_When_NoDot(self, *patches): 376 | data = { 377 | 'cool': 'yep' 378 | } 379 | keys = 'cool' 380 | result = GitHubAPI.get_value(data, keys) 381 | expected_result = 'yep' 382 | self.assertEqual(result, expected_result) 383 | 384 | @patch('github3api.GitHubAPI.clear_cursor') 385 | @patch('github3api.GitHubAPI.raise_if_error') 386 | @patch('github3api.GitHubAPI.post') 387 | @patch('github3api.GitHubAPI.get_value') 388 | def test__get_graphql_page_Should_YieldExpected_When_Called(self, get_value_patch, *patches): 389 | get_value_patch.side_effect = [ 390 | ['page1', 'page2'], 391 | {'hasNextPage': True, 'endCursor': 'cursor1'}, 392 | ['page3', 'page4'], 393 | {'hasNextPage': False} 394 | ] 395 | client = GitHubAPI(bearer_token='bearer-token') 396 | query = '--query--' 397 | variables = {'key1': 'value1'} 398 | keys = 'some.keys' 399 | result = client._get_graphql_page(query, variables, keys) 400 | self.assertEqual(next(result), ['page1', 'page2']) 401 | self.assertEqual(next(result), ['page3', 'page4']) 402 | with self.assertRaises(StopIteration): 403 | next(result) 404 | 405 | def test__check_graphqlratelimiterror_Should_ReturnTrue_When_Expected(self, *patches): 406 | 407 | self.assertTrue(GitHubAPI.check_graphqlratelimiterror(GraphqlRateLimitError('ratelimit error'))) 408 | 409 | def test__check_graphqlratelimiterror_Should_ReturnFalse_When_Expected(self, *patches): 410 | 411 | self.assertFalse(GitHubAPI.check_graphqlratelimiterror(KeyError('key error'))) 412 | 413 | @patch('github3api.GitHubAPI.sanitize_query') 414 | @patch('github3api.GitHubAPI._get_graphql_page') 415 | def test__graphql_Should_ReturnExpected_When_Page(self, get_graphql_page_patch, *patches): 416 | client = GitHubAPI(bearer_token='bearer-token') 417 | query = '--query--' 418 | variables = {'key1': 'value1'} 419 | keys = 'some.keys' 420 | result = client.graphql(query, variables, page=True, keys=keys) 421 | self.assertEqual(result, get_graphql_page_patch.return_value) 422 | 423 | @patch('github3api.GitHubAPI.sanitize_query') 424 | @patch('github3api.GitHubAPI.clear_cursor') 425 | @patch('github3api.GitHubAPI.raise_if_error') 426 | @patch('github3api.GitHubAPI.post') 427 | def test__graphql_Should_ReturnExpected_When_Called(self, post_patch, *patches): 428 | client = GitHubAPI(bearer_token='bearer-token') 429 | query = '--query--' 430 | variables = {'key1': 'value1'} 431 | result = client.graphql(query, variables) 432 | self.assertEqual(result, post_patch.return_value) 433 | --------------------------------------------------------------------------------