Skip to content

Commit d7ff1ad

Browse files
committed
[vstest]: upgrade swss vs tests to python3
this pr mainly contains the changes made by 2to3 conversion tool
1 parent c05601c commit d7ff1ad

10 files changed

+62
-44
lines changed

tests/conftest.py

+35-21
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@
66
import redis
77
import docker
88
import pytest
9-
import commands
109
import tarfile
11-
import StringIO
10+
import io
1211
import subprocess
12+
import sys
13+
if sys.version_info < (3, 0):
14+
import commands
1315

1416
from datetime import datetime
1517
from swsscommon import swsscommon
@@ -19,7 +21,10 @@
1921
from dvslib import dvs_lag
2022

2123
def ensure_system(cmd):
22-
(rc, output) = commands.getstatusoutput(cmd)
24+
if sys.version_info < (3, 0):
25+
(rc, output) = commands.getstatusoutput(cmd)
26+
else:
27+
(rc, output) = subprocess.getstatusoutput(cmd)
2328
if rc:
2429
raise RuntimeError('Failed to run command: %s. rc=%d. output: %s' % (cmd, rc, output))
2530

@@ -136,17 +141,17 @@ def runcmd(self, cmd):
136141
try:
137142
out = subprocess.check_output("ip netns exec %s %s" % (self.nsname, cmd), stderr=subprocess.STDOUT, shell=True)
138143
except subprocess.CalledProcessError as e:
139-
print "------rc={} for cmd: {}------".format(e.returncode, e.cmd)
140-
print e.output.rstrip()
141-
print "------"
144+
print("------rc={} for cmd: {}------".format(e.returncode, e.cmd))
145+
print(e.output.rstrip())
146+
print("------")
142147
return e.returncode
143148
return 0
144149

145150
def runcmd_async(self, cmd):
146151
return subprocess.Popen("ip netns exec %s %s" % (self.nsname, cmd), shell=True)
147152

148153
def runcmd_output(self, cmd):
149-
return subprocess.check_output("ip netns exec %s %s" % (self.nsname, cmd), shell=True)
154+
return subprocess.check_output("ip netns exec %s %s" % (self.nsname, cmd), shell=True).decode('utf-8')
150155

151156
class DockerVirtualSwitch(object):
152157
APP_DB_ID = 0
@@ -187,7 +192,10 @@ def __init__(self, name=None, imgname=None, keeptb=False, fakeplatform=None):
187192
for ctn in self.client.containers.list():
188193
if ctn.name == name:
189194
self.ctn = ctn
190-
(status, output) = commands.getstatusoutput("docker inspect --format '{{.HostConfig.NetworkMode}}' %s" % name)
195+
if sys.version_info < (3, 0):
196+
(status, output) = commands.getstatusoutput("docker inspect --format '{{.HostConfig.NetworkMode}}' %s" % name)
197+
else:
198+
(status, output) = subprocess.getstatusoutput("docker inspect --format '{{.HostConfig.NetworkMode}}' %s" % name)
191199
ctn_sw_id = output.split(':')[1]
192200
self.cleanup = False
193201
if self.ctn == None:
@@ -198,7 +206,10 @@ def __init__(self, name=None, imgname=None, keeptb=False, fakeplatform=None):
198206
if ctn.id == ctn_sw_id or ctn.name == ctn_sw_id:
199207
ctn_sw_name = ctn.name
200208

201-
(status, output) = commands.getstatusoutput("docker inspect --format '{{.State.Pid}}' %s" % ctn_sw_name)
209+
if sys.version_info < (3, 0):
210+
(status, output) = commands.getstatusoutput("docker inspect --format '{{.State.Pid}}' %s" % ctn_sw_name)
211+
else:
212+
(status, output) = subprocess.getstatusoutput("docker inspect --format '{{.State.Pid}}' %s" % ctn_sw_name)
202213
self.ctn_sw_pid = int(output)
203214

204215
# create virtual servers
@@ -214,7 +225,10 @@ def __init__(self, name=None, imgname=None, keeptb=False, fakeplatform=None):
214225
else:
215226
self.ctn_sw = self.client.containers.run('debian:jessie', privileged=True, detach=True,
216227
command="bash", stdin_open=True)
217-
(status, output) = commands.getstatusoutput("docker inspect --format '{{.State.Pid}}' %s" % self.ctn_sw.name)
228+
if sys.version_info < (3, 0):
229+
(status, output) = commands.getstatusoutput("docker inspect --format '{{.State.Pid}}' %s" % self.ctn_sw.name)
230+
else:
231+
(status, output) = subprocess.getstatusoutput("docker inspect --format '{{.State.Pid}}' %s" % self.ctn_sw.name)
218232
self.ctn_sw_pid = int(output)
219233

