Files
wif2ansible/test_inventory_keys.py
Kris Forbes 9e7e4054c4
All checks were successful
Build and Release / Build Windows Exe (push) Successful in 11s
Validate inventory hostnames via DNS resolution
2026-02-06 16:25:39 -05:00

60 lines
2.4 KiB
Python

import unittest
import unittest.mock
from wif2ansible.models import Server, Flow
from wif2ansible.inventory import generate_inventory
class TestInventoryKeys(unittest.TestCase):
@unittest.mock.patch('wif2ansible.inventory.is_valid_hostname')
def test_inventory_keys_are_hostnames(self, mock_resolves):
# Mock DNS to say server01 exists
mock_resolves.return_value = True
# Create a server with Ref, Hostname, IP
s1 = Server(reference="SERVER_REF_01", hostname="server01", ip_addresses=["192.168.1.10"], platform="windows")
# Create a flow matching this server
f1 = Flow(flow_id="1", source_ip="192.168.1.10", destination_ip="10.0.0.1", ports=[80])
servers = {"SERVER_REF_01": s1}
flows = [f1]
inventory = generate_inventory(servers, flows)
# Verify stricture
hosts = inventory['all']['hosts']
# Key should be HOSTNAME "server01" (prioritized over Ref)
self.assertIn("server01", hosts)
self.assertNotIn("192.168.1.10", hosts)
# Check variables
host_vars = hosts["server01"]
self.assertEqual(host_vars['ansible_host'], "192.168.1.10")
self.assertEqual(host_vars['ansible_connection'], "winrm")
@unittest.mock.patch('wif2ansible.inventory.is_valid_hostname')
def test_inventory_keys_resolution(self, mock_resolves):
# Setup mock: 'bad_name' -> False, 'good_name' -> True
def side_effect(name):
if name == "bad_name": return False
if name == "good_name": return True
return False
mock_resolves.side_effect = side_effect
# Server with a BAD hostname but a GOOD reference (simulated)
# Actually logic is candidates: [hostname, cleaned_ref, rev_dns]
# Let's say hostname is "bad_name" and cleaned ref is "good_name"
s1 = Server(reference="SRV01 good_name", hostname="bad_name", ip_addresses=["10.10.10.10"])
f1 = Flow(flow_id="1", source_ip="10.10.10.10", destination_ip="1.1.1.1", ports=[80])
inventory = generate_inventory({"k":s1}, [f1])
hosts = inventory['all']['hosts']
# It should have skipped "bad_name" and picked "good_name" (from cleaned ref)
self.assertIn("good_name", hosts)
self.assertNotIn("bad_name", hosts)
if __name__ == '__main__':
unittest.main()