Add tests for GcpInstance

This commit is contained in:
Shreya 2021-02-04 21:02:53 +05:30
parent 413aa35b5b
commit eed5ea1337
2 changed files with 45 additions and 4 deletions

View File

@ -17,13 +17,13 @@ class GcpInstance(CloudInstance):
Used to determine if on GCP. See https://cloud.google.com/compute/docs/storing-retrieving-metadata#runninggce
"""
def is_instance(self):
return self.on_gcp
return self._on_gcp
def get_cloud_provider_name(self) -> Environment:
return Environment.GCP
def __init__(self):
self.on_gcp = False
self._on_gcp = False
try:
# If not on GCP, this domain shouldn't resolve.
@ -31,7 +31,7 @@ class GcpInstance(CloudInstance):
if response:
logger.debug("Got ok metadata response: on GCP")
self.on_gcp = True
self._on_gcp = True
if "Metadata-Flavor" not in response.headers:
logger.warning("Got unexpected GCP Metadata format")
@ -42,4 +42,4 @@ class GcpInstance(CloudInstance):
logger.warning("On GCP, but metadata response not ok: {}".format(response.status_code))
except requests.RequestException:
logger.debug("Failed to get response from GCP metadata service: This instance is not on GCP")
self.on_gcp = False
self._on_gcp = False

View File

@ -0,0 +1,41 @@
import pytest
import requests
import requests_mock
from common.cloud.environment_names import Environment
from common.cloud.gcp.gcp_instance import GCP_METADATA_SERVICE_URL, GcpInstance
def get_test_gcp_instance(url, **kwargs):
with requests_mock.Mocker() as m:
m.get(url, **kwargs)
test_gcp_instance_object = GcpInstance()
return test_gcp_instance_object
# good request
@pytest.fixture
def good_request_mock_instance():
return get_test_gcp_instance(GCP_METADATA_SERVICE_URL)
def test_is_instance_good_request(good_request_mock_instance):
assert good_request_mock_instance.is_instance()
def test_get_cloud_provider_name_good_request(good_request_mock_instance):
assert good_request_mock_instance.get_cloud_provider_name() == Environment.GCP
# bad request
@pytest.fixture
def bad_request_mock_instance():
return get_test_gcp_instance(GCP_METADATA_SERVICE_URL, exc=requests.RequestException)
def test_is_instance_bad_request(bad_request_mock_instance):
assert bad_request_mock_instance.is_instance() is False
def test_get_cloud_provider_name_bad_request(bad_request_mock_instance):
assert bad_request_mock_instance.get_cloud_provider_name() == Environment.GCP