如何单元测试函数打开json文件?

时间:2017-07-18 10:19:15

标签: python-3.x unit-testing

以下功能打开并加载Json文件。我的问题是测试它的最佳方法是什么?

def read_file_data(filename, path):
    os.chdir(path)
    with open(filename,  encoding="utf8") as data_file:
        json_data = json.load(data_file)
    return json_data

filenamepath作为sys.argv传入。

我想我在测试用例中需要样本数据才能开始但不确定我将如何实际使用它来测试函数

class TestMyFunctions(unittest.TestCase):
    def test_read_file_data(self):
        sample_json = {
                      'name' : 'John',
                      'shares' : 100,
                      'price' : 1230.23
                      }

任何指针都会受到赞赏。

3 个答案:

答案 0 :(得分:0)

我认为你想要做的就是制作JSON文件,对该JSON文件的内存版本进行硬编码,并在两者之间断言等于。

根据您的代码:

class TestMyFunctions(unittest.TestCase):
    def test_read_file_data(self):
        import json
        sample_json = {
                      'name' : 'John',
                      'shares' : 100,
                      'price' : 1230.23
                      }
        sample_json = json.dump(sample_json, ensure_ascii=False)
        path = /path/to/file
        filename = testcase.json
        self.assertEqual(read_file_data(filename, path), sample_json)

答案 1 :(得分:0)

如上所述,您无需重新测试标准python库代码是否正常工作,因此通过创建一个硬编码文件,您也可以通过在代码单元之外进行测试来破坏单元测试的重点。 / p>

相反,正确的方法是使用pythons mocking framework来模拟文件的打开。因此测试你的函数返回正确读取的json。

e.g。

from unittest.mock import patch, mock_open
import json

class TestMyFunctions(unittest.TestCase):


@patch("builtins.open", new_callable=mock_open,
       read_data=json.dumps({'name' : 'John','shares' : 100,
                        'price' : 1230.23}))
def test_read_file_data(self):
    expected_output = {
                  'name' : 'John',
                  'shares' : 100,
                  'price' : 1230.23
                  }
    filename = 'example.json'
    actual_output = read_file_data(filename, 'example/path')

    # Assert filename is file that is opened
    mock_file.assert_called_with(filename)

    self.assertEqual(expected_output, actual_output)

答案 2 :(得分:0)

  1. 请首先检查以下答案: How to use mock_open with json.load()?

  2. 一些答案​​使用json.dump而不是json.dumps插值,这是错误的。

  3. 读取,打开,加载(如前所述)已通过标准Python库的测试,因此您宁愿考虑测试一些实际列的值/类型或json文件中的某些行,如果您做到了,这将不再是单元测试,它将是集成测试,因为您已经将依赖项与方法(在这种情况下为json数据)耦合了,这对于通过嘲笑。