用py.test捕获sys.exit

时间:2017-01-12 20:44:13

标签: python generator pytest

如何在返回生成器的函数中使用pytest捕获sys.exit()?在以下代码中,f()仅返回 hello world x = True。但是使用x = False,我希望代码能够启动SystemExit

def test_generator():
    with pytest.raises (SystemExit) as excinfo:
        def f(x = True):
            if x:
                yield 'hello world'
            sys.exit('Test')
        f (x = False)
    assert 'Test' == excinfo.value

py.test抱怨没有引发异常。如果我按yield更改return,则代码可以正常运行。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

仅调用生成器函数不会执行其中的任何代码 - 只有在迭代返回的生成器时才会执行。试试list(f(x=False)),或者f(x=False).next()