• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pytest.main函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pytest.main函数的典型用法代码示例。如果您正苦于以下问题:Python main函数的具体用法?Python main怎么用?Python main使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了main函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: run

	def run(self, params, args):

		(exitonfail, pretty) = self.fillParams([
			('exitonfail', False),
			('pretty', True)
			])

		exitonfail = self.str2bool(exitonfail)
		pretty = self.str2bool(pretty)

		current_dir = os.getcwd()
		os.chdir('/opt/stack/lib/python3.7/site-packages/stack/commands/report/system')
		tests = glob('tests/*')

		# make it real ugly.
		if exitonfail and not pretty:
			_return_code = main(['--verbose', '--exitfirst', *args, *tests])
		# exit with first failure
		elif exitonfail:
			_return_code = main(['--verbose', '--capture=no', '--exitfirst', *args, *tests])
		# show tracebacks of failures but don't fail.
		elif not pretty:
			_return_code = main(['--verbose', '--capture=no', *args, *tests])
		# pretty and no tracebacks
		else:
			_return_code = main(['--verbose', '--capture=no', '--tb=no', *args, *tests])

		os.chdir(current_dir)

		# If any of the tests failed, throw an error
		if _return_code > 0:
			raise CommandError(self, "One or more tests failed")
开发者ID:StackIQ,项目名称:stacki,代码行数:32,代码来源:__init__.py


示例2: test

def test(arguments=''):
    """Run ODL tests given by arguments."""
    import pytest
    this_dir = os.path.dirname(__file__)
    odl_root = os.path.abspath(os.path.join(this_dir, os.pardir, os.pardir))
    base_args = '-x {odl_root}/odl {odl_root}/test '.format(odl_root=odl_root)
    pytest.main(base_args + arguments)
开发者ID:arcaduf,项目名称:odl,代码行数:7,代码来源:testutils.py


示例3: test_pytest

def test_pytest():
    try:
        import pytest
        import os
        pytest.main('-xvs %s' % os.path.dirname(__file__))
    except ImportError:
        print 'error importing pytest'
开发者ID:FinchPowers,项目名称:StarCluster,代码行数:7,代码来源:__init__.py


示例4: run

 def run(self):
     import pytest
     if self.noweb:
         exit_code = pytest.main(['-m', 'not web'])
     else:
         exit_code = pytest.main([])
     sys.exit(exit_code)
开发者ID:Fxe,项目名称:escher,代码行数:7,代码来源:setup.py


示例5: main

def main():
    logging.basicConfig(level=logging.DEBUG)

    # cleanup any existing data
    netnode.Netnode(TEST_NAMESPACE).kill()

    pytest.main(['--capture=sys', os.path.dirname(__file__)])
开发者ID:williballenthin,项目名称:ida-netnode,代码行数:7,代码来源:test_netnode.py


示例6: run_tests

def run_tests(args):
    """Run tests."""
    args = args # args is unused

    path = os.path.abspath(os.path.dirname(__file__))
    sys.argv[1] = path
    pytest.main()
开发者ID:FrBrGeorge,项目名称:modelmachine,代码行数:7,代码来源:__main__.py


示例7: main

def main():
    if len(sys.argv) > 1:
        wd = sys.argv[1]
    else:
        wd = "."
    student_dirs = filter(os.path.isdir, os.listdir(wd))
    students = []
    for sdir in student_dirs:
        os.path.join(wd, sdir)

        class Student:
            name = sdir
            dirname = os.path.join(wd, sdir)

        students.append(Student)
    for s in students:
        for fname in os.listdir(s.dirname):
            if fname.startswith("test_"):
                s.code = open(os.path.join(s.dirname, fname)).read()
                s.code = s.code.replace("def test_", "def test_" + s.name + "_")
    code = "\n".join(s.code for s in students)
    pooled_test_paths = []
    for s in students:
        path = os.path.join(s.dirname, "tests_pooled.py")
        fw = open(path, "w")
        fw.write(code)
        fw.close()
        print "Written", path
        pooled_test_paths.append(path)
        init_path = os.path.join(s.dirname, "__init__.py")
        if not os.path.isfile(init_path):
            open(init_path, "w").close()
    for path in pooled_test_paths:
        pytest.main(["--color=no", path])
