Skip to content

Commit b815c52

Browse files
committed
Rewrite load test data function in unit tests
Helper to load test data for unit tests. This function supports loading data files relative to the test file. It works even if the test file is in a subfolder, allowing your test data to be organized in corresponding subfolders alongside the tests.
1 parent eb5f62f commit b815c52

File tree

4 files changed

+76
-35
lines changed

4 files changed

+76
-35
lines changed

tests/test_data.py

Lines changed: 0 additions & 21 deletions
This file was deleted.

tests/unit/helpers/load_data.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# -*- coding: utf-8 -*-
2+
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3+
4+
"""
5+
Helper functions for loading structured test data for unit tests.
6+
7+
Provides functions to locate JSON test_data files based on the
8+
location of the test script in tests/unit/ and to return the data
9+
as lists of tuples for use in pytest parameterization.
10+
"""
11+
12+
import json
13+
from pathlib import Path
14+
15+
CURRENT_FILE = Path(__file__).resolve()
16+
UNIT_TESTS_DIR = CURRENT_FILE.parents[1] # project_root/tests/unit
17+
PROJECT_ROOT = CURRENT_FILE.parents[3] # project_root
18+
19+
REL_UNITS_TO_ROOT = UNIT_TESTS_DIR.relative_to(PROJECT_ROOT) # tests/unit
20+
21+
22+
def load_test_data(script_dir: Path, data_path: str, use_subfold: bool = True) -> list:
23+
"""
24+
Load structured test data for a test file.
25+
26+
The directory structure is derived from:
27+
tests/unit/<test_type>/<optional_subfolder>/...
28+
29+
Args:
30+
test_script_dir: Directory containing the test file.
31+
data_path: Name of the test_data folder to load.
32+
use_sub: Dive into same subfolders as script_dir in test_data
33+
34+
Returns:
35+
List of tuples extracted from the JSON file.
36+
"""
37+
try:
38+
# Normal expected case: script_dir lives under tests/unit
39+
relative = script_dir.relative_to(UNIT_TESTS_DIR).parts
40+
except ValueError:
41+
# Fallback for tox/CI environments where paths differ
42+
# Find the path fragment "tests/unit" and slice from there
43+
parts = list(script_dir.parts)
44+
try:
45+
idx = parts.index("unit") # project/tests/unit/...
46+
relative = parts[idx + 1 :]
47+
except ValueError:
48+
# Last-resort fallback: treat as having no subfolder
49+
relative = ()
50+
51+
test_type = relative[0]
52+
subfolder = Path(*relative[1:]) if len(relative) > 1 else None
53+
54+
# Build data.json path
55+
base = REL_UNITS_TO_ROOT / test_type / "test_data"
56+
if subfolder and use_subfold:
57+
base /= subfolder
58+
59+
data_file = base / data_path / "data.json"
60+
61+
with data_file.open("r", encoding="utf-8") as f:
62+
data = json.load(f)
63+
64+
return [tuple(item.values()) for item in data]

tests/unit/inventory/test_nb_inventory.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
__metaclass__ = type
88

9-
import os
109
from functools import partial
10+
from pathlib import Path
1111
from unittest.mock import Mock, call, mock_open, patch
1212

1313
import pytest
@@ -17,7 +17,9 @@
1717
from ansible_collections.netbox.netbox.plugins.inventory.nb_inventory import (
1818
InventoryModule,
1919
)
20-
from ansible_collections.netbox.netbox.tests.test_data import load_test_data
20+
from ansible_collections.netbox.netbox.tests.unit.helpers.load_data import (
21+
load_test_data,
22+
)
2123

2224
except ImportError:
2325
import sys
@@ -27,15 +29,12 @@
2729

2830
sys.path.append("plugins/inventory")
2931
sys.path.append("tests")
30-
from test_data import load_test_data
32+
from tests.unit.helpers.load_data import load_test_data
3133

32-
load_relative_test_data = partial(
33-
load_test_data, os.path.dirname(os.path.abspath(__file__))
34-
)
34+
load_relative_test_data = partial(load_test_data, Path(__file__).resolve().parent)
3535

3636

3737
class MockInventory:
38-
3938
def __init__(self):
4039
self.variables = {}
4140

tests/unit/module_utils/test_netbox_base_class.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,9 @@
88
__metaclass__ = type
99

1010
import re
11-
import os
1211
from functools import partial
12+
from pathlib import Path
1313
from unittest.mock import MagicMock
14-
1514
import pytest
1615

1716
try:
@@ -21,7 +20,9 @@
2120
from ansible_collections.netbox.netbox.plugins.module_utils.netbox_utils import (
2221
NetboxModule,
2322
)
24-
from ansible_collections.netbox.netbox.tests.test_data import load_test_data
23+
from ansible_collections.netbox.netbox.tests.unit.helpers.load_data import (
24+
load_test_data,
25+
)
2526

2627
MOCKER_PATCH_PATH = "ansible_collections.netbox.netbox.plugins.module_utils.netbox_utils.NetboxModule"
2728
except ImportError:
@@ -34,13 +35,11 @@
3435
sys.path.append("tests")
3536
from netbox_dcim import NB_DEVICES
3637
from netbox_utils import NetboxModule
37-
from test_data import load_test_data
38+
from tests.unit.helpers.load_data import load_test_data
3839

3940
MOCKER_PATCH_PATH = "netbox_utils.NetboxModule"
4041

41-
load_relative_test_data = partial(
42-
load_test_data, os.path.dirname(os.path.abspath(__file__))
43-
)
42+
load_relative_test_data = partial(load_test_data, Path(__file__).resolve().parent)
4443

4544

4645
@pytest.fixture

0 commit comments

Comments
 (0)