用 py.test 赶上 sys.exit

catch sys.exit with py.test

如何在 returns 生成器的函数中使用 pytest 捕获 sys.exit()?在下面的代码中,f() only returns hello world if 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,代码可以正常工作。有什么想法吗?

仅仅调用一个生成器函数并不会执行其中的任何代码——这只会在您迭代返回的生成器时发生。尝试 list(f(x=False)),或者 f(x=False).next()