-
Notifications
You must be signed in to change notification settings - Fork 10
Initial Client and Config class for tfe #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c4f76d5
feat: config class for tfe
taru-garg-2000 57ec2a0
feat: add client
taru-garg-2000 3d661e1
fix: cleanup types
taru-garg-2000 fafa55d
tests: improve tests for client and config
taru-garg-2000 5ac2dbf
tests: make lint happy
taru-garg-2000 aaeb372
chore: add git hooks for pre-commit formatting
taru-garg-2000 795f989
fix: add shebang to precommit hook
taru-garg-2000 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,6 +13,7 @@ htmlcov | |
| .pytest_cache/ | ||
| .mypy_cache/ | ||
| .ruff_cache/ | ||
| *.egg-info | ||
|
|
||
| # Visual Studio Code | ||
| .vscode/ | ||
|
|
||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| #!/usr/bin/env bash | ||
|
|
||
| set -euo pipefail | ||
|
|
||
| # Call block to block the commit with a message. | ||
| block() { | ||
| echo "$@" | ||
| echo "Commit blocked - see errors above." | ||
| exit 1 | ||
| } | ||
|
|
||
| # Add all check functions to this space separated list. | ||
| # They are executed in this order (see end of file). | ||
| CHECKS="fmt lint" | ||
|
|
||
| # Run fmt against changed files compared to origin/main | ||
| fmt() { | ||
| echo "==> Running fmt on all files" | ||
| make fmt || block "Formatting failed" | ||
|
|
||
| # Re-add any files that were changed by the fixers | ||
| git add -u | ||
| } | ||
|
|
||
| lint() { | ||
| echo "==> Running lint on all files" | ||
| make lint || block "Linting failed" | ||
|
|
||
| # Re-add any files that were changed by the fixers | ||
| git add -u | ||
| } | ||
|
|
||
| for CHECK in $CHECKS; do | ||
| # Force each check into a subshell to avoid crosstalk. | ||
| ( $CHECK ) || exit $? | ||
| done |
This file contains hidden or 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
This file contains hidden or 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
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| from unittest.mock import Mock, patch | ||
|
|
||
| import pytest | ||
|
|
||
| from tfe import client, config | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def test_config(): | ||
| return config.Config(address="https://app.terraform.io", token="test-token") | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_response(): | ||
| response = Mock() | ||
| response.headers = { | ||
| "TFP-API-Version": "2.5.0", | ||
| "X-TFE-Version": "v202308-1", | ||
| "TFP-AppName": "HCP Terraform", | ||
| } | ||
| response.raise_for_status.return_value = None | ||
| return response | ||
|
|
||
|
|
||
| class TestClient: | ||
| @patch("requests.Session.get") | ||
| def test_client_initialization(self, mock_get, test_config, mock_response): | ||
| """Test basic client setup works.""" | ||
| mock_get.return_value = mock_response | ||
|
|
||
| client_instance = client.Client(config=test_config) | ||
|
|
||
| assert client_instance.config.address == "https://app.terraform.io" | ||
| assert client_instance.config.token == "test-token" | ||
| assert client_instance.base_url == "https://app.terraform.io/api/v2/" | ||
| assert ( | ||
| client_instance.registry_base_url | ||
| == "https://app.terraform.io/api/registry/" | ||
| ) | ||
|
|
||
| @patch("requests.Session.get") | ||
| def test_url_normalization(self, mock_get, mock_response): | ||
| """Test that paths get normalized with trailing slashes.""" | ||
| mock_get.return_value = mock_response | ||
|
|
||
| cfg = config.Config( | ||
| address="https://example.com", | ||
| token="test", | ||
| base_path="/custom/api", # no trailing slash | ||
| registry_base_path="/registry", # no trailing slash | ||
| ) | ||
|
|
||
| client_instance = client.Client(config=cfg) | ||
|
|
||
| assert client_instance.base_url == "https://example.com/custom/api/" | ||
| assert client_instance.registry_base_url == "https://example.com/registry/" | ||
|
|
||
| @patch("requests.Session.get") | ||
| def test_api_metadata_extraction(self, mock_get, test_config, mock_response): | ||
| """Test that API metadata gets extracted from response headers.""" | ||
| mock_get.return_value = mock_response | ||
|
|
||
| client_instance = client.Client(config=test_config) | ||
|
|
||
| assert client_instance.remote_api_version == "2.5.0" | ||
| assert client_instance.remote_tfe_version == "v202308-1" | ||
| assert client_instance.app_name == "HCP Terraform" | ||
|
|
||
| @patch("requests.Session.get") | ||
| def test_cloud_vs_enterprise_detection(self, mock_get, test_config): | ||
| """Test detection between cloud and enterprise instances.""" | ||
| # Test HCP Terraform (cloud) | ||
| cloud_response = Mock() | ||
| cloud_response.headers = {"TFP-AppName": "HCP Terraform"} | ||
| cloud_response.raise_for_status.return_value = None | ||
| mock_get.return_value = cloud_response | ||
|
|
||
| cloud_client = client.Client(config=test_config) | ||
| assert cloud_client.is_cloud() is True | ||
| assert cloud_client.is_enterprise() is False | ||
|
|
||
| # Test Terraform Enterprise | ||
| enterprise_response = Mock() | ||
| enterprise_response.headers = {"TFP-AppName": "Terraform Enterprise"} | ||
| enterprise_response.raise_for_status.return_value = None | ||
| mock_get.return_value = enterprise_response | ||
|
|
||
| enterprise_client = client.Client(config=test_config) | ||
| assert enterprise_client.is_cloud() is False | ||
| assert enterprise_client.is_enterprise() is True | ||
|
|
||
| @patch("requests.Session.get") | ||
| def test_fake_api_version_for_testing(self, mock_get, test_config, mock_response): | ||
| """Test the fake API version setter for testing scenarios.""" | ||
| mock_get.return_value = mock_response | ||
|
|
||
| client_instance = client.Client(config=test_config) | ||
|
|
||
| # Original version from mock | ||
| assert client_instance.remote_api_version == "2.5.0" | ||
|
|
||
| # Set fake version | ||
| client_instance.set_fake_remote_api_version("3.0.0") | ||
| assert client_instance.remote_api_version == "3.0.0" |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| import pytest | ||
| import requests | ||
|
|
||
| from tfe import config | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def reset_environment(monkeypatch): | ||
| """Reset environment variables before each test.""" | ||
| monkeypatch.delenv("TFE_ADDRESS", raising=False) | ||
| monkeypatch.delenv("TFE_TOKEN", raising=False) | ||
| monkeypatch.delenv("TFE_HOST", raising=False) | ||
| monkeypatch.setenv("TFE_TOKEN", "abc123") | ||
| yield | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def cfg(): | ||
| """Provide a fresh Config instance with clean environment.""" | ||
| return config.Config() | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def test_session(): | ||
| """Provide a clean requests session without default headers.""" | ||
| session = requests.Session() | ||
| session.headers["User-Agent"] = "test" | ||
| session.headers["Authorization"] = "Bearer test" | ||
| return session | ||
|
|
||
|
|
||
| class TestConfig: | ||
| def test_default_config(self, cfg): | ||
| """Test that default configuration values are set correctly.""" | ||
| assert cfg.address == config.DEFAULT_ADDRESS | ||
| assert cfg.base_path == config.DEFAULT_BASE_PATH | ||
| assert cfg.registry_base_path == config.DEFAULT_REGISTRY_PATH | ||
| assert isinstance(cfg.http_client, requests.Session) | ||
| assert "User-Agent" in cfg.http_client.headers | ||
| assert cfg.retry_log_hook is None | ||
| assert cfg.retry_server_errors is False | ||
|
|
||
| def test_env_address_and_token(self, monkeypatch): | ||
| """Test that environment variables TFE_ADDRESS and TFE_TOKEN are read correctly.""" | ||
| monkeypatch.setenv("TFE_ADDRESS", "https://custom.tfe") | ||
| cfg = config.Config() | ||
| assert cfg.address == "https://custom.tfe" | ||
| assert cfg.token == "abc123" | ||
|
|
||
| def test_env_host_fallback(self, monkeypatch): | ||
| """Test that TFE_HOST is used as fallback when TFE_ADDRESS is not set.""" | ||
| monkeypatch.setenv("TFE_HOST", "host.tfe") | ||
| cfg = config.Config() | ||
| assert cfg.address == "https://host.tfe" | ||
|
|
||
| def test_explicit_address_override(self): | ||
| """Test that explicitly passed address overrides environment variables.""" | ||
| cfg = config.Config(address="https://explicit.tfe") | ||
| assert cfg.address == "https://explicit.tfe" | ||
|
|
||
| def test_headers_update(self): | ||
| """Test that custom headers are properly merged with default headers.""" | ||
| custom_headers = {"Authorization": "Bearer testtoken", "X-Test": "yes"} | ||
| cfg = config.Config(headers=custom_headers) | ||
| assert "Authorization" in cfg.http_client.headers | ||
| assert cfg.http_client.headers["Authorization"] == "Bearer testtoken" | ||
| assert "X-Test" in cfg.http_client.headers | ||
| assert cfg.http_client.headers["X-Test"] == "yes" | ||
| assert "User-Agent" in cfg.http_client.headers | ||
|
|
||
| def test_retry_log_hook_and_server_errors(self): | ||
| """Test that retry configuration is properly set.""" | ||
|
|
||
| def dummy_hook(retries, response): | ||
| pass | ||
|
|
||
| cfg = config.Config(retry_log_hook=dummy_hook, retry_server_errors=True) | ||
| assert cfg.retry_log_hook == dummy_hook | ||
| assert cfg.retry_server_errors is True | ||
|
|
||
| def test_custom_session(self, test_session): | ||
| """Test that User-Agent is set when session has no default User-Agent.""" | ||
| cfg = config.Config(http_client=test_session) | ||
| assert "User-Agent" in cfg.http_client.headers | ||
| assert cfg.http_client.headers["User-Agent"] == "test" | ||
| assert cfg.http_client.headers["Authorization"] == "Bearer test" | ||
|
|
||
| def test_validate_config(self, monkeypatch): | ||
| """Test that configuration validation works as expected.""" | ||
| with pytest.raises(ValueError, match="API token is required") as _: | ||
| monkeypatch.setenv("TFE_TOKEN", "") | ||
| _ = config.Config(token="") | ||
|
|
||
| with pytest.raises(ValueError, match="Address must include protocol") as _: | ||
| monkeypatch.setenv("TFE_TOKEN", "test-token") | ||
| monkeypatch.setenv("TFE_ADDRESS", "test.foo.bar") | ||
| _ = config.Config() |
This file contains hidden or 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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.