我有以下代码:
@istest
@patch.object(Chapter, 'get_author')
@patch.object(Chapter, 'get_page_count')
def test_book(self, mock_get_author, mock_get_page_count):
book = Book() # Chapter is a field in book
mock_get_author.return_value = 'Author name'
mock_get_page_count.return_value = 43
book.get_information() # calls get_author and then get_page_count
Run Code Online (Sandbox Code Playgroud)
在我的代码中,在 get_author 之后调用的 get_page_count 返回“Autor name”而不是预期值 43。我该如何解决这个问题?我尝试了以下方法:
@patch('application.Chapter')
def test_book(self, chapter):
mock_chapters = [chapter.Mock(), chapter.Mock()]
mock_chapters[0].get_author.return_value = 'Author name'
mock_chapters[1].get_page_count.return_value = 43
chapter.side_effect = mock_chapters
book.get_information()
Run Code Online (Sandbox Code Playgroud)
但后来我收到一个错误:
TypeError: must be type, not MagicMock
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的任何建议!
我有一个日志类,允许将前缀添加到日志中.如果没有给出前缀,则默认为"".
class PrefixedLog(Loggable):
def __init__(self):
self._prefix = None
@property
def prefix(self):
if self._prefix:
return self._prefix
else:
return ""
@prefix.setter
def prefix(self, value):
self._prefix = value
@property
def log(self):
if not hasattr(self, '_log') or not self._log:
log = logging.getLogger(self.__class__.__name__)
self._log = LoggerAdapter(self._prefix, log)
return self._log
Run Code Online (Sandbox Code Playgroud)
我有另一个类,然后创建另一个类的对象,我正在尝试设置前缀:
class A(PrefixedLog):
def __init__(self, **kwargs):
super(A, self).__init__(**kwargs)
self.b = B()
Run Code Online (Sandbox Code Playgroud)
带前缀的类:
class B(PrefixedLog):
self.another_class = AnotherClass()
if self.prefix:
self.another_class.prefix = 'desired prefix'
Run Code Online (Sandbox Code Playgroud)
我收到这个错误:
AttributeError: 'B' object has no attribute '_prefix'
Run Code Online (Sandbox Code Playgroud)
在...上
if self.prefix:
Run Code Online (Sandbox Code Playgroud)
线.
我已经搜索了解决方案,但大多数都与格式问题有关...我已经确定没有标签.关于问题可能是什么的任何想法?提前致谢. …