Skip to content

Commit

Permalink
Add PEP8 validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Frédéric Guillot committed Apr 18, 2017
1 parent 9ff4f0f commit b5cdf0e
Show file tree
Hide file tree
Showing 50 changed files with 189 additions and 222 deletions.
1 change: 1 addition & 0 deletions netman/adapters/switches/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def brocade_factory_ssh(switch_descriptor, lock):
lock=lock
)


def brocade_factory_telnet(switch_descriptor, lock):
warnings.warn("Use SwitchFactory.get_switch_by_descriptor directly to instantiate a switch", DeprecationWarning)
return FlowControlSwitch(
Expand Down
15 changes: 7 additions & 8 deletions netman/adapters/switches/brocade.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@
from netman.core.objects.exceptions import IPNotAvailable, UnknownIP, UnknownVlan, UnknownAccessGroup, BadVlanNumber, \
BadVlanName, UnknownInterface, TrunkVlanNotSet, VlanVrfNotSet, UnknownVrf, BadVrrpTimers, BadVrrpPriorityNumber, \
BadVrrpTracking, VrrpAlreadyExistsForVlan, VrrpDoesNotExistForVlan, NoIpOnVlanForVrrp, BadVrrpAuthentication, \
BadVrrpGroupNumber, DhcpRelayServerAlreadyExists, UnknownDhcpRelayServer, VlanAlreadyExist, NetmanException, \
BadVrrpGroupNumber, DhcpRelayServerAlreadyExists, UnknownDhcpRelayServer, VlanAlreadyExist, \
InvalidAccessGroupName
from netman.core.objects.interface import Interface
from netman.core.objects.interface_states import OFF, ON
from netman.core.objects.interface_states import OFF
from netman.core.objects.port_modes import ACCESS, TRUNK
from netman.core.objects.switch_base import SwitchBase
from netman.core.objects.vlan import Vlan
Expand Down Expand Up @@ -165,7 +165,7 @@ def set_interface_native_vlan(self, interface_id, vlan):

def reset_interface(self, interface_id):
result = self.shell.do("show vlan {}".format(interface_id))
if result and ('Invalid input' in result[0] or 'Error' in result[0]) :
if result and ('Invalid input' in result[0] or 'Error' in result[0]):
raise UnknownInterface(interface_id)

operations = self._get_vlan_association_removal_operations(result)
Expand All @@ -185,8 +185,7 @@ def set_interface_state(self, interface_id, state):
self.shell.do("disable" if state is OFF else "enable")

def unset_interface_access_vlan(self, interface_id):
content = self.shell.do("show vlan brief | include {}"
.format(_to_short_name(interface_id)))
content = self.shell.do("show vlan brief | include {}".format(_to_short_name(interface_id)))
if len(content) == 0:
raise UnknownInterface(interface_id)

Expand Down Expand Up @@ -397,7 +396,6 @@ def add_vif_data_to_vlans(self, vlans):
if current_vlan:
add_interface_vlan_data(current_vlan, int_vlan_data)


def add_dhcp_relay_server(self, vlan_number, ip_address):
vlan = self._get_vlan(vlan_number, include_vif_data=True)

Expand Down Expand Up @@ -457,6 +455,7 @@ def _get_vlan_association_removal_operations(self, result):
operations.append((vlan, state.lower()))
return operations


def parse_vlan(vlan_data):
regex.match("^vlan (\d+).*", vlan_data[0])
current_vlan = VlanBrocade(int(regex[0]))
Expand Down Expand Up @@ -575,11 +574,11 @@ def parse_interface(if_data):
if regex.match("^\w*Ethernet([^\s]*) is (\w*).*", if_data[0]):
i = Interface(name="ethernet {}".format(regex[0]), port_mode=ACCESS, shutdown=regex[1] == "disabled")
for line in if_data:
if regex.match("Port name is (.*)", line): i.description = regex[0]
if regex.match("Port name is (.*)", line):
i.description = regex[0]
return i



class VlanBrocade(Vlan):
def __init__(self, *args, **kwargs):
super(VlanBrocade, self).__init__(*args, **kwargs)
Expand Down
4 changes: 2 additions & 2 deletions netman/adapters/switches/cached.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def get_interfaces(self):
if self.interfaces_cache.refresh_items:
self.interfaces_cache = InterfaceCache(
(interface.name, interface)
for interface in self.real_switch.get_interfaces())
for interface in self.real_switch.get_interfaces())
return copy.deepcopy(self.interfaces_cache.values())

def get_bond(self, number):
Expand Down Expand Up @@ -339,7 +339,7 @@ def edit_bond_spanning_tree(self, number, edge=None):
self.real_switch.edit_bond_spanning_tree(number, edge=edge)

def add_vrrp_group(self, vlan_number, group_id, ips=None, priority=None,
hello_interval=None, dead_interval=None ,track_id=None,
hello_interval=None, dead_interval=None, track_id=None,
track_decrement=None):
self.real_switch.add_vrrp_group(vlan_number, group_id, ips=ips,
priority=priority,
Expand Down
20 changes: 12 additions & 8 deletions netman/adapters/switches/cisco.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def add_ip_to_vlan(self, vlan_number, ip_network):
if has_ips:
self.ssh.do('no ip redirects')
result = self.ssh.do('ip address {} {}{}'.format(ip_network.ip, ip_network.netmask,
" secondary" if has_ips else ""))
" secondary" if has_ips else ""))
if len(result) > 0:
raise IPNotAvailable(ip_network, reason="; ".join(result))
else:
Expand Down Expand Up @@ -480,16 +480,20 @@ def _set_unicast_rpf_strict(self):


def parse_interface(data):
if data and (regex.match("interface (\w*Ethernet[^\s]*)", data[0])
or regex.match("interface (Port-channel[^\s]*)", data[0])):
if data and (regex.match("interface (\w*Ethernet[^\s]*)", data[0]) or regex.match("interface (Port-channel[^\s]*)", data[0])):
i = Interface(name=regex[0], shutdown=False)
port_mode = access_vlan = native_vlan = trunk_vlans = None
for line in data:
if regex.match(" switchport mode (.*)", line): port_mode = regex[0]
if regex.match(" switchport access vlan (\d*)", line): access_vlan = int(regex[0])
if regex.match(" switchport trunk native vlan (\d*)", line): native_vlan = int(regex[0])
if regex.match(" switchport trunk allowed vlan (.*)", line): trunk_vlans = regex[0]
if regex.match(" shutdown", line): i.shutdown = True
if regex.match(" switchport mode (.*)", line):
port_mode = regex[0]
if regex.match(" switchport access vlan (\d*)", line):
access_vlan = int(regex[0])
if regex.match(" switchport trunk native vlan (\d*)", line):
native_vlan = int(regex[0])
if regex.match(" switchport trunk allowed vlan (.*)", line):
trunk_vlans = regex[0]
if regex.match(" shutdown", line):
i.shutdown = True

