Best Python code snippet using pytest
platform.py
Source:platform.py
1''' 2Platform Genie Ops Object for IOSXR.3'''4# super class5from genie.libs.ops.platform.platform import Platform as SuperPlatform6# Parser7from genie.libs.parser.iosxr.show_platform import ShowVersion, ShowSdrDetail,\8 ShowPlatform, ShowPlatformVm,\9 ShowInstallActiveSummary, ShowInventory,\10 ShowRedundancySummary, AdminShowDiagChassis,\11 ShowRedundancy, Dir12class Platform(SuperPlatform):13 '''Platform Genie Ops Object'''14 def get_active_uptime(self, item):15 for node in item:16 if 'active' in item[node]['role'].lower():17 return item[node]['node_uptime_in_seconds']18 19 def learn(self):20 '''Learn Platform Ops'''21 # ================22 # DeviceAttributes23 # ================24 # chassis25 self.add_leaf(cmd=ShowVersion,26 src='[chassis_detail]',27 dest='[chassis]')28 # chassis_sn29 self.add_leaf(cmd=AdminShowDiagChassis,30 src='[sn]',31 dest='[chassis_sn]')32 # rtr_type33 self.add_leaf(cmd=ShowVersion,34 src='[device_family]',35 dest='[rtr_type]')36 # os37 self.add_leaf(cmd=ShowVersion,38 src='[operating_system]',39 dest='[os]')40 # version41 self.add_leaf(cmd=ShowVersion,42 src='[software_version]',43 dest='[version]')44 # image45 self.add_leaf(cmd=ShowVersion,46 src='[image]',47 dest='[image]')48 # installed_packages49 self.add_leaf(cmd=ShowInstallActiveSummary,50 src='[active_packages]',51 dest='[installed_packages]')52 # config_register53 self.add_leaf(cmd=ShowVersion,54 src='[config_register]',55 dest='[config_register]')56 # main_mem57 self.add_leaf(cmd=ShowVersion,58 src='[processor_memory_bytes]',59 dest='[main_mem]')60 # dir61 self.add_leaf(cmd=Dir,62 src='[dir]',63 dest='[dir]')64 # sdr_owner65 self.add_leaf(cmd=ShowInstallActiveSummary,66 src='[sdr]',67 dest='[sdr_owner]')68 69 # =======================70 # VirtualDeviceAttributes71 # =======================72 # vd_id == sdr_id73 # vd_name == sdr_name74 self.add_leaf(cmd=ShowSdrDetail,75 src='[sdr_id][(?P<sdr_id>.*)][sdr_name][(?P<sdr_name>.*)]',76 dest='[virtual_device][(?P<sdr_id>.*)][vd_name][(?P<sdr_name>.*)]')77 # vd_dSDRsc_nod78 self.add_leaf(cmd=ShowSdrDetail,79 src='[sdr_id][(?P<sdr_id>.*)][dsdrsc_node][(?P<dsdrsc_node>.*)]',80 dest='[virtual_device][(?P<sdr_id>.*)][vd_dSDRsc_nod][(?P<dsdrsc_node>.*)]')81 # vd_dSDRsc_partner_node82 self.add_leaf(cmd=ShowSdrDetail,83 src='[sdr_id][(?P<sdr_id>.*)][dsdrsc_partner_node][(?P<dsdrsc_partner_node>.*)]',84 dest='[virtual_device][(?P<sdr_id>.*)][vd_dSDRsc_partner_node][(?P<dsdrsc_partner_node>.*)]')85 # vd_primary_node186 self.add_leaf(cmd=ShowSdrDetail,87 src='[sdr_id][(?P<sdr_id>.*)][primary_node1][(?P<primary_node1>.*)]',88 dest='[virtual_device][(?P<sdr_id>.*)][vd_primary_node1][(?P<primary_node1>.*)]')89 # vd_primary_node290 self.add_leaf(cmd=ShowSdrDetail,91 src='[sdr_id][(?P<sdr_id>.*)][primary_node2][(?P<primary_node2>.*)]',92 dest='[virtual_device][(?P<sdr_id>.*)][vd_primary_node2][(?P<primary_node2>.*)]')93 # vd_mac_addr94 self.add_leaf(cmd=ShowSdrDetail,95 src='[sdr_id][(?P<sdr_id>.*)][mac_address][(?P<mac_address>.*)]',96 dest='[virtual_device][(?P<sdr_id>.*)][vd_mac_addr][(?P<mac_address>.*)]')97 # ====================98 # MembershipAttributes99 # ====================100 # vd_ms_name == node_name101 # vd_ms_type == type102 self.add_leaf(cmd=ShowSdrDetail,103 src='[sdr_id][(?P<sdr_id>.*)][membership][(?P<node_name>.*)][type][(?P<type>.*)]',104 dest='[virtual_device][(?P<sdr_id>.*)][membership][(?P<node_name>.*)][vd_ms_type][(?P<type>.*)]')105 # vd_ms_status106 self.add_leaf(cmd=ShowSdrDetail,107 src='[sdr_id][(?P<sdr_id>.*)][membership][(?P<node_name>.*)][node_status][(?P<node_status>.*)]',108 dest='[virtual_device][(?P<sdr_id>.*)][membership][(?P<node_name>.*)][vd_ms_status][(?P<node_status>.*)]')109 # vd_ms_red_state110 self.add_leaf(cmd=ShowSdrDetail,111 src='[sdr_id][(?P<sdr_id>.*)][membership][(?P<node_name>.*)][red_state][(?P<red_state>.*)]',112 dest='[virtual_device][(?P<sdr_id>.*)][membership][(?P<node_name>.*)][vd_ms_red_state][(?P<red_state>.*)]')113 # vd_ms_partner_name114 self.add_leaf(cmd=ShowSdrDetail,115 src='[sdr_id][(?P<sdr_id>.*)][membership][(?P<node_name>.*)][partner_name][(?P<partner_name>.*)]',116 dest='[virtual_device][(?P<sdr_id>.*)][membership][(?P<node_name>.*)][vd_ms_partner_name][(?P<partner_name>.*)]')117 # ==============118 # SlotAttributes119 # ==============120 # card_name121 self.add_leaf(cmd=ShowPlatform,122 src='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][name][(?P<card_name>.*)]',123 dest='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][name][(?P<card_name>.*)]')124 # state125 self.add_leaf(cmd=ShowPlatform,126 src='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][state][(?P<state>.*)]',127 dest='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][state][(?P<state>.*)]')128 # config_state129 self.add_leaf(cmd=ShowPlatform,130 src='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][config_state][(?P<config_state>.*)]',131 dest='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][config_state][(?P<config_state>.*)]')132 # redundancy_state133 self.add_leaf(cmd=ShowPlatform,134 src='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][redundancy_state][(?P<redundancy_state>.*)]',135 dest='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][redundancy_state][(?P<redundancy_state>.*)]')136 # subslot137 self.add_leaf(cmd=ShowPlatform,138 src='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][subslot][(?P<subslot>.*)]',139 dest='[slot][(?P<slot_type>.*)][(?P<slot_name>.*)][subslot][(?P<subslot>.*)]')140 # rp_config_register141 self.add_leaf(cmd=ShowVersion,142 src='[rp_config_register][(?P<rp_config_register>.*)]',143 dest='[slot][rp][rp_config_register][(?P<rp_config_register>.*)]')144 # ==============145 # Redudancy146 # ==============147 # redundancy_communication148 self.add_leaf(cmd=ShowRedundancySummary,149 src='[redundancy_communication]',150 dest='[redundancy_communication]')151 # rp_uptime152 self.add_leaf(cmd=ShowRedundancy,153 src='[node]',154 dest='[rp_uptime]',155 action=self.get_active_uptime)156 # Make Ops object157 self.make(final_call=True)...
test_platform.py
Source:test_platform.py
1# Python2import unittest3# Ats4from pyats.topology import Device5# Genie Xbu_shared6from genie.libs.ops.platform.iosxe.asr900.platform import Platform7from genie.libs.ops.platform.iosxe.asr900.tests.platform_output import PlatformOutput8from genie.libs.parser.iosxe.show_platform import ShowVersion, \9 ShowRedundancy, \10 ShowInventory, \11 ShowPlatform12from genie.libs.parser.iosxe.show_platform import Dir13from genie.libs.parser.iosxe.show_issu import ShowIssuStateDetail,\14 ShowIssuRollbackTimer15class test_platform_all(unittest.TestCase):16 def setUp(self):17 self.device = Device(name='aDevice')18 self.device.os = 'iosxe'19 self.device.mapping={}20 self.device.mapping['cli']='cli'21 # Give the device as a connection type22 # This is done in order to call the parser on the output provided23 self.device.connectionmgr.connections['cli'] = self.device24 def test_complete(self):25 f = Platform(device=self.device)26 f.maker.outputs[ShowVersion] = \27 {'':PlatformOutput.showVersion}28 f.maker.outputs[Dir] = \29 {'':PlatformOutput.showDir}30 f.maker.outputs[ShowRedundancy] = \31 {'':PlatformOutput.showRedundancy}32 f.maker.outputs[ShowInventory] = \33 {'':PlatformOutput.showInventory}34 f.maker.outputs[ShowPlatform] = \35 {'':PlatformOutput.showPlatform}36 f.maker.outputs[ShowIssuStateDetail] = \37 {'':PlatformOutput.ShowIssuStateDetail}38 f.maker.outputs[ShowIssuRollbackTimer] = \39 {'':PlatformOutput.ShowIssuRollbackTimer}40 f.learn()41 self.assertEqual(f.chassis, PlatformOutput.platform_all['chassis'])42 self.assertEqual(f.chassis_sn, PlatformOutput.platform_all['chassis_sn'])43 self.assertEqual(f.rtr_type, PlatformOutput.platform_all['rtr_type'])44 self.assertEqual(f.os, PlatformOutput.platform_all['os'])45 self.assertEqual(f.version, PlatformOutput.platform_all['version'])46 self.assertEqual(f.image, PlatformOutput.platform_all['image'])47 self.assertEqual(f.config_register, PlatformOutput.platform_all['config_register'])48 self.assertEqual(f.main_mem, PlatformOutput.platform_all['main_mem'])49 self.assertEqual(f.dir, PlatformOutput.platform_all['dir'])50 self.assertEqual(f.redundancy_mode, PlatformOutput.platform_all['redundancy_mode'])51 self.assertEqual(f.switchover_reason, PlatformOutput.platform_all['switchover_reason'])52 self.assertEqual(f.redundancy_communication, PlatformOutput.platform_all['redundancy_communication'])53 self.maxDiff = None54 self.assertEqual(f.slot, PlatformOutput.platform_all['slot'])55 def test_missing_attributes_(self):56 f = Platform(device=self.device)57 f.maker.outputs[ShowVersion] = \58 {'':PlatformOutput.showVersion}59 f.maker.outputs[Dir] = \60 {'':PlatformOutput.showDir}61 f.maker.outputs[ShowRedundancy] = \62 {'':PlatformOutput.showRedundancy}63 f.maker.outputs[ShowInventory] = \64 {'':PlatformOutput.showInventory}65 f.maker.outputs[ShowPlatform] = \66 {'':PlatformOutput.showPlatform}67 f.maker.outputs[ShowIssuStateDetail] = \68 {'':PlatformOutput.ShowIssuStateDetail}69 f.maker.outputs[ShowIssuRollbackTimer] = \70 {'':PlatformOutput.ShowIssuRollbackTimer}71 f.learn()72 with self.assertRaises(KeyError):73 # slot 'R2' doesn't exist74 platform_slot_number = (f.slot['slot']['6'])75 def test_ignored(self):76 f = Platform(device=self.device)77 g = Platform(device=self.device)78 f.maker.outputs[ShowVersion] = \79 {'':PlatformOutput.showVersion}80 f.maker.outputs[Dir] = \81 {'':PlatformOutput.showDir}82 f.maker.outputs[ShowRedundancy] = \83 {'':PlatformOutput.showRedundancy}84 f.maker.outputs[ShowInventory] = \85 {'':PlatformOutput.showInventory}86 f.maker.outputs[ShowPlatform] = \87 {'':PlatformOutput.showPlatform}88 f.maker.outputs[ShowIssuStateDetail] = \89 {'':PlatformOutput.ShowIssuStateDetail}90 f.maker.outputs[ShowIssuRollbackTimer] = \91 {'':PlatformOutput.ShowIssuRollbackTimer}92 g.maker.outputs[ShowVersion] = \93 {'':PlatformOutput.showVersion}94 g.maker.outputs[Dir] = \95 {'':PlatformOutput.showDir}96 g.maker.outputs[ShowRedundancy] = \97 {'':PlatformOutput.showRedundancy}98 g.maker.outputs[ShowInventory] = \99 {'':PlatformOutput.showInventory}100 g.maker.outputs[ShowPlatform] = \101 {'':PlatformOutput.showPlatform}102 g.maker.outputs[ShowIssuStateDetail] = \103 {'':PlatformOutput.ShowIssuStateDetail}104 g.maker.outputs[ShowIssuRollbackTimer] = \105 {'':PlatformOutput.ShowIssuRollbackTimer}106 f.learn()107 g.learn()108 f.s = 2109 self.assertNotEqual(f, g)110 # Verify diff now111 diff = f.diff(g)112 sorted_diff = str(diff)113 sorted_result = ('+s: 2')114 self.assertEqual(sorted_diff, sorted_result)115 def test_empty_parser_output(self):116 f = Platform(device=self.device)117 f.maker.outputs[ShowVersion] = \118 {'':PlatformOutput.showVersion}119 # loading empty output120 f.maker.outputs[Dir] = \121 {'':PlatformOutput.showDirEmpty}122 f.maker.outputs[ShowRedundancy] = \123 {'':PlatformOutput.showRedundancy}124 f.maker.outputs[ShowInventory] = \125 {'':PlatformOutput.showInventory}126 f.maker.outputs[ShowPlatform] = \127 {'':PlatformOutput.showPlatform}128 f.maker.outputs[ShowIssuStateDetail] = \129 {'':PlatformOutput.ShowIssuStateDetail}130 f.maker.outputs[ShowIssuRollbackTimer] = \131 {'':PlatformOutput.ShowIssuRollbackTimer}132 f.learn()133 self.maxDiff = None134 self.assertEqual(f.slot, PlatformOutput.platform_all_empty_dir['slot'])135 def test_selective_attribute(self):136 f = Platform(device=self.device, attributes=['main_mem'])137 f.maker.outputs[ShowVersion] = \138 {'':PlatformOutput.showVersion}139 f.maker.outputs[Dir] = \140 {'':PlatformOutput.showDir}141 f.maker.outputs[ShowRedundancy] = \142 {'':PlatformOutput.showRedundancy}143 f.maker.outputs[ShowInventory] = \144 {'':PlatformOutput.showInventory}145 f.maker.outputs[ShowPlatform] = \146 {'':PlatformOutput.showPlatform}147 f.maker.outputs[ShowIssuStateDetail] = \148 {'':PlatformOutput.ShowIssuStateDetail}149 f.maker.outputs[ShowIssuRollbackTimer] = \150 {'':PlatformOutput.ShowIssuRollbackTimer}151 f.learn()152 self.assertIn('896500', f.main_mem)153 self.assertNotIn('111111', f.main_mem)154if __name__ == '__main__':...
main.py
Source:main.py
1##2# main.py3# Copyright 2010, Thorbjørn Lindeijer <thorbjorn@lindeijer.nl>4#5# This file is part of the TMX Viewer example.6#7# Redistribution and use in source and binary forms, with or without8# modification, are permitted provided that the following conditions are met:9#10# 1. Redistributions of source code must retain the above copyright notice,11# this list of conditions and the following disclaimer.12#13# 2. Redistributions in binary form must reproduce the above copyright14# notice, this list of conditions and the following disclaimer in the15# documentation and/or other materials provided with the distribution.16#17# THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR18# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF19# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO20# EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,22# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS23# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,24# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR25# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF26# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.27##28import sys29sys.path.append('./../')30sys.path.append('./../libtiled')31sys.path.append('./../QtProperty')32sys.path.append('./../libqt5')33sys.path.append('./../tiled')34sys.path.append('./../plugins')35from tmxviewer import TmxViewer36from PyQt5.QtWidgets import QApplication37from PyQt5.QtCore import (38 qWarning39)40class CommandLineOptions:41 def __init__(self):42 self.showHelp = False43 self.showVersion = False44 self.fileToOpen = ''45def showHelp():46 # TODO: Make translatable47 qWarning("Usage: tmxviewer [option] [file]\n\n"48 "Options:\n"49 " -h --help : Display this help\n"50 " -v --version : Display the version")51def showVersion():52 qWarning("TMX Map Viewer" + QApplication.applicationVersion())53def parseCommandLineArguments(options):54 arguments = sys.argv55 for i in range(1, len(arguments)):56 arg = arguments[i]57 if (arg == "--help") or arg == "-h":58 options.showHelp = True59 elif (arg == "--version"60 or arg == "-v"):61 options.showVersion = True62 elif arg[0] == '-':63 qWarning("Unknown option" + arg)64 options.showHelp = True65 elif (options.fileToOpen==''):66 options.fileToOpen = arg67def main(argv):68 # Avoid performance issues with X11 engine when rendering objects69 if sys.platform == 'linux':70 QApplication.setGraphicsSystem("raster")71 a = QApplication(argv)72 a.setOrganizationDomain("mapeditor.org")73 a.setApplicationName("TmxViewer")74 a.setApplicationVersion("1.0")75 options = CommandLineOptions()76 parseCommandLineArguments(options)77 if (options.showVersion):78 showVersion()79 if (options.showHelp or (options.fileToOpen=='' and not options.showVersion)):80 showHelp()81 if (options.showVersion82 or options.showHelp83 or options.fileToOpen==''):84 return 085 w = TmxViewer()86 if (not w.viewMap(options.fileToOpen)):87 return 188 w.show()89 return a.exec()90if __name__ == '__main__':...
pastedeploylab.py
Source:pastedeploylab.py
1#! /usr/bin/python2.72#3# How to run this python server4# $ sudo apt-get install python-virtualenv5# $ cd ~/6# $ virtualenv pastedeploy-demo7# $ cp pastedeploylab.py ~/pastedeploy-demo8# $ touch pastedeploylab.ini9# $ python pastedeploylab.py10#11# Now you can access this server through curl:12# $ curl http://localhost:8080 -v13# $ curl http://127.0.0.1:8080/calc?operator=plus&operand1=12&operand2=23 -v14'''ATTENTION: the INI configure file is at the bottom of source file'''15import os16import webob17from webob import Request18from webob import Response19from paste.deploy import loadapp20from wsgiref.simple_server import make_server21#Filter22class LogFilter():23 def __init__(self, app):24 self.app = app25 pass26 def __call__(self, environ, start_response):27 print "filter:LogFilter is called."28 return self.app(environ, start_response)29 @classmethod30 def factory(cls, global_conf, **kwargs):31 print "----------- LogFilter -------------"32 print "in LogFilter.factory", global_conf, kwargs33 return LogFilter34class ShowVersion():35 def __init__(self):36 pass37 def __call__(self, environ, start_response):38 start_response("200 OK", [("Content-type", "text/plain")])39 return ["Paste Deploy LAB: Version = 1.0.0",]40 @classmethod41 def factory(cls, global_conf, **kwargs):42 print "----------- ShowVersion -------------"43 print "in ShowVersion.factory", global_conf, kwargs44 return ShowVersion()45class Calculator():46 def __init__(self):47 pass48 def __call__(self, environ, start_response):49 req = Request(environ)50 res = Response()51 res.status = "200 OK"52 res.content_type = "text/plain"53 # get operands54 operator = req.GET.get("operator", None)55 operand1 = req.GET.get("operand1", None)56 operand2 = req.GET.get("operand2", None)57 #print req.GET58 opnd1 = int(operand1)59 opnd2 = int(operand2)60 if operator == u'plus':61 opnd1 = opnd1 + opnd262 elif operator == u'minus':63 opnd1 = opnd1 - opnd264 elif operator == u'star':65 opnd1 = opnd1 * opnd266 elif operator == u'slash':67 opnd1 = opnd1 / opnd268 res.body = "%s \nRESULT= %d" % (str(req.GET) , opnd1)69 return res(environ,start_response)70 @classmethod71 def factory(cls, global_conf, **kwargs):72 print "----------- Calculator -------------"73 print "in Calculator.factory", global_conf, kwargs74 return Calculator()75if __name__ == '__main__':76 configfile = "pastedeploylab.ini"77 appname = "pdl"78 wsgi_app = loadapp("config:%s" % os.path.abspath(configfile), appname)79 server = make_server('localhost', 8080, wsgi_app)80 server.serve_forever()81 pass82# Here is the INI configure file 'pastedeploylab.py'83'''84[DEFAULT]85global-key1=yang86global-key2=kk87[composite:pdl]88use=egg:Paste#urlmap89/:root90/calc:calc91[pipeline:root]92pipeline = logrequest showversion93[pipeline:calc]94pipeline = logrequest calculator95[filter:logrequest]96username = root97password = root12398paste.filter_factory = pastedeploylab:LogFilter.factory99[app:showversion]100version = 1.0.0101paste.app_factory = pastedeploylab:ShowVersion.factory102[app:calculator]103description = This is an "+-*/" Calculator104paste.app_factory = pastedeploylab:Calculator.factory...
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!