【问题标题】:How to write python unit test for the print statement?如何为打印语句编写python单元测试?
【发布时间】:2021-11-01 06:40:19
【问题描述】:

我是编写python单元测试的新手,请帮我为以下函数编写测试用例,该函数只有打印语句而不是返回语句。

import os
from pwd import getpwuid
from grp import getgrgid
import time

def info(self):
 if self.f:  // if -f  flag pass with file names then it will be trigger
    for i in self.f:
        owner = getpwuid(os.stat(i).st_uid).pw_name
        group = getgrgid(os.stat(i).st_gid).gr_name
        per = oct(os.stat(i).st_mode)[-3:]
        t = os.stat(i).st_mtime
        print("{} is owned by: {} , group by {} with "
              "permission {} and last modified on {}"
              .format(i, owner, group, per, time.ctime(t)))

【问题讨论】:

  • 这能回答你的问题吗? Python: Write unittest for console print
  • 可以修改info吗? print 采用 file 关键字参数来指定标准输出以外的文件;您可以让info 接受一个类似文件的对象,然后将其传递给print
  • @chepner 抱歉,我不明白。实际上,如果尝试遵循以下答案注释“ if self.f: AtrributeError: 'str' object has no attribute 'f'”,我会收到以下错误

标签: python python-3.x unit-testing


【解决方案1】:

你可以使用 contextlib 的redirect_stdout

import io
import unittest
from contextlib import redirect_stdout

import lib_containing_info

class TestInfo():
    def test_info(self)
        f = io.StringIO()
        with redirect_stdout(f):
            lib_containing_info.info()  # function being tested
        self.assertRegex(f.getvalue(), r"is owned by: ")

【讨论】:

  • 在尝试执行上述操作时出现以下错误。 if self.f: AtrributeError: 'str' object has no attribute 'f'
  • 你在哪里使用self.ff 是局部变量,不是实例属性。
猜你喜欢
  • 2016-02-19
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2021-12-21
  • 2012-10-03
  • 1970-01-01
  • 2019-05-03
相关资源
最近更新 更多