Best Python code snippet using pyresttest_python
bs.py
Source:bs.py  
...57    def __yaml(self):58        serialized = yaml.dump(self)59        return serialized60    def __get_module_root_dir(self, module: Module | str, env: str) -> str:61        module = self.__get_module(module)62        root_dir = self.__get_root_dir(module=module, env=env)63        return root_dir + '/' \64               + (module.root_dir_name or module.name)65    def __get_module_ssh_keys_dir(self, module: Module | str, env: str) -> str:66        keys_dir = module.ssh_keys_dir if module.ssh_keys_dir is not None else self.ssh_keys_dir67        return self.__get_property_for_env(keys_dir, env)68    def __get_root_dir(self, module: Module | str, env: str) -> str:69        keys_dir = module.root_dir if module.root_dir is not None else self.root_dir70        p = self.__get_property_for_env(keys_dir, env)71        p = os.path.expanduser(p)72        return p73    def __get_module_env_variables(self, module: Module | str, env: str) -> dict:74        module = self.__get_module(module)75        variables = os.environ.copy()76        variables['BS_ROOT_DIR'] = self.__get_module_root_dir(module=module, env=env)77        variables['BS_SSH_KEYS_DIR'] = self.__get_module_ssh_keys_dir(module=module, env=env)78        variables['BS_ENV'] = env79        for _module in self.modules:80            variables['BS_' + _module.name.upper().replace('-', '_') + "_MODULE"] = self.__get_service_name(81                _module,82                env83            )84        try:85            bootstrap_variables = self.variables[env]86        except KeyError:87            bootstrap_variables = {}88        try:89            module_variables = module.variables[env]90        except KeyError:91            module_variables = {}92        variables.update(bootstrap_variables)93        variables.update(module_variables)94        return variables95    def __get_stack_name(self, module: Module, env: str) -> str:96        return '{0}-{1}-{2}'.format(self.name, env, module.name)97    def down_module(self, module: Module | str, env: str | None = None):98        module = self.__get_module(module)99        env = env or self.default_env100        variables = self.__get_module_env_variables(module=module, env=env)101        os.chdir(self.__get_module_root_dir(module=module, env=env))102        command = [103            'docker-compose',104        ]105        command += [106            '-p',107            self.__get_stack_name(module, env),108            'down',109            '--remove-orphans'110        ]111        subprocess.run(command, env=variables)112    @staticmethod113    def __get_property_for_env(var: str | dict | None, env: str):114        if type(var) is dict:115            return var[env] if env in var else None116        return var117    def __get_module(self, module: str | Module) -> Module:118        if isinstance(module, Bootstrap.Module):119            return module120        for _module in self.modules:121            if _module.name == module:122                return _module123        raise Exception('Module ' + module + ' not found.')124    def __get_service_name(self, module: Module, env: str) -> str:125        return self.name + '-' + env + '-' + module.name126    def __assert_service_running(127            self, module: Module | str,128            env: str | None = None,129            service: str | None = None130    ):131        module = self.__get_module(module)132        env = env or self.default_env133        res = self.exec(module=module, service=service, env=env, command="/bin/sh -c 'echo OK'")134        if res.returncode != 0:135            Bootstrap.Console.log(service.upper() + ' is not running.', Bootstrap.Console.WARNING)136            answer = input('Run ' + module.name.upper() + ' to continue? (y|yes)').lower()137            if answer == 'yes' or answer == 'y':138                self.up_module(module=module, env=env)139    # region Public methods140    def up(141            self,142            env: str | None = None,143            rebuild: bool | str = False,144    ):145        rebuild = True if rebuild == 'true' or rebuild else False146        env = env or self.default_env147        for module in self.modules:148            self.up_module(module=module, rebuild=rebuild, env=env)149    def down(150            self,151            env: str | None = None,152    ):153        for module in self.modules:154            self.down_module(module=module, env=env)155    def up_module(156            self,157            module: Module | str,158            env: str | None = None,159            rebuild: bool | str = False,160            repo_branch: str | None = None161    ):162        rebuild = True if rebuild == 'true' or rebuild else False163        module = self.__get_module(module)164        env = env or self.default_env165        variables = self.__get_module_env_variables(module=module, env=env)166        module_root_dir = self.__get_module_root_dir(module=module, env=env)167        Bootstrap.Console.log('Module directory: ' + module_root_dir)168        Path(module_root_dir).mkdir(parents=True, exist_ok=True)169        os.chdir(module_root_dir)170        if not module.repo:171            Bootstrap.Console.log('Module repo not defined', Bootstrap.Console.FAIL)172            return173        if isinstance(module.repo, str):174            repo_src = module.repo175        else:176            repo_src = module.repo.get('src')177            repo_branch = module.repo.get('branch', repo_branch) if repo_branch is None else repo_branch178        check_first_clone_proc = subprocess.run(['git', 'rev-parse', '--is-inside-work-tree'], capture_output=True)179        if check_first_clone_proc.returncode != 0:180            pull_command_proc = subprocess.run(['git', 'clone', repo_src, '.'])181            if pull_command_proc.returncode != 0:182                Bootstrap.Console.log("Failed cloning from remote git repository!", Bootstrap.Console.WARNING)183                return184        if repo_branch:185            checkout_proc = subprocess.run(['git', 'checkout', repo_branch])186            if checkout_proc.returncode != 0:187                Bootstrap.Console.log("Checkout failed!", Bootstrap.Console.WARNING)188        command = [189            'docker-compose',190            '-p',191            self.__get_stack_name(module, env),192            'up', '-d', '--force-recreate', '--wait', '--remove-orphans'193        ]194        if rebuild:195            Bootstrap.Console.log('Rebuild containers', Bootstrap.Console.OKCYAN)196            command += ['--build']197        res = subprocess.run(command, env=variables)198        if res.returncode == 0:199            Bootstrap.Console.log(module.name.upper() + ': Running up scripts...', Bootstrap.Console.UNDERLINE)200            self.exec_module_commands(201                module,202                on='up',203                env=env,204                auto_scripts=True205            )206    def exec_module_commands(207            self,208            module: Module | str,209            on: str,210            env: str,211            auto_scripts: bool = True,212    ):213        module = self.__get_module(module)214        for command in module.commands:215            if command.on == on:216                self.exec_module_command(module=module, command=command, env=env, auto_scripts=auto_scripts)217    def exec_module_command(218            self,219            module: Module | str,220            command: Module.Command,221            env: str | None = None,222            auto_scripts: bool = True223    ):224        module = self.__get_module(module)225        command_list = [command.command] if isinstance(command.command, str) else command.command226        for single_command in command_list:227            self.__assert_service_running(228                module=command.module or module,229                env=env,230                service=command.service231            )232            self.exec(233                module=command.module or module,234                service=command.service,235                command=single_command,236                env=env237            )238            if auto_scripts:239                self.exec_module_commands(240                    module=command.module or module,241                    on='after-command-exec',242                    env=env,243                    auto_scripts=False244                )245    def exec(self, module: Module | str, service: str, command: str, env: str | None = None):246        env = env or self.default_env247        module = self.__get_module(module)248        os.chdir(self.__get_module_root_dir(module=module, env=env))249        variables = self.__get_module_env_variables(module=module, env=env)250        _command_str = (251            'docker-compose -p{0} exec {1} {2}'.format(252                self.__get_stack_name(module, env),253                service,254                command255            )256        ).format(**variables)257        _command = shlex.split(_command_str)258        return subprocess.run(_command, env=variables)259    @staticmethod260    def init_from_yaml(yaml_name: str = 'bs.yaml'):261        Bootstrap.__branding()...runtime.py
Source:runtime.py  
1import builtins2import sys as __sys3#----------------------------------------------------------------------------------------------------------------------------------#4def __get_module() -> object:5    """6    Returns the runtime module's object instance7    """8    return __sys.modules[__name__]9def __has_variable(variable_name: str) -> bool:10    """11    Returns true if the runtime module has the requested variable name defined.12    Is served out via the custom __getattr__ function as has_x() method names13    """14    module = __get_module()15    defined = hasattr(module, variable_name)16    found = False17    if defined:18        attr = getattr(module, variable_name)19        found = attr != None20    return found21def __get_variable(variable_name: str) -> object:22    """23    Returns the requested variable from the runtime module if it exists.24    Otherwise returning NoneType25    """26    if not __has_variable(variable_name):27        return None28    module = __get_module()29    return getattr(module, variable_name)30def __getattr__(key: str) -> object:31    """32    Custom get attribute handler for allowing access to the has_x method names33    of the engine runtime module. Also exposes the builtins module34    for the legacy Panda3d builtins provided by the ShowBase instance35    """36    result = None37    is_has_method = key.startswith('has_')38    is_get_method = key.startswith('get_')39    if len(key) > 4:40        variable_name = key[4:]41    else:42        variable_name = key...__init__.py
Source:__init__.py  
...21try:22    from _dpsim import Interface23finally:24    from .Interface import Interface25def __get_module(parts):26    full_name = ".".join(parts)27    name = parts[-1]28    if full_name in sys.modules:29        return sys.modules[full_name]30    else:31        module = types.ModuleType(name, 'Module created to provide a context for tests')32        sys.modules[full_name] = module33        parent = ".".join(parts[:-1])34        if parent == "":35            globals()[name] = module36        else:37            if parent in sys.modules:38                parent_module = sys.modules[parent]39            else:40                parent_module = __get_module(parts[:-1])41            parent_module.__dict__[name] = module42        return module43# Register aliases44for ctor in [x for x in _dpsim.__dict__ if re.match("^_(dp|emt|signal)", x) ]:45    parts = ctor.split("_")46    module_parts = parts[1:-1]47    name = parts[-1]48    module = __get_module(module_parts)49    module.__dict__[name] = _dpsim.__dict__[ctor]50__all__ = [51    'Component',52    'Interface',53    'Simulation',54    'SystemTopology',55    'Logger',56    'load_cim',...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!!
