Best Python code snippet using slash
run_tests.py
Source:run_tests.py  
...19    def __init__(self) -> None:20        self.stream = StreamWrapper(sys.stderr, max_width=CONSOLE_WIDTH)21    def write_header(self) -> None:22        """Write a header for this test run."""23        self.stream.write_separator("=")24        self.stream.write(f"{TITLE}\n")25        self.stream.write_separator("=")26        self.stream.writeln(27            f"Date: {datetime.datetime.utcnow().strftime(r'%Y-%m-%d %H:%M:%S')} UTC"28        )29    def write_footer(self, result: QualifierTestResult, duration: float) -> None:30        """Write a footer for this test run."""31        self.stream.writeln()32        self.stream.write_separator("=")33        self.stream.writeln(f"Test Suite Summary")34        self.stream.write_separator("-")35        if hasattr(result, "results"):36            self.stream.write(37                f"{' '*50} PASSED   FAILED   TOTAL   RESULT"38                "\n"39            )40            for section, section_results in result.results.items():41                section = textwrap.shorten(section, width=50, placeholder="...")42                total = len(section_results)43                passed = sum(test_result for test_result in section_results.values())44                failed = total - passed45                result = "FAIL" if failed else "PASS"46                self.stream.write(47                    f"{section:<50}  {passed:^6}   {failed:^6}  {total:^5}    {result}\n"48                )49        self.stream.write_separator("=")50        self.stream.writeln(f"Total running time: {duration:.3f}s")51    def run(self, test: unittest.TestSuite) -> None:52        """Run a test suite containing `unittest.TestCase` tests."""53        result = QualifierTestResult(self.stream)54        self.write_header()55        # Record the start time56        start = timeit.default_timer()57        # Pass the TestResult instance to the test suite to run the tests58        test(result)59        # Record the end time60        duration = timeit.default_timer() - start61        self.write_footer(result, duration)62TestOutcome = typing.Tuple[typing.Type[BaseException], BaseException, types.TracebackType]63TestClass = collections.namedtuple("TestClass", "type name")64class StreamWrapper:65    """Wrap an `io.TextIOBase` derived stream with utility methods."""66    def __init__(self, stream: io.TextIOBase, max_width: int = 100, verbosity: int = 0) -> None:67        self.stream = stream68        self.max_width = max_width69        self.verbosity = verbosity70    def __getattr__(self, attr: str) -> typing.Any:71        """Delegate attributes to the `io.TextIOBase` derived stream object."""72        return getattr(self.stream, attr)73    @staticmethod74    def fixed_width_text(text: str, width: int) -> str:75        """Create a string with a certain width by truncating and/or right-padding `text`."""76        return f"{text[:width]:<{width}}"77    def writeln(self, text: str = "") -> None:78        """Write a line to the stream."""79        if text:80            self.stream.write(text[:self.max_width])81        self.stream.write("\n")82    def write_separator(self, char: str = "-", length: typing.Optional[int] = None) -> None:83        """Write a separator line to the stream."""84        if not length:85            length = self.max_width86        multiplier = math.ceil(length / len(char))87        separator = char * multiplier88        self.writeln(separator[:self.max_width])89    def write_test_outcome(90        self,91        description: str,92        test_failures: typing.List[TestOutcome],93    ) -> None:94        """Write a test description."""95        description_length = self.max_width - 996        description = self.fixed_width_text(description, description_length)97        verdict = "[ PASS ]" if not test_failures else "[ FAIL ]"98        description = self.fixed_width_text(description, self.max_width - 8) + verdict99        self.writeln(description)100        if test_failures:101            for _, outcome in test_failures:102                self.write_subtest_failure(outcome)103                self.writeln()104                self.write_separator("-")105            self.writeln()106    def write_subtest_failure(self, outcome: TestOutcome) -> None:107        """Format subtest failure and write it to the stream."""108        self.writeln()109        self.write_separator("-")110        self.writeln("Failing test output:")111        _, exception, _ = outcome112        formatted_exception = ''.join(traceback.format_exception_only(type(exception), exception))113        self.stream.write(textwrap.indent(formatted_exception.rstrip(), prefix="  "))114    def write_section_header(self, section_title: str) -> None:115        """Write a section header, optionally including a subtest result header."""116        title_width = self.max_width - 10117        section_title = self.fixed_width_text(section_title, title_width)118        self.writeln()119        self.write_separator("=")120        self.write(f"{section_title}\n")121        self.write_separator("-")122class QualifierTestResult(unittest.TestResult):123    """A custom test result class used for testing entries for our Code Jam qualifier."""124    def __init__(self, stream: StreamWrapper) -> None:125        super().__init__(stream.stream)126        self.stream = stream127        self.current_testclass = TestClass(None, None)128        self.results = {}129        self.failure_output = None130        self._success = None131    @staticmethod132    def get_description(callable_object: typing.Callable) -> str:133        """Extract a description from the callable by looking at the docstring."""134        if callable_object.__doc__:135            description = callable_object.__doc__.splitlines()[0].rstrip(".!?")...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!!
