Best Python code snippet using tox_python
config.py
Source:config.py
...622 if '\n' in env:623 env = ','.join(env.split('\n'))624 env = [env]625 return mapcat(_expand_envstr, env)626def _split_factor_expr(expr):627 partial_envs = _expand_envstr(expr)628 return [set(e.split('-')) for e in partial_envs]629def _expand_envstr(envstr):630 # split by commas not in groups631 tokens = re.split(r'((?:\{[^}]+\})+)|,', envstr)632 envlist = [''.join(g).strip()633 for k, g in itertools.groupby(tokens, key=bool) if k]634 def expand(env):635 tokens = re.split(r'\{([^}]+)\}', env)636 parts = [token.split(',') for token in tokens]637 return [''.join(variant) for variant in itertools.product(*parts)]638 return mapcat(expand, envlist)639def mapcat(f, seq):640 return list(itertools.chain.from_iterable(map(f, seq)))641class DepConfig:642 def __init__(self, name, indexserver=None):643 self.name = name644 self.indexserver = indexserver645 def __str__(self):646 if self.indexserver:647 if self.indexserver.name == "default":648 return self.name649 return ":%s:%s" % (self.indexserver.name, self.name)650 return str(self.name)651 __repr__ = __str__652class IndexServerConfig:653 def __init__(self, name, url=None):654 self.name = name655 self.url = url656#: Check value matches substitution form657#: of referencing value from other section. E.g. {[base]commands}658is_section_substitution = re.compile("{\[[^{}\s]+\]\S+?}").match659RE_ITEM_REF = re.compile(660 r'''661 (?<!\\)[{]662 (?:(?P<sub_type>[^[:{}]+):)? # optional sub_type for special rules663 (?P<substitution_value>[^{}]*) # substitution key664 [}]665 ''',666 re.VERBOSE)667class SectionReader:668 def __init__(self, section_name, cfgparser, fallbacksections=None, factors=()):669 self.section_name = section_name670 self._cfg = cfgparser671 self.fallbacksections = fallbacksections or []672 self.factors = factors673 self._subs = {}674 self._subststack = []675 def addsubstitutions(self, _posargs=None, **kw):676 self._subs.update(kw)677 if _posargs:678 self.posargs = _posargs679 def getpath(self, name, defaultpath):680 toxinidir = self._subs['toxinidir']681 path = self.getstring(name, defaultpath)682 if path is not None:683 return toxinidir.join(path, abs=True)684 def getlist(self, name, sep="\n"):685 s = self.getstring(name, None)686 if s is None:687 return []688 return [x.strip() for x in s.split(sep) if x.strip()]689 def getdict(self, name, default=None, sep="\n"):690 s = self.getstring(name, None)691 if s is None:692 return default or {}693 value = {}694 for line in s.split(sep):695 if line.strip():696 name, rest = line.split('=', 1)697 value[name.strip()] = rest.strip()698 return value699 def getbool(self, name, default=None):700 s = self.getstring(name, default)701 if not s:702 s = default703 if s is None:704 raise KeyError("no config value [%s] %s found" % (705 self.section_name, name))706 if not isinstance(s, bool):707 if s.lower() == "true":708 s = True709 elif s.lower() == "false":710 s = False711 else:712 raise tox.exception.ConfigError(713 "boolean value %r needs to be 'True' or 'False'")714 return s715 def getargvlist(self, name, default=""):716 s = self.getstring(name, default, replace=False)717 return _ArgvlistReader.getargvlist(self, s)718 def getargv(self, name, default=""):719 return self.getargvlist(name, default)[0]720 def getstring(self, name, default=None, replace=True):721 x = None722 for s in [self.section_name] + self.fallbacksections:723 try:724 x = self._cfg[s][name]725 break726 except KeyError:727 continue728 if x is None:729 x = default730 else:731 x = self._apply_factors(x)732 if replace and x and hasattr(x, 'replace'):733 self._subststack.append((self.section_name, name))734 try:735 x = self._replace(x)736 finally:737 assert self._subststack.pop() == (self.section_name, name)738 # print "getstring", self.section_name, name, "returned", repr(x)739 return x740 def _apply_factors(self, s):741 def factor_line(line):742 m = re.search(r'^([\w{}\.,-]+)\:\s+(.+)', line)743 if not m:744 return line745 expr, line = m.groups()746 if any(fs <= self.factors for fs in _split_factor_expr(expr)):747 return line748 lines = s.strip().splitlines()749 return '\n'.join(filter(None, map(factor_line, lines)))750 def _replace_env(self, match):751 env_list = self.getdict('setenv')752 match_value = match.group('substitution_value')753 if not match_value:754 raise tox.exception.ConfigError(755 'env: requires an environment variable name')756 default = None757 envkey_split = match_value.split(':', 1)758 if len(envkey_split) is 2:759 envkey, default = envkey_split760 else:...
_config.py
Source:_config.py
...400 """if handed a list, action="append" was used for -e """401 if not isinstance(env, list):402 env = [env]403 return mapcat(_expand_envstr, env)404def _split_factor_expr(expr):405 partial_envs = _expand_envstr(expr)406 return [set(e.split('-')) for e in partial_envs]407def _expand_envstr(envstr):408 # split by commas not in groups409 tokens = re.split(r'(\{[^}]+\})|,', envstr)410 envlist = [''.join(g).strip()411 for k, g in itertools.groupby(tokens, key=bool) if k]412 def expand(env):413 tokens = re.split(r'\{([^}]+)\}', env)414 parts = [token.split(',') for token in tokens]415 return [''.join(variant) for variant in itertools.product(*parts)]416 return mapcat(expand, envlist)417def mapcat(f, seq):418 return list(itertools.chain.from_iterable(map(f, seq)))419class DepConfig:420 def __init__(self, name, indexserver=None):421 self.name = name422 self.indexserver = indexserver423 def __str__(self):424 if self.indexserver:425 if self.indexserver.name == "default":426 return self.name427 return ":%s:%s" %(self.indexserver.name, self.name)428 return str(self.name)429 __repr__ = __str__430class IndexServerConfig:431 def __init__(self, name, url=None):432 self.name = name433 self.url = url434RE_ITEM_REF = re.compile(435 r'''436 (?<!\\)[{]437 (?:(?P<sub_type>[^[:{}]+):)? # optional sub_type for special rules438 (?P<substitution_value>[^{}]*) # substitution key439 [}]440 ''',441 re.VERBOSE)442class IniReader:443 def __init__(self, cfgparser, fallbacksections=None, factors=()):444 self._cfg = cfgparser445 self.fallbacksections = fallbacksections or []446 self.factors = factors447 self._subs = {}448 self._subststack = []449 def addsubstitutions(self, _posargs=None, **kw):450 self._subs.update(kw)451 if _posargs:452 self.posargs = _posargs453 def getpath(self, section, name, defaultpath):454 toxinidir = self._subs['toxinidir']455 path = self.getdefault(section, name, defaultpath)456 if path is None:457 return path458 return toxinidir.join(path, abs=True)459 def getlist(self, section, name, sep="\n"):460 s = self.getdefault(section, name, None)461 if s is None:462 return []463 return [x.strip() for x in s.split(sep) if x.strip()]464 def getdict(self, section, name, sep="\n"):465 s = self.getdefault(section, name, None)466 if s is None:467 return {}468 value = {}469 for line in s.split(sep):470 if not line.strip():471 continue472 name, rest = line.split('=', 1)473 value[name.strip()] = rest.strip()474 return value475 def getargvlist(self, section, name):476 s = self.getdefault(section, name, '', replace=False)477 #if s is None:478 # raise tox.exception.ConfigError(479 # "no command list %r defined in section [%s]" %(name, section))480 commandlist = []481 current_command = ""482 for line in s.split("\n"):483 line = line.rstrip()484 i = line.find("#")485 if i != -1:486 line = line[:i].rstrip()487 if not line:488 continue489 if line.endswith("\\"):490 current_command += " " + line[:-1]491 continue492 current_command += line493 commandlist.append(self._processcommand(current_command))494 current_command = ""495 else:496 if current_command:497 raise tox.exception.ConfigError(498 "line-continuation for [%s] %s ends nowhere" %499 (section, name))500 return commandlist501 def _processcommand(self, command):502 posargs = getattr(self, "posargs", None)503 # Iterate through each word of the command substituting as504 # appropriate to construct the new command string. This505 # string is then broken up into exec argv components using506 # shlex.507 newcommand = ""508 for word in CommandParser(command).words():509 if word == "{posargs}" or word == "[]":510 if posargs:511 newcommand += " ".join(posargs)512 continue513 elif word.startswith("{posargs:") and word.endswith("}"):514 if posargs:515 newcommand += " ".join(posargs)516 continue517 else:518 word = word[9:-1]519 new_arg = ""520 new_word = self._replace(word)521 new_word = self._replace(new_word)522 new_arg += new_word523 newcommand += new_arg524 # Construct shlex object that will not escape any values,525 # use all values as is in argv.526 shlexer = shlex.shlex(newcommand, posix=True)527 shlexer.whitespace_split = True528 shlexer.escape = ''529 shlexer.commenters = ''530 argv = list(shlexer)531 return argv532 def getargv(self, section, name, default=None, replace=True):533 command = self.getdefault(534 section, name, default=default, replace=False)535 return self._processcommand(command.strip())536 def getbool(self, section, name, default=None):537 s = self.getdefault(section, name, default)538 if not s:539 s = default540 if s is None:541 raise KeyError("no config value [%s] %s found" % (542 section, name))543 if not isinstance(s, bool):544 if s.lower() == "true":545 s = True546 elif s.lower() == "false":547 s = False548 else:549 raise tox.exception.ConfigError(550 "boolean value %r needs to be 'True' or 'False'")551 return s552 def getdefault(self, section, name, default=None, replace=True):553 x = None554 for s in [section] + self.fallbacksections:555 try:556 x = self._cfg[s][name]557 break558 except KeyError:559 continue560 if x is None:561 x = default562 else:563 x = self._apply_factors(x)564 if replace and x and hasattr(x, 'replace'):565 self._subststack.append((section, name))566 try:567 x = self._replace(x)568 finally:569 assert self._subststack.pop() == (section, name)570 #print "getdefault", section, name, "returned", repr(x)571 return x572 def _apply_factors(self, s):573 def factor_line(line):574 m = re.search(r'^([\w{}\.,-]+)\:\s+(.+)', line)575 if not m:576 return line577 expr, line = m.groups()578 if any(fs <= self.factors for fs in _split_factor_expr(expr)):579 return line580 lines = s.strip().splitlines()581 return '\n'.join(filter(None, map(factor_line, lines)))582 def _replace_env(self, match):583 match_value = match.group('substitution_value')584 if not match_value:585 raise tox.exception.ConfigError(586 'env: requires an environment variable name')587 default = None588 envkey_split = match_value.split(':', 1)589 if len(envkey_split) is 2:590 envkey, default = envkey_split591 else:592 envkey = match_value...
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!!