You have mocked the ftp.nlst()
method and its returned value, you only need to pass in the self.ftp
object to the get_file_list()
function. Finally, assert whether the return value meets expectations.
E.g.
main.py
:
def get_file_list(ftp_conn):
filematch = '*.csv'
ftp_list = ftp_conn.nlst(filematch)
return ftp_list
test_main.py
:
import unittest
from unittest.mock import patch, MagicMock
import ftplib
from main import get_file_list
class TestExample(unittest.TestCase):
def setUp(self):
self.ftp = ftplib.FTP()
self.ftp.nlst = MagicMock(return_value=[1, 2, 3])
def test_get_file_list(self):
actual = get_file_list(self.ftp)
self.assertEqual(actual, [1, 2, 3])
if __name__ == '__main__':
unittest.main()
unit test result:
⚡ coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/66458222/test_main.py && coverage report -m --include='./src/**'
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Name Stmts Miss Cover Missing
-----------------------------------------------------------------------
src/stackoverflow/66458222/main.py 4 0 100%
src/stackoverflow/66458222/test_main.py 13 0 100%
-----------------------------------------------------------------------
TOTAL 17 0 100%