我的单元测试中是否存在未发现的逻辑错误?

Do I have an unfound logic error in my unit test?

我想看看我在 Python 单元测试中遗漏了什么(如果有的话)。我最近被要求编写一些单元测试。我是 IT 领域的新手,以前从未做过单元测试。在学习了几个教程之后,我对测试基本功能和确保一切正常工作有了不错的理解,但是有人可以看看下面的内容并告诉我我是否在逻辑上遗漏了什么吗?

此单元测试只是确保加载文件。我没有收到任何错误(这让我松了一口气——我已经为此做了很多工作!),但我觉得我可能遗漏了一些东西。下面是模型:

我的单元测试通过了,但我只是想知道我是否正在测试所有正确的东西。我找不到任何关于读取文件时潜在逻辑错误的单元测试。

import unittest, os, json

class TestLoadFile(unittest.TestCase):
    """Set up unittests for loading a file."""

    def setUp(self):
        data = {
            "name": "mike smith",
            "location": "atlanta, ga",
            "languages": {
                "first": "python",
                "second": "ruby",
                "third": "javascript"
            },
            "salary": "75000"
        }

        with open('test.json', 'w', encoding='utf-8') as f:
            json_info = json.dump(data, f, ensure_ascii=False, indent=4)

    def tearDown(self):
        os.unlink('test.json')

    def test_read_file(self):
        with open('test.json', 'r') as json_file:
            data = json.load(json_file)
            try:
              test_data_1 = data['name']
              test_data_2 = data['location']
              test_data_3 = data['languages']['second']
              test_data_4 = data['marital_status']

              # Assertions
              self.assertEqual(test_data_1, "mike smith")
              self.assertIn("atlanta", test_data_2)
              self.assertEqual(test_data_3, "ruby")
              self.assertRaises(KeyError, test_data_4)
            except:
              pass

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

请注意,这显然只是一个模型。我只包含了 try/except,因为它在 KeyError 处一直失败,我不确定如何在不包装 try/except 的情况下明确绕过它。有什么我应该测试但我没有测试的吗,特别是当涉及到涉及读取文件的单元测试时?我只是想成为一个更强大的代码 reader 以便它帮助我构建更好的单元测试。

非常感谢!

通常,单元测试涉及测试一小部分代码以确保其正常运行。但是,在这里您似乎只是在测试 python 是否正常运行(可以 write/read 一个文件,并将其解析为字典)。

在我看来这个测试似乎没有必要,因为我们知道 python 有效。我们不需要编写额外的单元测试来确保基本 python 功能正常工作,因为如果它只是随机停止工作,就会出现更大的问题。

但是,如果您编写了自定义方法来解析文件并且在解析后需要采用特定格式,我建议您一定要测试一下!

mycode.py
----
def parse_config(path_to_config):
  if not os.path.exists(path_to_config):
     raise RuntimeException(f"Config file not found at path: {path_to_config}")

config = {
 'name': None,
 'location': None,
 'languages': None
}
with open(path_to_config, 'r') as json_file:
 config_data = json.load(json_file)

 for config_key in config.keys():
   if config_key in config_data:
     config[config_key] = config_data[key]

return config

test.py
---
def test_parse_config():

 with self.assertRaises(RuntimeException):
   parse_config('')

 config = parse_config('test.json')

 self.assertEqual(config['name'], 'mike smith')
 self.assertEqual(config['location'], 'atlanta')

 with self.assertRaises(KeyError):
   config['marital_status']