Python模块单元测试的最佳文件结构组织? [英] Optimal file structure organization of Python module unittests?

查看:38
本文介绍了Python模块单元测试的最佳文件结构组织?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遗憾的是,我发现在 Python 中保持单元测试的方法太多了,而且它们通常没有很好的文档记录.

Sadly I observed that there are are too many ways to keep your unittest in Python and they are not usually well documented.

我正在寻找一种终极"结构,可以满足以下大部分要求:

I am looking for an "ultimate" structure, one would accomplish most of the below requirements:

  • 可被测试框架发现,包括:
    • pytest
    • 鼻子测试
    • 毒物

    请提供一个进行假测试的示例测试文件,指定文件名和目录.

    Please provide a sample test file that does a fake test, specify filename and directory.

    推荐答案

    这是我一直在使用的方法:

    Here's the approach I've been using:

    目录结构

    # All __init__.py files are empty in this example.
    app
        package_a
            __init__.py
            module_a.py
        package_b
            __init__.py
            module_b.py
        test
            __init__.py
            test_app.py
        __init__.py
    main.py
    

    ma​​in.py

    # This is the application's front-end.
    #
    # The import will succeed if Python can find the `app` package, which
    # will occur if the parent directory of app/ is in sys.path, either 
    # because the user is running the script from within that parect directory
    # or because the user has included the parent directory in the PYTHONPATH
    # environment variable.
    
    from app.package_a.module_a import aaa
    print aaa(123, 456)
    

    module_a.py

    # We can import a sibling module like this.
    from app.package_b.module_b import bbb
    def aaa(s, t):
        return '{0} {1}'.format(s, bbb(t))
    
    # We can also run module_a.py directly, using Python's -m option, which
    # allows you to run a module like a script.
    #
    #    python -m app.package_a.module_a
    if __name__ == '__main__':
        print aaa(111, 222)
        print bbb(333)
    

    module_b.py

    def bbb(s):
        return s + 1
    

    test_app.py

    import unittest
    
    # From the point of view of testing code, our working modules
    # are siblings. Imports work accordingly, as seen in module_a.
    from app.package_a.module_a import aaa
    from app.package_a.module_a import bbb
    
    class TestApp(unittest.TestCase):
    
        def test_aaa(self):
            self.assertEqual(aaa(77, 88), '77 89')
    
        def test_bbb(self):
            self.assertEqual(bbb(99), 100)
    
    # Simiarly, we can run our test modules directly as scripts using the -m option,
    # or using nose.
    #
    #    python -m app.test.test_app
    #    nosetests app/test/test_app.py
    
    if __name__ == '__main__':
        unittest.main()
    

    这篇关于Python模块单元测试的最佳文件结构组织?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