AttributeError:None没有属性“print”

2024-05-29 03:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在练习一些单元测试,并尝试检查for循环中的输出。这是我的运行代码

def main():

  for i in range(100):
    print("Argh!")

很基本,这是我的测试代码。在

^{pr2}$

这是我返回的错误消息。我不知道怎么解决这个问题。 更新:这是完整的追溯

======================================================================
ERROR: test_main (__main__.TestMain)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:/Users/jsalce/Documents/Testsuites/IfStatements/Testsuite.py", line 9, in test_main
    with mock.patch.object(RunFile, 'print') as mock_print:
  File "C:\Python33\lib\unittest\mock.py", line 1148, in __enter__
    original, local = self.get_original()
  File "C:\Python33\lib\unittest\mock.py", line 1122, in get_original
    "%s does not have the attribute %r" % (target, name)
AttributeError: <module 'RunFile' from      'C:\\Users\\jsalce\\Documents\\Testsuites\\IfStatements\\RunFile.py'> does not have the attribute 'print'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

提前谢谢大家!在


Tags: inpytestformainlinemockusers
1条回答
网友
1楼 · 发布于 2024-05-29 03:41:03

你通常需要一个易于处理的模块。通常,您需要修补比您要替换的内容高一级的内容。例如,如果您想修补模块bar中的foo函数,那么您需要mock.patch.object(bar, 'foo')。在

在您的例子中,技术上,printbuiltin,但是您可以在使用它的模块上修补它。这将添加一个可以测试断言的RunFile.print“方法”(实际上是一个模拟)。显然,由于print实际上并不存在于模块中,我们需要添加create=True来告诉mock来创建{},因为它还不存在。考虑到这一点,我将unittest重写为:

import RunFile

class TestMain(unittest.TestCase):
    def test_main(self):
        with mock.patch.object(RunFile, 'print', create=True) as mock_print:
            RunFile.main()
        expected_calls = [mock.call('Argh!') for _ in range(100)]
        mock_print.assert_has_calls(expected_calls)

if __name__ == '__main__':
    unittest.main()

相关问题 更多 >

    热门问题