Skip to content

Commit

Permalink
Add auth functions and tests.
Browse files Browse the repository at this point in the history
Signed-off-by: Zack Koppert <[email protected]>
  • Loading branch information
zkoppert committed Oct 3, 2023
1 parent 54860b8 commit 94bf44f
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
20 changes: 20 additions & 0 deletions auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""This is the module that contains functions related to authenticating to GitHub with a personal access token."""

import os
import github3


def auth_to_github():
"""Connect to github.com or GitHub Enterprise, depending on env variables."""
ghe = os.getenv("GH_ENTERPRISE_URL", default="").strip()
token = os.getenv("GH_TOKEN")
if ghe and token:
github_connection = github3.github.GitHubEnterprise(ghe, token=token)
elif token:
github_connection = github3.login(token=os.getenv("GH_TOKEN"))
else:
raise ValueError("GH_TOKEN environment variable not set")

if not github_connection:
raise ValueError("Unable to authenticate to GitHub")
return github_connection # type: ignore
51 changes: 51 additions & 0 deletions test_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Test cases for the auth module."""
import unittest
from unittest.mock import patch
import auth


class TestAuth(unittest.TestCase):
"""
Test case for the auth module.
"""

@patch("os.getenv")
@patch("github3.github.GitHubEnterprise")
def test_auth_to_github_enterprise(self, mock_github_enterprise, mock_getenv):
"""
Test the auth_to_github function when the GH_ENTERPRISE_URL and GH_TOKEN environment variables are set.
"""
mock_getenv.side_effect = ["https://github.enterprise.com", "token"]
mock_github_enterprise.return_value = "Authenticated to GitHub Enterprise"

result = auth.auth_to_github()

self.assertEqual(result, "Authenticated to GitHub Enterprise")

@patch("github3.login")
@patch("os.getenv")
def test_auth_to_github_com(self, mock_login, mock_getenv):
"""
Test the auth_to_github function when only the GH_TOKEN environment variable is set.
"""
mock_getenv.side_effect = ["", "token"]
mock_login.return_value = "Authenticated to github.com"

result = auth.auth_to_github()

self.assertEqual(result.url, "Authenticated to github.com")

@patch("os.getenv")
def test_auth_to_github_no_token(self, mock_getenv):
"""
Test the auth_to_github function when the GH_TOKEN environment variable is not set.
Expect a ValueError to be raised.
"""
mock_getenv.side_effect = ["", ""]

with self.assertRaises(ValueError):
auth.auth_to_github()


if __name__ == "__main__":
unittest.main()

0 comments on commit 94bf44f

Please sign in to comment.