Created
January 21, 2024 13:26
-
-
Save laiso/5d9ed680dd75034e2a8b657ed5a58270 to your computer and use it in GitHub Desktop.
How to check if a specific GitHub user is sponsoring me
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from gql import gql, Client | |
from gql.transport.requests import RequestsHTTPTransport | |
token = os.getenv("GITHUB_TOKEN") | |
transport = RequestsHTTPTransport( | |
url="https://api.github.com/graphql", | |
use_json=True, | |
headers={"Authorization": f"bearer {token}"}, | |
verify=True, | |
retries=3, | |
) | |
client = Client( | |
transport=transport, | |
fetch_schema_from_transport=True, | |
) | |
def is_sponsor(user) -> bool: | |
query = gql( | |
f""" | |
query {{ | |
user(login: "{user}") {{ | |
login | |
sponsorshipForViewerAsSponsorable(activeOnly: true) {{ | |
createdAt | |
}} | |
}} | |
}} | |
""" | |
) | |
result = client.execute(query) | |
return result["user"].get("sponsorshipForViewerAsSponsorable") is not None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest | |
from unittest.mock import patch | |
from sponsor import is_sponsor | |
class TestIsSponsor(unittest.TestCase): | |
@patch('main.client.execute') | |
def test_is_sponsor(self, mock_execute): | |
# モックの設定 | |
mock_execute.return_value = { | |
"user": { | |
"sponsorshipForViewerAsSponsorable": { | |
"createdAt": "2022-01-01T00:00:00Z" | |
} | |
} | |
} | |
# テストの実行 | |
result = is_sponsor('test_user') | |
self.assertTrue(result) | |
# モックが呼び出されたことを確認 | |
mock_execute.assert_called_once() | |
@patch('main.client.execute') | |
def test_is_not_sponsor(self, mock_execute): | |
# モックの設定 | |
mock_execute.return_value = { | |
"user": { | |
"sponsorshipForViewerAsSponsorable": None | |
} | |
} | |
# テストの実行 | |
result = is_sponsor('test_user') | |
self.assertFalse(result) | |
# モックが呼び出されたことを確認 | |
mock_execute.assert_called_once() | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment