V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
feng32
V2EX  ›  Python

Python unittest 如何运行子目录下的测试用例集

  •  
  •   feng32 · 2016-01-04 20:20:32 +08:00 · 6301 次点击
    这是一个创建于 3027 天前的主题,其中的信息可能已经有所发展或是发生改变。

    目录结构如下

    - module_a.py
    - module_b.py
    - test-suite.py
    - tests/
    -     test_a.py
    -     test_b.py

    请问如何在不使用命令行(它会自动设置 PATH )的情况下,让测试用例跑通?
    - 保证 test_a.py 可以 import module_a.py
    - 保证调用 python test-suite.py 就可以成功调用所有测试用例
    - 保证仅使用 Python 标准库中的东西,无额外依赖

    本来以为应该自己能解决的,但是搞了一个多小时还没搞定。在此请教 Python 高手。
    PS: 发回复前请确认方案可行哦

    第 1 条附言  ·  2016-01-05 17:16:34 +08:00

    问题解决了,就像 @zhuangzhuang1988 给的代码一样:

    import unittest
    
    suite  = unittest.TestLoader().discover("tests")
    unittest.TextTestRunner(verbosity = 2).run(suite)
    
    1. tests/ 目录下不需要放置 __init__.py
    2. 测试用例 import 模块不需要 from .. import xxx ,直接 import 就行
    3. 测试用例文件名必须以 test 开头,一般就用驼峰小写方法命名,不能有连字符 (hyphen)
    4. 每个测试用例是 unittest.TestCase 的一个子类,测试方法名也需要以 test 开头
    5. 执行的时候运行 python test-suite.py 即可

    把结果整理后贴在这里,希望可以帮到和我一样的初学者 :)

    5 条回复    2016-01-05 09:29:06 +08:00
    BiggerLonger
        1
    BiggerLonger  
       2016-01-04 20:54:10 +08:00
    pip install nose
    ahxxm
        2
    ahxxm  
       2016-01-04 21:02:13 +08:00
    发回复前谁知道可行不可行啊

    a) 你得把这项目打包成 project 再 pip install 之才可以 import project.module_a
    b) 你 tests 目录里没有__init__.py
    c) 装个 nose 不会怀孕,又不是项目本身的依赖, 2016 年(没拼错吧)了还不用 virtualenv ?

    另外你的 test_a.py 里如果需要调用 tests/下面的东西, os.path 或者 os.Path 用的是相对路径么?
    mengzhuo
        4
    mengzhuo  
       2016-01-04 23:24:04 +08:00
    楼上说得都没啥问题,但是我司的某个项目结构恰好是这样的,没有任何依赖

    - test.py
    - module
    |- a
    |- b
    -testcases
    |-test_a
    |-test_b

    楼主基础不牢啊
    sys.path 第一个就是当前目录,所以在 test_a 里写 import module_a 肯定可以正常执行的
    然后你就可以在 test-suite.py 里用 lululau 说的 discover 方法
    单独跑 test_a 可以用 python -m unittest testcases.test_a
    zhuangzhuang1988
        5
    zhuangzhuang1988  
       2016-01-05 09:29:06 +08:00   ❤️ 1
    import unittest
    tests = unittest.TestLoader().discover('test')
    unittest.TextTestRunner(verbosity=2).run(tests)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4596 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 01:08 · PVG 09:08 · LAX 18:08 · JFK 21:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.