问题:当元组的元素是列表对象时,如何返回元组的预期长度?
我在Python中编写了一个非常基本的单元测试类来开始学习TDD。我想允许我的类动态分配测试用例输入(存储为元组),具体取决于元组有多少元素。但是,当我检查元组的长度时,其唯一元素是列表对象,返回的长度是列表对象的长度 - 而不是元组。
预期功能:
a = (['a', 'b', 'c'])
len(a) # 1 - one element in the tuple
实际功能:
a = (['a', 'b', 'c'])
len(a) # 3 - which appears to be returning len(a[0])
现在,对于具有多个元素(包括列表对象)的元组,它确实返回了预期的元组长度。因此,当元组中的唯一元素是列表对象时,我的问题似乎才会出现。
这是我写的简单单元测试器类。现在我通过使用第13行的 else子句来解决这个问题。这似乎不是处理此问题的正确方法。
class Unit_Tester:
def __init__(self, function, tests):
self.function_to_test = function
self.test_list = tests
def unit_test(self, function_to_test, test_input, expected_output):
try:
number_of_inputs = len(test_input)
print(number_of_inputs)
if number_of_inputs == 1: function_output = function_to_test(test_input)
elif number_of_inputs == 2: function_output = function_to_test(test_input[0], test_input[1])
elif number_of_inputs == 3: function_output = function_to_test(test_input[0], test_input[1], test_input[2])
else: function_output = function_to_test(test_input)
except Exception as error:
print("Error occurred with test input: [{0}] value: {1}\nError Message: {2}\nCorrect the error and try again.\n"
.format(type(test_input), test_input, error))
else:
try:
assert function_output == expected_output
print(self.unit_test_response(True, test_input, function_output, expected_output))
except AssertionError:
print(self.unit_test_response(False, test_input, function_output, expected_output))
def unit_test_response(self, correct, test_input, function_output, expected_output):
score = "Test Passed" if correct else "Test Failed"
return "{0}\nInput: {1}\nExpected Output: {2}\nFunction Output: {3}\n".format(score, test_input, expected_output, function_output)
def run_unit_tests(self, function_to_test, test_list):
for test_tuple in test_list:
test_input, expected_output = test_tuple
self.unit_test(function_to_test, test_input, expected_output)
def run(self):
self.run_unit_tests(self.function_to_test, self.test_list)