【问题标题】:Get pass or fail output from Django unit tests从 Django 单元测试中获取通过或失败的输出
【发布时间】:2020-03-20 06:30:34
【问题描述】:

对于我的 Django 项目,我尝试从 python manage.py test 获取 0 或 1 个输出,以了解是否所有测试都已通过。

我想在 bash 脚本中运行测试,然后让脚本知道是否所有测试都已通过,如果是,则继续执行其他操作。

这是我能得到的最接近的,但输出不正确

output=$(python manage.py test)
output=$(python manage.py test 0 2>&1)

【问题讨论】:

    标签: python django bash testing


    【解决方案1】:

    您正在寻找manage.py test 命令which exits with a status of 1 whenever at least one test fails (or for any error), otherwise exits with 0 when all tests pass 的退出状态($?)。

    Stdlib unittest also has the same behavior.

    所以本质上,你的前提是错误的,实际上你的检查是不正确的——在第一个例子中,你将 STDOUT 从 python manage.py test 保存在变量 output 中,你的第二个例子会引发错误,除非你有一个名为 0 的包,其中包含 test*.py 模块;如果你有这样的包,那么第二个命令会将manage.py test 0 命令中的 STDOUT 和 STDERR 保存为变量 output

    您可以使用$? 来检查last 命令的退出状态:

    python manage.py test
    if [ $? = 0 ]; then
        # Success: do stuff
    else
        # Failure: do stuff
    fi
    

    但是有一个更好的方法,shell 可以在if 中隐式检查退出状态:

    if python manage.py test; then
        # Success: do stuff
    else
        # Failure: do stuff
    fi
    

    如果您不关心 STDOUT/STDERR,您可以将这些流重定向到 /dev/null,POSIX-ly:

    if python manage.py test >/dev/null 2>&1; then
        # Success: do stuff
    else
        # Failure: do stuff
    fi
    

    Bash-ism(适用于其他高级 shell):

    if python manage.py test &>/dev/null; then
        # Success: do stuff
    else
        # Failure: do stuff
    fi
    

    【讨论】:

    • 这是一个详细的答案!好东西
    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多