代码之家  ›  专栏  ›  技术社区  ›  sorin

如何使py.test或nose在所有python文件中查找测试?

  •  4
  • sorin  · 技术社区  · 16 年前

    我确实有几个小模块,测试在其中,并且 py.test 或 nose 不查找它们,因为它们不包含 test 在他们的文件名中。

    我怎么能说服你呢 P.试验 或 鼻子 要在所有python文件中查找测试,递归地-“”包括那些没有 测试 在其文件名“”中?

    在源文件中,我保留了标准命名约定: class testSomeName 用方法 def test_some_name .

    如果这是不可能的,我可以使用其他什么解决方案来获得相同的结果。

    我不想手动创建包含测试的所有文件的列表,我想要一个支持发现的解决方案。

    4 回复  |  直到 14 年前
        1
  •  5
  •   Rod    16 年前

    你也可以看看 Nose 它可以发现测试,而不必使用固定的文件名约定。

    您可以使用以下代码绕过用于筛选nose中文件的regexp。 创建一个python模块(即 my_nosetests.py )

    import nose
    from nose.plugins.base import Plugin
    
    class ExtensionPlugin(Plugin):
    
        name = "ExtensionPlugin"
    
        def options(self, parser, env):
            Plugin.options(self,parser,env)
    
        def configure(self, options, config):
            Plugin.configure(self, options, config)
            self.enabled = True
    
        def wantFile(self, file):
            return file.endswith('.py')
    
        def wantDirectory(self,directory):
            return True
    
        def wantModule(self,file):
            return True
    
    
    if __name__ == '__main__':
        includeDirs = ["-w", ".", ".."]
        nose.main(addplugins=[ExtensionPlugin()], argv=sys.argv.extend(includeDirs))
    

    现在运行 桃蚜属 好像你在跑步 nosetests 你应该让你的测试运行。请注意,实际上您正在加载所有模块并在其中搜索测试。注意模块加载的任何副作用。

        2
  •  6
  •   hpk42    16 年前

    用py.test很简单。创建一个 conftest.py 包含此内容的文件:

    # content of conftest.py file at root of your project
    def pytest_collect_file(path, parent):
        if path.ext == ".py":
            return parent.Module(path, parent)
    

    这将扩展收集过程,为每个“.py”文件创建一个测试“module”节点。把这个放进 混杂的事物 文件使其成为特定于项目的扩展名,如果键入以下内容,将自动加载该扩展名:

    py.test 
    

    出于信息目的,您还可以键入:

    py.test --collectonly
    

    要查看收集了哪些测试和文件,示例输出:

    <Directory 'morecollect'>
       <Module 'conftest.py'>
       <Directory 'pkg'>
         <Module 'test_x.py'>
            <Function 'test_hello2'>
       <Module 'x.py'>   # this is collected because of our conftest.py extension
         <Function 'test_hello'>
    

    如果需要,您也可以打包以上内容 混杂的事物 作为一个文件 installable plugin 并通过安装插件使扩展可用。在这种情况下,你不需要任何 混杂的事物 完全是文件。

        3
  •  5
  •   Andrew_1510    14 年前

    将文件“setup.cfg”放在项目的根目录下,它包含以下两行:

    [pytest]
    python_files=*.py
    

    然后py.test从所有 *.py 文件夹。这里解释一下: pytest docs

    鼻子:

    nosetests --all-modules
    
        4
  •  1
  •   Manoj Govindan    16 年前

    这个 documentation 说

    默认情况下,所有不以点开头的目录都将被遍历,以查找test_*.py和*.py文件。这些python文件以其包名导入。

    您能确保您的代码就是这样的吗?

    更新

    (警告:我没有尝试过/测试过这个)使用 hooks 用于收集目录和文件?

    py.test调用以下两个基本钩子来收集文件和目录:

    def pytest_collect_directory(path, parent):
        """ return Collection node or None for the given path. """
    
    def pytest_collect_file(path, parent):
        """ return Collection node or None for the given path. """
    

    两者均返回A collection node 对于给定路径。所有钩子实现返回的所有节点都将参与收集和运行协议。这个 parent 对象是父节点,可用于通过 parent.config 对象。

    推荐文章