这有点复杂,因为我正在调试一些很久以前用python2.7编写的代码
在迁移到python3的过程中(我知道,我知道),在尝试修复单元测试时遇到了这个问题
TypeError: object() takes no parameters
我将列出下面的函数。我必须替换很多函数和对象的名称。如果您看到模块名称不一致,请假定是输入错误。
首先是它呼叫的班级
class Parser(object):
def __init__(self, some_instance, some_file):
self._some_instance = some_instance
self.stream = Parser.formsomestream(some_file)
self.errors = []
@staticmethod
def formsomestream(some_file):
# return a stream
class BetterParser(Parser):
def parse(self):
# skip some steps, shouldn't relate to the problem
return details # this is a string
class CSVUploadManager(object):
def __init__(self, model_instance, upload_file):
self._model_instance = model_instance
self._upload_file = upload_file
# then bunch of functions here
# then.....
def _parse(self):
parser_instance = self._parser_class(self._model_instance, self._upload_file)
self._csv_details = parser_instance.parse()
# bunch of stuff follows
def _validate(self):
if not self._parsed:
self._parse()
validator_instance = self._validator_class(self._model_instance, self._csv_details)
# some attributes to set up here
def is_valid(self):
if not self._validated:
self._validate()
现在测试函数
从somewhere.to.this.validator导入MockUploadValidator
从另一个.place导入CSVUploadManager
class TestSomething(SomeConfigsToBeMixedIn):
@mock.patch('path.to.BetterParser.parse')
@mock.patch('path.to.SomeValidator.__new__')
@mock.patch('path.to.SomeValidator.validate')
def test_validator_is_called(self, mock_validator_new, mock_parse):
mock_validator_new.return_value = MockUploadValidator.__new__(MockUploadValidator)
mock_parse.return_value = mock_csv_details
mock_validator_new.return_value = MockUploadValidator()
string_io = build_some_string_io_woohoo() # this returns a StringIO
some_file = get_temp_from_stream(string_io)
upload_manager = CSVUploadManager(a_model_instance, some_file)
upload_manager.is_valid() # this is where it fails and produces that error
self.assertTrue(mock_parse.called)
self.assertTrue(mock_validator_new.called)
validator_new_call_args = (SomeValidator, self.cash_activity, mock_csv_details)
self.assertEqual(mock_validator_new._mock_call_args_list[0][0], validator_new_call_args)
如您所见,CSVUploadManager接收django模型实例和类似obj的文件,这会触发
self._parser_class
BetterParser
,那么
做它的事情。
TypeError:object()不接受任何参数
-
为什么会出现这种错误?
-
-
这也会导致其他测试(在不同的测试用例中)失败,如果我不使用失败的测试来测试它们,它们通常会通过。为什么?
-
编辑:添加回溯
Traceback (most recent call last):
File "/path/to/lib/python3.6/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "/path/to/test_file.py", line 39, in test_validator_is_called:
upload_manager.is_valid()
File "/path/to/manager.py", line 55, in is_valid
self._validate()
File "/path/to/manager.py", line 36, in _validate
validator_instance = self._validator_class(self._model_instance, self._csv_details)
TypeError: object() takes no parameters