network/tests/unit/test_nm_provider.py
Rich Megginson 88a2609327 test: ensure role gathers the facts it uses by having test clear_facts before include_role
The role gathers the facts it uses.  For example, if the user uses
`ANSIBLE_GATHERING=explicit`, the role uses the `setup` module with the
facts and subsets it requires.

This change allows us to test this.  Before every role invocation, the test
will use `meta: clear_facts` so that the role starts with no facts.

Create a task file tests/tasks/run_role_with_clear_facts.yml to do the tasks
to clear the facts and run the role.  Note that this means we don't need to
use `gather_facts` for the tests.

Some vars defined using `ansible_facts` have been changed to be defined with
`set_fact` instead.  This is because of the fact that `vars` are lazily
evaluated - the var might be referenced when the facts have been cleared, and
will issue an error like `ansible_facts["distribution"] is undefined`.  This is
typically done for blocks that have a `when` condition that uses `ansible_facts`
and the block has a role invocation using run_role_with_clear_facts.yml
These have been rewritten to define the `when` condition using `set_fact`.  This
is because the `when` condition is evaluated every time a task is invoked in the
block, and if the facts are cleared, this will raise an undefined variable error.

Signed-off-by: Rich Megginson <rmeggins@redhat.com>
2026-03-19 10:47:09 -06:00

39 lines
1.4 KiB
Python

#!/usr/bin/env python
"""Tests for network_connections Ansible module"""
# SPDX-License-Identifier: BSD-3-Clause
import os
import sys
TESTS_BASEDIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(1, os.path.join(TESTS_BASEDIR, "../..", "library"))
sys.path.insert(1, os.path.join(TESTS_BASEDIR, "../..", "module_utils"))
try:
from unittest import mock
except ImportError: # py2
import mock
sys.modules["ansible"] = mock.Mock()
sys.modules["ansible.module_utils.basic"] = mock.Mock()
sys.modules["ansible.module_utils"] = mock.Mock()
sys.modules["ansible.module_utils.network_lsr"] = __import__("network_lsr")
with mock.patch.dict("sys.modules", {"gi": mock.Mock(), "gi.repository": mock.Mock()}):
# pylint: disable=import-error, wrong-import-position
from network_lsr import nm_provider
def test_get_nm_ethtool_feature():
"""Test get_nm_ethtool_feature()"""
with mock.patch.object(nm_provider.Util, "NM") as nm_mock:
nm_feature = nm_provider.get_nm_ethtool_feature("esp_hw_offload")
assert nm_feature == nm_mock.return_value.ETHTOOL_OPTNAME_FEATURE_ESP_HW_OFFLOAD
def test_get_nm_ethtool_coalesce():
"""Test get_nm_ethtool_coalesce()"""
with mock.patch.object(nm_provider.Util, "NM") as nm_mock:
nm_feature = nm_provider.get_nm_ethtool_coalesce("rx_frames")
assert nm_feature == nm_mock.return_value.ETHTOOL_OPTNAME_COALESCE_RX_FRAMES