Python:使用文件进行模拟或伪造目录以进行单元测试 [英] Python: Creating a mock or fake directory with files for unittesting

查看:108
本文介绍了Python:使用文件进行模拟或伪造目录以进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为以下功能创建单元测试:

I am trying to create a unit test for the following function:

def my_function(path):
    #Search files at the given path
    for file in os.listdir(path):
        if file.endswith(".json"):
            #Search for file i'm looking for
            if file == "file_im_looking_for.json":
                #Open file
                os.chdir(path)
                json_file=json.load(open(file))
                print json_file["name"]

但是,我无法成功创建包含文件的伪目录,以使该功能正常运行而不是通过错误进行处理.

However I am having trouble successfully creating a fake directory with files in order for the function to work correctly and not through errors.

以下是我到目前为止所拥有的,但是对我来说不起作用,我不确定如何将"file_im_looking_for"作为伪造目录中的文件合并.

Below is what I have so far but it is not working for me, and I'm not sure how to incorporate "file_im_looking_for" as the file in the fake directory.

tmpfilepath = os.path.join(tempfile.gettempdir(), "tmp-testfile")
@mock.patch('my_module.os')

def test_my_function(self):

    # make the file 'exist'
    mock_path.endswith.return_value = True

    file_im_looking_for=[{
      "name": "test_json_file",
      "type": "General"
    }]

    my_module.my_function("tmpfilepath")

任何对我做错事的建议或解决此问题的其他建议,都表示赞赏!

Any advice where I'm going wrong or other ideas to approach this problem are appreciated!

推荐答案

首先,您忘记将模拟对象传递给测试函数.在测试中使用模拟的正确方法应该是这样的.

First of all, you forgot to pass the mocked object to test function. The right way to use mock in your test should be like this.

@mock.patch('my_module.os')
def test_my_function(self, mock_path):

无论如何,您不应该模拟endswith,而是模拟listdir.下面的代码段是一个示例,可能会对您有所帮助.

Anyway, you shouldn't mock the endswith, but the listdir. The snippet below is an example and may help you.

app.py

def check_files(path):
    files = []
    for _file in os.listdir(path):
        if _file.endswith('.json'):
            files.append(_file)
    return files

test_app.py

import unittest
import mock
from app import check_files


class TestCheckFile(unittest.TestCase):

    @mock.patch('app.os.listdir')
    def test_check_file_should_succeed(self, mock_listdir):
        mock_listdir.return_value = ['a.json', 'b.json', 'c.json', 'd.txt']
        files = check_files('.')
        self.assertEqual(3, len(files))

    @mock.patch('app.os.listdir')
    def test_check_file_should_fail(self, mock_listdir):
        mock_listdir.return_value = ['a.json', 'b.json', 'c.json', 'd.txt']
        files = check_files('.')
        self.assertNotEqual(2, len(files))

if __name__ == '__main__':
    unittest.main()

在评论中回答您的问题,您需要从应用程序中模拟json.loadsopen.

Answering your question in comment, you need to mock the json.loads and the open from your app.

@mock.patch('converter.open')
@mock.patch('converter.json.loads')
@mock.patch('converter.os.listdir')
def test_check_file_load_json_should_succeed(self, mock_listdir, mock_json_loads, mock_open):
    mock_listdir.return_value = ['a.json', 'file_im_looking_for.json', 'd.txt']
    mock_json_loads.return_value = [{"name": "test_json_file", "type": "General"}]
    files = check_files('.')
    self.assertEqual(1, len(files))

但是请记住!如果您过于广泛或难以维护,那么重构API应该是个好主意.

But remember! If your is too broad or hard to maintain, perhaps refactoring your API should be a good idea.

这篇关于Python:使用文件进行模拟或伪造目录以进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