Best Python code snippet using tempest_python
portforward.py
Source:portforward.py
...27 if ip:28 return ip[0].id29 else:30 return ['N/A']31def get_network_from_name(c, name):32 ret = c.list_networks(keyword=name)33 if len(ret) == 1:34 return ret[0]35 else:36 print "Unable to get network, got: %s" % ret37 sys.exit(1)38def get_instance_from_name(c, name, networkid=None):39 if networkid:40 ret = c.list_virtualmachines(keyword=name, name=name, networkid=networkid)41 else:42 ret = c.list_virtualmachines(keyword=name, name=name)43 if len(ret) == 1:44 return ret[0]45 else:46 print "Unable to get instance, got: %s" % ret47 sys.exit(1)48def get_id_from_address(c, address):49 try:50 res = c.list_publicipaddresses(ipaddress=address)[0]51 if res:52 return res53 else:54 print "Unable to get ip address id"55 sys.exit(0)56 except:57 print "Unable to get ip address id"58 sys.exit(1)59def print_tabulate(res, noheader=False, short=False, t='list'):60 config = read_config()61 c = conn(config)62 tbl = []63 for i in res:64 if t == 'list':65 if not i.__dict__.has_key('virtualmachinename'):66 i.__setattr__('virtualmachinename', 'None')67 if short:68 tbl.append([i.id])69 else:70 tbl.append([71 i.ipaddress,72 c.list_networks(id=i.networkid)[0].name,73 i.publicport,74 i.privateport,75 i.protocol,76 i.virtualmachinename,77 i.state,78 i.id,79 ])80 tbl = sorted(tbl, key=operator.itemgetter(0))81 if (noheader or short):82 print tabulate(tbl, tablefmt="plain")83 else:84 tbl.insert(0, ['ip', 'network', 'public port', 'private port', 'proto',85 'vmname', 'state', 'uuid'])86 print tabulate(tbl, headers="firstrow")87def main():88 config = read_config()89 c = conn(config)90 args = docopt(__doc__, version='%s %s' % (__cli_name__, __version__))91 if args['list']:92 if args['--network']:93 res = c.list_portforwardingrules(networkid=get_network_from_name(c,94 args['--network']).id)95 elif args['--pubip']:96 res = c.list_portforwardingrules(ipaddressid=get_id_from_address(c,97 args['--pubip']).id)98 else:99 res = c.list_portforwardingrules()100 elif args['add']:101 try:102 if args['--pubip']:103 ipid = get_id_from_address(c, args['--pubip']).id104 network_id = get_id_from_address(c, args['--pubip']).networkid105 elif args['--network']:106 ipid = get_default_snat_id(c, get_network_from_name(c,107 args['--network']).id)108 network_id = get_network_from_name(c, args['--network']).id109 else:110 print "Either --network or --pubip must be specified"111 sys.exit(1)112 except Exception as e:113 print "Unable to determine network or ip: %s" % e114 sys.exit(1)115 try:116 vmid = get_instance_from_name(c, args['INSTANCE'], networkid=network_id).id117 except Exception as e:118 print "Unable to find specified instance: %s" % e119 sys.exit(1)120 try:121 for f in args['--forward']:122 proto_port = f.split('/')...
fixed_network.py
Source:fixed_network.py
...15from automation.common.utils import misc as misc_utils16from automation import config17CONF = config.CONF18LOG = logging.getLogger(__name__)19def get_network_from_name(name, compute_networks_client):20 """Get a full network dict from just a network name21 :param str name: the name of the network to use22 :param NetworksClient compute_networks_client: The network client23 object to use for making the network lists api request24 :return: The full dictionary for the network in question25 :rtype: dict26 :raises InvalidConfiguration: If the name provided is invalid, the networks27 list returns a 404, there are no found networks, or the found network28 is invalid29 """30 caller = misc_utils.find_test_caller()31 if not name:32 raise exceptions.InvalidConfiguration()33 networks = compute_networks_client.list_networks()34 networks = [n for n in networks if n['label'] == name]35 # Check that a network exists, else raise an InvalidConfigurationException36 if len(networks) == 1:37 network = sorted(networks)[0]38 elif len(networks) > 1:39 msg = ("Network with name: %s had multiple matching networks in the "40 "list response: %s\n Unable to specify a single network" % (41 name, networks))42 if caller:43 msg = '(%s) %s' % (caller, msg)44 LOG.warn(msg)45 raise exceptions.InvalidConfiguration()46 else:47 msg = "Network with name: %s not found" % name48 if caller:49 msg = '(%s) %s' % (caller, msg)50 LOG.warn(msg)51 raise exceptions.InvalidConfiguration()52 # To be consistent between neutron and nova network always use name even53 # if label is used in the api response. If neither is present than then54 # the returned network is invalid.55 name = network.get('name') or network.get('label')56 if not name:57 msg = "Network found from list doesn't contain a valid name or label"58 if caller:59 msg = '(%s) %s' % (caller, msg)60 LOG.warn(msg)61 raise exceptions.InvalidConfiguration()62 network['name'] = name63 return network64def get_tenant_network(creds_provider, compute_networks_client):65 """Get a network usable by the primary tenant66 :param creds_provider: instance of credential provider67 :param compute_networks_client: compute network client. We want to have the68 compute network client so we can have use a common approach for both69 neutron and nova-network cases. If this is not an admin network70 client, set_network_kwargs might fail in case fixed_network_name71 is the network to be used, and it's not visible to the tenant72 :return a dict with 'id' and 'name' of the network73 """74 caller = misc_utils.find_test_caller()75 fixed_network_name = CONF.compute.fixed_network_name76 net_creds = creds_provider.get_primary_creds()77 network = getattr(net_creds, 'network', None)78 if not network or not network.get('name'):79 if fixed_network_name:80 msg = ('No valid network provided or created, defaulting to '81 'fixed_network_name')82 if caller:83 msg = '(%s) %s' % (caller, msg)84 LOG.debug(msg)85 try:86 network = get_network_from_name(fixed_network_name,87 compute_networks_client)88 except exceptions.InvalidConfiguration:89 network = {}90 msg = ('Found network %s available for tenant' % network)91 if caller:92 msg = '(%s) %s' % (caller, msg)93 LOG.info(msg)94 return network95def set_networks_kwarg(network, kwargs=None):96 """Set 'networks' kwargs for a server create if missing97 :param network: dict of network to be used with 'id' and 'name'98 :param kwargs: server create kwargs to be enhanced99 :return: new dict of kwargs updated to include networks100 """...
ipaddress.py
Source:ipaddress.py
...18from zone import get_zone19from docopt import docopt20__cli_name__="rbc-publicips"21from rbc_tools import __version__22def get_network_from_name(c, name):23 ret = c.list_networks(keyword=name)24 if len(ret) == 1:25 return ret[0]26 else:27 print "Unable to get network, got: %s" % ret28 sys.exit(1)29def get_id_from_address(c, address):30 try:31 res = c.list_publicipaddresses(ipaddress=address)[0]32 if res:33 return res34 else:35 print "Unable to get ip address id"36 sys.exit(0)37 except:38 print "Unable to get ip address id"39 sys.exit(1)40def print_tabulate(res, noheader=False, short=False):41 config = read_config()42 c = conn(config)43 tbl = []44 for i in res:45 if not i.__dict__.has_key('associatednetworkname'):46 if i.__dict__.has_key('vpcid'):47 i.__setattr__('associatednetworkname', "%s (VPC)" % c.list_vpcs(id=i.vpcid)[0].name)48 if i.isstaticnat:49 vmname = i.virtualmachinename50 else:51 vmname = ""52 if i.issourcenat:53 snat = "Yes"54 else:55 snat = "No"56 if short:57 tbl.append([i.name])58 else:59 tbl.append([60 i.ipaddress,61 i.zonename,62 i.associatednetworkname,63 vmname,64 snat,65 i.allocated,66 ])67 tbl = sorted(tbl, key=operator.itemgetter(2))68 if (noheader or short):69 print tabulate(tbl, tablefmt="plain")70 else:71 tbl.insert(0, ['ip', 'zone', 'network', 'staticnat', 'sourcenat', 'allocated'])72 print tabulate(tbl, headers="firstrow")73def main():74 config = read_config()75 c = conn(config)76 args = docopt(__doc__, version='%s %s' % (__cli_name__, __version__))77 if args['list']:78 res = c.list_publicipaddresses()79 elif args['allocate']:80 res = [c.associate_ipaddress(networkid=get_network_from_name(c, args['NETWORK']).id).get_result()]81 elif args['release']:82 res = [c.disassociate_ipaddress(id=get_id_from_address(c, args['IPADDRESS']).id).get_result()]83 print "Released ip address: %s" % args['IPADDRESS']84 sys.exit(0)85 if res:86 print_tabulate(res, noheader=args['--noheader'], short=args['--short'])87 else:88 print "Unable to execute command"...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!