|
| 1 | +"""Tests for authentication helpers.""" |
| 2 | + |
| 3 | +from unittest.mock import patch |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from github_backup import github_backup |
| 8 | + |
| 9 | + |
| 10 | +def test_token_from_gh_flag_parses(): |
| 11 | + args = github_backup.parse_args(["--token-from-gh", "testuser"]) |
| 12 | + assert args.token_from_gh is True |
| 13 | + |
| 14 | + |
| 15 | +def test_get_auth_reads_token_from_gh_cli(create_args): |
| 16 | + args = create_args(token_from_gh=True) |
| 17 | + |
| 18 | + with patch( |
| 19 | + "github_backup.github_backup.subprocess.check_output", |
| 20 | + return_value=b"gho_test_token\n", |
| 21 | + ) as mock_check_output: |
| 22 | + auth = github_backup.get_auth(args, encode=False) |
| 23 | + |
| 24 | + assert auth == "gho_test_token:x-oauth-basic" |
| 25 | + mock_check_output.assert_called_once_with( |
| 26 | + ["gh", "auth", "token"], stderr=github_backup.subprocess.PIPE |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +def test_get_auth_reads_token_from_gh_cli_for_enterprise_host(create_args): |
| 31 | + args = create_args(token_from_gh=True, github_host="ghe.example.com") |
| 32 | + |
| 33 | + with patch( |
| 34 | + "github_backup.github_backup.subprocess.check_output", |
| 35 | + return_value=b"gho_enterprise_token\n", |
| 36 | + ) as mock_check_output: |
| 37 | + auth = github_backup.get_auth(args, encode=False) |
| 38 | + |
| 39 | + assert auth == "gho_enterprise_token:x-oauth-basic" |
| 40 | + mock_check_output.assert_called_once_with( |
| 41 | + ["gh", "auth", "token", "--hostname", "ghe.example.com"], |
| 42 | + stderr=github_backup.subprocess.PIPE, |
| 43 | + ) |
| 44 | + |
| 45 | + |
| 46 | +def test_token_from_gh_is_cached(create_args): |
| 47 | + args = create_args(token_from_gh=True) |
| 48 | + |
| 49 | + with patch( |
| 50 | + "github_backup.github_backup.subprocess.check_output", |
| 51 | + return_value=b"gho_cached_token\n", |
| 52 | + ) as mock_check_output: |
| 53 | + assert github_backup.get_auth(args, encode=False) == "gho_cached_token:x-oauth-basic" |
| 54 | + assert github_backup.get_auth(args, encode=False) == "gho_cached_token:x-oauth-basic" |
| 55 | + |
| 56 | + mock_check_output.assert_called_once() |
| 57 | + |
| 58 | + |
| 59 | +def test_token_from_gh_rejects_as_app(create_args): |
| 60 | + args = create_args(token_from_gh=True, as_app=True) |
| 61 | + |
| 62 | + with pytest.raises(Exception) as exc_info: |
| 63 | + github_backup.get_auth(args, encode=False) |
| 64 | + |
| 65 | + assert "--token-from-gh cannot be used with --as-app" in str(exc_info.value) |
0 commit comments