1

I am new to writing python unit tests, Please help me to write test cases for the below function which is having only print statements instead of return statements.

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)))
Deepak Mourya
  • 340
  • 2
  • 10
  • 1
    Does this answer your question? [Python: Write unittest for console print](https://stackoverflow.com/questions/33767627/python-write-unittest-for-console-print) – mkrieger1 Sep 02 '21 at 19:45
  • Can you modify `info`? `print` takes a `file` keyword argument to specify a file other than standard output; you can have `info` accept a file-like object and just pass it on to `print`. – chepner Sep 03 '21 at 21:25
  • @chepner Sorry but I didn't understand. Actually, I am getting the following error if trying to follow the below answer comment " if self.f: AtrributeError: 'str' object has no attribute 'f' " – Deepak Mourya Sep 03 '21 at 21:32

1 Answers1

2

You can use contextlib's 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: ")
ti7
  • 16,375
  • 6
  • 40
  • 68