From 9333feae7610427832e15cb1d40b948a4a43aada Mon Sep 17 00:00:00 2001 From: Alex Kavanagh Date: Mon, 23 Oct 2023 12:41:31 +0100 Subject: [PATCH] Mock get_platform / add CHARMHELPERS_IN_UNITTEST Patch osplatform.get_platform() to return "ubuntu" if the environment variable CHARMHELPERS_IN_UNITTEST is set to something truthy. This is to enable unit testing in classic charms on NON ubuntu systems (e.g. Debian bookworm) where the function is often called via a decorator that is evaluated at module load time and thus is very, very tricky to mock out, as it is often 'hit' during the test discovery phase. --- README.rst | 13 +++++++++++++ charmhelpers/osplatform.py | 9 ++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 35c168ccb..8967d675b 100644 --- a/README.rst +++ b/README.rst @@ -36,6 +36,19 @@ Dev/Test See the HACKING.md file for information about testing and development. +Unit Test Mode +============== + +If the environment variable `CHARMHELPERS_IN_UNITTEST` is set to a truthy value +(e.g. 'on', 'true', 'anything') then then `osplatform.get_platform()` will +*always* return `ubuntu`. This prevents it from attempting to call into +platform libraries. This is needed as many charms try to call this function +during module loading (via function decorators) and this makes it very +difficult to mock out. + +Set this variable in the `tox.ini` of the charm using the `setenv` parameter in +a testenv. + License ======= diff --git a/charmhelpers/osplatform.py b/charmhelpers/osplatform.py index 1ace468f7..69cd3bd9a 100644 --- a/charmhelpers/osplatform.py +++ b/charmhelpers/osplatform.py @@ -2,7 +2,7 @@ import os -def get_platform(): +def _get_platform(): """Return the current OS platform. For example: if current os platform is Ubuntu then a string "ubuntu" @@ -47,3 +47,10 @@ def _get_platform_from_fs(): for k, v in content.items(): content[k] = v.strip('"') return content["NAME"] + + +## If the unit-test mode is set, the platform is always "ubuntu" +if not os.environ.get('CHARMHELPERS_IN_UNITTEST', False): + get_platform = _get_platform +else: + get_platform = lambda: "ubuntu"