Skip to content

Commit 77e455d

Browse files
authored
Deprecate ansible_host.py (#1658)
* Deprecate ansible_host.py The functionalities in ansible_host.py , including the AnsibleHost class and some exceptions, have been implemented in the common library. This file can be deprecated in case people new to sonic-mgmt waste time on old libraries. Changes: 1. Remove ansible_host.py 2. Replace all the AnsibleHost related calls with more appropriate fixtures or functions. 3. Remove duplicated localhost fixture definition Signed-off-by: Xin Wang <[email protected]>
1 parent c31a5fb commit 77e455d

23 files changed

+326
-402
lines changed

tests/ansible_host.py

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

tests/bgp/test_bgp_fact.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from ansible_host import AnsibleHost
21

32
def test_bgp_facts(duthost):
43
"""compare the bgp facts between observed states and target state"""

tests/common/devices.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def run_module(module_args, complex_args):
6060

6161
res = self.module(*module_args, **complex_args)[self.hostname]
6262
if res.is_failed and not module_ignore_errors:
63-
raise RunAnsibleModuleFail("run module {} failed, errmsg {}".format(self.module_name, res))
63+
raise RunAnsibleModuleFail("run module {} failed".format(self.module_name), res)
6464

6565
return res
6666

tests/common/errors.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,26 @@
11
"""
22
Customize exceptions
33
"""
4+
from ansible.plugins.loader import callback_loader
5+
from ansible.errors import AnsibleError
6+
7+
48
class UnsupportedAnsibleModule(Exception):
59
pass
610

7-
class RunAnsibleModuleFail(Exception):
8-
pass
11+
12+
def dump_ansible_results(results, stdout_callback='yaml'):
13+
cb = callback_loader.get(stdout_callback)
14+
return cb._dump_results(results) if cb else results
15+
16+
17+
class RunAnsibleModuleFail(AnsibleError):
18+
19+
"""Sub-class AnsibleError when module exceptions occur."""
20+
21+
def __init__(self, msg, results=None):
22+
super(RunAnsibleModuleFail, self).__init__(msg)
23+
self.results = results
24+
25+
def __str__(self):
26+
return "{}\nAnsible Results => {}".format(self.message, dump_ansible_results(self.results))

tests/common/plugins/ansible_fixtures.py

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,3 @@ def ansible_adhoc(request):
1515
def init_host_mgr(**kwargs):
1616
return plugin.initialize(request.config, request, **kwargs)
1717
return init_host_mgr
18-
19-
20-
# Same as for ansible_adhoc, let's have localhost fixture with session scope
21-
# as it feels that during session run the localhost object should persist unchanged.
22-
# Also, we have autouse=True here to force pytest to evaluate localhost fixture to overcome
23-
# some hidden dependency between localhost and ansible_adhoc (even with default scope) (FIXME)
24-
@pytest.fixture(scope='session', autouse=True)
25-
def localhost(request):
26-
"""Return a host manager representing localhost."""
27-
# NOTE: Do not use ansible_adhoc as a dependent fixture since that will assert specific command-line parameters have
28-
# been supplied. In the case of localhost, the parameters are provided as kwargs below.
29-
plugin = request.config.pluginmanager.getplugin("ansible")
30-
return plugin.initialize(request.config, request, inventory='localhost,', connection='local',
31-
host_pattern='localhost').localhost

tests/common/plugins/ptfadapter/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import pytest
44

55
from ptfadapter import PtfTestAdapter
6-
from ansible_host import AnsibleHost
76

87
DEFAULT_PTF_NN_PORT = 10900
98
DEFAULT_DEVICE_NUM = 0

tests/common/reboot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import time
22
import logging
33
from multiprocessing.pool import ThreadPool, TimeoutError
4-
from ansible_host import AnsibleModuleException
4+
from errors import RunAnsibleModuleFail
55

66
logger = logging.getLogger(__name__)
77

@@ -148,8 +148,8 @@ def execute_reboot_helper():
148148
while finalizer_state == 'activating':
149149
try:
150150
res = duthost.command('systemctl is-active warmboot-finalizer.service',module_ignore_errors=True)
151-
except AnsibleModuleException as err:
152-
res = err.module_result
151+
except RunAnsibleModuleFail as err:
152+
res = err.results
153153

154154
finalizer_state = res['stdout'].strip()
155155
logger.info('warmboot finalizer service state {}'.format(finalizer_state))

tests/conftest.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,14 @@
1111
import tarfile
1212
import logging
1313
import time
14+
import string
15+
import re
1416

1517
import pytest
1618
import csv
1719
import yaml
1820
import ipaddr as ipaddress
1921

20-
from ansible_host import AnsibleHost
2122
from collections import defaultdict
2223
from common.fixtures.conn_graph_facts import conn_graph_facts
2324
from common.devices import SonicHost, Localhost, PTFHost, EosHost, FanoutHost
@@ -173,6 +174,7 @@ def testbed_devices(ansible_adhoc, testbed, duthost):
173174

174175
return devices
175176

177+
176178
def disable_ssh_timout(dut):
177179
'''
178180
@summary disable ssh session on target dut
@@ -225,12 +227,20 @@ def duthost(ansible_adhoc, testbed, request):
225227

226228

227229
@pytest.fixture(scope="module")
228-
def ptfhost(testbed_devices):
229-
"""
230-
Shortcut fixture for getting PTF host
231-
"""
230+
def localhost(ansible_adhoc):
231+
return Localhost(ansible_adhoc)
232+
233+
234+
@pytest.fixture(scope="module")
235+
def ptfhost(ansible_adhoc, testbed):
236+
if "ptf" in testbed:
237+
return PTFHost(ansible_adhoc, testbed["ptf"])
238+
else:
239+
# when no ptf defined in testbed.csv
240+
# try to parse it from inventory
241+
ptf_host = duthost.host.options["inventory_manager"].get_host(duthost.hostname).get_vars()["ptf_host"]
242+
return PTFHost(ansible_adhoc, ptf_host)
232243

233-
return testbed_devices["ptf"]
234244

235245
@pytest.fixture(scope="module")
236246
def nbrhosts(ansible_adhoc, testbed, creds):

tests/fdb/test_fdb.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from ansible_host import AnsibleHost
21

32
import pytest
43
import ptf.testutils as testutils
@@ -168,7 +167,7 @@ def test_fdb(ansible_adhoc, testbed, ptfadapter, duthost, ptfhost, pkt_type):
168167
host_facts = duthost.setup()['ansible_facts']
169168
conf_facts = duthost.config_facts(host=duthost.hostname, source="persistent")['ansible_facts']
170169

171-
# remove existing IPs from PTF host
170+
# remove existing IPs from PTF host
172171
ptfhost.script('scripts/remove_ip.sh')
173172
# set unique MACs to PTF interfaces
174173
ptfhost.script('scripts/change_mac.sh')

tests/lldp/test_lldp.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from ansible_host import AnsibleHost
21
import logging
32
import pytest
43

@@ -32,15 +31,14 @@ def test_lldp(duthost, localhost, collect_techsupport):
3231
assert v['port']['ifname'] == mg_facts['minigraph_neighbors'][k]['port']
3332

3433

35-
def test_lldp_neighbor(duthost, localhost, ansible_adhoc, eos, collect_techsupport):
34+
def test_lldp_neighbor(duthost, localhost, eos, collect_techsupport):
3635
""" verify LLDP information on neighbors """
3736

3837
mg_facts = duthost.minigraph_facts(host=duthost.hostname)['ansible_facts']
3938
res = duthost.shell("docker exec -i lldp lldpcli show chassis | grep \"SysDescr:\" | sed -e 's/^\\s*SysDescr:\\s*//g'")
4039
dut_system_description = res['stdout']
4140
lldp_facts = duthost.lldp()['ansible_facts']
4241
host_facts = duthost.setup()['ansible_facts']
43-
lhost = AnsibleHost(ansible_adhoc, 'localhost', True)
4442

4543
config_facts = duthost.config_facts(host=duthost.hostname, source="running")['ansible_facts']
4644
nei_meta = config_facts.get('DEVICE_NEIGHBOR_METADATA', {})
@@ -56,7 +54,7 @@ def test_lldp_neighbor(duthost, localhost, ansible_adhoc, eos, collect_techsuppo
5654
logger.info("Neighbor device {} does not sent management IP via lldp".format(v['chassis']['name']))
5755
hostip = nei_meta[v['chassis']['name']]['mgmt_addr']
5856

59-
nei_lldp_facts = lhost.lldp_facts(host=hostip, version='v2c', community=eos['snmp_rocommunity'])['ansible_facts']
57+
nei_lldp_facts = localhost.lldp_facts(host=hostip, version='v2c', community=eos['snmp_rocommunity'])['ansible_facts']
6058
print nei_lldp_facts
6159
neighbor_interface = v['port']['ifname']
6260
# Verify the published DUT system name field is correct

0 commit comments

Comments
 (0)