From 8587b8cb79a1f40018af49a7363d5fa79513c664 Mon Sep 17 00:00:00 2001 From: Jasper Lievisse Adriaanse Date: Tue, 20 Feb 2018 20:11:14 +0100 Subject: [PATCH] initial import of WIP napalm-s350 driver --- .gitignore | 66 ++++ .travis.yml | 23 ++ AUTHORS | 1 + CONTRIBUTING | 1 + LICENSE | 201 ++++++++++++ MANIFEST.in | 3 + README.md | 8 + napalm_s350/__init__.py | 18 ++ napalm_s350/s350.py | 295 ++++++++++++++++++ napalm_s350/templates/.placeholder | 0 napalm_s350/utils/__init__.py | 1 + .../utils/textfsm_templates/.placeholder | 0 pylama.ini | 6 + requirements-dev.txt | 10 + requirements.txt | 3 + setup.cfg | 37 +++ setup.py | 31 ++ test/unit/TestDriver.py | 80 +++++ test/unit/TestS350Driver.py | 40 +++ test/unit/conftest.py | 57 ++++ test/unit/s350/initial.conf | 1 + test/unit/s350/merge_good.conf | 1 + test/unit/s350/merge_good.diff | 1 + test/unit/s350/merge_typo.conf | 2 + test/unit/s350/mock_data/.placeholder | 0 test/unit/s350/new_good.conf | 1 + test/unit/s350/new_good.diff | 1 + test/unit/s350/new_typo.conf | 2 + test/unit/test_getters.py | 11 + tox.ini | 9 + 30 files changed, 910 insertions(+) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 AUTHORS create mode 100644 CONTRIBUTING create mode 100644 LICENSE create mode 100644 MANIFEST.in create mode 100644 README.md create mode 100644 napalm_s350/__init__.py create mode 100644 napalm_s350/s350.py create mode 100644 napalm_s350/templates/.placeholder create mode 100644 napalm_s350/utils/__init__.py create mode 100644 napalm_s350/utils/textfsm_templates/.placeholder create mode 100644 pylama.ini create mode 100644 requirements-dev.txt create mode 100644 requirements.txt create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 test/unit/TestDriver.py create mode 100644 test/unit/TestS350Driver.py create mode 100644 test/unit/conftest.py create mode 100644 test/unit/s350/initial.conf create mode 100644 test/unit/s350/merge_good.conf create mode 100644 test/unit/s350/merge_good.diff create mode 100644 test/unit/s350/merge_typo.conf create mode 100644 test/unit/s350/mock_data/.placeholder create mode 100644 test/unit/s350/new_good.conf create mode 100644 test/unit/s350/new_good.diff create mode 100644 test/unit/s350/new_typo.conf create mode 100644 test/unit/test_getters.py create mode 100644 tox.ini diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5c76993 --- /dev/null +++ b/.gitignore @@ -0,0 +1,66 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +report.json +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints + +*~ +*.swp diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..f23fbda --- /dev/null +++ b/.travis.yml @@ -0,0 +1,23 @@ +language: python +python: +- 2.7 +install: +- pip install -r requirements-dev.txt +- pip install . +- pip install -e git+https://github.com/napalm-automation/napalm-base.git@develop#egg=napalm-base +- pip install coveralls + +deploy: + provider: pypi + user: dbarroso + password: + secure: IIifRr9K771snku+qI7yz8T/cJC4ZO/fUYUNILhMB5eQtF2/MAEU7W1owGfcIqE9SW7fhPAXqVrnb7AcdFyjjbkZn6uoYYlh5LrQaCXgbfol5Yg+OSsRKFwhEOBcKFrtqz3W6UPunN6CX4v2gn2UCmWSyQ3XERgqKxobBVSOMb1G9PTy/Zk0ZUvGJc05bxWj3xuVQKg904VpnhQJ6q1h4d9SV+dQClP4eDRbEwe+ICKX3S2JPa/PiJfWrIsCL12yT+iZ/aiDwfSBjh+o3HMdt98cB3FkHAibEZnvpLOpUCmjX1rMyqyJEqVgDM1mQ4vyoYO5DNFv94ZufGJnJP+TIbkkSaFy9ZpeC2V+7K03TM+g1rZD3BKK50u3kL86KsHao14SZHV58l7/b3023IUr4MwrQgoLlHMhw9IFFC8bYmP/6aylae5fR/+5inGloSByzWLAKKQ0FLPPkCoeukmldyphjZ8HnGdhEu566kO9R5gxJ4edsbeimsRAO3oZ/EByQcgOytJjVKjMpn7fhiSblJO8KB4+M5d5fXUn5RZ31P3g8RFfG1Jqx2l9eOd4i8u9l3NkRd9WO8q5wyF/hvC/u4RcIMnRYl5hPWMBNY6uGGj7aq7o+XETTLVFirCwHBKre6OLdaVpW1ZciJP07Xb9qhyPLCeP3E9VM/OAz9rs5KI= + on: + tags: true + branch: master + +script: +- py.test --cov-report= test/ + +after_success: +- coveralls diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..be1b657 --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +Jasper Lievisse Adriaanse diff --git a/CONTRIBUTING b/CONTRIBUTING new file mode 100644 index 0000000..6ccfd34 --- /dev/null +++ b/CONTRIBUTING @@ -0,0 +1 @@ +Please, read http://napalm.readthedocs.io/en/latest/contributing/index.html diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..e72c41c --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,3 @@ +include requirements.txt +include napalm_s350/templates/*.j2 +include napalm_s350/utils/textfsm_templates/*.tpl diff --git a/README.md b/README.md new file mode 100644 index 0000000..cf8171d --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +# napalm-s350 + +Napalm driver targeting Cisco SG350 devices. + +## Supported devices + +This driver initially targets the Cisco SG350 device though other, similar, devices may +be supported. diff --git a/napalm_s350/__init__.py b/napalm_s350/__init__.py new file mode 100644 index 0000000..4d037b3 --- /dev/null +++ b/napalm_s350/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2018 Jasper Lievisse Adriaanse. All rights reserved. +# +# The contents of this file are licensed under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. + +"""napalm-s350 package.""" +from napalm_s350.s350 import S350Driver # noqa + +__all__ = ('S350Driver',) diff --git a/napalm_s350/s350.py b/napalm_s350/s350.py new file mode 100644 index 0000000..6d48175 --- /dev/null +++ b/napalm_s350/s350.py @@ -0,0 +1,295 @@ +# -*- coding: utf-8 -*- +# Copyright 2018 Jasper Lievisse Adriaanse. All rights reserved. +# +# The contents of this file are licensed under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. + +""" +Napalm driver for Cisco S350 devices. + +Read https://napalm.readthedocs.io for more information. +""" + +from __future__ import print_function +from __future__ import unicode_literals + +import netaddr +import re +import socket + +from netmiko import ConnectHandler +from napalm.base import NetworkDriver +from napalm.base.exceptions import ( + ConnectionException, + SessionLockedException, + MergeConfigException, + ReplaceConfigException, + CommandErrorException, +) + +from napalm.base.utils import py23_compat + + +class S350Driver(NetworkDriver): + """Napalm driver for S350.""" + + def __init__(self, hostname, username, password, timeout=60, optional_args=None): + """Constructor.""" + self.device = None + self.hostname = hostname + self.username = username + self.password = password + self.timeout = timeout + + if optional_args is None: + optional_args = {} + + self._dest_file_system = optional_args.get('dest_file_system', None) + + # Netmiko possible arguments + netmiko_argument_map = { + 'port': None, + 'secret': '', + 'verbose': False, + 'keepalive': 30, + 'global_delay_factor': 1, + 'use_keys': False, + 'key_file': None, + 'ssh_strict': False, + 'system_host_keys': False, + 'alt_host_keys': False, + 'alt_key_file': '', + 'ssh_config_file': None, + 'allow_agent': False, + } + + # Allow for passing additional Netmiko arguments + self.netmiko_optional_args = {} + for k, v in netmiko_argument_map.items(): + try: + self.netmiko_optional_args[k] = optional_args[k] + except KeyError: + pass + + self.port = optional_args.get('port', 22) + self.device = None + + def open(self): + """Open a connection to the device.""" + self.device = ConnectHandler(device_type='cisco_s300', + host=self.hostname, + username=self.username, + password=self.password, + **self.netmiko_optional_args) + self.device.enable() + + + def _discover_file_system(self): + try: + return self.device._autodetect_fs() + except Exception: + msg = "Netmiko _autodetect_fs failed (to work around specify " \ + "dest_file_system in optional_args)." + raise CommandErrorException(msg) + + + def close(self): + """Close the connection to the device.""" + self.device.disconnect() + + def _send_command(self, command): + """Wrapper for self.device.send.command(). + + If command is a list will iterate through commands until valid command. + """ + try: + if isinstance(command, list): + for cmd in command: + output = self.device.send_command(cmd) + if "% Invalid" not in output: + break + else: + output = self.device.send_command(command) + return output.strip() + except (socket.error, EOFError) as e: + raise ConnectionClosedException(str(e)) + + + def _parse_uptime(self, uptime_str): + """Parse an uptime string into number of seconds""" + uptime_str = uptime_str.strip() + days, timespec = uptime_str.split(',') + + hours, minutes, seconds = timespec.split(':') + + uptime_sec = (int(days) * 86400) + (int(hours) * 3600) + (int(minutes) * 60) + int(seconds) + return uptime_sec + + + def get_config(self, retrieve='all'): + """ + get_config for S350. Since this firmware doesn't support a candidate + configuration we leave it empty. + """ + + configs = { + 'startup': '', + 'running': '', + 'candidate': '', + } + + if retrieve in ('all', 'startup'): + output = self._send_command('show startup-config') + configs['startup'] = output + + if retrieve in ('all', 'running'): + output = self._send_command('show running-config') + configs['running'] = output + + return configs + + def get_facts(self): + """Return a set of facts from the device.""" + serial_number, fqdn, os_version, hostname, domain_name = ('Unknown',) * 5 + + # Submit commands to the device. + show_ver = self._send_command('show version | include Version') + show_sys = self._send_command('show system') + show_inv = self._send_command('show inventory') + show_hosts = self._send_command('show hosts | begin Default Domain Table') + show_int_st = self._send_command('show interface status | include gi') + + # os_version + for line in show_ver.splitlines(): + # First version line is the active version + if 'Version' in line: + _, os_version = line.split('Version: ') + break + + # hostname, uptime + for line in show_sys.splitlines(): + if line.startswith('System Name:'): + _, hostname = line.split('System Name:') + hostname = hostname.strip() + elif line.startswith('System Description:'): + _, model = line.split('System Description:') + model = model.strip() + elif line.startswith('System Up Time (days,hour:min:sec):'): + _, uptime_str = line.split('System Up Time (days,hour:min:sec):') + uptime = self._parse_uptime(uptime_str) + + # serial_number + for line in show_inv.splitlines(): + if 'SN:' in line: + serial_number = line.split('SN: ')[-1] + break + + # fqdn + domain_line = show_hosts.splitlines()[4] + domainname = domain_line.split()[0] + fqdn = '{0}.{1}'.format(hostname, domainname) + + # interface_list + interfaces = [] + for line in show_int_st.splitlines(): + interfaces.append(py23_compat.text_type(line.split()[0])) + + return { + 'fqdn': py23_compat.text_type(fqdn), + 'hostname': py23_compat.text_type(hostname), + 'interface_list': interfaces, + 'model': py23_compat.text_type(model), + 'os_version': py23_compat.text_type(os_version), + 'serial_number': py23_compat.text_type(serial_number), + 'uptime': uptime, + 'vendor': u'Cisco', + } + + def get_interfaces_ip(self): + """Returns all configured interface IP addresses.""" + interfaces = {} + show_ip_int = self._send_command('show ip int | include (UP|DOWN)') + + # Limit to valid interfaces (i.e. ignore vlan 1) + valid_interfaces = [i for i in show_ip_int.splitlines() if i.split()[-1] == 'Valid'] + + for interface in valid_interfaces: + network, name = interface.split()[:2] + + ip = netaddr.IPNetwork(network) + + family = 'ipv{0}'.format(ip.version) + + interfaces[name] = { + family: { + str(ip.ip): { + 'prefix_length': ip.prefixlen + } + } + } + + return interfaces + + def get_lldp_neighbors(self): + """get_lldp_neighbors implementation for s350""" + neighbors = {} + output = self._send_command('show lldp neighbors | begin \ \ Port') + + for line in output.splitlines()[2:]: + line_elems = line.split() + local_port = line_elems[0] + remote_port = line_elems[2] + remote_name = line_elems[3] + + neighbors[local_port] = { + 'hostname': remote_name, + 'port': remote_port, + } + + return neighbors + + + def get_ntp_servers(self): + """get_ntp_servers implementation for S350""" + ntp_servers = {} + output = self._send_command('show sntp status | include Server') + + for line in output.splitlines(): + ntp_servers[line.split()[2]] = {} + + return ntp_servers + + def is_alive(self): + """Returns an indication of the state of the connection.""" + null = chr(0) + + if self.device is None: + return {'is_alive': False} + + # Send a NUL byte to keep the connection alive. + try: + self.device.write_channel(null) + return {'is_alive': self.device.remote_conn.transport.is_active()} + except (socket.error, EOFError): + # If we couldn't send it, the connection is not available. + return {'is_alive': False} + + # If we made it here, assume the worst. + return {'is_alive': False} + + + @property + def dest_file_system(self): + # First ensure we have an open connection. + if self.device and self._dest_file_system is None: + self._dest_file_system = self._discover_file_system() + return self._dest_file_system diff --git a/napalm_s350/templates/.placeholder b/napalm_s350/templates/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/napalm_s350/utils/__init__.py b/napalm_s350/utils/__init__.py new file mode 100644 index 0000000..678164a --- /dev/null +++ b/napalm_s350/utils/__init__.py @@ -0,0 +1 @@ +"""napalm.utils package.""" diff --git a/napalm_s350/utils/textfsm_templates/.placeholder b/napalm_s350/utils/textfsm_templates/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/pylama.ini b/pylama.ini new file mode 100644 index 0000000..3146a20 --- /dev/null +++ b/pylama.ini @@ -0,0 +1,6 @@ +[pylama] +linters = mccabe,pep257,pep8,pyflakes +ignore = D203, + +[pylama:pep8] +max_line_length = 120 diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..1b9ee1d --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,10 @@ +coveralls +ddt +flake8-import-order +pytest +pytest-cov +pytest-json +pytest-pythonpath +pylama +mock +tox \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3381e1b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +napalm>=2.0.0 +netmiko>=1.4.3 +netaddr diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..12e6447 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,37 @@ +[pylama] +linters = mccabe,pep8,pyflakes +ignore = D203,C901 +skip = .tox/* + +[pylama:pep8] +max_line_length = 100 + +[tool:pytest] +norecursedirs = + .git + .tox + .env + dist + build + south_migraitons + migrations + napalm/base/test +python_files = + test_*.py + *_test.py + tests.py +addopts = + --cov=napalm + --cov-report term-missing + -vs + --pylama +json_report = report.json +jsonapi = true + +[coverage:run] +include = + napalm_s350/* + +[coverage:report] +omit = + napalm_s350/test/* diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..0b1182e --- /dev/null +++ b/setup.py @@ -0,0 +1,31 @@ +"""setup.py file.""" + +import uuid + +from setuptools import setup, find_packages +from pip.req import parse_requirements + +__author__ = 'Jasper Lievisse Adriaanse ' + +install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1()) +reqs = [str(ir.req) for ir in install_reqs] + +setup( + name="napalm-s350", + version="0.1.0", + packages=find_packages(), + author="Jasper Lievisse Adriaanse", + author_email="j@jasper.la", + description="Network Automation and Programmability Abstraction Layer with Multivendor support", + classifiers=[ + 'Topic :: Utilities', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Operating System :: POSIX :: Linux', + 'Operating System :: MacOS', + ], + url="https://github.com/jasperla/napalm-s350", + include_package_data=True, + install_requires=reqs, +) diff --git a/test/unit/TestDriver.py b/test/unit/TestDriver.py new file mode 100644 index 0000000..bff6dbe --- /dev/null +++ b/test/unit/TestDriver.py @@ -0,0 +1,80 @@ +# Copyright 2018 Jasper Lievisse Adriaanse. All rights reserved. +# +# The contents of this file are licensed under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. + +"""Tests.""" + +import unittest + +from napalm_s350 import s350 +from napalm.base.test.base import TestConfigNetworkDriver, TestGettersNetworkDriver +import json + + +class TestConfigDriver(unittest.TestCase, TestConfigNetworkDriver): + """Group of tests that test Configuration related methods.""" + + @classmethod + def setUpClass(cls): + """Run before starting the tests.""" + hostname = '127.0.0.1' + username = 'vagrant' + password = 'vagrant' + cls.vendor = 's350' + + optional_args = {'port': 12443, } + cls.device = s350.S350Driver(hostname, username, password, timeout=60, + optional_args=optional_args) + cls.device.open() + + cls.device.load_replace_candidate(filename='%s/initial.conf' % cls.vendor) + cls.device.commit_config() + + +class TestGetterDriver(unittest.TestCase, TestGettersNetworkDriver): + """Group of tests that test getters.""" + + @classmethod + def setUpClass(cls): + """Run before starting the tests.""" + cls.mock = True + + hostname = '127.0.0.1' + username = 'vagrant' + password = 'vagrant' + cls.vendor = 's350' + + optional_args = {'port': 12443, } + cls.device = s350.S350Driver(hostname, username, password, timeout=60, + optional_args=optional_args) + + if cls.mock: + cls.device.device = FakeDevice() + else: + cls.device.open() + + +class FakeDevice: + """Test double.""" + + @staticmethod + def read_json_file(filename): + """Return the content of a file with content formatted as json.""" + with open(filename) as data_file: + return json.load(data_file) + + @staticmethod + def read_txt_file(filename): + """Return the content of a file.""" + with open(filename) as data_file: + return data_file.read() diff --git a/test/unit/TestS350Driver.py b/test/unit/TestS350Driver.py new file mode 100644 index 0000000..754771b --- /dev/null +++ b/test/unit/TestS350Driver.py @@ -0,0 +1,40 @@ +# Copyright 2018 Jasper Lievisse Adriaanse. All rights reserved. +# +# The contents of this file are licensed under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. + +"""Tests.""" + +import unittest + +from napalm_s350 import s350 +from napalm.base.test.base import TestConfigNetworkDriver + + +class TestConfigS350Driver(unittest.TestCase, TestConfigNetworkDriver): + """Group of tests that test Configuration related methods.""" + + @classmethod + def setUpClass(cls): + """Run before starting the tests.""" + hostname = '127.0.0.1' + username = 'vagrant' + password = 'vagrant' + cls.vendor = 's350' + + optional_args = {'port': 12443, } + cls.device = s350.S350Driver(hostname, username, password, timeout=60, + optional_args=optional_args) + cls.device.open() + + cls.device.load_replace_candidate(filename='%s/initial.conf' % cls.vendor) + cls.device.commit_config() diff --git a/test/unit/conftest.py b/test/unit/conftest.py new file mode 100644 index 0000000..8639955 --- /dev/null +++ b/test/unit/conftest.py @@ -0,0 +1,57 @@ +"""Test fixtures.""" +from builtins import super + +import pytest +from napalm.base.test import conftest as parent_conftest + +from napalm.base.test.double import BaseTestDouble + +from napalm_s350 import s350 + + +@pytest.fixture(scope='class') +def set_device_parameters(request): + """Set up the class.""" + def fin(): + request.cls.device.close() + request.addfinalizer(fin) + + request.cls.driver = s350.S350Driver + request.cls.patched_driver = PatchedS350Driver + request.cls.vendor = 's350' + parent_conftest.set_device_parameters(request) + + +def pytest_generate_tests(metafunc): + """Generate test cases dynamically.""" + parent_conftest.pytest_generate_tests(metafunc, __file__) + + +class PatchedS350Driver(s350.S350Driver): + """Patched S350 Driver.""" + + def __init__(self, hostname, username, password, timeout=60, optional_args=None): + """Patched S350 Driver constructor.""" + super().__init__(hostname, username, password, timeout, optional_args) + + self.patched_attrs = ['device'] + self.device = FakeS350Device() + + +class FakeS350Device(BaseTestDouble): + """S350 device test double.""" + + def run_commands(self, command_list, encoding='json'): + """Fake run_commands.""" + result = list() + + for command in command_list: + filename = '{}.{}'.format(self.sanitize_text(command), encoding) + full_path = self.find_file(filename) + + if encoding == 'json': + result.append(self.read_json_file(full_path)) + else: + result.append({'output': self.read_txt_file(full_path)}) + + return result diff --git a/test/unit/s350/initial.conf b/test/unit/s350/initial.conf new file mode 100644 index 0000000..859698e --- /dev/null +++ b/test/unit/s350/initial.conf @@ -0,0 +1 @@ +Initial configuration diff --git a/test/unit/s350/merge_good.conf b/test/unit/s350/merge_good.conf new file mode 100644 index 0000000..89ef127 --- /dev/null +++ b/test/unit/s350/merge_good.conf @@ -0,0 +1 @@ +Some changes that will be merged while testing diff --git a/test/unit/s350/merge_good.diff b/test/unit/s350/merge_good.diff new file mode 100644 index 0000000..2b6918c --- /dev/null +++ b/test/unit/s350/merge_good.diff @@ -0,0 +1 @@ +The diff when merging `merged_good.conf` diff --git a/test/unit/s350/merge_typo.conf b/test/unit/s350/merge_typo.conf new file mode 100644 index 0000000..da7e876 --- /dev/null +++ b/test/unit/s350/merge_typo.conf @@ -0,0 +1,2 @@ +Some changes that will be merge while testing. Should contain a typo or something that triggers +an error during the load/commmit phase diff --git a/test/unit/s350/mock_data/.placeholder b/test/unit/s350/mock_data/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/test/unit/s350/new_good.conf b/test/unit/s350/new_good.conf new file mode 100644 index 0000000..e142fa9 --- /dev/null +++ b/test/unit/s350/new_good.conf @@ -0,0 +1 @@ +A full new configuration. It will be used to test the replace operation diff --git a/test/unit/s350/new_good.diff b/test/unit/s350/new_good.diff new file mode 100644 index 0000000..a313d37 --- /dev/null +++ b/test/unit/s350/new_good.diff @@ -0,0 +1 @@ +A diff between `initial.conf` and `new_good.conf` diff --git a/test/unit/s350/new_typo.conf b/test/unit/s350/new_typo.conf new file mode 100644 index 0000000..b97f25f --- /dev/null +++ b/test/unit/s350/new_typo.conf @@ -0,0 +1,2 @@ +A full new configuration. However, it should contain a typo or something that triggers an error +during commit/load phase. diff --git a/test/unit/test_getters.py b/test/unit/test_getters.py new file mode 100644 index 0000000..4e4cb4e --- /dev/null +++ b/test/unit/test_getters.py @@ -0,0 +1,11 @@ +"""Tests for getters.""" + +from napalm.base.test.getters import BaseTestGetters + + +import pytest + + +@pytest.mark.usefixtures("set_device_parameters") +class TestGetter(BaseTestGetters): + """Test get_* methods.""" diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..746e406 --- /dev/null +++ b/tox.ini @@ -0,0 +1,9 @@ +[tox] +envlist = py27,py34,py35,py36 + +[testenv] +deps = + -rrequirements.txt + -rrequirements-dev.txt +commands = + py.test {posargs}