I am trying to write unit test for function calling system process os.popen
.
Function:
def change_from(lineTag):
Lines = []
command = "ls -al"
lines = os.popen(command).readlines()
for line in lines:
if lineTag in line:
temp = line.split(":")
Lines.append(temp[1])
return Lines
Initialy I just wrote a simple test:
def test_change_from(self):
lineTag = "undocumented_line:"
Lines = ['43', '45', '47', '50', '51', '52', '53', '54', '55']
self.assertEqual(change_from(lineTag), Lines)
It passed, but gave me warning:
ResourceWarning: unclosed file <_io.TextIOWrapper name=3 encoding='UTF-8'>
lines = os.popen(command).readlines()
So I tried using Mock library to "simulate" os process:
Test:
import unittest
import os
from mock import *
@patch('os.popen')
def test_change_from(self, mock_subproc_popen):
mock_subproc_popen.return_value = Mock(communicate=('ouput', 'error'), returncode=0)
lineTag = "undocumented_line:"
Lines = ['43', '45', '47', '50', '51', '52', '53', '54', '55']
self.assertEqual(change_from(lineTag), Lines)
And I am getting error while running test:
for line in lines:
TypeError: 'Mock' object is not iterable
How could I correctly mock the os.popen process to have test passing without warnings?