开发者ID:AlexeyFeigin,项目名称:Python2015,代码行数:34,代码来源:pool_tests.py


示例8: run_tests

 def run_tests(self):
     import pytest
     error_code = pytest.main(['-k', 'parse/test/test_settings.py'])
     if error_code:
         sys.exit(errcode)
     errcode = pytest.main(self.test_args)
     sys.exit(errcode)
开发者ID:gJigsaw,项目名称:KataBankOCR,代码行数:7,代码来源:setup.py


示例9: do_list

def do_list(args, unknown_args):
    """Print a lists of tests than what pytest offers."""
    # Run test collection and get the tree out.
    old_output = sys.stdout
    try:
        sys.stdout = output = StringIO()
        pytest.main(['--collect-only'])
    finally:
        sys.stdout = old_output

    # put the output in a more readable tree format.
    lines = output.getvalue().split('\n')
    output_lines = []
    for line in lines:
        match = re.match(r"(\s*)<([^ ]*) '([^']*)'", line)
        if not match:
            continue
        indent, nodetype, name = match.groups()

        # only print top-level for short list
        if args.list:
            if not indent:
                output_lines.append(
                    os.path.basename(name).replace('.py', ''))
        else:
            print(indent + name)

    if args.list:
        colify(output_lines)
开发者ID:LLNL,项目名称:spack,代码行数:29,代码来源:test.py


示例10: merge_config

def merge_config(args):
    collect_config = CollectConfig()
    with silence():
        pytest.main(['--collect-only'], plugins=[collect_config])
    if not collect_config.path:
        return

    config = ConfigParser()
    config.read(collect_config.path)
    if not config.has_section('pytest-watch'):
        return

    for cli_name in args:
        if not cli_name.startswith(CLI_OPTION_PREFIX):
            continue
        config_name = cli_name[len(CLI_OPTION_PREFIX):]

        # Let CLI options take precedence
        if args[cli_name]:
            continue

        # Find config option
        if not config.has_option('pytest-watch', config_name):
            continue

        # Merge config option using the expected type
        if isinstance(args[cli_name], bool):
            args[cli_name] = config.getboolean('pytest-watch', config_name)
        else:
            args[cli_name] = config.get('pytest-watch', config_name)
开发者ID:sysradium,项目名称:pytest-watch,代码行数:30,代码来源:config.py


示例11: test

def test():
    r"""
    Run all the doctests available.
    """
    import pytest
    path = os.path.split(__file__)[0]
    pytest.main(args=[path, '--doctest-modules', '-r s'])
开发者ID:davidbrough1,项目名称:pymks,代码行数:7,代码来源:__init__.py


示例12: main

def main(args):
    print("Running tests, args:", args)
    if args and args != ['-v']:
        return pytest.main(['--capture=sys'] + args)

    engine = tenjin.Engine(cache=False)
    major_version = sys.version_info[0]
    minor_version = sys.version_info[1]
    # Note: This naming is duplicated in .travis.yml
    cov_rc_file_name = jp(_here, '.coverage_rc_' +  str(os.environ.get('TRAVIS_PYTHON_VERSION', str(major_version) + '.' + str(minor_version))))
    with open(cov_rc_file_name, 'w') as cov_rc_file:
        cov_rc_file.write(engine.render(jp(_here, "coverage_rc.tenjin"), dict(
            major_version=major_version, minor_version=minor_version, type_check_supported=type_check.vcheck())))

    rc = pytest.main(['--capture=sys', '--cov=' + _here + '/..', '--cov-report=term-missing', '--cov-config=' + cov_rc_file_name] + (args if args == ['-v'] else []))

    print()
    try:
        del os.environ['PYTHONPATH']
    except KeyError:
        pass
    for env_name in 'prod', 'preprod', 'devlocal', 'devs', 'devi':
        demo_out = jp(_here, env_name + '.demo_out')
        print("Validating demo for env {env} - output in {out}".format(env=env_name, out=demo_out))
        osenv = {'PYTHONPATH': ':'.join(sys.path)}
        with open(demo_out, 'w') as outf:
            rc |= subprocess.check_call((sys.executable, _here + '/../demo/demo.py', '--env', env_name), env=osenv, stdout=outf)
    print()

    return rc
