Python Nose:使用Multiprocess插件将测试结果日志记录到文件中

12 投票
1 回答
6403 浏览
提问于 2025-04-17 12:26

我正在尝试把我的测试输出记录到一个文件里,同时还想让它们并行运行。为此,我打算使用multiprocess插件和xunit插件。

我知道这两个插件不能一起使用,因为xunit不会记录任何内容,因为multiprocess并不会直接发送输出。

https://github.com/nose-devs/nose/issues/2

我想找一个替代方案,可以让我把输出写到文件里。这样做的原因是我在运行Selenium测试,每次出错时,错误信息的堆栈跟踪非常长,导致标准输出几乎被填满。

如果有一些方法能缓解这个问题也不错,因为Selenium的文档对如何配置日志输出的说明非常少。

我还尝试了一种比较简单的标准输出重定向:

#nosetests > file.txt

但这也不管用。

1 个回答

16

如果你想在命令行中使用基本的重定向,可以这样做:

nosetests &> output.txt

不过根据你的问题,似乎你更想做这样的事情:

$nosetests --processes 4 --with-xunit --xunit-file=test_output.xml

完整示例

$ls
test_nose.py    test_nose.pyc

$cat test_nose.py

import sys
import os
import time

def setUp():
    pass

def test_1():
    time.sleep(5)
    with open('test_pid_' + str(os.getpid()), 'w') as f:
        f.write(str(os.getpid()) + '\n')

def test_2():
    time.sleep(5)
    with open('test_pid_' + str(os.getpid()), 'w') as f:
        f.write(str(os.getpid()) + '\n')

def test_3():
    time.sleep(5)
    with open('test_pid_' + str(os.getpid()), 'w') as f:
        f.write(str(os.getpid()) + '\n')

def test_4():
    time.sleep(5)
    with open('test_pid_' + str(os.getpid()), 'w') as f:
        f.write(str(os.getpid()) + '\n')

def tearDown():
    pass

$ nosetests --processes 4 --with-xunit --xunit-file=test_output.xml
....
----------------------------------------------------------------------
Ran 4 tests in 5.223s

OK

$ ls
test_nose.py    test_output.xml test_pid_55247  test_pid_55249
test_nose.pyc   test_pid_55246  test_pid_55248

$ cat test_pid*
55246
55247
55248
55249

$ xmllint -format test_output.xml 
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="nosetests" tests="0" errors="0" failures="0" skip="0"/>

看起来这并没有像你说的那样工作 :)

但是

$nosetests --processes 4 &> output.txt

还有

$nosetests --with-xunit --xunit-file=test_output.xml

去做吧。

参考资料:

在 Bash 脚本中重定向 stderr 和 stdout

$man xmllint

$nosetests -h

撰写回答