220234
# create virtual server
@@ -284,7 +298,7 @@ def check_ready(self, timeout=30):
284298
# get process status
285299
res = self.ctn.exec_run("supervisorctl status")
286300
try:
287-
out = res.output
301+
out = res.output.decode('utf-8')
288302
except AttributeError:
289303
out = res
290304
for l in out.split('\n'):
@@ -322,7 +336,7 @@ def net_cleanup(self):
322336

323337
res = self.ctn.exec_run("ip link show")
324338
try:
325-
out = res.output
339+
out = res.output.decode('utf-8')
326340
except AttributeError:
327341
out = res
328342
for l in out.split('\n'):
@@ -335,7 +349,7 @@ def net_cleanup(self):
335349
m = re.compile("(eth|lo|Bridge|Ethernet)").match(pname)
336350
if not m:
337351
self.ctn.exec_run("ip link del {}".format(pname))
338-
print "remove extra link {}".format(pname)
352+
print("remove extra link {}".format(pname))
339353
return
340354

341355
def ctn_restart(self):
@@ -389,19 +403,19 @@ def runcmd(self, cmd):
389403
res = self.ctn.exec_run(cmd)
390404
try:
391405
exitcode = res.exit_code
392-
out = res.output
406+
out = res.output.decode('utf-8')
393407
except AttributeError:
394408
exitcode = 0
395409
out = res
396410
if exitcode != 0:
397-
print "-----rc={} for cmd {}-----".format(exitcode, cmd)
398-
print out.rstrip()
399-
print "-----"
411+
print("-----rc={} for cmd {}-----".format(exitcode, cmd))
412+
print(out.rstrip())
413+
print("-----")
400414

401415
return (exitcode, out)
402416

403417
def copy_file(self, path, filename):
404-
tarstr = StringIO.StringIO()
418+
tarstr = io.StringIO()
405419
tar = tarfile.open(fileobj=tarstr, mode="w")
406420
tar.add(filename, os.path.basename(filename))
407421
tar.close()
@@ -455,7 +469,7 @@ def CountSubscribedObjects(self, pubsub, ignore=None, timeout=10):
455469
while True and idle < timeout:
456470
message = pubsub.get_message()
457471
if message:
458-
print message
472+
print(message)
459473
if ignore:
460474
fds = message['channel'].split(':')
461475
if fds[2] in ignore:
@@ -482,7 +496,7 @@ def GetSubscribedAppDbObjects(self, pubsub, ignore=None, timeout=10):
482496
while True and idle < timeout:
483497
message = pubsub.get_message()
484498
if message:
485-
print message
499+
print(message)
486500
key = message['channel'].split(':', 1)[1]
487501
# In producer/consumer_state_table scenarios, every entry will
488502
# show up twice for every push/pop operation, so skip the second
@@ -524,7 +538,7 @@ def GetSubscribedAsicDbObjects(self, pubsub, ignore=None, timeout=10):
524538
while True and idle < timeout:
525539
message = pubsub.get_message()
526540
if message:
527-
print message
541+
print(message)
528542
key = message['channel'].split(':', 1)[1]
529543
if ignore:
530544
fds = message['channel'].split(':')

tests/dvslib/dvs_vlan.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from dvs_database import DVSDatabase
1+
from .dvs_database import DVSDatabase
22

33
class DVSVlan(object):
44
def __init__(self, adb, cdb, sdb, cntrdb, appdb):

tests/port_dpb.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def get_oid(self):
8787
return self._oid
8888

8989
def print_port(self):
90-
print "Port: %s Lanes: %s Speed: %d, Index: %d"%(self._name, self._lanes, self._speed, self._index)
90+
print("Port: %s Lanes: %s Speed: %d, Index: %d"%(self._name, self._lanes, self._speed, self._index))
9191

9292
def port_merge(self, child_ports):
9393
child_ports.sort(key=lambda x: x.get_port_num())
@@ -218,7 +218,7 @@ def verify_asic_db(self):
218218
(status, fvs) = self._asic_db_ptbl.get(self.get_oid())
219219
assert(status == True)
220220
fvs_dict = self.get_fvs_dict(fvs)
221-
if (fvs_dict.has_key("SAI_PORT_ATTR_HW_LANE_LIST")):
221+
if ("SAI_PORT_ATTR_HW_LANE_LIST" in fvs_dict):
222222
assert(fvs_dict['SAI_PORT_ATTR_HW_LANE_LIST'] == self.get_lanes_asic_db_str())
223223
assert(fvs_dict['SAI_PORT_ATTR_SPEED'] == str(self.get_speed()))
224224

