How to use inventory method in molecule

Best Python code snippet using molecule_python

cnos_bgp.py

Source:cnos_bgp.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: utf-8 -*-3#4# Copyright (C) 2017 Lenovo, Inc.5#6# This file is part of Ansible7#8# Ansible is free software: you can redistribute it and/or modify9# it under the terms of the GNU General Public License as published by10# the Free Software Foundation, either version 3 of the License, or11# (at your option) any later version.12#13# Ansible is distributed in the hope that it will be useful,14# but WITHOUT ANY WARRANTY; without even the implied warranty of15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the16# GNU General Public License for more details.17#18# You should have received a copy of the GNU General Public License19# along with Ansible. If not, see <http://www.gnu.org/licenses/>.20#21# Module to send BGP commands to Lenovo Switches22# Lenovo Networking23#24ANSIBLE_METADATA = {'metadata_version': '1.0',25 'status': ['preview'],26 'supported_by': 'community'}27DOCUMENTATION = '''28---29module: cnos_bgp30author: "Dave Kasberg (@dkasberg)"31short_description: Manage BGP resources and attributes on devices running Lenovo CNOS32description:33 - This module allows you to work with Border Gateway Protocol (BGP) related configurations.34 The operators used are overloaded to ensure control over switch BGP configurations. This35 module is invoked using method with asNumber as one of its arguments. The first level of36 the BGP configuration allows to set up an AS number, with the following attributes going37 into various configuration operations under the context of BGP. After passing this level,38 there are eight BGP arguments that will perform further configurations. They are bgpArg1,39 bgpArg2, bgpArg3, bgpArg4, bgpArg5, bgpArg6, bgpArg7, and bgpArg8. For more details on40 how to use these arguments, see [Overloaded Variables].41 This module uses SSH to manage network device configuration.42 The results of the operation will be placed in a directory named 'results'43 that must be created by the user in their local directory to where the playbook is run.44 For more information about this module from Lenovo and customizing it usage for your45 use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_bgp.html)46version_added: "2.3"47extends_documentation_fragment: cnos48options:49 asNum:50 description:51 - AS number52 required: Yes53 default: Null54 bgpArg1:55 description:56 - This is an overloaded bgp first argument. Usage of this argument can be found is the User Guide referenced above.57 required: Yes58 default: Null59 choices: [address-family,bestpath,bgp,cluster-id,confederation,enforce-first-as,fast-external-failover,60 graceful-restart,graceful-restart-helper,log-neighbor-changes,maxas-limit,neighbor,router-id,shutdown,61 synchronization,timers,vrf]62 bgpArg2:63 description:64 - This is an overloaded bgp second argument. Usage of this argument can be found is the User Guide referenced above.65 required: No66 default: Null67 choices: [ipv4 or ipv6, always-compare-med,compare-confed-aspath,compare-routerid,dont-compare-originator-id,tie-break-on-age,68 as-path,med,identifier,peers]69 bgpArg3:70 description:71 - This is an overloaded bgp third argument. Usage of this argument can be found is the User Guide referenced above.72 required: No73 default: Null74 choices: [aggregate-address,client-to-client,dampening,distance,maximum-paths,network,nexthop,redistribute,save,synchronization,75 ignore or multipath-relax, confed or missing-as-worst or non-deterministic or remove-recv-med or remove-send-med]76 bgpArg4:77 description:78 - This is an overloaded bgp fourth argument. Usage of this argument can be found is the User Guide referenced above.79 required: No80 default: Null81 choices: [Aggregate prefix, Reachability Half-life time,route-map, Distance for routes external,ebgp or ibgp,82 IP prefix <network>,IP prefix <network>/<length>, synchronization, Delay value, direct, ospf, static, memory]83 bgpArg5:84 description:85 - This is an overloaded bgp fifth argument. Usage of this argument can be found is the User Guide referenced above.86 required: No87 default: Null88 choices: [as-set, summary-only, Value to start reusing a route, Distance for routes internal, Supported multipath numbers,89 backdoor, map, route-map ]90 bgpArg6:91 description:92 - This is an overloaded bgp sixth argument. Usage of this argument can be found is the User Guide referenced above.93 required: No94 default: Null95 choices: [summary-only,as-set, route-map name, Value to start suppressing a route, Distance for local routes, Network mask,96 Pointer to route-map entries]97 bgpArg7:98 description:99 - This is an overloaded bgp seventh argument. Usage of this argument can be found is the User Guide referenced above.100 required: No101 default: Null102 choices: [ Maximum duration to suppress a stable route(minutes), backdoor,route-map, Name of the route map ]103 bgpArg8:104 description:105 - This is an overloaded bgp eigth argument. Usage of this argument can be found is the User Guide referenced above.106 required: No107 default: Null108 choices: [ Un-reachability Half-life time for the penalty(minutes), backdoor]109'''110EXAMPLES = '''111Tasks: The following are examples of using the module cnos_bgp. These are written in the main.yml file of the tasks directory.112---113- name: Test BGP - neighbor114 cnos_bgp:115 host: "{{ inventory_hostname }}"116 username: "{{ hostvars[inventory_hostname]['username'] }}"117 password: "{{ hostvars[inventory_hostname]['password'] }}"118 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"119 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"120 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"121 asNum: 33122 bgpArg1: "neighbor"123 bgpArg2: "10.241.107.40"124 bgpArg3: 13125 bgpArg4: "address-family"126 bgpArg5: "ipv4"127 bgpArg6: "next-hop-self"128- name: Test BGP - BFD129 cnos_bgp:130 host: "{{ inventory_hostname }}"131 username: "{{ hostvars[inventory_hostname]['username'] }}"132 password: "{{ hostvars[inventory_hostname]['password'] }}"133 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"134 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"135 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"136 asNum: 33137 bgpArg1: "neighbor"138 bgpArg2: "10.241.107.40"139 bgpArg3: 13140 bgpArg4: "bfd"141- name: Test BGP - address-family - dampening142 cnos_bgp:143 host: "{{ inventory_hostname }}"144 username: "{{ hostvars[inventory_hostname]['username'] }}"145 password: "{{ hostvars[inventory_hostname]['password'] }}"146 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"147 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"148 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"149 asNum: 33150 bgpArg1: "address-family"151 bgpArg2: "ipv4"152 bgpArg3: "dampening"153 bgpArg4: 13154 bgpArg5: 233155 bgpArg6: 333156 bgpArg7: 15157 bgpArg8: 33158- name: Test BGP - address-family - network159 cnos_bgp:160 host: "{{ inventory_hostname }}"161 username: "{{ hostvars[inventory_hostname]['username'] }}"162 password: "{{ hostvars[inventory_hostname]['password'] }}"163 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"164 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"165 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"166 asNum: 33167 bgpArg1: "address-family"168 bgpArg2: "ipv4"169 bgpArg3: "network"170 bgpArg4: "1.2.3.4/5"171 bgpArg5: "backdoor"172- name: Test BGP - bestpath - always-compare-med173 cnos_bgp:174 host: "{{ inventory_hostname }}"175 username: "{{ hostvars[inventory_hostname]['username'] }}"176 password: "{{ hostvars[inventory_hostname]['password'] }}"177 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"178 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"179 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"180 asNum: 33181 bgpArg1: "bestpath"182 bgpArg2: "always-compare-med"183- name: Test BGP - bestpath-compare-confed-aspat184 cnos_bgp:185 host: "{{ inventory_hostname }}"186 username: "{{ hostvars[inventory_hostname]['username'] }}"187 password: "{{ hostvars[inventory_hostname]['password'] }}"188 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"189 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"190 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"191 asNum: 33192 bgpArg1: "bestpath"193 bgpArg2: "compare-confed-aspath"194- name: Test BGP - bgp195 cnos_bgp:196 host: "{{ inventory_hostname }}"197 username: "{{ hostvars[inventory_hostname]['username'] }}"198 password: "{{ hostvars[inventory_hostname]['password'] }}"199 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"200 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"201 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"202 asNum: 33203 bgpArg1: "bgp"204 bgpArg2: 33205- name: Test BGP - cluster-id206 cnos_bgp:207 host: "{{ inventory_hostname }}"208 username: "{{ hostvars[inventory_hostname]['username'] }}"209 password: "{{ hostvars[inventory_hostname]['password'] }}"210 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"211 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"212 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"213 asNum: 33214 bgpArg1: "cluster-id"215 bgpArg2: "1.2.3.4"216- name: Test BGP - confederation-identifier217 cnos_bgp:218 host: "{{ inventory_hostname }}"219 username: "{{ hostvars[inventory_hostname]['username'] }}"220 password: "{{ hostvars[inventory_hostname]['password'] }}"221 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"222 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"223 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"224 asNum: 33225 bgpArg1: "confederation"226 bgpArg2: "identifier"227 bgpArg3: 333228- name: Test BGP - enforce-first-as229 cnos_bgp:230 host: "{{ inventory_hostname }}"231 username: "{{ hostvars[inventory_hostname]['username'] }}"232 password: "{{ hostvars[inventory_hostname]['password'] }}"233 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"234 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"235 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"236 asNum: 33237 bgpArg1: "enforce-first-as"238- name: Test BGP - fast-external-failover239 cnos_bgp:240 host: "{{ inventory_hostname }}"241 username: "{{ hostvars[inventory_hostname]['username'] }}"242 password: "{{ hostvars[inventory_hostname]['password'] }}"243 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"244 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"245 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"246 asNum: 33247 bgpArg1: "fast-external-failover"248- name: Test BGP - graceful-restart249 cnos_bgp:250 host: "{{ inventory_hostname }}"251 username: "{{ hostvars[inventory_hostname]['username'] }}"252 password: "{{ hostvars[inventory_hostname]['password'] }}"253 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"254 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"255 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"256 asNum: 33257 bgpArg1: "graceful-restart"258 bgpArg2: 333259- name: Test BGP - graceful-restart-helper260 cnos_bgp:261 host: "{{ inventory_hostname }}"262 username: "{{ hostvars[inventory_hostname]['username'] }}"263 password: "{{ hostvars[inventory_hostname]['password'] }}"264 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"265 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"266 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"267 asNum: 33268 bgpArg1: "graceful-restart-helper"269- name: Test BGP - maxas-limit270 cnos_bgp:271 host: "{{ inventory_hostname }}"272 username: "{{ hostvars[inventory_hostname]['username'] }}"273 password: "{{ hostvars[inventory_hostname]['password'] }}"274 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"275 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"276 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"277 asNum: 33278 bgpArg1: "maxas-limit"279 bgpArg2: 333280- name: Test BGP - neighbor281 cnos_bgp:282 host: "{{ inventory_hostname }}"283 username: "{{ hostvars[inventory_hostname]['username'] }}"284 password: "{{ hostvars[inventory_hostname]['password'] }}"285 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"286 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"287 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"288 asNum: 33289 bgpArg1: "neighbor"290 bgpArg2: "10.241.107.40"291 bgpArg3: 13292 bgpArg4: "address-family"293 bgpArg5: "ipv4"294 bgpArg6: "next-hop-self"295- name: Test BGP - router-id296 cnos_bgp:297 host: "{{ inventory_hostname }}"298 username: "{{ hostvars[inventory_hostname]['username'] }}"299 password: "{{ hostvars[inventory_hostname]['password'] }}"300 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"301 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"302 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"303 asNum: 33304 bgpArg1: "router-id"305 bgpArg2: "1.2.3.4"306- name: Test BGP - synchronization307 cnos_bgp:308 host: "{{ inventory_hostname }}"309 username: "{{ hostvars[inventory_hostname]['username'] }}"310 password: "{{ hostvars[inventory_hostname]['password'] }}"311 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"312 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"313 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"314 asNum: 33315 bgpArg1: "synchronization"316- name: Test BGP - timers317 cnos_bgp:318 host: "{{ inventory_hostname }}"319 username: "{{ hostvars[inventory_hostname]['username'] }}"320 password: "{{ hostvars[inventory_hostname]['password'] }}"321 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"322 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"323 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"324 asNum: 33325 bgpArg1: "timers"326 bgpArg2: 333327 bgpArg3: 3333328- name: Test BGP - vrf329 cnos_bgp:330 host: "{{ inventory_hostname }}"331 username: "{{ hostvars[inventory_hostname]['username'] }}"332 password: "{{ hostvars[inventory_hostname]['password'] }}"333 deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"334 enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"335 outputfile: "./results/test_bgp_{{ inventory_hostname }}_output.txt"336 asNum: 33337 bgpArg1: "vrf"338'''339RETURN = '''340msg:341 description: Success or failure message. Upon any failure, the method returns an error display string.342 returned: always343 type: string344'''345import sys346import paramiko347import time348import argparse349import socket350import array351import json352import time353import re354try:355 from ansible.module_utils import cnos356 HAS_LIB = True357except:358 HAS_LIB = False359from ansible.module_utils.basic import AnsibleModule360from collections import defaultdict361def main():362 module = AnsibleModule(363 argument_spec=dict(364 outputfile=dict(required=True),365 host=dict(required=True),366 username=dict(required=True),367 password=dict(required=True, no_log=True),368 enablePassword=dict(required=False, no_log=True),369 deviceType=dict(required=True),370 bgpArg1=dict(required=True),371 bgpArg2=dict(required=False),372 bgpArg3=dict(required=False),373 bgpArg4=dict(required=False),374 bgpArg5=dict(required=False),375 bgpArg6=dict(required=False),376 bgpArg7=dict(required=False),377 bgpArg8=dict(required=False),378 asNum=dict(required=True),),379 supports_check_mode=False)380 username = module.params['username']381 password = module.params['password']382 enablePassword = module.params['enablePassword']383 bgpArg1 = module.params['bgpArg1']384 bgpArg2 = module.params['bgpArg2']385 bgpArg3 = module.params['bgpArg3']386 bgpArg4 = module.params['bgpArg4']387 bgpArg5 = module.params['bgpArg5']388 bgpArg6 = module.params['bgpArg6']389 bgpArg7 = module.params['bgpArg7']390 bgpArg8 = module.params['bgpArg8']391 asNum = module.params['asNum']392 outputfile = module.params['outputfile']393 hostIP = module.params['host']394 deviceType = module.params['deviceType']395 output = ""396 # Create instance of SSHClient object397 remote_conn_pre = paramiko.SSHClient()398 # Automatically add untrusted hosts (make sure okay for security policy in your environment)399 remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())400 # initiate SSH connection with the switch401 remote_conn_pre.connect(hostIP, username=username, password=password)402 time.sleep(2)403 # Use invoke_shell to establish an 'interactive session'404 remote_conn = remote_conn_pre.invoke_shell()405 time.sleep(2)406 # Enable and enter configure terminal then send command407 output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn)408 output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn)409 # Make terminal length = 0410 output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn)411 # Go to config mode412 output = output + cnos.waitForDeviceResponse("configure d\n", "(config)#", 2, remote_conn)413 # Send the CLi command414 output = output + cnos.routerConfig(remote_conn, deviceType, "(config)#", 2, "bgp", asNum,415 bgpArg1, bgpArg2, bgpArg3, bgpArg4, bgpArg5, bgpArg6, bgpArg7, bgpArg8)416 # Save it into the file417 file = open(outputfile, "a")418 file.write(output)419 file.close()420 # Logic to check when changes occur or not421 errorMsg = cnos.checkOutputForError(output)422 if(errorMsg is None):423 module.exit_json(changed=True, msg="BGP configurations accomplished")424 else:425 module.fail_json(msg=errorMsg)426if __name__ == '__main__':...

