2017-07-18 100 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)