tests/test_mirror_ipv6_separate.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ def test_CreateMirrorIngressAndEgress(self, dvs, testlog):
284284
self.create_acl_table(ingress_table, ports, "MIRROR")
285285

286286
# Check that the table has been created
287-
table_ids = asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE",
287+
table_ids = asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE",
288288
len(asic_db.default_acl_tables) + 1)
289289
table_entries = [oid for oid in table_ids if oid not in asic_db.default_acl_tables]
290290
original_entry = table_entries[0]
@@ -293,7 +293,7 @@ def test_CreateMirrorIngressAndEgress(self, dvs, testlog):
293293
self.create_acl_table(duplicate_ingress_table, ports, "MIRROR")
294294

295295
# Check that there is still only one table, and that it is the original table
296-
table_ids = asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE",
296+
table_ids = asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE",
297297
len(asic_db.default_acl_tables) + 1)
298298
table_entries = [oid for oid in table_ids if oid not in asic_db.default_acl_tables]
299299
assert table_entries[0] == original_entry
@@ -305,14 +305,14 @@ def test_CreateMirrorIngressAndEgress(self, dvs, testlog):
305305
self.create_acl_table(egress_table, ports, "MIRROR", "egress")
306306

307307
# Check that there are two tables
308-
asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE",
308+
asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE",
309309
len(asic_db.default_acl_tables) + 2)
310310

311311
# Attempt to create another MIRROR table with egress ACLs
312312
self.create_acl_table(duplicate_egress_table, ports, "MIRROR", "egress")
313313

314314
# Check that there are still only two tables
315-
asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE",
315+
asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE",
316316
len(asic_db.default_acl_tables) + 2)
317317

318318
self.remove_acl_table(ingress_table)

tests/test_nhg.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import re
3+
import sys
34
import time
45
import json
56
import pytest
@@ -206,7 +207,7 @@ def asic_route_nhg_fvs(k):
206207
if not fvs:
207208
return None
208209

209-
print fvs
210+
print(fvs)
210211
nhgid = fvs.get("SAI_ROUTE_ENTRY_ATTR_NEXT_HOP_ID")
211212
if nhgid is None:
212213
return None
@@ -216,7 +217,10 @@ def asic_route_nhg_fvs(k):
216217

217218
MAX_ECMP_COUNT = 512
218219
MAX_PORT_COUNT = 10
219-
IP_INTEGER_BASE = int(ipaddress.IPv4Address(unicode("2.2.2.0")))
220+
if sys.version_info < (3, 0):
221+
IP_INTEGER_BASE = int(ipaddress.IPv4Address(unicode("2.2.2.0")))
222+
else:
223+
IP_INTEGER_BASE = int(ipaddress.IPv4Address(str("2.2.2.0")))
220224

221225
config_db = dvs.get_config_db()
222226
fvs = {"NULL": "NULL"}

tests/test_port_mac_learn.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def check_learn_mode_in_asicdb(self, interface_oid, learn_mode):
6060
return True
6161
else:
6262
return False
63-
63+
6464
def test_PortMacLearnMode(self, dvs, testlog):
6565
self.setup_db(dvs)
6666

@@ -126,7 +126,7 @@ def test_PortchannelMacLearnMode(self, dvs, testlog):
126126
("mtu", "9100")])
127127
tbl.set("PortChannel001", fvs)
128128
time.sleep(1)
129-
129+
130130
# create vlan
131131
tbl = swsscommon.Table(self.cdb, "VLAN")
132132
fvs = swsscommon.FieldValuePairs([("vlanid", "3")])

tests/test_setro.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def test_SetReadOnlyAttribute(self, dvs, testlog):
3636

3737
key = "SAI_OBJECT_TYPE_SWITCH:" + swRid
3838

39-
print key
39+
print(key)
4040

4141
ntf.send("set_ro", key, fvp)
4242

tests/test_tunnel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def remove_and_test_tunnel(self, db, asicdb, tunnel_name):
134134
status, fvs = tunnel_table.get(tunnel_sai_obj)
135135

136136
# get overlay loopback interface oid to check if it is deleted with the tunnel
137-
overlay_infs_id = {f:v for f,v in fvs}["SAI_TUNNEL_ATTR_OVERLAY_INTERFACE"]
137+
overlay_infs_id = {f:v for f,v in fvs}["SAI_TUNNEL_ATTR_OVERLAY_INTERFACE"]
138138

