Best Python code snippet using lemoncheesecake
shellcommands.py
Source:shellcommands.py  
...328    """ A hook for abritrary shell commands.329        This hook introdces a consistent "pass" and "fail" logic for the checks.330        >>> tst = ShellCommandHook()331        >>> tst.CHECK_TOOL = 'true'332        >>> checks = [tst.make_check(x) for x in ('hello', 'world', '!!!')]333        >>> tst.adaptive_execution(checks=checks)334        == will check 3 files.335        == running: true hello 336        == true passed.337        == running: true world 338        == true passed.339        == running: true !!! 340        == true passed.341        0342        >>> tst.CHECK_TOOL = 'false'343        >>> checks = [tst.make_check(x) for x in ('hello', 'world', '!!!')]344        >>> tst.adaptive_execution(checks=checks)345        == will check 3 files.346        == running: false hello 347        == failed: false hello348        == Game Over: continues_used=1 returncode=1349        1350        >>> tst.CHECK_TOOL = 'false'351        >>> checks = iter([tst.make_check(x) for x in ('hello', 'world', '!!!')])352        >>> tst.adaptive_execution(checks=checks)353        == starting up: F354        == Game Over: continues_used=1 returncode=1355        == failed: false hello356        1357        >>> tst.CHECK_TOOL = 'true'358        >>> checks = iter([tst.make_check(x) for x in ('hello', 'world', '!!!')])359        >>> tst.adaptive_execution(checks=checks)360        == starting up: ...361        0362    """363    CHECK_TOOL = None364    RETURNCODE_ON_STDOUT = 0365    RETURNCODE_ON_STDERR = 0366    def _msg_hook_startup(self, checks=(), **kwd):367        msg = ('==', colors.cyan(self.NAME),) if self.NAME else ('==',)368        if hasattr(checks, '__len__'):369            if len(checks) > 1:370                msg += ('will check', colors.yellow(str(len(checks))), 'files.')371            elif len(checks) == 1:372                msg += ('will check', colors.yellow('1'), 'file.')373            else:374                return375        else:376            msg += ('starting up: ',)377        echo.bold(*msg, **kwd)378    def _msg_simple_check_start(self, check=None, **kwd):379        check_name = os.path.basename(check.args[0])380        args = ' '.join(check.args[1:]) if check.args else ''381        kwargs = check.kwargs if check.kwargs else ''382        msg = ('== running:', colors.cyan(check_name), args, kwargs)383        echo.white(*msg, **kwd)384    def _fmt_checked(self, outcome=None):385        check = outcome.check386        check_name = os.path.basename(check.args[0])387        if self.is_returncode(outcome):388            if type(outcome) is CompletedCheck:389                result = outcome.result390                command = (colors.yellow(os.path.basename(result.command[0])),) + result.command[1:]391                msg = ('== failed:', colors.yellow(' '.join(command)))392                if result.stdout or result.stderr:393                    msg += ('\n',)394                if result.stdout:395                    msg += (396                        # colors.cyan('\n> > > stdout > > >\n'),397                        '\n',398                        result.stdout,399                        # colors.cyan('\n< < < stdout < < <')400                    )401                if result.stderr:402                    msg += (403                        # colors.yellow('\n> > > stderr > > >\n'),404                        '\n',405                        colors.yellow(result.stderr),406                        # colors.yellow('\n< < < stderr < < <')407                    )408            elif type(outcome) is ErroredCheck:409                msg = ('== errored:', colors.yellow(check_name), outcome.exc_info[0], outcome.exc_info[1])410        else:411            msg = ('==', colors.cyan(check_name), 'passed.')412        return msg413    def _msg_generator_checked(self, outcome, **kwd):414        if type(outcome) is ErroredCheck:415            char = 'X'416        elif self.is_returncode(outcome):417            char = 'F'418        elif type(outcome) is CompletedCheck:419            char = '.'420        else:421            char = '?!'422        kwd.setdefault('nl', False)423        echo.bold(char, nl=False)424    def make_check(self, *args, **kwd):425        """ Make a check (combine function and args).426            >>> tst = ShellCommandHook()427            >>> len(tst.make_check().args)428            0429            >>> tst.CHECK_TOOL = 'flowtool'430            >>> len(tst.make_check().args)431            1432            >>> tst.CHECK_TOOL = ('flowtool', '--flow')433            >>> len(tst.make_check().args)434            2435        """436        if self.CHECK_TOOL is not None:437            if isinstance(self.CHECK_TOOL, (tuple, list)):438                tool_args = []439                for arg in self.CHECK_TOOL: # pylint: disable=E1133440                    if arg == '>managed_config<':441                        tool_args.append(self.get_configfile(do_setup=True))442                    else:443                        tool_args.append(arg)444                args = tuple(tool_args) + args445            else:446                args = (str(self.CHECK_TOOL),) + args447        return make_command_check(*args, **kwd)...universal.py
Source:universal.py  
...24            i.e. a linter hook will in this mode check all files differing from origin/master25    >>> from click.testing import CliRunner26    >>> runner = CliRunner()27    >>> githook = UniversalGithook()28    >>> githook.generate_checks = lambda: [make_check(print_args, 'foo', bar='baz')]29    >>> result = runner.invoke(githook.click_command, [])30    >>> result.exception31    >>> result.exit_code32    033    >>> output_lines = result.output.split('\\n')[:-1]34    >>> len(output_lines)35    436    >>> output_lines[0] == '== will run 1 check.'37    True38"""39import os40import sys41import click42from collections import namedtuple43from flowtool.style import echo, colors44from flowtool.style import debug45from flowtool.python import read_stdin_nonblocking46from flowtool_git.common import local_repo, GitCommandError47from flowtool_githooks.discovering import find_file_patterns_in_project48from flowtool_githooks.discovering import find_changed_file_patterns49from flowtool_githooks.discovering import find_added_file_patterns50def print_args(*cmdline, **kwd):51    """ Print the args that are given to this function.52        Serves as a fallback for the check_func of a53        UniversalGithook.54        >>> print_args()55        dummy-check: () {}56    """57    echo.white('dummy-check:', cmdline, kwd)58def dummy_check(*args, **kwd):59    """ A dummy function, that will never fail.60        >>> dummy_check()61    """62Check = namedtuple('Check', ['func', 'args', 'kwargs'])63CompletedCheck = namedtuple('CompletedCheck', ['check', 'result'])64ErroredCheck = namedtuple('ErroredCheck', ['check', 'exc_info', 'returncode'])65def make_check(func=None, *args, **kwd):66    """ Create a Check object to be run by a UniversalGithook.67        >>> check = make_check(make_check, make_check)68        >>> check.func is check.args[0]69        True70    """71    return Check(func, args, kwd)72class UniversalGithook(object):73    """ The most simple form of a universal git hook.74        >>> tst = UniversalGithook()75        >>> tst.adaptive_execution(checks=iter([tst.make_check(x) for x in range(9)]))76        == starting up: .........77        078    """79    NAME = None80    FILE_PATTERNS = '*'81    CHECK_FUNC = None82    EXCEPTION_RETURNCODE = -283    CONTINUES = 084    PROGRESSBAR_MIN_COUNT = 485    SIMPLE_GENERATOR = False86    repo = local_repo()87    @classmethod88    def hook_setup(cls, cmd=None):89        """ Setup function for the hook90            >>> tst = UniversalGithook()91            >>> tst.hook_setup('install')92            >>> tst.hook_setup('uninstall')93        """94    def __init__(self):95        """ Create self.click_command. It shall be instance-bound,96            but click seemingly cannot decorate methods.97        """98        @click.command()99        @click.argument('args', nargs=-1)100        def click_command(args=()):101            sys.exit(self.adaptive_execution(args=args))102            # sys.exit(self.adaptive_execution(args=args))103        self.click_command = click_command104    RuntimeInfo = namedtuple(105        'RuntimeInfo',106        [107            'arg0',108            'args',109            'stdin',110            'run_mode',111        ],112    )113    arg0 = sys.argv[0]114    @property115    def args(self):116        if not hasattr(self, '_args'):117            self._args = tuple(sys.argv[1:])118        return self._args119    @args.setter120    def args(self, value):121        self._args = value122    @property123    def stdin(self):124        if not hasattr(self, '_stdin'):125            stdin = list(read_stdin_nonblocking(ignore_error=True))126            self._stdin = ''.join(stdin) if stdin else stdin127        return self._stdin128    @stdin.setter129    def stdin(self, value):130        self._stdin = value131    @property132    def run_mode(self):133        if not hasattr(self, '_run_mode'):134            arg0dir = self.arg0.split(os.sep)[-2]135            if arg0dir.endswith('.d'):136                self._run_mode = arg0dir[:-2]137            else:138                self._run_mode = 'standalone'139        return self._run_mode140    @run_mode.setter141    def run_mode(self, value):142        self._run_mode = value143    def collect_infos(self):144        """ Runtime information is collected through cached properties,145            to avoid unnecessary system calls. This function provides146            a combined test case and convenience function.147            >>> tst = UniversalGithook()148            >>> tst.stdin = 'foobar!baz'149            >>> infos = tst.collect_infos()150            >>> type(infos.args) is tuple151            True152            >>> infos.stdin153            'foobar!baz'154            >>> infos.run_mode155            'standalone'156            >>> tst.run_mode = 'something'157        """158        info = self.RuntimeInfo(self.arg0, self.args, self.stdin, self.run_mode)159        return info160    def _check_func_name(self, func):161        return func.__name__ if hasattr(func, '__name__') else '<anon_check>'162    def _msg_simple_check_start(self, check=None, **kwd):163        check_name = self._check_func_name(check.func)164        args = '(%s)' % ', '.join(map(str,check.args)) if check.args else ''165        kwargs = check.kwargs if check.kwargs else ''166        msg = ('== running:', colors.cyan(check_name), args, kwargs)167        echo.white(*msg, **kwd)168    def _fmt_checked(self, outcome=None):169        check = outcome.check170        check_name = self._check_func_name(check.func)171        if self.is_returncode(outcome):172            msg = ('==', colors.cyan(check_name), 'errored.')173        else:174            msg = ('==', colors.cyan(check_name), 'passed.')175        return msg176    def _msg_simple_checked(self, outcome=None, **kwd):177        msg = self._fmt_checked(outcome)178        if self.is_returncode(outcome):179            echo.yellow(*msg, **kwd)180        else:181            echo.white(*msg, **kwd)182    def _msg_progressbar_failed(self, outcome=None, **kwd):183        msg = self._fmt_checked(outcome, **kwd)184        if self.is_returncode(outcome):185            echo.yellow('\n', *msg, **kwd)186    def _msg_generator_checked(self, outcome, **kwd):187        if type(outcome) is ErroredCheck:188            char = 'X'189        elif type(outcome) is CompletedCheck:190            char = '.'191        else:192            char = '?!'193        kwd.setdefault('nl', False)194        echo.bold(char, **kwd)195    def make_check(self, *args, **kwd):196        """ Make a check (combine function and args).197            >>> tst = UniversalGithook()198            >>> tst.CHECK_FUNC = 'test'199            >>> tst.make_check().func200            'test'201        """202        check_func = self.CHECK_FUNC if self.CHECK_FUNC is not None else dummy_check203        return make_check(check_func, *args, **kwd)204    def generate_checks(self):205        """ Generate checks.206            >>> tst = UniversalGithook()207            >>> tst.run_mode208            'standalone'209            >>> len(tst.generate_checks()) > 42210            True211            >>> tst.run_mode = 'pre-commit'212            >>> lst = list(tst.generate_checks())213            >>> tst.run_mode = 'commit-msg'214            >>> lst == list(tst.generate_checks())215            True216            >>> tst.run_mode = 'pre-push'217            >>> bool(iter(tst.generate_checks()))218            True219        """220        if self.run_mode in ('pre-commit', 'commit-msg'):221            check_these = find_added_file_patterns(self.FILE_PATTERNS)222        elif self.run_mode in ('pre-push',):223            check_these = find_changed_file_patterns(self.FILE_PATTERNS)224        elif self.run_mode == 'standalone':225            check_these = find_file_patterns_in_project(self.FILE_PATTERNS)226        else:227            check_these = []228        return [self.make_check(f) for f in check_these]229    def run_check(self, check, **kwd):230        """ Run a check.231            >>> tst = UniversalGithook()232            >>> tst.run_check(make_check(print_args, 'Kowabunga!'))233            dummy-check: ('Kowabunga!',) {}234            ...235        """236        kwd.update(check.kwargs)237        try:238            check_result = check.func(*check.args, **kwd)239            return self.check_completed(check, check_result)240        except:241            return self.check_errored(check, sys.exc_info())242    def check_completed(self, check, result):243        return CompletedCheck(check, result)244    def check_errored(self, check, exc_info):245        return ErroredCheck(check, exc_info, self.EXCEPTION_RETURNCODE)246    def _msg_hook_startup(self, checks=(), **kwd):247        msg = ('==', colors.yellow(self.NAME),) if self.NAME else ('==',)248        if hasattr(checks, '__len__'):249            if len(checks) > 1:250                msg += ('will run', colors.green(str(len(checks))), 'checks.')251            elif len(checks) == 1:252                msg += ('will run', colors.green('1'), 'check.')253            else:254                return255        else:256            msg += ('starting up: ',)257        echo.bold(*msg, **kwd)258    def is_returncode(self, outcome):259        if type(outcome) is CompletedCheck:260            return 0261        else:262            return 1263    def execute_simple(self, checks=None, continues=None, **kwd):264        """ Simple procedure for hook execution.265            >>> tst = UniversalGithook()266            >>> tst.generate_checks = lambda: [make_check(print_args, 'Kowabunga!')]267            >>> tst.execute_simple()268            == will run 1 check.269            == running: print_args (Kowabunga!) 270            dummy-check: ('Kowabunga!',) {}271            == print_args passed.272            0273        """274        if checks is None:275            checks = self.generate_checks()276        if continues is None:277            continues = self.CONTINUES278        self._msg_hook_startup(checks)279        results = []280        fails = 0281        for check in checks:282            self._msg_simple_check_start(check)283            outcome = self.run_check(check, **kwd)284            self._msg_simple_checked(outcome)285            results.append(outcome)286            if self.is_returncode(outcome):287                fails += 1288                if fails >= continues:289                    return self.game_over(results, fails=fails)290        returncode = self.summarize(results, verbose=False)291        if returncode is None:292            returncode = 0293        return returncode294    def execute_progressbar(self, checks=None, continues=None, **kwd):295        """ Procedure for hook execution using the click progressbar.296            >>> tst = UniversalGithook()297            >>> tst.generate_checks = lambda: [make_check(print_args, 'Kowabunga!')]298            >>> tst.execute_progressbar()299            == will run 1 check.300            <BLANKLINE>301            <BLANKLINE>302            dummy-check: ('Kowabunga!',) {}303            0304        """305        if checks is None:306            checks = self.generate_checks()307        if continues is None:308            continues = self.CONTINUES309        self._msg_hook_startup(checks)310        echo.white()311        results = []312        fails = 0313        with click.progressbar(checks) as bar:314            for check in bar:315                outcome = self.run_check(check, **kwd)316                results.append(outcome)317                if self.is_returncode(outcome):318                    self._msg_progressbar_failed(outcome)319                    fails += 1320                    if fails >= continues:321                        return self.game_over(results, fails=fails)322        returncode = self.summarize(results, verbose=False)323        if returncode is None:324            returncode = 0325        return returncode326    def execute_generator(self, checks=(), continues=None, **kwd):327        """ Procedure for hook execution using the click progressbar.328            >>> tst = UniversalGithook()329            >>> tst.generate_checks = lambda: (i for i in [])330            >>> tst.execute_generator()331            <BLANKLINE>332            0333            >>> tst.generate_checks = lambda: [make_check(lambda x: '', 'Kowabunga!')]334            >>> tst.execute_generator()335            <BLANKLINE>336            0337        """338        if checks is None:339            checks = self.generate_checks()340        if continues is None:341            continues = self.CONTINUES342        self._msg_hook_startup(checks, nl=False)343        results = []344        fails = 0345        for check in checks:346            outcome = self.run_check(check, **kwd)347            self._msg_generator_checked(outcome)348            results.append(outcome)349            if self.is_returncode(outcome):350                fails += 1351                if fails >= continues:352                    echo.white('')353                    return self.game_over(results, fails=fails, verbose=True)354        echo.white('')355        returncode = self.summarize(results, verbose=True)356        if returncode is None:357            returncode = 0358        return returncode359    def adaptive_execution(self, args=None, checks=None, **kwd):360        """ Auto select the execution style based on the capabilities of the checklist.361            >>> tst = UniversalGithook()362            >>> chk = make_check(lambda x: 'Kowa-', 'bunga!')363            >>> def checklist(n):364            ...     for _ in range(n):365            ...         yield chk366            ...367            >>> tst.generate_checks = lambda: []368            >>> tst.adaptive_execution()369            0370            >>> tst.generate_checks = lambda: [chk]371            >>> tst.adaptive_execution()372            == will run 1 check.373            == running: <lambda> (bunga!) 374            == <lambda> passed.375            0376        """377        if checks is None:378            checks = self.generate_checks()379        if hasattr(checks, '__len__'):380            if len(checks) < self.PROGRESSBAR_MIN_COUNT:381                return self.execute_simple(checks=checks, **kwd)382            else:383                return self.execute_progressbar(checks=checks, **kwd)384        else:385            if self.SIMPLE_GENERATOR:386                return self.execute_simple(checks=checks, **kwd)387            else:388                return self.execute_generator(checks=checks, **kwd)389    def game_over(self, results=(), fails=None, verbose=None):390        returncode = self.is_returncode(results[-1])391        echo.white('== Game Over:', 'continues_used=%s' % fails, 'returncode=%s' % returncode)392        if verbose:393            returncode = self.summarize(results, verbose=verbose)394        if returncode is None:395            returncode = 0396        return returncode397    def summarize(self, results=(), verbose=None):398        """ Summarize a list of CompletedCheck and ErroredCheck.399            >>> tst = UniversalGithook()400            >>> tst.summarize([CompletedCheck(make_check('func'), 0)])401            0402            >>> tst.summarize([ErroredCheck(make_check('func'), ('a', 'b', 'c'), 100)], verbose=True)403            == <anon_check> errored.404            1405        """406        returncode = 0407        fails = 0408        for outcome in results:409            ret = self.is_returncode(outcome)410            returncode |= ret411            if verbose and ret:412                self._msg_simple_checked(outcome)...check.py
Source:check.py  
1#!/bin/true2#3# test.py - part of autospec4# Copyright (C) 2015 Intel Corporation5#6# This program is free software: you can redistribute it and/or modify7# it under the terms of the GNU General Public License as published by8# the Free Software Foundation, either version 3 of the License, or9# (at your option) any later version.10#11# This program is distributed in the hope that it will be useful,12# but WITHOUT ANY WARRANTY; without even the implied warranty of13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the14# GNU General Public License for more details.15#16# You should have received a copy of the GNU General Public License17# along with this program.  If not, see <http://www.gnu.org/licenses/>.18#19# Deduce and emmit the patterns for %check20#21import os22import re23import count24import util25tests_config = ""26def check_regression(pkg_dir, skip_tests):27    """Check the build log for test regressions using the count module."""28    if skip_tests:29        return30    result = count.parse_log(os.path.join(pkg_dir, "results/build.log"))31    titles = [('Package', 'package name', 1),32              ('Total', 'total tests', 1),33              ('Pass', 'total passing', 1),34              ('Fail', 'total failing', 0),35              ('Skip', 'tests skipped', 0),36              ('XFail', 'expected fail', 0)]37    res_str = ""38    for line in result.strip('\n').split('\n'):39        s_line = line.split(',')40        for idx, title in enumerate(titles):41            if s_line[idx]:42                if (s_line[idx] != '0') or (title[2] > 0):43                    print("{}: {}".format(title[1], s_line[idx]))44                res_str += "{} : {}\n".format(title[0], s_line[idx])45    util.write_out(os.path.join(pkg_dir, "testresults"), res_str)46def scan_for_tests(src_dir, config, requirements, content):47    """Scan source directory for test files and set tests_config accordingly."""48    global tests_config49    if config.config_opts.get('skip_tests') or tests_config:50        return51    makeflags = "%{?_smp_mflags} " if config.parallel_build else ""52    make_check = "make {}check".format(makeflags)53    cmake_check = "make test"54    make_check_openmpi = "module load openmpi\nexport OMPI_MCA_rmaps_base_oversubscribe=1\n" \55                         "make {}check\nmodule unload openmpi".format(makeflags)56    cmake_check_openmpi = "module load openmpi\nexport OMPI_MCA_rmaps_base_oversubscribe=1\n" \57                          "make test\nmodule unload openmpi"58    if config.config_opts.get('allow_test_failures'):59        make_check_openmpi = "module load openmpi\nexport OMPI_MCA_rmaps_base_oversubscribe=1\n" \60                             "make {}check || :\nmodule unload openmpi".format(makeflags)61        cmake_check_openmpi = "module load openmpi\nexport OMPI_MCA_rmaps_base_oversubscribe=1\n" \62                              "make test || :\nmodule unload openmpi"63    perl_check = "make TEST_VERBOSE=1 test"64    setup_check = """PYTHONPATH=%{buildroot}$(python -c "import sys; print(sys.path[-1])") python setup.py test"""65    meson_check = "meson test -C builddir --print-errorlogs"66    waf_check = "./waf test -vvv"67    if config.config_opts.get('allow_test_failures'):68        make_check += " || :"69        cmake_check += " || :"70        perl_check += " || :"71        setup_check += " || :"72        meson_check += " || :"73        waf_check += " || :"74    testsuites = {75        "makecheck": make_check,76        "perlcheck": perl_check,77        "setup.py": setup_check,78        "cmake": "cd clr-build; " + cmake_check,79        "rakefile": "pushd %{buildroot}%{gem_dir}/gems/" + content.gem_subdir + "\nrake --trace test TESTOPTS=\"-v\"\npopd",80        "rspec": "pushd %{buildroot}%{gem_dir}/gems/" + content.gem_subdir + "\nrspec -I.:lib spec/\npopd",81        "meson": meson_check,82        "waf": waf_check,83    }84    if config.config_opts.get('32bit'):85        testsuites["makecheck"] += "\ncd ../build32;\n" + make_check + " || :"86        testsuites["cmake"] += "\ncd ../clr-build32;\n" + cmake_check + " || :"87        testsuites["meson"] += "\ncd ../build32;\n" + meson_check + " || :"88        testsuites["waf"] += "\ncd ../build32;\n" + waf_check + " || :"89        if config.config_opts.get('build_special_32'):90            testsuites["makecheck"] += "\ncd ../build-special-32;\n" + make_check + " || :"91            testsuites["cmake"] += "\ncd ../clr-build-special-32;\n" + cmake_check + " || :"92            testsuites["meson"] += "\ncd ../build-special-32;\n" + meson_check + " || :"93            testsuites["waf"] += "\ncd ../build-special-32;\n" + waf_check + " || :"94    if config.config_opts.get('build_special'):95        testsuites["makecheck"] += "\ncd ../build-special;\n" + make_check + " || :"96        testsuites["cmake"] += "\ncd ../clr-build-special;\n" + cmake_check + " || :"97        testsuites["meson"] += "\ncd ../build-special;\n" + meson_check + " || :"98        testsuites["waf"] += "\ncd ../build-special;\n" + waf_check + " || :"99    if config.config_opts.get('build_special2'):100        testsuites["makecheck"] += "\ncd ../build-special2;\n" + make_check + " || :"101        testsuites["cmake"] += "\ncd ../clr-build-special2;\n" + cmake_check + " || :"102        testsuites["meson"] += "\ncd ../build-special2;\n" + meson_check + " || :"103        testsuites["waf"] += "\ncd ../build-special2;\n" + waf_check + " || :"104    if config.config_opts.get('use_avx2'):105        testsuites["makecheck"] += "\ncd ../buildavx2;\n" + make_check + " || :"106        testsuites["cmake"] += "\ncd ../clr-build-avx2;\n" + cmake_check + " || :"107    if config.config_opts.get('use_avx512'):108        testsuites["makecheck"] += "\ncd ../buildavx512;\n" + make_check + " || :"109        testsuites["cmake"] += "\ncd ../clr-build-avx512;\n" + cmake_check + " || :"110    if config.config_opts.get('openmpi'):111        testsuites["makecheck"] += "\ncd ../build-openmpi;\n" + make_check_openmpi112        testsuites["cmake"] += "\ncd ../clr-build-openmpi;\n" + cmake_check_openmpi113    files = os.listdir(src_dir)114    if config.default_pattern == "cmake":115        makefile_path = os.path.join(src_dir, "CMakeLists.txt")116        if not os.path.isfile(makefile_path):117            return118        if "enable_testing" in util.open_auto(makefile_path).read():119            tests_config = testsuites["cmake"]120    elif config.default_pattern in ["cpan", "configure", "configure_ac", "autogen"] and "Makefile.in" in files:121        makefile_path = os.path.join(src_dir, "Makefile.in")122        if os.path.isfile(makefile_path):123            with util.open_auto(makefile_path, 'r') as make_fp:124                lines = make_fp.readlines()125            for line in lines:126                if line.startswith("check:"):127                    tests_config = testsuites["makecheck"]128                    break129                if line.startswith("test:"):130                    tests_config = testsuites["perlcheck"]131                    break132    elif config.default_pattern in ["configure", "configure_ac", "autogen"] and "Makefile.am" in files:133        tests_config = testsuites["makecheck"]134    elif config.default_pattern in ["cpan"] and "Makefile.PL" in files:135        tests_config = testsuites["perlcheck"]136    elif config.default_pattern == "distutils3" and "setup.py" in files:137        with util.open_auto(os.path.join(src_dir, "setup.py"), 'r') as setup_fp:138            setup_contents = setup_fp.read()139        if "test_suite" in setup_contents or "pbr=True" in setup_contents:140            tests_config = testsuites["setup.py"]141    elif config.default_pattern == "R":142        tests_config = "export _R_CHECK_FORCE_SUGGESTS_=false\n"              \143                       "R CMD check --no-manual --no-examples --no-codoc "    \144                       + content.rawname + " || :"145    elif config.default_pattern == "meson":146        found_tests = False147        makefile_path = os.path.join(src_dir, "meson.build")148        if not os.path.isfile(makefile_path):149            return150        for dirpath, _, files in os.walk(src_dir):151            for f in files:152                if f == "meson.build":153                    with util.open_auto(os.path.join(dirpath, f)) as fp:154                        if any(re.search(r'^\s*test\s*\(.+', line) for line in fp):155                            found_tests = True156                            tests_config = testsuites["meson"]157                            break158            if found_tests:159                break160    elif config.default_pattern == "waf":161        tests_config = testsuites["waf"]162    if "tox.ini" in files:163        requirements.add_buildreq("tox")164        requirements.add_buildreq("pytest")165        requirements.add_buildreq("virtualenv")166        requirements.add_buildreq("pluggy")167        requirements.add_buildreq("py-python")168def load_specfile(specfile):169    """Load the specfile object."""...binary-trees.py
Source:binary-trees.py  
...16    if l is None:17        return 118    else:19        return 1 + check_tree(l) + check_tree(r)20def make_check(itde, make=make_tree, check=check_tree):21    i, d = itde22    return check(make(d))23def get_argchunks(i, d, chunksize=5000):24    assert chunksize % 2 == 025    chunk = []26    for k in range(1, i + 1):27        chunk.extend([(k, d)])28        if len(chunk) == chunksize:29            yield chunk30            chunk = []31    if len(chunk) > 0:32        yield chunk33def main(n, min_depth=4):34    max_depth = max(min_depth + 2, n)35    stretch_depth = max_depth + 136    if mp.cpu_count() > 1:37        pool = mp.Pool()38        chunkmap = pool.map39    else:40        chunkmap = map41    print('stretch tree of depth {0}\t check: {1}'.format(42          stretch_depth, make_check((0, stretch_depth))))43    long_lived_tree = make_tree(max_depth)44    mmd = max_depth + min_depth45    for d in range(min_depth, stretch_depth, 2):46        i = 2 ** (mmd - d)47        cs = 048        for argchunk in get_argchunks(i,d):49            cs += sum(chunkmap(make_check, argchunk))50        print('{0}\t trees of depth {1}\t check: {2}'.format(i, d, cs))51    print('long lived tree of depth {0}\t check: {1}'.format(52          max_depth, check_tree(long_lived_tree)))53if __name__ == '__main__':54    import sys55    sys.path.append("../timer")56    from timer_embedded import timeit...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!!