开发者ID:lhupfeldt,项目名称:multiconf,代码行数:30,代码来源:run.py


示例13: test

def test(coverage=False):
    args = []

    if coverage:
        args.append("--cov=.")

    pytest.main(args)
开发者ID:puffinrocks,项目名称:puffin,代码行数:7,代码来源:puffin.py


示例14: main

def main(argv):
    if '--help' in argv:
        print("Usage: ./runtests.py <testfiles>")
        return

    mydir = os.path.dirname(os.path.abspath(__file__))

    verbosity_args = []

    if 'PYGI_TEST_VERBOSE' in os.environ:
        verbosity_args += ['--capture=no']

    if 'TEST_NAMES' in os.environ:
        names = os.environ['TEST_NAMES'].split()
    elif 'TEST_FILES' in os.environ:
        names = []
        for filename in os.environ['TEST_FILES'].split():
            names.append(filename[:-3])
    elif len(argv) > 1:
        names = []
        for filename in argv[1:]:
            names.append(filename.replace('.py', ''))
    else:
        return pytest.main([mydir] + verbosity_args)

    def unittest_to_pytest_name(name):
        parts = name.split(".")
        parts[0] = os.path.join(mydir, parts[0] + ".py")
        return "::".join(parts)

    return pytest.main([unittest_to_pytest_name(n) for n in names] + verbosity_args)
开发者ID:GNOME,项目名称:pygobject,代码行数:31,代码来源:runtests.py


示例15: main

def main():
    import os
    import sys
    from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
    from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach
    
    sys.path[0] = os.getcwd()
    os.chdir(sys.argv[1])
    secret = sys.argv[2]
    port = int(sys.argv[3])
    testFx = sys.argv[4]
    args = sys.argv[5:]    

    DONT_DEBUG.append(os.path.normcase(__file__))
    DEBUG_ENTRYPOINTS.add(get_code(main))

    enable_attach(secret, ('127.0.0.1', port), redirect_output = False)
    sys.stdout.flush()
    print('READY')
    sys.stdout.flush()
    wait_for_attach()

    try:
        if testFx == 'pytest':
            import pytest
            pytest.main(args)
        else:
            import nose
            nose.run(argv=args)
        sys.exit()
    finally:
        pass
开发者ID:JoelMarcey,项目名称:nuclide,代码行数:32,代码来源:testlauncher.py


示例16: run_tests

def run_tests():
    # pytest treats the string given it like a Python string in code, applying an \ sequences to it. Just changing \\ to / makes it unhappy (one test fails, Macs get confused). Just pass in the file name, not the path.
    self_name = os.path.basename(__file__)
    # Get the .py name to this file; it can be run from a .pyc, but that boogers pytest.
    self_name = os.path.splitext(self_name)[0] + ".py"
    # Run all tests -- see http://pytest.org/latest/usage.html#calling-pytest-from-python-code. Produce `XML output <http://pytest.org/latest/usage.html#creating-junitxml-format-files>`_ so that a grader can extract the pass/fail stats.
    pytest.main(self_name + " --junitxml=unit_test.xml")  #' --tb=line' +
开发者ID:nw341,项目名称:mav,代码行数:7,代码来源:mav_recharging_test.py


示例17: main

def main(args):
    os.environ['MULTICONF_WARN_JSON_NESTING'] = 'true'
    
    print("Running tests", args)
    if args and args != ['-v']:
        return pytest.main(['--capture=sys'] + args)

    engine = tenjin.Engine()
    major_version = sys.version_info[0]
    cov_rc_file_name = jp(here, '.coverage_rc_' +  str(major_version))
    with open(cov_rc_file_name, 'w') as cov_rc_file:
        cov_rc_file.write(engine.render(jp(here, "coverage_rc.tenjin"), dict(major_version=major_version)))

    rc = pytest.main(['--capture=sys', '--cov=' + here + '/..', '--cov-report=term-missing', '--cov-config=' + cov_rc_file_name] + (args if args == ['-v'] else []))

    print("Validating demo for all envs")
    try:
        del os.environ['PYTHONPATH']
    except KeyError:
        pass
    for env_name in 'prod', 'preprod', 'devlocal', 'devs', 'devi':
        print()
        osenv = {'PYTHONPATH': ':'.join(sys.path)}
        rc |= subprocess.call((sys.executable, here + '/../demo/demo.py', '--env', env_name), env=osenv)

    return rc
