Skip to content

Commit

Permalink
add unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
MiaAltieri committed Feb 19, 2024
1 parent 0670225 commit 5a752ee
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 21 deletions.
2 changes: 1 addition & 1 deletion lib/charms/mongos/v0/mongos_client_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def _on_relation_changed(self, event) -> None:

self.charm.set_external_connectivity(external_connectivity)
if external_connectivity:
self.charm.open_mongos_port
self.charm.open_mongos_port()

def remove_connection_info(self) -> None:
"""Sends the URI to the related parent application"""
Expand Down
26 changes: 8 additions & 18 deletions src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from pathlib import Path

from typing import Set, List, Optional, Dict
from exceptions import ApplicationHostNotFoundError

from charms.mongodb.v0.mongodb_secrets import SecretCache
from charms.mongos.v0.mongos_client_interface import MongosProvider
Expand All @@ -25,7 +24,7 @@
from config import Config

import ops
from ops.model import BlockedStatus, MaintenanceStatus, WaitingStatus, Relation, Unit
from ops.model import BlockedStatus, MaintenanceStatus, WaitingStatus, Relation
from ops.charm import InstallEvent, StartEvent, RelationDepartedEvent

import logging
Expand Down Expand Up @@ -355,7 +354,7 @@ def get_mongos_host(self) -> str:
the client wishes to connect to mongos (inside Juju or outside).
"""
if self.is_external_client:
return self._unit_ip(self.unit)
return self._unit_ip
else:
return Config.MONGOS_SOCKET_URI_FMT

Expand All @@ -364,21 +363,7 @@ def _generate_relation_departed_key(rel_id: int) -> str:
"""Generates the relation departed key for a specified relation id."""
return f"relation_{rel_id}_departed"

def _unit_ip(self, unit: Unit) -> str:
"""Returns the ip address of a given unit."""
# check if host is current host
if unit == self.unit:
return str(
self.model.get_binding(Config.Relations.PEERS).network.bind_address
)
# check if host is a peer
elif unit in self._peers.data:
return str(self._peers.data[unit].get("private-address"))
# raise exception if host not found
else:
raise ApplicationHostNotFoundError

def open_mongos_port():
def open_mongos_port(self):
try:
logger.debug("opening tcp port")
subprocess.check_call(["open-port", "{}/TCP".format(Config.MONGOS_PORT)])
Expand All @@ -389,6 +374,11 @@ def open_mongos_port():
# END: helper functions

# BEGIN: properties
@property
def _unit_ip(self) -> str:
"""Returns the ip address of the unit."""
return str(self.model.get_binding(Config.Relations.PEERS).network.bind_address)

@property
def is_external_client(self) -> Optional[str]:
"""Returns the database requested by the hosting application of the subordinate charm."""
Expand Down
35 changes: 34 additions & 1 deletion tests/unit/test_charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,21 @@
from parameterized import parameterized
from unittest import mock


from charms.operator_libs_linux.v1 import snap
from ops.model import BlockedStatus, WaitingStatus
from ops.testing import Harness

from charm import MongosOperatorCharm
from charm import MongosOperatorCharm, subprocess

from .helpers import patch_network_get

from charms.data_platform_libs.v0.data_interfaces import DatabaseRequiresEvents

CLUSTER_ALIAS = "cluster"
MONGOS_SOCKET_URI_FMT = (
"%2Fvar%2Fsnap%2Fcharmed-mongodb%2Fcommon%2Fvar%2Fmongodb-27018.sock"
)


class TestCharm(unittest.TestCase):
Expand Down Expand Up @@ -143,3 +147,32 @@ def test_status_shows_mongos_waiting(self):
self.harness.add_relation("cluster", "config-server")
self.harness.charm.on.update_status.emit()
self.assertTrue(isinstance(self.harness.charm.unit.status, WaitingStatus))

@patch_network_get(private_address="1.1.1.1")
def test_mongos_host(self):
"""TBD."""
self.harness.charm.app_peer_data["external-connectivity"] = json.dumps(False)
mongos_host = self.harness.charm.get_mongos_host()
self.assertEqual(mongos_host, MONGOS_SOCKET_URI_FMT)

self.harness.charm.app_peer_data["external-connectivity"] = json.dumps(True)
mongos_host = self.harness.charm.get_mongos_host()
self.assertEqual(mongos_host, "1.1.1.1")

@patch("subprocess.check_call")
def test_set_port(self, _call):
"""Test verifies operation of set port."""
self.harness.charm.open_mongos_port()

# Make sure the port is opened and the service is started
self.assertEqual(_call.call_args_list, [mock.call(["open-port", "27018/TCP"])])

@patch("subprocess.check_call")
def test_set_port_failure(self, _call):
"""Test verifies that we raise the correct errors when we fail to open a port."""
_call.side_effect = subprocess.CalledProcessError(
cmd="open-port 27018/TCP", returncode=1
)

with self.assertRaises(subprocess.CalledProcessError):
self.harness.charm.open_mongos_port()
4 changes: 3 additions & 1 deletion tests/unit/test_config_server_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ def setUp(self):
# related to duplicated events.
delattr(DatabaseRequiresEvents, f"{CLUSTER_ALIAS}_database_created")
delattr(DatabaseRequiresEvents, f"{CLUSTER_ALIAS}_endpoints_changed")
delattr(DatabaseRequiresEvents, f"{CLUSTER_ALIAS}_read_only_endpoints_changed")
delattr(
DatabaseRequiresEvents, f"{CLUSTER_ALIAS}_read_only_endpoints_changed"
)
except AttributeError:
# Ignore the events not existing before the first test.
pass
Expand Down

0 comments on commit 5a752ee

Please sign in to comment.