Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何模拟python内置方法_Python_Unit Testing_Python Mock - Fatal编程技术网

如何模拟python内置方法

如何模拟python内置方法,python,unit-testing,python-mock,Python,Unit Testing,Python Mock,我有一个python方法可以执行以下操作: 使用os.listdir(/test)列出目录下的文件 正则表达式匹配目录下的一些文件,将文件放入列表中 从列表中的文件中读取内容,执行一些聚合操作 显然,在我的例子中,我要测试的唯一有趣的部分是2,3,所以1肯定是我想要嘲笑的东西。我开始在setUp()和tearDown()中的/test文件夹下创建/删除补丁文件。但同事告诉我,在unitest中执行I/O不是个好主意 那么,在我的unitest中模拟os.listdir()构建的最佳方法是什么?或

我有一个python方法可以执行以下操作:

  • 使用os.listdir(/test)列出目录下的文件
  • 正则表达式匹配目录下的一些文件,将文件放入列表中
  • 从列表中的文件中读取内容,执行一些聚合操作
  • 显然,在我的例子中,我要测试的唯一有趣的部分是2,3,所以1肯定是我想要嘲笑的东西。我开始在setUp()和tearDown()中的/test文件夹下创建/删除补丁文件。但同事告诉我,在unitest中执行I/O不是个好主意

    那么,在我的unitest中模拟os.listdir()构建的最佳方法是什么?或者有什么选择

    我能做些什么来实现以下目标:

    setUp() {
        #mock a few files eg.test1.txt, test2.txt, test3.txt under directory /test 
        #without physically creating them using I/O
    }
    tearDown() {
       #whatever cleanup required 
    }
    

    使用模拟模块怎么样

    >>> import os
    >>> from mock import MagicMock
    >>> os.listdir = MagicMock(return_value=['file1.txt', 'file2.txt', 'file3.txt'])
    >>> os.listdir('./test')
    ['file1.txt', 'file2.txt', 'file3.txt']
    
    如果你不想使用mokey补丁(即破解)操作系统,那么你可以使用mock_操作系统或类似的工具

    阅读有关启动和停止的信息:

    和:

    我发现Mock模块是列出文件和读取模拟数据的方法。这些当然可以在一个测试中合并,但为了清晰起见,我已经在一个工作文件中将它们分离出来

    import unittest
    from mock import patch, mock_open
    import os
    
    
    class Test(unittest.TestCase):
        @patch.object(os, 'listdir')
        def test_listdir(self, mock_listdir):
            expected = ['file1.txt', 'file2.txt']
            mock_listdir.return_value = expected
            self.assertEquals(expected, Code().get_folder("~"))
    
        def test_file_mock(self):
            expected_string = "Some File Contents"
            mocked_file_object = mock_open(read_data=expected_string)
            with patch('__main__.open', mocked_file_object, create=True) as mocked_open:
                self.assertEquals(expected_string, Code().get_file_as_string('any'))
    
    
    class Code(object):
        def get_folder(self, folder):
            return os.listdir(folder)
    
        def get_file_as_string(self, afile):
            with open(afile, 'r') as handle:
                return handle.read()
    
    
    if __name__ == '__main__':
        unittest.main()
    

    谢谢:)MagicMock会给你一个范围吗?比如模拟开始和停止。看看我答案中的链接。:)