Fix python code according to pylama errors

This commit is contained in:
Pieprzycki Piotr
2016-12-16 15:47:51 +01:00
parent 9b4d3aec64
commit 5afafa5522
4 changed files with 762 additions and 798 deletions

View File

@@ -13,19 +13,8 @@ deploy:
tags: true
branch: master
script:
- cd test/unit
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_arp_table
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_bgp_neighbors
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_environment
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_facts
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_interfaces
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_interfaces_counters
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_interfaces_ip
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_lldp_neighbors
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_lldp_neighbors_detail
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_mac_address_table
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_ntp_stats
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_get_snmp_information
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_ios_only_bgp_time_conversion
- nosetests -v TestIOSDriver:TestGetterIOSDriver.test_ping
- cd ../..
- py.test --cov-report= --cov=napalm_vyos test/
- pylama .
after_success:
- coveralls
- if [ $TRAVIS_TAG ]; then curl -X POST https://readthedocs.org/build/napalm; fi

View File

@@ -31,9 +31,8 @@ from netmiko import SCPConn
# NAPALM base
from napalm_base.base import NetworkDriver
from napalm_base.exceptions import ConnectionException, SessionLockedException, \
MergeConfigException, ReplaceConfigException,\
CommandErrorException
from napalm_base.exceptions import ConnectionException, \
MergeConfigException, ReplaceConfigException
class VyOSDriver(NetworkDriver):
@@ -58,7 +57,6 @@ class VyOSDriver(NetworkDriver):
self._old_config = None
self._ssh_usekeys = False
# Netmiko possible arguments
netmiko_argument_map = {
'port': None,
@@ -92,16 +90,17 @@ class VyOSDriver(NetworkDriver):
self.global_delay_factor = optional_args.get('global_delay_factor', 1)
self.port = optional_args.get('port', 22)
def open(self):
self._device = ConnectHandler(device_type='vyos',
host=self._hostname,
username=self._username,
password=self._password,
**self.netmiko_optional_args)
self._scp_client = SCPConn(self._device)
try:
self._scp_client = SCPConn(self._device)
except:
raise ConnectionException("Failed to open connection ")
def close(self):
self._device.disconnect()
@@ -114,7 +113,7 @@ class VyOSDriver(NetworkDriver):
support a replace using a configuration string.
"""
if filename is not None:
if os.path.exists(filename) == True:
if os.path.exists(filename) is True:
self._scp_client.scp_transfer_file(filename, self._DEST_FILENAME)
print self._device.send_command("cp "+self._BOOT_FILENAME+" "+self._BACKUP_FILENAME)
output_loadcmd = self._device.send_config_set(['load '+self._DEST_FILENAME])
@@ -124,12 +123,12 @@ class VyOSDriver(NetworkDriver):
if match_failed:
raise ReplaceConfigException("Failed replace config: "
+output_loadcmd)
+ output_loadcmd)
if not match_loaded:
if not match_notchanged:
raise ReplaceConfigException("Failed replace config: "
+output_loadcmd)
+ output_loadcmd)
else:
raise ReplaceConfigException("config file is not found")
@@ -141,9 +140,10 @@ class VyOSDriver(NetworkDriver):
Only configuration in set-format is supported with load_merge_candidate.
"""
if filename is not None:
if os.path.exists(filename) == True:
if os.path.exists(filename) is True:
with open(filename) as f:
print self._device.send_command("cp "+self._BOOT_FILENAME+" "+self._BACKUP_FILENAME)
print self._device.send_command("cp "+self._BOOT_FILENAME+" "
+ self._BACKUP_FILENAME)
self._new_config = f.read()
cfg = [x for x in self._new_config.split("\n") if x is not ""]
output_loadcmd = self._device.send_config_set(cfg)
@@ -152,8 +152,7 @@ class VyOSDriver(NetworkDriver):
if match_setfailed or match_delfailed:
raise MergeConfigException("Failed merge config: "
+output_loadcmd)
+ output_loadcmd)
else:
raise MergeConfigException("config file is not found")
elif config is not None:
@@ -161,7 +160,6 @@ class VyOSDriver(NetworkDriver):
else:
raise MergeConfigException("no configuration found")
def discard_config(self):
self._device.exit_config_mode()
@@ -183,20 +181,17 @@ class VyOSDriver(NetworkDriver):
def rollback(self, filename=None):
"""Rollback configuration to filename or to self.rollback_cfg file."""
if filename is None:
filename=self._BACKUP_FILENAME
filename = self._BACKUP_FILENAME
output_loadcmd = self._device.send_config_set(['load '+filename])
match = re.findall("Load complete.", output_loadcmd)
if not match:
raise ReplaceConfigException("Failed rollback config: "
+output_loadcmd)
+ output_loadcmd)
else:
self._device.send_config_set(['commit', 'save'])
def get_environment(self):
"""
'vmstat' output:
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
@@ -223,17 +218,17 @@ class VyOSDriver(NetworkDriver):
}
},
"temperature": {
"invalid" : {
"invalid": {
"temperature": 0.0,
"is_alert" : False,
"is_alert": False,
"is_critical": False
}
},
"power": {
"invalid" : {
"status" : True,
"invalid": {
"status": True,
"capacity": 0.0,
"output" : 0.0
"output": 0.0
}
},
"cpu": {
@@ -243,13 +238,12 @@ class VyOSDriver(NetworkDriver):
},
"memory": {
"available_ram": int(available_ram),
"used_ram" : int(used_ram)
"used_ram": int(used_ram)
}
}
return environment
def get_interfaces(self):
"""
"show interfaces" output example:
@@ -270,7 +264,8 @@ class VyOSDriver(NetworkDriver):
# 'match' example:
# [("br0", "u", "D"), ("eth0", "u", "u"), ("eth1", "u", "u")...]
iface_state = {iface_name:{"State": state, "Link": link} for iface_name, state, link in match}
iface_state = {iface_name: {"State": state, "Link": link} for iface_name,
state, link in match}
output_conf = self._device.send_command("show configuration")
@@ -284,7 +279,6 @@ class VyOSDriver(NetworkDriver):
ifaces_detail = config["interfaces"][iface_type]
for iface_name in ifaces_detail:
description = self._get_value("description", ifaces_detail[iface_name])
if description is None:
description = ""
@@ -302,19 +296,17 @@ class VyOSDriver(NetworkDriver):
iface_dict.update({
iface_name: {
"is_up" : bool(is_up),
"is_enabled" : bool(is_enabled),
"description" : unicode(description),
"last_flapped" : float(-1),
"speed" : int(speed),
"mac_address" : unicode(hw_id)
"is_up": bool(is_up),
"is_enabled": bool(is_enabled),
"description": unicode(description),
"last_flapped": float(-1),
"speed": int(speed),
"mac_address": unicode(hw_id)
}
})
return iface_dict
# for avoiding KeyError
@staticmethod
def _get_value(key, target_dict):
if key in target_dict:
@@ -322,7 +314,6 @@ class VyOSDriver(NetworkDriver):
else:
return None
def get_arp_table(self):
# 'age' is not implemented yet
@@ -349,9 +340,9 @@ class VyOSDriver(NetworkDriver):
# ["10.129.2.254", "ether", "00:50:56:97:af:b1", "C", "eth0"]
# [u'10.0.12.33', u'(incomplete)', u'eth1']
if "incomplete" in line[1]:
macaddr=unicode("00:00:00:00:00:00")
macaddr = unicode("00:00:00:00:00:00")
else:
macaddr=unicode(line[2])
macaddr = unicode(line[2])
arp_table.append(
{
@@ -364,7 +355,6 @@ class VyOSDriver(NetworkDriver):
return arp_table
def get_ntp_stats(self):
"""
'ntpq -np' output example
@@ -380,7 +370,8 @@ class VyOSDriver(NetworkDriver):
for ntp_info in output:
remote, refid, st, t, when, hostpoll, reachability, delay, offset, jitter = ntp_info.split()
remote, refid, st, t, when, hostpoll, reachability, delay, offset, \
jitter = ntp_info.split()
# 'remote' contains '*' if the machine synchronized with NTP server
synchronized = "*" in remote
@@ -391,22 +382,21 @@ class VyOSDriver(NetworkDriver):
when = when if when != '-' else 0
ntp_stats.append({
"remote" : unicode(ip),
"referenceid" : unicode(refid),
"remote": unicode(ip),
"referenceid": unicode(refid),
"synchronized": bool(synchronized),
"stratum" : int(st),
"type" : unicode(t),
"when" : unicode(when),
"hostpoll" : int(hostpoll),
"stratum": int(st),
"type": unicode(t),
"when": unicode(when),
"hostpoll": int(hostpoll),
"reachability": int(reachability),
"delay" : float(delay),
"offset" : float(offset),
"jitter" : float(jitter)
"delay": float(delay),
"offset": float(offset),
"jitter": float(jitter)
})
return ntp_stats
def get_ntp_peers(self):
output = self._device.send_command("ntpq -np").split("\n")[2:]
@@ -436,10 +426,10 @@ class VyOSDriver(NetworkDriver):
192.168.1.4 4 64522 0 0 0 0 0 never Active
"""
output = self._device.send_command("show ip bgp summary").split("\n")
match = re.search(".* router identifier (\d+\.\d+\.\d+\.\d+), local AS number (\d+)", output[0])
match = re.search(".* router identifier (\d+\.\d+\.\d+\.\d+), local AS number (\d+)",
output[0])
if not match:
return {}
router_id = unicode(match.group(1))
@@ -454,7 +444,7 @@ class VyOSDriver(NetworkDriver):
bgp_info = [i.strip() for i in output[6:-2] if i is not ""]
for i in bgp_info:
peer_id , bgp_version, remote_as, msg_rcvd, msg_sent, table_version, \
peer_id, bgp_version, remote_as, msg_rcvd, msg_sent, table_version, \
in_queue, out_queue, up_time, state_prefix = i.split()
is_enabled = "(Admin)" not in state_prefix
@@ -496,17 +486,17 @@ class VyOSDriver(NetworkDriver):
bgp_neighbor_data["global"]["peers"].setdefault(peer_id, {})
peer_dict = {
"description": unicode(""),
"is_enabled" : bool(is_enabled),
"local_as" : int(local_as),
"is_up" : bool(is_up),
"remote_id" : unicode(remote_rid),
"uptime" : int(self._bgp_time_conversion(up_time)),
"remote_as" : int(remote_as)
"is_enabled": bool(is_enabled),
"local_as": int(local_as),
"is_up": bool(is_up),
"remote_id": unicode(remote_rid),
"uptime": int(self._bgp_time_conversion(up_time)),
"remote_as": int(remote_as)
}
af_dict = dict()
af_dict[address_family] = {
"sent_prefixes" : int(-1),
"sent_prefixes": int(-1),
"accepted_prefixes": int(accepted_prefixes),
"received_prefixes": int(received_prefixes)
}
@@ -516,9 +506,8 @@ class VyOSDriver(NetworkDriver):
return bgp_neighbor_data
def _bgp_time_conversion(self, bgp_uptime):
uptime_letters = set(["y", "w", "h", "d"])
# uptime_letters = set(["y", "w", "h", "d"])
if "never" in bgp_uptime:
return -1
@@ -547,14 +536,14 @@ class VyOSDriver(NetworkDriver):
(minutes * self._MINUTE_SECONDS) + seconds)
return uptime
def get_interfaces_counters(self):
# 'rx_unicast_packet', 'rx_broadcast_packets', 'tx_unicast_packets',
# 'tx_multicast_packets' and 'tx_broadcast_packets' are not implemented yet
"""
'show interfaces detail' output example:
eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state
UP group default qlen 1000
link/ether 00:50:56:86:8c:26 brd ff:ff:ff:ff:ff:ff
~~~
RX: bytes packets errors dropped overrun mcast
@@ -563,12 +552,9 @@ class VyOSDriver(NetworkDriver):
32776498 279273 0 0 0 0
"""
output = self._device.send_command("show interfaces detail")
interfaces = re.findall("(\S+): <.*", output)
count = re.findall("(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+", output)
counters = dict()
j = 0
for i in count:
@@ -582,16 +568,16 @@ class VyOSDriver(NetworkDriver):
else:
counters.update({
interfaces[j / 2]: {
"tx_errors" : int(i[2]),
"tx_discards" : int(i[3]),
"tx_octets" : int(i[0]),
"tx_unicast_packets" : int(i[1]),
"tx_errors": int(i[2]),
"tx_discards": int(i[3]),
"tx_octets": int(i[0]),
"tx_unicast_packets": int(i[1]),
"tx_multicast_packets": int(-1),
"tx_broadcast_packets": int(-1),
"rx_errors" : int(rx_errors),
"rx_discards" : int(rx_discards),
"rx_octets" : int(rx_octets),
"rx_unicast_packets" : int(rx_unicast_packets),
"rx_errors": int(rx_errors),
"rx_discards": int(rx_discards),
"rx_octets": int(rx_octets),
"rx_unicast_packets": int(rx_unicast_packets),
"rx_multicast_packets": int(rx_multicast_packets),
"rx_broadcast_packets": int(rx_broadcast_packets)
}
@@ -600,7 +586,6 @@ class VyOSDriver(NetworkDriver):
return counters
def get_snmp_information(self):
# 'acl' is not implemented yet
@@ -611,7 +596,6 @@ class VyOSDriver(NetworkDriver):
snmp = dict()
snmp["community"] = dict()
try:
for i in config["service"]["snmp"]["community"]:
snmp["community"].update({
@@ -634,10 +618,8 @@ class VyOSDriver(NetworkDriver):
def get_facts(self):
output_uptime = self._device.send_command("cat /proc/uptime | awk '{print $1}'")
uptime = int(float(output_uptime))
output = self._device.send_command("show version").split("\n")
ver_str = [line for line in output if "Version" in line][0]
version = self.parse_version(ver_str)
@@ -667,25 +649,23 @@ class VyOSDriver(NetworkDriver):
iface_list.append(iface_name)
facts = {
"uptime" : int(uptime),
"vendor" : unicode("VyOS"),
"os_version" : unicode(version),
"serial_number" : unicode(snumber),
"model" : unicode(hwmodel),
"hostname" : unicode(hostname),
"fqdn" : unicode(fqdn),
"uptime": int(uptime),
"vendor": unicode("VyOS"),
"os_version": unicode(version),
"serial_number": unicode(snumber),
"model": unicode(hwmodel),
"hostname": unicode(hostname),
"fqdn": unicode(fqdn),
"interface_list": iface_list
}
return facts
@staticmethod
def parse_version(ver_str):
version = ver_str.split()[-1]
return version
@staticmethod
def parse_snumber(sn_str):
sn = sn_str.split(":")
@@ -696,7 +676,6 @@ class VyOSDriver(NetworkDriver):
model = model_str.split(":")
return model[1].strip()
def get_interfaces_ip(self):
output = self._device.send_command("show interfaces")
output = output.split("\n")
@@ -725,11 +704,10 @@ class VyOSDriver(NetworkDriver):
if ip_ver not in ifaces_ip[iface_name]:
ifaces_ip[iface_name][ip_ver] = dict()
ifaces_ip[iface_name][ip_ver][ip_addr] = { "prefix_length": int(mask) }
ifaces_ip[iface_name][ip_ver][ip_addr] = {"prefix_length": int(mask)}
return ifaces_ip
@staticmethod
def _get_ip_version(ip_address):
if ":" in ip_address:
@@ -737,7 +715,6 @@ class VyOSDriver(NetworkDriver):
elif "." in ip_address:
return "ipv4"
def get_users(self):
output = self._device.send_command("show configuration commands").split("\n")
@@ -749,7 +726,6 @@ class VyOSDriver(NetworkDriver):
user_auth = dict()
for user in user_name:
sshkeys = list()
# extract the configuration which relates to 'user'
@@ -766,7 +742,8 @@ class VyOSDriver(NetworkDriver):
else:
level = 0
# "set system login user alice authentication public-keys alice@example.com key 'ABC'"
# "set system login user alice authentication public-keys
# alice@example.com key 'ABC'"
elif len(line) == 10 and line[8] == "key":
sshkeys.append(line[9].strip("'"))
@@ -780,7 +757,6 @@ class VyOSDriver(NetworkDriver):
return user_auth
def ping(self, destination, source="", ttl=255, timeout=5, size=100, count=5):
# does not support multiple destination yet
@@ -793,24 +769,23 @@ class VyOSDriver(NetworkDriver):
command += "interface %s " % source
ping_result = dict()
output_ping = self._device.send_command(command)
if "Unknown host" in output_ping:
err ="Unknown host"
err = "Unknown host"
else:
err =""
err = ""
if err is not "":
ping_result["error"] = err
else:
# 'packet_info' example:
# ['5', 'packets', 'transmitted,' '5', 'received,' '0%', 'packet', 'loss,', 'time', '3997ms']
# ['5', 'packets', 'transmitted,' '5', 'received,' '0%', 'packet',
# 'loss,', 'time', '3997ms']
packet_info = output_ping.split("\n")[-2]
packet_info = [x.strip() for x in packet_info.split()]
sent = int(packet_info[0])
received = int(packet_info[3])
lost = sent - received
@@ -835,11 +810,11 @@ class VyOSDriver(NetworkDriver):
ping_result["success"] = {
"probes_sent": sent,
"packet_loss": lost,
"rtt_min" : rtt_min,
"rtt_max" : rtt_max,
"rtt_avg" : rtt_avg,
"rtt_stddev" : rtt_stddev,
"results" : [{"ip_address": destination, "rtt": rtt_avg}]
"rtt_min": rtt_min,
"rtt_max": rtt_max,
"rtt_avg": rtt_avg,
"rtt_stddev": rtt_stddev,
"results": [{"ip_address": destination, "rtt": rtt_avg}]
}
return ping_result

View File

@@ -5,7 +5,7 @@ ignore = D203,C901
[pylama:pep8]
max_line_length = 100
[pytest]
[tools:pytest]
addopts = --cov=./ -vs
json_report = report.json
jsonapi = true

View File

@@ -28,7 +28,7 @@ class TestConfigVyOSDriver(unittest.TestCase, TestConfigNetworkDriver):
cls.vendor = 'vyos'
cls.port = '2200'
optional_args = {'port': '2200' }
optional_args = {'port': '2200'}
cls.device = vyos.VyOSDriver(hostname, username, password,
timeout=60, optional_args=optional_args)
cls.device.open()