139139
ps = swsscommon.ProducerStateTable(db, self.APP_TUNNEL_DECAP_TABLE_NAME)
140140
ps.set(tunnel_name, create_fvs(), 'DEL')

tests/test_vrf.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def is_vrf_attributes_correct(self, db, table, key, expected_attributes):
4444
assert status, "Got an error when get a key"
4545

4646
# filter the fake 'NULL' attribute out
47-
fvs = filter(lambda x : x != ('NULL', 'NULL'), fvs)
47+
fvs = [x for x in fvs if x != ('NULL', 'NULL')]
4848

4949
attr_keys = {entry[0] for entry in fvs}
5050
assert attr_keys == set(expected_attributes.keys())
@@ -78,7 +78,7 @@ def vrf_create(self, dvs, vrf_name, attributes, expected_attributes):
7878
assert len(intf_entries) == 1
7979
assert intf_entries[0] == vrf_name
8080
exp_attr = {}
81-
for an in xrange(len(attributes)):
81+
for an in range(len(attributes)):
8282
exp_attr[attributes[an][0]] = attributes[an][1]
8383
self.is_vrf_attributes_correct(self.pdb, "VRF_TABLE", vrf_name, exp_attr)
8484

@@ -142,7 +142,7 @@ def boolean_gen(self):
142142

143143

144144
def mac_addr_gen(self):
145-
ns = [random.randint(0, 255) for _ in xrange(6)]
145+
ns = [random.randint(0, 255) for _ in range(6)]
146146
ns[0] &= 0xfe
147147
mac = ':'.join("%02x" % n for n in ns)
148148
return mac, mac.upper()
@@ -177,13 +177,13 @@ def test_VRFMgr_Comprehensive(self, dvs, testlog):
177177

178178
random.seed(int(time.clock()))
179179

180-
for n in xrange(2**len(attributes)):
180+
for n in range(2**len(attributes)):
181181
# generate testcases for all combinations of attributes
182182
req_attr = []
183183
exp_attr = {}
184184
vrf_name = "Vrf_%d" % n
185185
bmask = 0x1
186-
for an in xrange(len(attributes)):
186+
for an in range(len(attributes)):
187187
if (bmask & n) > 0:
188188
req_res, exp_res = attributes[an][2]()
189189
req_attr.append((attributes[an][0], req_res))

tests/test_warm_reboot.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -661,15 +661,15 @@ def test_swss_neighbor_syncup(self, dvs, testlog):
661661
# use "change" if neighbor is in FAILED state
662662
for i in range(0, len(ips), 2):
663663
(rc, output) = dvs.runcmd(['sh', '-c', "ip -4 neigh | grep {}".format(ips[i])])
664-
print output
664+
print(output)
665665
if output:
666666
dvs.runcmd("ip neigh change {} dev {} lladdr {} nud reachable".format(ips[i], intfs[i/2], macs[i]))
667667
else:
668668
dvs.runcmd("ip neigh add {} dev {} lladdr {} nud reachable".format(ips[i], intfs[i/2], macs[i]))
669669

670670
for i in range(0, len(v6ips), 2):
671671
(rc, output) = dvs.runcmd(['sh', '-c', "ip -6 neigh | grep {}".format(v6ips[i])])
672-
print output
672+
print(output)
673673
if output:
674674
dvs.runcmd("ip -6 neigh change {} dev {} lladdr {} nud reachable".format(v6ips[i], intfs[i/2], macs[i]))
675675
else:
@@ -995,9 +995,9 @@ def test_swss_port_state_syncup(self, dvs, testlog):
995995
# appDB port table operation
996996
orchStateCount = 0
997997
for message in pubsubMessages:
998-
print message
998+
print(message)
999999
key = message['channel'].split(':', 1)[1]
1000-
print key
1000+
print(key)
10011001
if message['data'] != 'hset' and message['data'] != 'del':
10021002
continue
10031003
if key.find(swsscommon.APP_PORT_TABLE_NAME)==0:
@@ -2040,7 +2040,7 @@ def test_system_warmreboot_neighbor_syncup(self, dvs, testlog):
20402040
# waited 10 above already
20412041
i = 10
20422042
while (not kernel_restore_neighs_done(restoretbl)):
2043-
print "Waiting for kernel neighbors restore process done: {} seconds".format(i)
2043+
print("Waiting for kernel neighbors restore process done: {} seconds".format(i))
20442044
time.sleep(10)
20452045
i += 10
20462046

0 commit comments

Comments
 (0)