Skip to content

Commit

Permalink
Mock get_platform / add CHARMHELPERS_IN_UNITTEST
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ajkavanagh committed Oct 23, 2023
1 parent fb4c776 commit 9333fea
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
13 changes: 13 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
=======

Expand Down
9 changes: 8 additions & 1 deletion charmhelpers/osplatform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"

0 comments on commit 9333fea

Please sign in to comment.