如何为print语句编写python单元测试?

2024-10-01 09:41:40 发布

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

我是编写python单元测试的新手,请帮助我为下面的函数编写测试用例,该函数只有print语句而不是return语句

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)))

Tags: 函数fromimportselfiftimeoswith
1条回答
网友
1楼 · 发布于 2024-10-01 09:41:40

您可以使用contextlib的^{}

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: ")

相关问题 更多 >