python - 如何从测试内部访问 py.test capsys?

标签 python unit-testing pytest python-unittest

py.test 文档说我应该将 capsys 参数添加到我的测试方法中,但在我的情况下这似乎不可能。

class testAll(unittest.TestCase):

    def setUp(self):
        self.cwd = os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0])
        os.chdir(self.cwd)

    def execute(self, cmd, result=0):
        """
        Helper method used by many other tests, that would prevent replicating too much code.
        """
        # cmd = "%s > /dev/null 2>&1" % cmd
        ret = os.system(cmd) >> 8
        self.assertEqual(ret, result, "`%s` returned %s instead of %s (cws=%s)\n\t%s" % (cmd, ret, result, os.getcwd(), OUTPUT)) ### << how to access the output from here

    def test_1(self):
        self.execute("do someting", 0) 

最佳答案

您可以在继承 capsys 的类中定义一个辅助函数。 fixture :

@pytest.fixture(autouse=True)
def capsys(self, capsys):
    self.capsys = capsys
然后在测试中调用这个函数:
out,err = self.capsys.readouterr()

assert out == 'foobar'
感谢 Michał Krassowski 的解决方法,帮助我解决了类似的问题。
https://github.com/pytest-dev/pytest/issues/2504#issuecomment-309475790

关于python - 如何从测试内部访问 py.test capsys?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16039463/

相关文章:

python - 删除 csv 中的最后一行

python 数字长度验证器

python - 在 Pandas DataFrame 子集(副本)上设置值很慢

android - 如何基于 Observable 返回值对 Presenter 方法进行单元测试?

python - 使用绝对路径时出现IOError : [Errno 2] No such file or directory - on linux,

python - Pytest - 重用为不同用户提供不同输出的固定装置

python - 如何在 django 翻译中保留内联链接?

javascript - 如何使用实用 meteor :mocha? 在 Meteor 的单元测试中伪造用户

android - 无法解决 Gradle 中的 Mockito 依赖项

python - 如何断言类型等于给定值