if not port_mode:
i.port_mode = DYNAMIC
Expand Down
5 changes: 3 additions & 2 deletions netman/adapters/switches/juniper/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def get_vlan_from_node(self, vlan_node, config):
l3_if_type, l3_if_name = get_l3_interface(vlan_node)
if l3_if_name is not None:
interface_vlan_node = first(config.xpath("data/configuration/interfaces/interface/name[text()=\"{}\"]/.."
"/unit/name[text()=\"{}\"]/..".format(l3_if_type, l3_if_name)))
"/unit/name[text()=\"{}\"]/..".format(l3_if_type, l3_if_name)))
if interface_vlan_node is not None:
vlan.ips = parse_ips(interface_vlan_node)
vlan.access_groups[IN] = parse_inet_filter(interface_vlan_node, "input")
Expand Down Expand Up @@ -1191,13 +1191,15 @@ def interface_speed_update(interface_name, speed):
</interface>
""".format(interface_name, speed))


def protocol_interface_update(name):
return to_ele("""
<interface>
<name>{}</name>
</interface>
""".format(name))


def list_vlan_members(interface_node, config):
vlans = set()
for members in interface_node.xpath("unit/family/ethernet-switching/vlan/members"):
Expand Down Expand Up @@ -1269,4 +1271,3 @@ def __init__(self, name, shutdown):

def to_interface(self):
return Interface(name=self.name, shutdown=self.shutdown, port_mode=ACCESS)

1 change: 0 additions & 1 deletion netman/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,3 @@


NETMAN_API_VERSION = 2

1 change: 0 additions & 1 deletion netman/api/api_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ def exception_to_response(exception, code):
else:
data['error'] = "Unexpected error: {}".format(exception.__class__.__name__)


response = json_response(data, code)
response.status_code = code

Expand Down
6 changes: 3 additions & 3 deletions netman/api/netman_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ def logger(self):

def hook_to(self, server):
self.app = server
server.add_url_rule('/netman/info',endpoint="netman_info",view_func=self.get_info, methods=['GET'])
server.add_url_rule('/netman/apidocs/', endpoint="netman_apidocs" ,view_func=self.api_docs, methods=['GET'])
server.add_url_rule('/netman/apidocs/<path:filename>', endpoint="netman_apidocs" ,view_func=self.api_docs, methods=['GET'])
server.add_url_rule('/netman/info', endpoint="netman_info", view_func=self.get_info, methods=['GET'])
server.add_url_rule('/netman/apidocs/', endpoint="netman_apidocs", view_func=self.api_docs, methods=['GET'])
server.add_url_rule('/netman/apidocs/<path:filename>', endpoint="netman_apidocs", view_func=self.api_docs, methods=['GET'])

@to_response
def get_info(self):
Expand Down
2 changes: 1 addition & 1 deletion netman/api/objects/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ def to_api(self, core_object, version=None):
return self.at_most(version).to_api(core_object)

def to_core(self, api_dict, version=None):
return self.at_most(version).to_core(api_dict)
return self.at_most(version).to_core(api_dict)
4 changes: 2 additions & 2 deletions netman/api/switch_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1013,7 +1013,7 @@ def set_vlan_arp_routing_state(self, switch, vlan_number, state):
``true`` or ``false``
"""

switch.set_vlan_arp_routing_state(vlan_number, ON if state == True else OFF)
switch.set_vlan_arp_routing_state(vlan_number, ON if state is True else OFF)

return 204, None

