Best Python code snippet using tempest_python
openstack.py
Source:openstack.py  
...41            if external is not None:42                return network.get('id')43        return None44    def _check_router_external_gateway(self):45        routers = self.client.list_routers().get('routers')46        for router in routers:47            external = router.get('external_gateway_info')48            if external is not None:49                return router.get('id')50        return None51    def create(self, name, cidr, **kargs):52        admin_state_up = kargs.pop('admin_state_up', True)53        ip_version = kargs.pop('ip_version', 4)54        # step1: create network with empty name and admin_state_up55        network = {'name': '',56                   'admin_state_up': admin_state_up}57        net = self.client.create_network({'network': network}).get('network')58        network_id = net['id']59        # step 2: create subnet60        sub = {"network_id": network_id,61               "ip_version": ip_version,62               "cidr": cidr,63               "name": name}64        subnet = self.client.create_subnet({'subnet': sub}).get('subnet')65        result = {'name': subnet['name'],66                  'description': None,67                  'id': subnet['id'],68                  'cidr': subnet['cidr'],69                  'cloud': PROVIDER,70                  'gateway_ip': subnet['gateway_ip'],71                  'security_group': None,72                  'allocation_pools': subnet['allocation_pools'],73                  'dns_nameservers': subnet['dns_nameservers']74                  }75        return result76    def show(self, subnet_id):77        subnet = self.client.show_subnet(subnet_id).get('subnet')78        result = {'name': subnet['name'],79                  'description': None,80                  'id': subnet['id'],81                  'cidr': subnet['cidr'],82                  'cloud': PROVIDER,83                  'gateway': subnet['gateway_ip'],84                  'security_group': None,85                  'allocation_pools': subnet['allocation_pools'],86                  'dns_nameservers': subnet['dns_nameservers']87                  }88        return result89    def list(self, **search_opts):90        subnets = self.client.list_subnets(**search_opts).get('subnets')91        result = []92        for subnet in subnets:93            sub = {'name': subnet['name'],94                   'description': None,95                   'id': subnet['id'],96                   'cidr': subnet['cidr'],97                   'cloud': PROVIDER,98                   'gateway': subnet['gateway_ip'],99                   'security_group': None,100                   'allocation_pools': subnet['allocation_pools'],101                   'dns_nameservers': subnet['dns_nameservers']102                   }103            result.append(sub)104        return result105    def update(self, network_id, network):106        # Now we can't update network, I'm trying again107        return None108    def delete(self, network_id):109        return self.client.delete_network(network_id)110    def connect_external_net(self, subnet_id):111        router_id = self._check_router_external_gateway()112        if router_id is None:113            network_id = self._check_external_network()114            if network_id is None:115                raise Exception()116            router = {117                "name": "default",118                "external_gateway_info": {119                    "network_id": "{}".format(network_id)120                }121            }122            router = self.create_router({'router': router})123        body = {124            "subnet_id": "{}".format(subnet_id)125        }126        return self.client.add_interface_router(router_id, body)127    def disconnect_external_net(self, network_id):128        #just detach all connect to router have external_gateway129        pass130    def allocate_public_ip(self):131        external_net = self._check_external_network()132        if external_net:133            create_dict = {'floating_network_id': external_net,134                           'tenant_id': self.network_quota.tenant_id}135            self.client.create_floatingip({'floatingip': create_dict})136        else:137            return False138        return True139    def list_public_ip(self, **search_opts):140        """141        :param search_opts:142        :return: list PublicIP143        """144        result = self.client.list_floatingips(**search_opts)145        ips = result.get('floatingips')146        return_format = []147        for ip in ips:148            return_format.append({149                'public_ip': ip.get('floating_ip_address'),150                'id': ip.get('id')151            })152        return return_format153    def release_public_ip(self, public_ip_id):154        self.client.delete_floatingip(public_ip_id)155        return True156class OpenstackQuota(BaseQuota):157    """docstring for OpenstackQuota"""158    def __init__(self, client, tenant_id=None, limit=None):159        super(OpenstackQuota, self).__init__()160        self.client = client161        self.tenant_id = tenant_id162        self.limit = limit163        self._setup()164    def _setup(self):165        if self.tenant_id is None:166            self.tenant_id = \167                self.client.get_quotas_tenant().get('tenant')['tenant_id']168        if self.limit is None:169            self.limit = self.client.show_quota(self.tenant_id).get('quota')170    def get_networks(self):171        subnets = self.client.list_subnets().get('subnets')172        list_cidrs = []173        for subnet in subnets:174            list_cidrs.append({175                "net_id": subnet['id'],176                "cidr": "{}".format(subnet['cidr']),177                "allocation_pools": subnet['allocation_pools']178            })179        networks = {180            "max": self.limit['network'],181            "used": len(list_cidrs),182            "list_cidrs": list_cidrs,183            "VPCs": None184        }185        return networks186    def get_security_groups(self):187        list_security_groups = self.client.list_security_groups(188            tenant_id=self.tenant_id).get('security_groups')189        list_scgs = []190        for scg in list_security_groups:191            list_scgs.append({192                "security_group_id": scg['id'],193                "rules_max": self.limit['security_group_rule'],194                "rules_used": len(scg['security_group_rules']),195                "list_rules": scg['security_group_rules']196            })197        security_groups = {198            "max": self.limit['security_group'],199            "used": len(list_security_groups),200            "list_security_groups": list_scgs201        }202        return security_groups203    def get_floating_ips(self):204        ips = self.client.list_floatingips().get('floatingips')205        list_ips = []206        for ip in ips:207            list_ips.append(ip['floating_ip_address'])208        floating_ips = {209            "max": self.limit['security_group'],210            "used": len(list_ips),211            "list_floating_ips": list_ips212        }213        return floating_ips214    def get_routers(self):215        rts = self.client.list_routers().get('routers')216        list_routers = []217        for router in rts:218            list_routers.append({219                "router_id": router['id'],220                "is_gateway": True221            })222        routers = {223            "max": self.limit['router'],224            "used": len(list_routers),225            "list_routers": list_routers226        }227        return routers228    def get_internet_gateways(self):229        routers = self.client.list_routers().get('routers')230        internet_gateways = []231        for router in routers:232            egi = router.get('external_gateway_info', None)233            if egi is not None:234                internet_gateways.append({235                    'internet_gateway_id': router['id']236                })...pyredes.py
Source:pyredes.py  
1import json2import re3import os4def mask_to_decimal(mask: int) -> str:5    mask_binary = []6    mask_tmp = ""7    for i in range(1, 33):8        mask_tmp += "1" if i <= mask else "0"9        if i % 8 == 0:10            mask_binary.append(mask_tmp[i - 8: i])11    return ".".join([str(int(octeto, 2)) for octeto in mask_binary])12class Routing:13    # ToDo14    pass15class Router:16    # ToDo17    def __init__(self):18        pass19class Red:20    # ToDo21    def __init__(self):22        self.routers = {}23class PyRedes:24    def __init__(self):25        self.path_file = os.path.dirname(os.path.abspath(__file__))26        self.red = Red()27    def start(self):28        while True:29            print(" Pyredes by https://github.com/nemiass ".center(60, "*"))30            print("[1] - generar modelo\n[2] - enrrutar\n[3] - <salir>")31            opcion = input(">>>").strip()32            if opcion == "1":33                self.generar_modelo()34            elif opcion == "2":35                self.enrrutar()36            elif opcion == "3":37                break38            input("[enter continuar...]")39            # limpiar pantalla para windows40            os.system("cls")41    def generar_modelo(self):42        while True:43            print("cantidad de routers:")44            num_routers = input(">>>").strip()45            if re.match('[0-9]', num_routers):46                break47        if os.path.exists(f"{self.path_file}/config.json"):48            print("El archivo ya existe, ¡¡desea reemplazarlo!! [s/n]")49            opcion = input(">>>").strip()50            if opcion == "s":51                self.generar_model_json(int(num_routers))52            elif opcion == "n":53                print("`config.json` no fue modificado!")54            else:55                print("niguna opción seleccionada, regresando al inicio...")56                return57        else:58            self.generar_model_json(int(num_routers))59    def generar_model_json(self, n_r: int):60        model_json = {"Conf.Genrales": {61            "Interfaces": {62                "interfaz-lan": "gigabitEthernet",63                "interfaz-wan": "serial"64            }65        }}66        list_routers = []67        indices = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"68        with open(f"{self.path_file}/config.json", "w", encoding="utf-8") as f:69            for i in range(n_r):70                model = {71                    f"{indices[i]}": {72                        "Area": "",73                        "Vecinos": "",74                        "Interfaces": {75                            "lan": {76                                "ip-red": "",77                                "puertos:": [78                                    ""79                                ]80                            },81                            "wan": {82                                "ip-red": "",83                                "puertos": [84                                    ""85                                ]86                            }87                        }88                    }89                }90                list_routers.append(model)91            model_json["Routers"] = list_routers92            json.dump(model_json, f, indent=4)93        print("Modelos generados correctamente `config.json`")94    def load_json_model(self):95        if os.path.exists(f"{self.path_file}/config.json"):96            with open(f"{self.path_file}/config.json", "r", encoding="utf-8") as f:97                json_model = json.load(f)98                print(json_model)99                # ToDo100                return 1101        print("No existe el archivo `config.json`")102        return 0103    def enrrutar(self):104        if not self.load_json_model():105            return106        while True:107            print("Enrrutamiento:")108            print("[1] - estatico\n[2] - rip v1\n[3] - ospf\n[4] - eigrp\n[5] - bgp\n[6] - <salir>")109            opcion = input(">>>").strip()110            if opcion == "1":111                pass112            elif opcion == "2":113                pass114            elif opcion == "3":115                pass116            elif opcion == "4":117                pass118            elif opcion == "5":119                pass120            elif opcion == "6":121                break122            else:123                break124if __name__ == "__main__":125    pr = PyRedes()...test007_list_router.py
Source:test007_list_router.py  
2    def list_router(self, conn):3        try:4            print("\r\n---List Routers---------")5            print("List of Routers:")6            # list_routers(filters=None)7            routers = conn.list_routers()8            for router in routers:9                print(router.name)10        except Exception as e:
...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!!
