Ner*_*uda 5 python dictionary types unit-testing assertion
我正在构建一个单元测试,断言/检查字典中的所有值是否具有相同的数据类型:float。
Python版本3.7.4
假设我有四个不同的字典:
dictionary1: dict = {
"key 1": 1.0,
}
dictionary2: dict = {
"key 1": "1.0",
}
dictionary3: dict = {
"key 1": 1.0,
"key 2": 2.0,
"key 3": 3.0
}
dictionary4: dict = {
"key 1": "1",
"key 2": "2",
"key 3": 3
}
Run Code Online (Sandbox Code Playgroud)
以及这样的单元测试用例:
class AssertTypeUnitTest(unittest.TestCase):
def test_value_types(self):
dictionary: dict = dictionary
self.assertTrue(len(list(map(type, (dictionary[key] for key in dictionary)))) is 1 and
list(map(type, (dictionary[key] for key in dictionary)))[0] is float)
if __name__ == "__main__":
unittest.main()
Run Code Online (Sandbox Code Playgroud)
预期的结果是,AssertionError如果字典中有一个值不是float,它会抛出一个 ,即它会为 执行此操作dictionary2,但不会为 执行此操作dictionary1。
现在,虽然测试确实适用于 1 个键值对,但在这种情况下,我该如何对多个键值对执行此操作,dictionary3而dictionary4无需添加另一个 for 循环?
IE
for type in list(map(type, (dictionary[key] for key in dictionary))):
self.assertTrue(type is float)
Run Code Online (Sandbox Code Playgroud)
谢谢!
您可以将项目的类型转换为集合并断言它等于一组float:
self.assertSetEqual(set(map(type, dictionary.values())), {float})
Run Code Online (Sandbox Code Playgroud)