Full Screen

Full Screen

game_inventory_test.py

Source:game_inventory_test.py Github

copy

Full Screen

...7# This file contains tests to check if your code is working correctly.8# Run this file to check whether you have a good solution!9# (note: passing all tests does not mean that your code is correct)10class GameInventoryTests(unittest.TestCase):11 def test_display_inventory(self):12 _inventory = {'rope': 1, 'torch': 6}13 expected_output = \14"""rope: 115torch: 6"""16 saved_stdout = sys.stdout17 try:18 mocked_stdout = StringIO()19 sys.stdout = mocked_stdout20 display_inventory(_inventory)21 self.assertEqual(mocked_stdout.getvalue().strip(), expected_output)22 finally:23 sys.stdout = saved_stdout24 def test_print_table(self):25 _inventory = {'rope': 1, 'torch': 6}26 expected_output = \27"""-----------------28item name | count29-----------------30 rope | 131 torch | 632-----------------"""33 saved_stdout = sys.stdout34 try:35 mocked_stdout = StringIO()36 sys.stdout = mocked_stdout37 print_table(_inventory)38 self.assertEqual(mocked_stdout.getvalue().strip(), expected_output)39 finally:40 sys.stdout = saved_stdout41 def test_print_table_count_asc(self):42 _inventory = {'rope': 1, 'torch': 6, 'blanket': 3}43 expected_output = \44"""-----------------45item name | count46-----------------47 rope | 148 blanket | 349 torch | 650-----------------"""51 saved_stdout = sys.stdout52 try:53 mocked_stdout = StringIO()54 sys.stdout = mocked_stdout55 print_table(_inventory, "count,asc")56 self.assertEqual(mocked_stdout.getvalue().strip(), expected_output)57 finally:58 sys.stdout = saved_stdout59 def test_print_table_count_desc(self):60 _inventory = {'rope': 1, 'torch': 6, 'blanket': 3}61 expected_output = \62"""-----------------63item name | count64-----------------65 torch | 666 blanket | 367 rope | 168-----------------"""69 saved_stdout = sys.stdout70 try:71 mocked_stdout = StringIO()72 sys.stdout = mocked_stdout73 print_table(_inventory, "count,desc")74 self.assertEqual(mocked_stdout.getvalue().strip(), expected_output)75 finally:76 sys.stdout = saved_stdout77 def test_add_single_item(self):78 _inventory = {'rope': 1, 'torch': 6}79 added_items = ['torch']80 add_to_inventory(_inventory, added_items)81 self.assertDictEqual(_inventory, {'rope': 1, 'torch': 7})82 def test_add_multiple_items(self):83 _inventory = {'rope': 1, 'torch': 6}84 added_items = ['torch', 'torch', 'torch']85 add_to_inventory(_inventory, added_items)86 self.assertDictEqual(_inventory, {'rope': 1, 'torch': 9})87 def test_remove_single_item(self):88 _inventory = {'rope': 1, 'torch': 6}89 removed_items = ['rope']90 remove_from_inventory(_inventory, removed_items)91 self.assertDictEqual(_inventory, {'torch': 6})92 def test_remove_multiple_items(self):93 _inventory = {'rope': 1, 'torch': 6}94 removed_items = ['torch', 'torch', 'torch']95 remove_from_inventory(_inventory, removed_items)96 self.assertDictEqual(_inventory, {'rope': 1, 'torch': 3})97 def test_import_inventory(self):98 _inventory = {'rope': 1, 'torch': 6}99 import_inventory(_inventory, "test_inventory.csv")100 self.assertDictEqual(_inventory, {101 'rope': 1,102 'torch': 6,103 'battleaxe': 1,104 'dagger': 3,105 'gold coin': 1106 })107 def test_import_inventory_catches_filenotfounderror(self):108 _inventory = {'rope': 1, 'torch': 6}109 expected_output = "File 'no_such_file.csv' not found!"110 saved_stdout = sys.stdout111 try:112 mocked_stdout = StringIO()113 sys.stdout = mocked_stdout114 import_inventory(_inventory, "no_such_file.csv")115 self.assertEqual(mocked_stdout.getvalue().strip(), expected_output)116 finally:117 sys.stdout = saved_stdout118 def test_export_inventory(self):119 export_inventory({'dagger': 3, 'gold coin': 1, "battleaxe": 1},120 "test_inventory_export.csv")121 with open("test_inventory_export.csv", newline='') as csvfile:122 expected = ["dagger", "gold coin", "battleaxe", "dagger", "dagger"]123 expected.sort()124 reader = csv.reader(csvfile, delimiter=',', quotechar='|')125 for row in reader:126 row.sort()127 self.assertListEqual(expected, row)128 def test_export_inventory_catches_permissionerror(self):129 _inventory = {'rope': 1, 'torch': 6}130 expected_output = "You don't have permission creating file '/nopermission.csv'!"131 saved_stdout = sys.stdout132 try:133 mocked_stdout = StringIO()134 sys.stdout = mocked_stdout135 export_inventory(_inventory, "/nopermission.csv")136 self.assertEqual(mocked_stdout.getvalue().strip(), expected_output)137 finally:138 sys.stdout = saved_stdout139def main():140 unittest.main()141if __name__ == '__main__':...