开发者ID:henriklynggaard,项目名称:multiconf,代码行数:26,代码来源:test.py


示例18: RunInSingleDir

def RunInSingleDir(module_name_seq, xmlout, dirname):
    """ Run pytest TestProgram w/ given argv"""

    module_fullpath_list = []
    for module_name in module_name_seq:
        parts = module_name.split('.')
        modname = parts[0]
        test_spec = '.'.join(parts[1:])
        
        module_fullpath = os.path.join(dirname, modname)
        if os.path.isdir(module_fullpath):
            pass
        elif not module_fullpath.endswith('.py'):
            module_fullpath += '.py'
        
        if test_spec:
            module_fullpath += '::' + test_spec.replace('.', '::')

        module_fullpath_list.append(module_fullpath)
        
    result = wingtest_common.XmlTestResult(xmlout)
    runner = wingtest_common.XmlTestRunner(result)
    plugin = CPytestPlugin(dirname, result, runner)
    try:
        import pytest
        # -s turns off stdout/err capturing
        # -p no:terminal turns off printing test result status to stdout
        # --tb=native gets parseable tracebacks on exceptions
        pytest.main(args=['-s', '-p', 'no:terminal', '--tb=native'] + module_fullpath_list, plugins=[plugin])
    except SystemExit:
        raise
    except Exception:
        # Note that import error from test files end up here, so this is
        # not just for runner exceptions
        xmlout._write_exc_info(sys.exc_info())
开发者ID:aorfi,项目名称:2015-2016-Backup,代码行数:35,代码来源:run_pytest_xml.py


示例19: run

def run(**kwargs):
    config_name = kwargs.get('config_name', None)
    groups = kwargs.get('run_groups', [])
    old_groups = kwargs.get('groups', None)
    explain = kwargs.get('explain', None)

    groups_to_run = []
    groups.extend(old_groups or [])

    # Collect from pytest only once!
    pytest.main(['--collect-only', 'fuel_tests', ])
    from fuel_tests.tests.conftest import test_names

    for g in set(groups):
        if g in test_names:
            sys.exit(pytest.main('-m {}'.format(g)))
        if config_name:
            register_system_test_cases(
                groups=[g],
                configs=[config_name])
            groups_to_run.append("{0}({1})".format(g, config_name))
        else:
            register_system_test_cases(groups=[g])
            groups_to_run.append(g)
    if not set([split_group_config(i)[0] if split_group_config(i) else i
               for i in groups_to_run]) < set(get_groups()):
        sys.exit('There are no cases mapped to current group, '
                 'please be sure that you put right test group name.')
    if explain:
        print_explain(groups)
    else:
        register(groups=["run_system_test"], depends_on_groups=groups_to_run)
        TestProgram(groups=['run_system_test'],
                    argv=clean_argv_proboscis()).run_and_exit()
开发者ID:mmalchuk,项目名称:openstack-fuel-qa,代码行数:34,代码来源:run_system_test.py


示例20: main

def main(argv=None):
    """Get arguments and run tests."""
    if not argv:
        argv = sys.argv[1:]

    parser  = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('-l', '--local', action="store_true",
                        help="Skip remote tests")

    args = parser.parse_args(argv)

    # Move us up one if we are in the tests directory
    if os.path.basename(os.path.abspath('.')) == 'tests':
        os.chdir('..')

    # Run the tests
    print('Running py.test tests')
    if args.local:
        print('Skipping remote queue tests')
        pytest.main(['tests/test_options.py', 'tests/test_queue.py',
                     'tests/test_local.py', 'tests/test_config.py'])
    else:
        pytest.main()

    print('py.test tests complete, running local queue test.')
    check_call([sys.executable, 'tests/local_queue.py'])
开发者ID:MikeDacre,项目名称:python-cluster,代码行数:29,代码来源:run_tests.py



注:本文中的pytest.main函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pytest.param函数代码示例发布时间:2022-05-27
下一篇:
Python pytest.importorskip函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap