How to use _get_os_environ method in tox

Best Python code snippet using tox_python

venv.py

Source:venv.py Github

copy

Full Screen

...271 def _needs_reinstall(self, setupdir, action):272 setup_py = setupdir.join("setup.py")273 setup_cfg = setupdir.join("setup.cfg")274 args = [self.envconfig.envpython, str(setup_py), "--name"]275 env = self._get_os_environ()276 output = action.popen(277 args, cwd=setupdir, redirect=False, returnout=True, env=env, capture_err=False278 )279 name = next(280 (i for i in output.split("\n") if i and not i.startswith("pydev debugger:")), ""281 )282 args = [283 self.envconfig.envpython,284 "-c",285 "import sys; import json; print(json.dumps(sys.path))",286 ]287 out = action.popen(args, redirect=False, returnout=True, env=env)288 try:289 sys_path = json.loads(out)290 except ValueError:291 sys_path = []292 egg_info_fname = ".".join((to_filename(name), "egg-info"))293 for d in reversed(sys_path):294 egg_info = py.path.local(d).join(egg_info_fname)295 if egg_info.check():296 break297 else:298 return True299 needs_reinstall = any(300 conf_file.check() and conf_file.mtime() > egg_info.mtime()301 for conf_file in (setup_py, setup_cfg)302 )303 # Ensure the modification time of the egg-info folder is updated so we304 # won't need to do this again.305 # TODO(stephenfin): Remove once the minimum version of setuptools is306 # high enough to include https://github.com/pypa/setuptools/pull/1427/307 if needs_reinstall:308 egg_info.setmtime()309 return needs_reinstall310 def install_pkg(self, dir, action, name, is_develop=False):311 assert action is not None312 if getattr(self, "just_created", False):313 action.setactivity(name, dir)314 self.finish()315 pip_flags = ["--exists-action", "w"]316 else:317 if is_develop and not self._needs_reinstall(dir, action):318 action.setactivity("{}-noop".format(name), dir)319 return320 action.setactivity("{}-nodeps".format(name), dir)321 pip_flags = ["--no-deps"] + ([] if is_develop else ["-U"])322 pip_flags.extend(["-v"] * min(3, reporter.verbosity() - 2))323 if self.envconfig.extras:324 dir += "[{}]".format(",".join(self.envconfig.extras))325 target = [dir]326 if is_develop:327 target.insert(0, "-e")328 self._install(target, extraopts=pip_flags, action=action)329 def developpkg(self, setupdir, action):330 self.install_pkg(setupdir, action, "develop-inst", is_develop=True)331 def installpkg(self, sdistpath, action):332 self.install_pkg(sdistpath, action, "inst")333 def _installopts(self, indexserver):334 options = []335 if indexserver:336 options += ["-i", indexserver]337 if self.envconfig.pip_pre:338 options.append("--pre")339 return options340 def run_install_command(self, packages, action, options=()):341 def expand(val):342 # expand an install command343 if val == "{packages}":344 for package in packages:345 yield package346 elif val == "{opts}":347 for opt in options:348 yield opt349 else:350 yield val351 cmd = list(chain.from_iterable(expand(val) for val in self.envconfig.install_command))352 env = self._get_os_environ()353 self.ensure_pip_os_environ_ok(env)354 old_stdout = sys.stdout355 sys.stdout = codecs.getwriter("utf8")(sys.stdout)356 try:357 self._pcall(358 cmd,359 cwd=self.envconfig.config.toxinidir,360 action=action,361 redirect=reporter.verbosity() < reporter.Verbosity.DEBUG,362 env=env,363 )364 finally:365 sys.stdout = old_stdout366 def ensure_pip_os_environ_ok(self, env):367 for key in ("PIP_RESPECT_VIRTUALENV", "PIP_REQUIRE_VIRTUALENV", "__PYVENV_LAUNCHER__"):368 env.pop(key, None)369 if all("PYTHONPATH" not in i for i in (self.envconfig.passenv, self.envconfig.setenv)):370 # If PYTHONPATH not explicitly asked for, remove it.371 if "PYTHONPATH" in env:372 if sys.version_info < (3, 4) or bool(env["PYTHONPATH"]):373 # https://docs.python.org/3/whatsnew/3.4.html#changes-in-python-command-behavior374 # In a posix shell, setting the PATH environment variable to an empty value is375 # equivalent to not setting it at all.376 reporter.warning(377 "Discarding $PYTHONPATH from environment, to override "378 "specify PYTHONPATH in 'passenv' in your configuration."379 )380 env.pop("PYTHONPATH")381 # installing packages at user level may mean we're not installing inside the venv382 env["PIP_USER"] = "0"383 # installing without dependencies may lead to broken packages384 env["PIP_NO_DEPS"] = "0"385 def _install(self, deps, extraopts=None, action=None):386 if not deps:387 return388 d = {}389 ixservers = []390 for dep in deps:391 if isinstance(dep, (str, py.path.local)):392 dep = DepConfig(str(dep), None)393 assert isinstance(dep, DepConfig), dep394 if dep.indexserver is None:395 ixserver = self.envconfig.config.indexserver["default"]396 else:397 ixserver = dep.indexserver398 d.setdefault(ixserver, []).append(dep.name)399 if ixserver not in ixservers:400 ixservers.append(ixserver)401 assert ixserver.url is None or isinstance(ixserver.url, str)402 for ixserver in ixservers:403 packages = d[ixserver]404 options = self._installopts(ixserver.url)405 if extraopts:406 options.extend(extraopts)407 self.run_install_command(packages=packages, options=options, action=action)408 def _get_os_environ(self, is_test_command=False):409 if is_test_command:410 # for executing tests we construct a clean environment411 env = {}412 for env_key in self.envconfig.passenv:413 if env_key in os.environ:414 env[env_key] = os.environ[env_key]415 else:416 # for executing non-test commands we use the full417 # invocation environment418 env = os.environ.copy()419 # in any case we honor per-testenv setenv configuration420 env.update(self.envconfig.setenv)421 env["VIRTUAL_ENV"] = str(self.path)422 return env423 def test(424 self,425 redirect=False,426 name="run-test",427 commands=None,428 ignore_outcome=None,429 ignore_errors=None,430 display_hash_seed=False,431 ):432 if commands is None:433 commands = self.envconfig.commands434 if ignore_outcome is None:435 ignore_outcome = self.envconfig.ignore_outcome436 if ignore_errors is None:437 ignore_errors = self.envconfig.ignore_errors438 with self.new_action(name) as action:439 cwd = self.envconfig.changedir440 if display_hash_seed:441 env = self._get_os_environ(is_test_command=True)442 # Display PYTHONHASHSEED to assist with reproducibility.443 action.setactivity(name, "PYTHONHASHSEED={!r}".format(env.get("PYTHONHASHSEED")))444 for i, argv in enumerate(commands):445 # have to make strings as _pcall changes argv[0] to a local()446 # happens if the same environment is invoked twice447 message = "commands[{}] | {}".format(448 i, " ".join([pipes.quote(str(x)) for x in argv])449 )450 action.setactivity(name, message)451 # check to see if we need to ignore the return code452 # if so, we need to alter the command line arguments453 if argv[0].startswith("-"):454 ignore_ret = True455 if argv[0] == "-":456 del argv[0]457 else:458 argv[0] = argv[0].lstrip("-")459 else:460 ignore_ret = False461 try:462 self._pcall(463 argv,464 cwd=cwd,465 action=action,466 redirect=redirect,467 ignore_ret=ignore_ret,468 is_test_command=True,469 )470 except tox.exception.InvocationError as err:471 if ignore_outcome:472 msg = "command failed but result from testenv is ignored\ncmd:"473 reporter.warning("{} {}".format(msg, err))474 self.status = "ignored failed command"475 continue # keep processing commands476 reporter.error(str(err))477 self.status = "commands failed"478 if not ignore_errors:479 break # Don't process remaining commands480 except KeyboardInterrupt:481 self.status = "keyboardinterrupt"482 raise483 def _pcall(484 self,485 args,486 cwd,487 venv=True,488 is_test_command=False,489 action=None,490 redirect=True,491 ignore_ret=False,492 returnout=False,493 env=None,494 ):495 if env is None:496 env = self._get_os_environ(is_test_command=is_test_command)497 # construct environment variables498 env.pop("VIRTUALENV_PYTHON", None)499 bin_dir = str(self.envconfig.envbindir)500 env["PATH"] = os.pathsep.join([bin_dir, os.environ["PATH"]])501 reporter.verbosity2("setting PATH={}".format(env["PATH"]))502 # get command503 args[0] = self.getcommandpath(args[0], venv, cwd)504 if sys.platform != "win32" and "TOX_LIMITED_SHEBANG" in os.environ:505 args = prepend_shebang_interpreter(args)506 cwd.ensure(dir=1) # ensure the cwd exists507 return action.popen(508 args,509 cwd=cwd,510 env=env,...

Full Screen

Full Screen

tox_poetry.py

Source:tox_poetry.py Github

copy

Full Screen

...34 for extra in venv.envconfig.extras:35 cmd += ['-E', extra]36 action.setactivity('installdeps', ' '.join(cmd))37 # Force UTF-8 encoding, since tox log parser epxects this (~ tox\action.py", line 128, in popen).38 env = venv._get_os_environ() # pylint: disable=protected-access39 env["PYTHONIOENCODING"] = "UTF-8"40 venv._pcall( # pylint: disable=protected-access41 cmd,42 action=action,43 cwd=project_root,44 env=env,...

Full Screen

Full Screen

session.py

Source:session.py Github

copy

Full Screen

...22 returnout=False):23 cwd.ensure(dir=1)24 args[0] = self.getcommandpath(args[0], venv, cwd)25 if hasattr(self, '_get_os_environ'):26 environ = self._get_os_environ(is_test_command=is_test_command)27 else:28 environ = self._getenv(testcommand=testcommand)29 return action.popen(args, cwd=cwd, env=environ,30 redirect=redirect, ignore_ret=ignore_ret)31 def is_allowed_external(self, _):32 return True33def main(args=None):34 try:35 config = prepare(args)36 retcode = TaxSession(config).runcommand()37 raise SystemExit(retcode)38 except KeyboardInterrupt:...

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