Add helper module for testing operator charms.

In our testing we often work around the fact that the operator
harness does not provide a `network_get()` by customizing the
_TestingModelBackend class which is a bit fragile. This helper module
implements a patch decorator for `network_get()` instead.

Change-Id: Iafabf81ecf3ea719c37144a24915a92643b98d7f
This commit is contained in:
Peter Sabaini 2022-10-19 11:10:49 +02:00
parent 66ad9918f6
commit 47f79f3b72
2 changed files with 43 additions and 0 deletions

32
ops_openstack/testing.py Normal file
View File

@ -0,0 +1,32 @@
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
"""Helpers for testing operator charms."""
import typing
from unittest import mock
def patch_network_get(network_data=None) -> typing.Callable:
if network_data is None:
network_data = {
"bind-addresses": [
{
"addresses": [{"value": "10.0.0.10"}],
}
],
}
def network_get(*args, **kwargs) -> dict:
"""Patch network_get.
Creates a patch for the not-yet-implemented testing backend needed
for `bind_address`.
This patch decorator can be used for cases such as:
self.model.get_binding(event.relation).network.bind_address
"""
return network_data
return mock.patch(
"ops.testing._TestingModelBackend.network_get", network_get
)

View File

@ -27,6 +27,7 @@ from ops.model import (
)
import ops_openstack.core
from ops_openstack import testing
class OpenStackTestPlugin1(ops_openstack.core.OSBaseCharm):
@ -368,3 +369,13 @@ class TestOSBaseCharm(CharmTestCase):
self.harness.update_config({'source': 'value'})
self.assertTrue(
isinstance(self.harness.charm.unit.status, ActiveStatus))
class TestTesting(unittest.TestCase):
def test_patch_network_get(self):
network_data = {
'bind-addresses': [{'addresses': [{'value': '1.1.1.1'}]}],
}
with testing.patch_network_get(network_data) as p:
self.assertDictEqual(p(), network_data)