2017-07-18 41 views
0

下面的函数打开并加载Json文件。我的问题是什么是测试它的最好方法?如何进行单元测试打开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 
         } 

任何指针将不胜感激。

+0

'self.assertEqual(sample_json,read_file_data(文件名,路径))'的所有代码 – DeepSpace

+0

第一只使该标准Python库的API调用。该代码已经过测试,不应再次测试,只应测试自己的代码。其次,函数涉及使用代码外部的资源(文件):在单元测试中,您通常会嘲笑这些资源。 This [article](https://www.toptal.com/python/an-introduction-to-mocking-in-python)可能会给你一些想法 –

回答

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) 
+0

@ Jeremy Barnes,谢谢。你能澄清什么路径和文件名指向?如果它引用一个外部json文件,那么sample_json有什么意义? – Darth

+0

示例JSON将成为外部json文件中数据的硬编码版本。它们要进行比较以确保read_file_data函数的正确操作。 这就是'self.assertEqual'调用的用途。 根据我的经验,测试通常是在特定情况和特定输入产生一个且仅有一个特定输出或程序响应的测试用例。 所以,你编写你的JSON文件,在代码中重新创建它,并断言该函数返回的JSON完全是你想要的。 谢谢你要求更多的清晰度。 –

0

如前所述上面,你不需要重新测试标准Python库的代码工作正常,所以通过创建作为还指出一个硬编码的文件,你击败的点通过在您的代码单元之外进行测试来进行单元测试。

相反,正确的做法是使用pythons嘲笑框架来模拟文件的打开。从而测试你的函数返回正确读入的json。

例如

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)