Expand Down Expand Up @@ -1062,4 +1062,4 @@ def unset_vlan_unicast_rpf_mode(self, switch, vlan_number):
"""

switch.unset_vlan_unicast_rpf_mode(vlan_number)
return 204, None
return 204, None
1 change: 1 addition & 0 deletions netman/api/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ def is_access_group_name(data, **_):

return {'access_group_name': data}


def is_vrf_name(data, **_):
if data == "" or " " in data:
raise BadRequest('Malformed VRF name')
Expand Down
5 changes: 2 additions & 3 deletions netman/core/objects/flow_control_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ def __new__(cls, *args, **kwargs):

return obj


@do_not_wrap_with_flow_control
@contextmanager
def transaction(self):
Expand All @@ -72,8 +71,8 @@ def start_transaction(self):
self.lock.acquire()
try:
if not self.wrapped_switch.connected:
self.wrapped_switch.connect()
self._has_auto_connected = True
self.wrapped_switch.connect()
self._has_auto_connected = True

self.wrapped_switch.start_transaction()
except Exception:
Expand Down
2 changes: 1 addition & 1 deletion netman/core/objects/interface_states.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@


ON = "ON"
OFF = "OFF"
OFF = "OFF"
1 change: 1 addition & 0 deletions netman/core/objects/switch_transactional.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

def transactional(fn):
warnings.warn("Deprecated, make your own annotation this one will disappear", DeprecationWarning)

@wraps(fn)
def wrapper(self, *args, **kwargs):
if self.in_transaction:
Expand Down
7 changes: 3 additions & 4 deletions netman/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

#!/usr/bin/env python
import argparse
from logging import DEBUG, getLogger

Expand All @@ -31,6 +30,7 @@
app = Flask('netman')
app.url_map.converters['regex'] = RegexConverter


@app.before_request
def log_request():
logger = getLogger("netman.api")
Expand All @@ -39,6 +39,7 @@ def log_request():
logger.debug("body : {}".format(repr(request.data) if request.data else "<<empty>>"))
logger.debug("Headers : " + ", ".join(["{0}={1}".format(h[0], h[1]) for h in request.headers]))


lock_factory = ThreadingLockFactory()
switch_factory = FlowControlSwitchFactory(MemoryStorage(), lock_factory)
real_switch_factory = RealSwitchFactory()
Expand All @@ -52,7 +53,6 @@ def log_request():
def load_app(session_inactivity_timeout=None):
if session_inactivity_timeout:
switch_session_manager.session_inactivity_timeout = session_inactivity_timeout

return app


Expand All @@ -61,12 +61,11 @@ def load_app(session_inactivity_timeout=None):
parser.add_argument('--host', nargs='?', default="127.0.0.1")
parser.add_argument('--port', type=int, nargs='?', default=5000)
parser.add_argument('--session-inactivity-timeout', type=int, nargs='?')

args = parser.parse_args()

params = {}
if args.session_inactivity_timeout:
params["session_inactivity_timeout"] = args.session_inactivity_timeout

load_app(**params).run(host=args.host, port=args.port, threaded=True)

1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pbr>=1.8
Flask>=0.11
paramiko==1.15.1
netaddr>=0.7.13
Expand Down
2 changes: 0 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

#!/usr/bin/env python

from setuptools import setup

setup(
Expand Down
2 changes: 1 addition & 1 deletion test-requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ Sphinx
sphinxcontrib-httpdomain
gunicorn>=19.4.5
futures>=3.0.4

flake8
3 changes: 0 additions & 3 deletions tests/adapters/compliance_tests/add_interface_to_bond_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,3 @@ def test_resets_the_interface_access_vlan(self):

assert_that(interface.access_vlan, is_(none()))
self.janitor.remove_vlan(90)



1 change: 0 additions & 1 deletion tests/adapters/compliance_tests/get_interfaces_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,3 @@ def tearDown(self):
self.janitor.remove_bond(1)
self.janitor.remove_vlan(1000)
super(GetInterfacesTest, self).tearDown()

1 change: 0 additions & 1 deletion tests/adapters/compliance_tests/get_vlan_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

from netman.core.objects.access_groups import IN, OUT
from netman.core.objects.exceptions import UnknownVlan
from netman.core.objects.interface_states import OFF
from tests import has_message
from tests.adapters.compliance_test_case import ComplianceTestCase

Expand Down
2 changes: 1 addition & 1 deletion tests/adapters/compliance_tests/remove_bond_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def test_remove_its_members_from_the_bond(self):
self.try_to.add_interface_to_bond(self.test_port, 42)

self.client.remove_bond(42)

interface = self.client.get_interface(self.test_port)
assert_that(interface.bond_master, is_(None))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from hamcrest import assert_that, is_

from netman.core.objects.exceptions import UnknownInterface
from netman.core.objects.interface_states import ON, OFF
from netman.core.objects.interface_states import ON
from tests import has_message
from tests.adapters.compliance_test_case import ComplianceTestCase

Expand Down
2 changes: 1 addition & 1 deletion tests/adapters/configured_test_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def skip_on_switches(*to_skip):
def resource_decorator(fn):
@wraps(fn)
def wrapper(self, *args, **kwargs):
if not self.switch_descriptor.model in to_skip:
if self.switch_descriptor.model not in to_skip:
return fn(self, *args, **kwargs)

else:
Expand Down
2 changes: 0 additions & 2 deletions tests/adapters/model_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,5 +214,3 @@
]
}
]


6 changes: 2 additions & 4 deletions tests/adapters/shell/mock_terminal_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def start(self):
self.write("Done!\n")
self.exit()


class AmbiguousCommand(SSHCommand):
def __init__(self, name, *args):
self.name = name
Expand Down Expand Up @@ -91,6 +92,7 @@ def passwd_change_protocol_prompt(instance):
instance.protocol.prompt = "hostname#"
instance.protocol.password_input = False


def passwd_write_password_to_transport(instance):
instance.writeln("MockSSH: password is %s" % instance.valid_password)

Expand All @@ -116,7 +118,3 @@ def finish():
this.protocol.keyHandlers.pop("k")

self.protocol.keyHandlers.update({"k": finish})




1 change: 1 addition & 0 deletions tests/adapters/shell/telnet_login_special_cases_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class PasswordHangingMockTelnet(MockTelnet):
def validate_password(self, _):
pass


class SwitchTelnetFactory(Factory):
def __init__(self, prompt, commands):
self.prompt = prompt
Expand Down
Loading

0 comments on commit b5cdf0e

Please sign in to comment.