diff --git a/development.md b/development.md index 5277d0f..592bbf0 100644 --- a/development.md +++ b/development.md @@ -36,8 +36,8 @@ script options that you can chose to run. `hatch run test:run-coverage` -2. To run tests without code coverage report outs use : - `hatch run test:run-coverage` +2. To run tests without code coverage report outs use: + `hatch run test:run-no-cov` 3. To run tests with an xml report generated use: `hatch run test:run-report` diff --git a/src/pyosmeta/github_api.py b/src/pyosmeta/github_api.py index 1099820..789d0c8 100644 --- a/src/pyosmeta/github_api.py +++ b/src/pyosmeta/github_api.py @@ -57,9 +57,19 @@ def get_token(self) -> str | None: ------- str The provided API key in the .env file. + + Raises + ------ + KeyError + If the GITHUB_TOKEN environment variable is not found. """ load_dotenv() - return os.environ["GITHUB_TOKEN"] + try: + return os.environ["GITHUB_TOKEN"] + except KeyError: + raise KeyError( + "Oops! A GITHUB_TOKEN environment variable wasn't found." + ) @property def api_endpoint(self): diff --git a/tests/unit/test_github_api.py b/tests/unit/test_github_api.py new file mode 100644 index 0000000..e9f03b6 --- /dev/null +++ b/tests/unit/test_github_api.py @@ -0,0 +1,45 @@ +import os + +import pytest +import secrets + +from pyosmeta.github_api import GitHubAPI + + +@pytest.fixture +def mock_github_token(monkeypatch): + """Fixture to create a mock token - i don't believe this + is working as expected either.""" + # Generate a random token + random_token = secrets.token_hex(16) + + # Mocking the GitHub token in the environment variable + monkeypatch.setenv("GITHUB_TOKEN", random_token) + + +@pytest.fixture +def mock_missing_github_token(monkeypatch, tmpdir): + os.chdir(tmpdir) + # Remove the GitHub token from the environment variable + monkeypatch.delenv("GITHUB_TOKEN", raising=False) + + +def test_get_token(mock_github_token): + """Test that get_token accesses the token correctly when it is + present.""" + github_api = GitHubAPI() + token = github_api.get_token() + + assert token == os.environ["GITHUB_TOKEN"] + + +# This test should work but it keeps finding my local envt var +# Even tho i'm removing it in the monkey patch and using a temp +# Directory +# def test_missing_token(mock_missing_github_token, tmpdir): +# """Test that a keyerror is raised when the token is missing.""" +# os.chdir(tmpdir) +# github_api = GitHubAPI() + +# with pytest.raises(KeyError, match="Oops! A GITHUB_TOKEN environment"): +# github_api.get_token()