X-Git-Url: https://osm.etsi.org/gitweb/?p=osm%2FN2VC.git;a=blobdiff_plain;f=modules%2Flibjuju%2Ftests%2Fbase.py;fp=modules%2Flibjuju%2Ftests%2Fbase.py;h=e1ec45238228e284ba41294b6f08161d89cae0f9;hp=0000000000000000000000000000000000000000;hb=68858c1915122c2dbc8999a5cd3229694abf5f3a;hpb=032a71b2a6692b8b4e30f629a1f906d246f06736 diff --git a/modules/libjuju/tests/base.py b/modules/libjuju/tests/base.py new file mode 100644 index 0000000..e1ec452 --- /dev/null +++ b/modules/libjuju/tests/base.py @@ -0,0 +1,67 @@ +import mock +import subprocess +import uuid + +import pytest + +from juju.controller import Controller +from juju.client.connection import JujuData + + +def is_bootstrapped(): + result = subprocess.run(['juju', 'switch'], stdout=subprocess.PIPE) + return ( + result.returncode == 0 and + len(result.stdout.decode().strip()) > 0) + +bootstrapped = pytest.mark.skipif( + not is_bootstrapped(), + reason='bootstrapped Juju environment required') + + +class CleanController(): + def __init__(self): + self.controller = None + + async def __aenter__(self): + self.controller = Controller() + await self.controller.connect_current() + return self.controller + + async def __aexit__(self, exc_type, exc, tb): + await self.controller.disconnect() + + +class CleanModel(): + def __init__(self): + self.controller = None + self.model = None + + async def __aenter__(self): + self.controller = Controller() + await self.controller.connect_current() + + model_name = 'model-{}'.format(uuid.uuid4()) + self.model = await self.controller.add_model(model_name) + + # save the model UUID in case test closes model + self.model_uuid = self.model.info.uuid + + # Ensure that we connect to the new model by default. This also + # prevents failures if test was started with no current model. + self._patch_cm = mock.patch.object(JujuData, 'current_model', + return_value=model_name) + self._patch_cm.start() + + return self.model + + async def __aexit__(self, exc_type, exc, tb): + self._patch_cm.stop() + await self.model.disconnect() + await self.controller.destroy_model(self.model_uuid) + await self.controller.disconnect() + + +class AsyncMock(mock.MagicMock): + async def __call__(self, *args, **kwargs): + return super().__call__(*args, **kwargs)