How to use add_testenv_attribute_obj method in tox

Best Python code snippet using tox_python

config.py

Source:config.py Github

copy

Full Screen

...52 Any postprocess function must return a value which will then be set53 as the final value in the testenv section.54 """55 self._testenv_attr.append(VenvAttribute(name, type, default, help, postprocess))56 def add_testenv_attribute_obj(self, obj):57 """ add an ini-file variable as an object.58 This works as the ``add_testenv_attribute`` function but expects59 "name", "type", "help", and "postprocess" attributes on the object.60 """61 assert hasattr(obj, "name")62 assert hasattr(obj, "type")63 assert hasattr(obj, "help")64 assert hasattr(obj, "postprocess")65 self._testenv_attr.append(obj)66 def _parse_args(self, args):67 return self.argparser.parse_args(args)68 def _format_help(self):69 return self.argparser.format_help()70class VenvAttribute:71 def __init__(self, name, type, default, help, postprocess):72 self.name = name73 self.type = type74 self.default = default75 self.help = help76 self.postprocess = postprocess77class DepOption:78 name = "deps"79 type = "line-list"80 help = "each line specifies a dependency in pip/setuptools format."81 default = ()82 def postprocess(self, testenv_config, value):83 deps = []84 config = testenv_config.config85 for depline in value:86 m = re.match(r":(\w+):\s*(\S+)", depline)87 if m:88 iname, name = m.groups()89 ixserver = config.indexserver[iname]90 else:91 name = depline.strip()92 ixserver = None93 name = self._replace_forced_dep(name, config)94 deps.append(DepConfig(name, ixserver))95 return deps96 def _replace_forced_dep(self, name, config):97 """98 Override the given dependency config name taking --force-dep-version99 option into account.100 :param name: dep config, for example ["pkg==1.0", "other==2.0"].101 :param config: Config instance102 :return: the new dependency that should be used for virtual environments103 """104 if not config.option.force_dep:105 return name106 for forced_dep in config.option.force_dep:107 if self._is_same_dep(forced_dep, name):108 return forced_dep109 return name110 @classmethod111 def _is_same_dep(cls, dep1, dep2):112 """113 Returns True if both dependency definitions refer to the114 same package, even if versions differ.115 """116 dep1_name = pkg_resources.Requirement.parse(dep1).project_name117 dep2_name = pkg_resources.Requirement.parse(dep2).project_name118 return dep1_name == dep2_name119class PosargsOption:120 name = "args_are_paths"121 type = "bool"122 default = True123 help = "treat positional args in commands as paths"124 def postprocess(self, testenv_config, value):125 config = testenv_config.config126 args = config.option.args127 if args:128 if value:129 args = []130 for arg in config.option.args:131 if arg:132 origpath = config.invocationcwd.join(arg, abs=True)133 if origpath.check():134 arg = testenv_config.changedir.bestrelpath(origpath)135 args.append(arg)136 testenv_config._reader.addsubstitutions(args)137 return value138class InstallcmdOption:139 name = "install_command"140 type = "argv"141 default = "pip install {opts} {packages}"142 help = "install command for dependencies and package under test."143 def postprocess(self, testenv_config, value):144 if '{packages}' not in value:145 raise tox_plus.exception.ConfigError(146 "'install_command' must contain '{packages}' substitution")147 return value148def parseconfig(args=None):149 """150 :param list[str] args: Optional list of arguments.151 :type pkg: str152 :rtype: :class:`Config`153 :raise SystemExit: toxinit file is not found154 """155 pm = get_plugin_manager()156 if args is None:157 args = sys.argv[1:]158 # prepare command line options159 parser = Parser()160 pm.hook.tox_addoption(parser=parser)161 # parse command line options162 option = parser._parse_args(args)163 interpreters = tox_plus.interpreters.Interpreters(hook=pm.hook)164 config = Config(pluginmanager=pm, option=option, interpreters=interpreters)165 config._parser = parser166 config._testenv_attr = parser._testenv_attr167 # parse ini file168 basename = config.option.configfile169 if os.path.isabs(basename):170 inipath = py.path.local(basename)171 else:172 for path in py.path.local().parts(reverse=True):173 inipath = path.join(basename)174 if inipath.check():175 break176 else:177 feedback("toxini file %r not found" % (basename), sysexit=True)178 try:179 parseini(config, inipath)180 except tox_plus.exception.InterpreterNotFound:181 exn = sys.exc_info()[1]182 # Use stdout to match test expectations183 py.builtin.print_("ERROR: " + str(exn))184 # post process config object185 pm.hook.tox_configure(config=config)186 return config187def feedback(msg, sysexit=False):188 py.builtin.print_("ERROR: " + msg, file=sys.stderr)189 if sysexit:190 raise SystemExit(1)191class VersionAction(argparse.Action):192 def __call__(self, argparser, *args, **kwargs):193 version = tox_plus.__version__194 py.builtin.print_("%s imported from %s" % (version, tox_plus.__file__))195 raise SystemExit(0)196class CountAction(argparse.Action):197 def __call__(self, parser, namespace, values, option_string=None):198 if hasattr(namespace, self.dest):199 setattr(namespace, self.dest, int(getattr(namespace, self.dest)) + 1)200 else:201 setattr(namespace, self.dest, 0)202@hookimpl203def tox_addoption(parser):204 # formatter_class=argparse.ArgumentDefaultsHelpFormatter)205 parser.add_argument("--version", nargs=0, action=VersionAction,206 dest="version",207 help="report version information to stdout.")208 parser.add_argument("-h", "--help", action="store_true", dest="help",209 help="show help about options")210 parser.add_argument("--help-ini", "--hi", action="store_true", dest="helpini",211 help="show help about ini-names")212 parser.add_argument("-v", nargs=0, action=CountAction, default=0,213 dest="verbosity",214 help="increase verbosity of reporting output.")215 parser.add_argument("--showconfig", action="store_true",216 help="show configuration information for all environments. ")217 parser.add_argument("-l", "--listenvs", action="store_true",218 dest="listenvs", help="show list of test environments")219 parser.add_argument("-c", action="store", default="tox.ini",220 dest="configfile",221 help="use the specified config file name.")222 parser.add_argument("-e", action="append", dest="env",223 metavar="envlist",224 help="work against specified environments (ALL selects all).")225 parser.add_argument("--notest", action="store_true", dest="notest",226 help="skip invoking test commands.")227 parser.add_argument("--sdistonly", action="store_true", dest="sdistonly",228 help="only perform the sdist packaging activity.")229 parser.add_argument("--installpkg", action="store", default=None,230 metavar="PATH",231 help="use specified package for installation into venv, instead of "232 "creating an sdist.")233 parser.add_argument("--develop", action="store_true", dest="develop",234 help="install package in the venv using 'setup.py develop' via "235 "'pip -e .'")236 parser.add_argument('-i', action="append",237 dest="indexurl", metavar="URL",238 help="set indexserver url (if URL is of form name=url set the "239 "url for the 'name' indexserver, specifically)")240 parser.add_argument("--pre", action="store_true", dest="pre",241 help="install pre-releases and development versions of dependencies. "242 "This will pass the --pre option to install_command "243 "(pip by default).")244 parser.add_argument("-r", "--recreate", action="store_true",245 dest="recreate",246 help="force recreation of virtual environments")247 parser.add_argument("--result-json", action="store",248 dest="resultjson", metavar="PATH",249 help="write a json file with detailed information "250 "about all commands and results involved.")251 # We choose 1 to 4294967295 because it is the range of PYTHONHASHSEED.252 parser.add_argument("--hashseed", action="store",253 metavar="SEED", default=None,254 help="set PYTHONHASHSEED to SEED before running commands. "255 "Defaults to a random integer in the range [1, 4294967295] "256 "([1, 1024] on Windows). "257 "Passing 'noset' suppresses this behavior.")258 parser.add_argument("--force-dep", action="append",259 metavar="REQ", default=None,260 help="Forces a certain version of one of the dependencies "261 "when configuring the virtual environment. REQ Examples "262 "'pytest<2.7' or 'django>=1.6'.")263 parser.add_argument("--sitepackages", action="store_true",264 help="override sitepackages setting to True in all envs")265 parser.add_argument("--skip-missing-interpreters", action="store_true",266 help="don't fail tests for missing interpreters")267 parser.add_argument("args", nargs="*",268 help="additional arguments available to command positional substitution")269 # add various core venv interpreter attributes270 parser.add_testenv_attribute(271 name="envdir", type="path", default="{toxworkdir}/{envname}",272 help="venv directory")273 parser.add_testenv_attribute(274 name="envtmpdir", type="path", default="{envdir}/tmp",275 help="venv temporary directory")276 parser.add_testenv_attribute(277 name="envlogdir", type="path", default="{envdir}/log",278 help="venv log directory")279 def downloadcache(testenv_config, value):280 if value:281 # env var, if present, takes precedence282 downloadcache = os.environ.get("PIP_DOWNLOAD_CACHE", value)283 return py.path.local(downloadcache)284 parser.add_testenv_attribute(285 name="downloadcache", type="string", default=None, postprocess=downloadcache,286 help="(deprecated) set PIP_DOWNLOAD_CACHE.")287 parser.add_testenv_attribute(288 name="changedir", type="path", default="{toxinidir}",289 help="directory to change to when running commands")290 parser.add_testenv_attribute_obj(PosargsOption())291 parser.add_testenv_attribute(292 name="skip_install", type="bool", default=False,293 help="Do not install the current package. This can be used when "294 "you need the virtualenv management but do not want to install "295 "the current package")296 parser.add_testenv_attribute(297 name="ignore_errors", type="bool", default=False,298 help="if set to True all commands will be executed irrespective of their "299 "result error status.")300 def recreate(testenv_config, value):301 if testenv_config.config.option.recreate:302 return True303 return value304 parser.add_testenv_attribute(305 name="recreate", type="bool", default=False, postprocess=recreate,306 help="always recreate this test environment.")307 def setenv(testenv_config, value):308 setenv = value309 config = testenv_config.config310 if "PYTHONHASHSEED" not in setenv and config.hashseed is not None:311 setenv['PYTHONHASHSEED'] = config.hashseed312 return setenv313 parser.add_testenv_attribute(314 name="setenv", type="dict", postprocess=setenv,315 help="list of X=Y lines with environment variable settings")316 def passenv(testenv_config, value):317 # Flatten the list to deal with space-separated values.318 value = list(319 itertools.chain.from_iterable(320 [x.split(' ') for x in value]))321 passenv = set(["PATH", "PIP_INDEX_URL", "LANG", "LD_LIBRARY_PATH"])322 # read in global passenv settings323 p = os.environ.get("TOX_TESTENV_PASSENV", None)324 if p is not None:325 passenv.update(x for x in p.split() if x)326 # we ensure that tmp directory settings are passed on327 # we could also set it to the per-venv "envtmpdir"328 # but this leads to very long paths when run with jenkins329 # so we just pass it on by default for now.330 if sys.platform == "win32":331 passenv.add("SYSTEMDRIVE") # needed for pip6332 passenv.add("SYSTEMROOT") # needed for python's crypto module333 passenv.add("PATHEXT") # needed for discovering executables334 passenv.add("TEMP")335 passenv.add("TMP")336 else:337 passenv.add("TMPDIR")338 for spec in value:339 for name in os.environ:340 if fnmatchcase(name.upper(), spec.upper()):341 passenv.add(name)342 return passenv343 parser.add_testenv_attribute(344 name="passenv", type="line-list", postprocess=passenv,345 help="environment variables needed during executing test commands "346 "(taken from invocation environment). Note that tox always "347 "passes through some basic environment variables which are "348 "needed for basic functioning of the Python system. "349 "See --showconfig for the eventual passenv setting.")350 parser.add_testenv_attribute(351 name="whitelist_externals", type="line-list",352 help="each lines specifies a path or basename for which tox will not warn "353 "about it coming from outside the test environment.")354 parser.add_testenv_attribute(355 name="platform", type="string", default=".*",356 help="regular expression which must match against ``sys.platform``. "357 "otherwise testenv will be skipped.")358 def sitepackages(testenv_config, value):359 return testenv_config.config.option.sitepackages or value360 parser.add_testenv_attribute(361 name="sitepackages", type="bool", default=False, postprocess=sitepackages,362 help="Set to ``True`` if you want to create virtual environments that also "363 "have access to globally installed packages.")364 def pip_pre(testenv_config, value):365 return testenv_config.config.option.pre or value366 parser.add_testenv_attribute(367 name="pip_pre", type="bool", default=False, postprocess=pip_pre,368 help="If ``True``, adds ``--pre`` to the ``opts`` passed to "369 "the install command. ")370 def develop(testenv_config, value):371 option = testenv_config.config.option372 return not option.installpkg and (value or option.develop)373 parser.add_testenv_attribute(374 name="usedevelop", type="bool", postprocess=develop, default=False,375 help="install package in develop/editable mode")376 def basepython_default(testenv_config, value):377 if value is None:378 for f in testenv_config.factors:379 if f in default_factors:380 return default_factors[f]381 return sys.executable382 return str(value)383 parser.add_testenv_attribute(384 name="basepython", type="string", default=None, postprocess=basepython_default,385 help="executable name or path of interpreter used to create a "386 "virtual test environment.")387 parser.add_testenv_attribute_obj(InstallcmdOption())388 parser.add_testenv_attribute_obj(DepOption())389 parser.add_testenv_attribute(390 name="commands", type="argvlist", default="",391 help="each line specifies a test command and can use substitution.")392class Config(object):393 """ Global Tox config object. """394 def __init__(self, pluginmanager, option, interpreters):395 #: dictionary containing envname to envconfig mappings396 self.envconfigs = {}397 self.invocationcwd = py.path.local()398 self.interpreters = interpreters399 self.pluginmanager = pluginmanager400 #: option namespace containing all parsed command line options401 self.option = option402 @property...

Full Screen

Full Screen

plugin.py

Source:plugin.py Github

copy

Full Screen

...29 version = result.decode('utf-8').strip()30 return 'python={}'.format(version)31@hookimpl32def tox_addoption(parser):33 parser.add_testenv_attribute_obj(CondaDepOption())34 parser.add_testenv_attribute(35 name="conda_channels",36 type="line-list",37 help="each line specifies a conda channel"38 )39@hookimpl40def tox_configure(config):41 # This is a pretty cheesy workaround. It allows tox to consider changes to42 # the conda dependencies when it decides whether an existing environment43 # needs to be updated before being used44 for _, envconfig in config.envconfigs.items():45 conda_deps = [DepConfig(str(name)) for name in envconfig.conda_deps]46 envconfig.deps.extend(conda_deps)47def find_conda():...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

...5from tox import hookimpl6from .install import install_debian_deps, InvocationError7@hookimpl8def tox_addoption(parser):9 parser.add_testenv_attribute_obj(DebianDepOption())10 parser.add_testenv_attribute_obj(AptOptOption())11class DebianDepOption:12 name = "debian_deps"13 type = "line-list"14 help = "debian package dependency"15 default = ()16 def postprocess(self, testenv_config, value):17 return value18class AptOptOption:19 name = "apt_opts"20 type = "line-list"21 help = "options to pass to apt-get"22 default = ()23 def postprocess(self, testenv_config, value):24 return value...

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 tox 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