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
freshmanc
V2EX  ›  Python

关于 unittest,如何从文件添加测试用例?

  •  
  •   freshmanc · 2017-04-27 23:58:05 +08:00 · 2963 次点击
    这是一个创建于 2526 天前的主题,其中的信息可能已经有所发展或是发生改变。

    近日学校软件测试实验课……任务需要做一个 func 函数做类似这样的工作(不使用库函数):

    datetime.date(year,month,day)+datetime.timedelta(days =2)
    

    函数实现问题不大,用元组输入输出,错误输入(月份,日期越界什么的)抛出异常,在网上了解到 unittest 这个工具,网上的教程以及官方文档中提及 testcase 都是直接把用例写在代码里,不知有没有从外部文件导入测试用例的方法?

    6 条回复    2017-04-28 17:33:22 +08:00
    freshmanc
        1
    freshmanc  
    OP
       2017-04-28 00:01:42 +08:00 via Android
    啊…写的时候突然想到异常怎么做,就改了正文然而没改标题…
    xiechengen
        2
    xiechengen  
       2017-04-28 00:55:21 +08:00
    有的,还可以写在 xml file 里方便后期更改
    gefranks
        3
    gefranks  
       2017-04-28 00:58:44 +08:00
    我们有个很老的框架是用 excel 组织的用例.用例都是类似函数一样的。然后用 java 里面的反射来执行真正的函数
    awkun
        4
    awkun  
       2017-04-28 12:48:15 +08:00
    doctest 也可以独立文件的~


    x.py

    ```
    def add(a, b):
    return a + b
    ```

    case.txt

    ```
    >>> from x import add
    >>> add(1, 2)
    3
    >>> add(3, 97)
    100
    >>> add(3, 3) != 5
    True
    ```

    ```
    $ python -m doctest -v case.txt
    Trying:
    from x import add
    Expecting nothing
    ok
    Trying:
    add(1, 2)
    Expecting:
    3
    ok
    Trying:
    add(3, 97)
    Expecting:
    100
    ok
    Trying:
    add(3, 3) != 5
    Expecting:
    True
    ok
    1 items passed all tests:
    4 tests in case.txt
    4 tests in 1 items.
    4 passed and 0 failed.
    Test passed.
    ```

    https://docs.python.org/2/library/doctest.html
    awkun
        5
    awkun  
       2017-04-28 12:55:03 +08:00
    freshmanc
        6
    freshmanc  
    OP
       2017-04-28 17:33:22 +08:00 via Android
    @xiechengen 啊,确实用 xml 之类的比 csv 方便很多
    @gefranks 不懂 Java,不过提供了一个好思路
    @awkun 谢谢你的代码…如果从文件中获取数据例如
    2016 2 30
    2017 3 26
    当作测试数据,不知道是否可行?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5439 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:09 · PVG 17:09 · LAX 02:09 · JFK 05:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.