Skip to content

Commit

Permalink
Fixup unittests and linting
Browse files Browse the repository at this point in the history
  • Loading branch information
bschimke95 committed Feb 2, 2024
1 parent 95dcf3a commit 564529e
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 32 deletions.
21 changes: 8 additions & 13 deletions charms/k8s/lib/charms/k8s/v0/k8sd_api_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,27 +425,22 @@ def is_cluster_ready(self):
return cluster_status.metadata.status.Ready
return False

def check_k8sd_ready(self) -> str:
"""Check if k8sd is ready.
Returns:
bool: True if k8sd is ready to accept API requests, False otherwise.
"""
def check_k8sd_ready(self):
"""Check if k8sd is ready."""
endpoint = "/cluster/1.0/ready"
self._send_request(endpoint, "GET", EmptyResponse)

def bootstrap_k8s_snap(self, name: str, address: str) -> None:
"""Bootstrap the k8s cluster.
Args:
name: name of the node
address: address to which k8sd should be bound
TODO: Add bootstrap config support
"""
endpoint = "/cluster/control"
body = {
"bootstrap": True,
"name": name,
"address": address
}
body = {"bootstrap": True, "name": name, "address": address}
self._send_request(endpoint, "POST", EmptyResponse, body)

def request_auth_token(self, username: str, groups: List[str]) -> str:
Expand Down
19 changes: 11 additions & 8 deletions charms/k8s/src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,24 +83,27 @@ def _apply_snap_requirements(self):
]
for c in commands:
subprocess.check_call(shlex.split(c))

@on_error(
WaitingStatus("Waiting for k8sd"), InvalidResponseError, K8sdConnectionError
)

@on_error(WaitingStatus("Waiting for k8sd"), InvalidResponseError, K8sdConnectionError)
def _check_k8sd_ready(self):
"""Check if k8sd is ready to accept requests."""
status.add(ops.MaintenanceStatus("Check k8sd ready"))
self.api_manager.check_k8sd_ready()
self.api_manager.check_k8sd_ready()

@on_error(ops.WaitingStatus("Failed to bootstrap k8s snap"), InvalidResponseError, K8sdConnectionError)
@on_error(
ops.WaitingStatus("Failed to bootstrap k8s snap"),
InvalidResponseError,
K8sdConnectionError,
)
def _bootstrap_k8s_snap(self):
"""Bootstrap k8s if it's not already bootstrapped."""
# TODO: Remove `is_cluster_bootstrapped` check once https://github.com/canonical/k8s-snap/pull/99 landed.
# TODO: Remove `is_cluster_bootstrapped` check once
# https://github.com/canonical/k8s-snap/pull/99 landed.
if not self.api_manager.is_cluster_bootstrapped():
status.add(ops.MaintenanceStatus("Bootstrapping Cluster"))
binding = self.model.get_binding("juju-info")
address = binding and binding.network.ingress_address
# k8s/x to k8s-x to avoid trouble with urls etc.
# k8s/x to k8s-x to avoid trouble with urls
name = self.unit.name.replace("/", "-")

# TODO: Make port (and address) configurable.
Expand Down
28 changes: 19 additions & 9 deletions charms/k8s/tests/unit/test_k8sd_api_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@
AuthTokenResponse,
BaseRequestModel,
CreateJoinTokenResponse,
EmptyResponse,
InvalidResponseError,
K8sdAPIManager,
K8sdConnectionError,
TokenMetadata,
UnixSocketHTTPConnection,
UpdateComponentResponse,
)


Expand Down Expand Up @@ -108,6 +108,20 @@ def setUp(self):
self.mock_factory = MagicMock()
self.api_manager = K8sdAPIManager(factory=self.mock_factory)

@patch("lib.charms.k8s.v0.k8sd_api_manager.K8sdAPIManager._send_request")
def test_bootstrap_k8s_snap(self, mock_send_request):
mock_send_request.return_value = EmptyResponse(
status_code=200, type="test", error_code=0, metadata="foo"
)

self.api_manager.bootstrap_k8s_snap("test-node", "127.0.0.1:6400")
mock_send_request.assert_called_once_with(
"/cluster/control",
"POST",
EmptyResponse,
{"bootstrap": True, "name": "test-node", "address": "127.0.0.1:6400"},
)

def test_create_join_token_invalid_response(self):
mock_connection = MagicMock()
self.mock_factory.create_connection.return_value.__enter__.return_value = mock_connection
Expand Down Expand Up @@ -156,27 +170,23 @@ def test_create_join_token(self, mock_send_request):

@patch("lib.charms.k8s.v0.k8sd_api_manager.K8sdAPIManager._send_request")
def test_enable_component__enable(self, mock_send_request):
mock_send_request.return_value = UpdateComponentResponse(
status_code=200, type="test", error_code=0
)
mock_send_request.return_value = EmptyResponse(status_code=200, type="test", error_code=0)

self.api_manager.enable_component("foo", True)
mock_send_request.assert_called_once_with(
"/1.0/k8sd/components/foo",
"PUT",
UpdateComponentResponse,
EmptyResponse,
{"status": "enabled"},
)

@patch("lib.charms.k8s.v0.k8sd_api_manager.K8sdAPIManager._send_request")
def test_enable_component__disable(self, mock_send_request):
mock_send_request.return_value = UpdateComponentResponse(
status_code=200, type="test", error_code=0
)
mock_send_request.return_value = EmptyResponse(status_code=200, type="test", error_code=0)

self.api_manager.enable_component("foo", False)
mock_send_request.assert_called_once_with(
"/1.0/k8sd/components/foo", "PUT", UpdateComponentResponse, {"status": "disabled"}
"/1.0/k8sd/components/foo", "PUT", EmptyResponse, {"status": "disabled"}
)

@patch("lib.charms.k8s.v0.k8sd_api_manager.K8sdAPIManager._send_request")
Expand Down
9 changes: 7 additions & 2 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def pytest_addoption(parser: pytest.Parser):
Args:
parser: Pytest parser.
"""
parser.addoption("--charm-file", dest="charm_files", action="append", default=list())
parser.addoption("--charm-file", dest="charm_files", action="append", default=[])


@dataclass
Expand Down Expand Up @@ -99,6 +99,9 @@ def _craft_resource(self, _name: str, resource: dict) -> Optional[str]:
async def resolve(self, charm_files: List[str]) -> Path:
"""Build or find the charm with ops_test.
Args:
charm_files: The list charms files to resolve
Return:
path to charm file
Expand Down Expand Up @@ -177,7 +180,9 @@ async def kubernetes_cluster(request: pytest.FixtureRequest, ops_test: OpsTest):
model = "main"
charm_names = ("k8s", "k8s-worker")
charms = [Charm(ops_test, Path("charms") / p) for p in charm_names]
charm_files = await asyncio.gather(*[charm.resolve(request.config.option.charm_files) for charm in charms])
charm_files = await asyncio.gather(
*[charm.resolve(request.config.option.charm_files) for charm in charms]
)
deployments = [
CharmDeploymentArgs(
entity_url=str(path),
Expand Down

0 comments on commit 564529e

Please sign in to comment.