Full Screen

Full Screen

game_inventory.py

Source:game_inventory.py Github

copy

Full Screen

1# This is the file where you must work.2# Write code in the functions (and create new functions) so that they work3# according to the requirements.4def display_inventory(inventory):5 """Display the contents of the inventory in a simple way."""6 if inventory:7 for key in inventory:8 print(str(key) + ": " + str(inventory[key]))9def add_to_inventory(inventory, added_items):10 """Add to the inventory dictionary a list of items from added_items."""11 added_items = make_it_a_list(added_items)12 for item in added_items:13 if item not in inventory:14 inventory[item] = 115 else:16 inventory[item] = inventory[item] + 117 return inventory18def remove_from_inventory(inventory, removed_items):19 """Remove from the inventory dictionary a list of items from removed_items."""20 removed_items = make_it_a_list(removed_items)21 for item in removed_items:22 if item in inventory:23 inventory[item] = inventory[item] - 124 if inventory[item] < 1:25 del inventory[item]26 return inventory27def make_it_a_list(single_item_string):28 if type(single_item_string) is not list:29 single_item_string = [single_item_string]30 return single_item_string31def print_table(inventory, order=""):32 """33 Display the contents of the inventory in an ordered, well-organized table34 with each column right-aligned.35 """36 the_longest_key, the_longest_value = number_of_whitespaces(inventory)37 number_of_dashes = the_longest_key + len(" | ") + the_longest_value38 print_table_header(number_of_dashes, the_longest_key, the_longest_value)39 if order.lower() == "count,desc":40 inventory = set_values_in_order(inventory, True)41 elif order.lower() == "count,asc":42 inventory = set_values_in_order(inventory, False)43 for item in inventory:44 print(45 item.rjust(the_longest_key)46 + " | "47 + str(inventory[item]).rjust(the_longest_value)48 )49 print("-" * number_of_dashes)50def print_table_header(number_of_dashes, the_longest_key, the_longest_value):51 print("-" * number_of_dashes)52 print(53 "item name".rjust(the_longest_key)54 + " | "55 + "count".rjust(the_longest_value)56 )57 print("-" * number_of_dashes)58def number_of_whitespaces(inventory):59 the_longest_key = len("item name")60 the_longest_value = len("count")61 for key in inventory:62 if len(key) > the_longest_key:63 the_longest_key = len(key)64 if len(str(inventory[key])) > the_longest_value:65 the_longest_value = len(str(inventory[key]))66 return the_longest_key, the_longest_value67def set_values_in_order(inventory, do_reverse):68 return {69 key: value for key, value70 in sorted(inventory.items(), key=lambda x: x[1], reverse=do_reverse)71 }72def import_inventory(inventory, filename="import_inventory.csv"):73 """Import new inventory items from a CSV file."""74 items_to_add = []75 try:76 with open(filename, "r", encoding="utf-8") as new_items:77 for line in new_items:78 line = line.replace(", ", ",")79 line = line.split("\n")[0]80 items_to_add = items_to_add + line.split(",")81 except FileNotFoundError:82 print(f"File '{filename}' not found!")83 return84 add_to_inventory(inventory, items_to_add)85 return inventory86def export_inventory(inventory, filename="export_inventory.csv"):87 """Export the inventory into a CSV file."""88 if inventory:89 write_it = ""90 for key, value in inventory.items():91 write_it += ("," + key) * value92 try:93 with open(filename, "w", encoding="utf-8") as save_inventory:94 save_inventory.write(write_it[1:])95 except PermissionError:96 print(f"You don't have permission creating file '{filename}'!")97 return98if __name__ == "__main__":99 inventory = {"raz": 1, "dwa": 2, "osiem": 11, "dwadzieścia": 18}100 add_to_inventory(101 inventory,102 ["raz", "dwa", "trzy", "trzy", "cztery", "trzy", "trzy"]103 )104 remove_from_inventory(inventory, "pięć")105 print_table(inventory, "")106 import_inventory(inventory, "items.csv")107 print_table(inventory, "count,desc")...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run molecule automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful