How to use exit_code_str method in tox

Best Python code snippet using tox_python

tasks.py

Source:tasks.py Github

copy

Full Screen

1"""A widget used to display DM Task information.2"""3from datetime import datetime4from typing import Any, Dict, List, Tuple5import pandas6from rich.panel import Panel7from rich.style import Style8from rich.text import Text9from squonk2.dm_api import DmApi, DmApiRv10from squad import common11from squad.access_token import AccessToken12from .base import SortOrder, TopicRenderer13# List of columns using names, styles and justification14_COLUMNS: List[Tuple[str, Style, str]] = [15 ("UUID", common.UUID_STYLE, "left"),16 ("Created (UTC)", common.DATE_STYLE, "left"),17 ("Purpose", None, "left"),18 ("Purpose UUID", common.UUID_STYLE, "left"),19 ("Version", common.TASK_PURPOSE_VERSION_STYLE, "left"),20 ("Done", None, "center"),21 ("Code", None, "center"),22 ("Removal", None, "center"),23]24# Styles for instance phases.25_PURPOSE_STYLE: Dict[str, Style] = {26 "DATASET": Style(color="magenta"),27 "FILE": Style(color="bright_cyan"),28 "INSTANCE": Style(color="green"),29 "PROJECT": Style(color="bright_white"),30}31_DEFAULT_PURPOSE_STYLE: Style = Style(color="yellow3")32# Value used for unset exit_code33_UNSET_EXIT_CODE: int = -999_999_99934class Tasks(TopicRenderer):35 """Displays tasks."""36 def __init__(self) -> None:37 # Default sort column38 self.num_columns = len(_COLUMNS)39 self.sort_column = 140 def render(self) -> Panel:41 """Render the widget."""42 # Time to get projects?43 now = datetime.now()44 if (45 self.last_response_time is None46 or now - self.last_response_time > self.refresh_interval47 ):48 # No response, or we now need to replace what we have.49 # Get an access token (it may be the one we already have)50 self.access_token = AccessToken.get_dm_access_token(51 prior_token=self.access_token52 )53 self.last_response_time = now54 if self.access_token:55 # Got a token, time to get a new set of results...56 set_admin_response: DmApiRv = DmApi.set_admin_state(57 self.access_token, admin=True58 )59 if set_admin_response.success:60 self.last_response = DmApi.get_available_tasks(self.access_token)61 else:62 self.last_response = None63 # Results in a table.64 self.prepare_table(_COLUMNS)65 assert self.table66 # Populate rows based on the last response.67 # We populate 'data' with the project material68 # so that we can sort on 'created' date using pandas.69 data: Dict[str, List[Any]] = {}70 row_number: int = 171 if self.last_response and self.last_response.success:72 for task in self.last_response.msg["tasks"]:73 data[f"{row_number}"] = [74 task["id"],75 task["created"],76 task["purpose"],77 task["purpose_id"],78 task.get("purpose_version", 0),79 task.get("done", False),80 task.get("exit_code", _UNSET_EXIT_CODE),81 task.get("removal", False),82 ]83 row_number += 184 if data:85 data_frame: pandas.DataFrame = pandas.DataFrame.from_dict(86 data, orient="index"87 )88 for _, row in data_frame.sort_values(89 by=[self.sort_column], ascending=self.sort_order == SortOrder.ASCENDING90 ).iterrows():91 purpose: str = row[2]92 # Render exit code.93 # Green or red.94 # But cater for unset codes.95 exit_code: int = row[6]96 exit_code_str = str(exit_code)97 exit_code_style: Style = Style(color="green1")98 if exit_code == _UNSET_EXIT_CODE:99 exit_code_str = "-"100 exit_code_style = Style(color="bright_black")101 elif exit_code != 0:102 exit_code_style = Style(color="bright_red", reverse=True)103 # Populate the row...104 self.table.add_row(105 str(self.table.row_count + 1),106 row[0],107 row[1],108 Text(109 purpose,110 style=_PURPOSE_STYLE.get(purpose, _DEFAULT_PURPOSE_STYLE),111 ),112 row[3],113 str(row[4]) if row[4] else "",114 common.TICK if row[5] else common.CROSS,115 Text(exit_code_str, style=exit_code_style),116 common.TICK if row[7] else common.CROSS,117 )118 title: str = f"Tasks ({self.table.row_count})"119 return Panel(120 self.table,121 title=title,...

Full Screen

Full Screen

exception.py

Source:exception.py Github

copy

Full Screen

1import os2import signal3def exit_code_str(exception_name, command, exit_code):4 """String representation for an InvocationError, with exit code5 NOTE: this might also be used by plugin tests (tox-venv at the time of writing),6 so some coordination is needed if this is ever moved or a different solution for this hack7 is found.8 NOTE: this is a separate function because pytest-mock `spy` does not work on Exceptions9 We can use neither a class method nor a static because of https://bugs.python.org/issue23078.10 Even a normal method failed with "TypeError: descriptor '__getattribute__' requires a11 'BaseException' object but received a 'type'".12 """13 str_ = "{} for command {}".format(exception_name, command)14 if exit_code is not None:15 str_ += " (exited with code {:d})".format(exit_code)16 if (os.name == "posix") and (exit_code > 128):17 signals = {18 number: name for name, number in vars(signal).items() if name.startswith("SIG")19 }20 number = exit_code - 12821 name = signals.get(number)22 if name:23 str_ += (24 "\nNote: this might indicate a fatal error signal "25 "({:d} - 128 = {:d}: {})".format(number + 128, number, name)26 )27 return str_28class Error(Exception):29 def __str__(self):30 return "{}: {}".format(self.__class__.__name__, self.args[0])31class MissingSubstitution(Error):32 FLAG = "TOX_MISSING_SUBSTITUTION"33 """placeholder for debugging configurations"""34 def __init__(self, name):35 self.name = name36class ConfigError(Error):37 """Error in tox configuration."""38class UnsupportedInterpreter(Error):39 """Signals an unsupported Interpreter."""40class InterpreterNotFound(Error):41 """Signals that an interpreter could not be found."""42class InvocationError(Error):43 """An error while invoking a script."""44 def __init__(self, command, exit_code=None):45 super(Error, self).__init__(command, exit_code)46 self.command = command47 self.exit_code = exit_code48 def __str__(self):49 return exit_code_str(self.__class__.__name__, self.command, self.exit_code)50class MissingFile(Error):51 """An error while invoking a script."""52class MissingDirectory(Error):53 """A directory did not exist."""54class MissingDependency(Error):55 """A dependency could not be found or determined."""56class MissingRequirement(Error):57 """A requirement defined in :config:`require` is not met."""58class MinVersionError(Error):59 """The installed tox version is lower than requested minversion."""60 def __init__(self, message):61 self.message = message...

Full Screen

Full Screen

req_run.py

Source:req_run.py Github

copy

Full Screen

1import time2SLEEP_TIMES = [0.01, 0.01, 0.03, 0.05, 0.1, 0.2]3class Sleeper:4 def __init__(self):5 self.idx = 06 def sleep(self):7 if self.idx >= len(SLEEP_TIMES):8 sleep_time = SLEEP_TIMES[-1]9 else:10 sleep_time = SLEEP_TIMES[self.idx]11 self.idx += 112 time.sleep(sleep_time)13def check_output(args):14 import os15 import base6416 import random17 import shlex18 from subprocess import CalledProcessError19 rand_bytes = random.getrandbits(128).to_bytes(16, 'little')20 iden = base64.urlsafe_b64encode(rand_bytes).decode('utf-8')21 cmd_path = f"/var/run/req_run/{iden}.cmd"22 with open(os.open(cmd_path, os.O_CREAT | os.O_WRONLY, 0o755), "w") as cmd:23 cmd.write("#!/bin/bash\n")24 cmd.write(" ".join(shlex.quote(arg) for arg in args))25 with open("/var/run/req_run/reqs", "a") as req_run:26 req_run.write(iden + "\n")27 sleeper = Sleeper()28 while not os.path.exists(f"/var/run/req_run/{iden}.code"):29 sleeper.sleep()30 exit_code_str = ""31 sleeper = Sleeper()32 while 1:33 with open(f"/var/run/req_run/{iden}.code") as code_f:34 exit_code_str = code_f.read().strip()35 if exit_code_str:36 break37 sleeper.sleep()38 exit_code = int(exit_code_str)39 with open(f"/var/run/req_run/{iden}.stdout", "rb") as stdout_f:40 stdout = stdout_f.read()41 with open(f"/var/run/req_run/{iden}.stderr", "rb") as stderr_f:42 stderr = stderr_f.read()43 if exit_code:44 raise CalledProcessError(exit_code, args, stdout, stderr)...

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