Mock을 사용하여 함수 / 메소드가 호출되지 않았 음을 확인
Mock 라이브러리를 사용하여 응용 프로그램을 테스트하고 있지만 일부 함수가 호출되지 않았다고 주장하고 싶습니다. 모의 문서는 mock.assert_called_with
and와 같은 메소드에 대해 이야기 mock.assert_called_once_with
하지만 mock.assert_not_called
모의가 호출 되지 않았는지 확인하는 것과 관련이 있거나 비슷한 것을 찾지 못했습니다 .
시원하거나 파이썬처럼 보이지는 않지만 다음과 같은 것을 사용할 수 있습니다.
def test_something:
# some actions
with patch('something') as my_var:
try:
# args are not important. func should never be called in this test
my_var.assert_called_with(some, args)
except AssertionError:
pass # this error being raised means it's ok
# other stuff
이것을 달성하는 방법에 대한 아이디어가 있습니까?
도움을 주셔서 감사합니다 :)
이것은 귀하의 경우에 효과가 있습니다.
assert not my_var.called, 'method should not have been called'
견본;
>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have been'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: a was called and should not have been
오래된 질문이지만 현재 mock
라이브러리 (unittest.mock의 백 포트)가 assert_not_called
메소드를 지원 한다는 것을 추가하고 싶습니다 .
당신을 업그레이드하십시오.
pip install mock --upgrade
당신은 확인할 수 called
속성을, 그러나 당신의 주장이 실패 할 경우, 당신이 알고 싶을 것이다 다음 것은 뭔가 에 대한 정보가 처음부터 표시하는 당신은뿐만 아니라 준비 할 수 있도록 예상치 못한 통화. 를 사용하면 대신 unittest
내용을 확인할 수 있습니다 call_args_list
.
self.assertItemsEqual(my_var.call_args_list, [])
실패하면 다음과 같은 메시지가 나타납니다.
AssertionError : 요소 개수가 같지 않았습니다. 첫 번째는 0, 두 번째는 1 : call ( 'first argument', 4)
클래스를 사용하여 테스트 할 때 unittest.TestCase 를 상속하면 다음 과 같은 메소드를 사용할 수 있습니다.
- assertTrue
- 주장하다
- assertEqual
비슷합니다 ( 파이썬 문서 에서 나머지를 찾으십시오).
In your example we can simply assert if mock_method.called property is False, which means that method was not called.
import unittest
from unittest import mock
import my_module
class A(unittest.TestCase):
def setUp(self):
self.message = "Method should not be called. Called {times} times!"
@mock.patch("my_module.method_to_mock")
def test(self, mock_method):
my_module.method_to_mock()
self.assertFalse(mock_method.called,
self.message.format(times=mock_method.call_count))
With python >= 3.5
you can use mock_object.assert_not_called()
.
Judging from other answers, no one except @rob-kennedy talked about the call_args_list
.
It's a powerful tool for that you can implement the exact contrary of MagicMock.assert_called_with()
call_args_list
is a list of call
objects. Each call
object represents a call made on a mocked callable.
>>> from unittest.mock import MagicMock
>>> m = MagicMock()
>>> m.call_args_list
[]
>>> m(42)
<MagicMock name='mock()' id='139675158423872'>
>>> m.call_args_list
[call(42)]
>>> m(42, 30)
<MagicMock name='mock()' id='139675158423872'>
>>> m.call_args_list
[call(42), call(42, 30)]
Consuming a call
object is easy, since you can compare it with a tuple of length 2 where the first component is a tuple containing all the positional arguments of the related call, while the second component is a dictionary of the keyword arguments.
>>> ((42,),) in m.call_args_list
True
>>> m(42, foo='bar')
<MagicMock name='mock()' id='139675158423872'>
>>> ((42,), {'foo': 'bar'}) in m.call_args_list
True
>>> m(foo='bar')
<MagicMock name='mock()' id='139675158423872'>
>>> ((), {'foo': 'bar'}) in m.call_args_list
True
So, a way to address the specific problem of the OP is
def test_something():
with patch('something') as my_var:
assert ((some, args),) not in my_var.call_args_list
Note that this way, instead of just checking if a mocked callable has been called, via MagicMock.called
, you can now check if it has been called with a specific set of arguments.
That's useful. Say you want to test a function that takes a list and call another function, compute()
, for each of the value of the list only if they satisfy a specific condition.
You can now mock compute
, and test if it has been called on some value but not on others.
참고URL : https://stackoverflow.com/questions/12187122/assert-a-function-method-was-not-called-using-mock
'IT story' 카테고리의 다른 글
이전 버전의 R 패키지 설치 (0) | 2020.07.21 |
---|---|
1 == 1 == 1이 true를 반환하고“1”==“1”==“1”이 true를 반환하고“a”==“a”==“a”가 false를 반환하는 이유 (0) | 2020.07.21 |
인수 '()'및 키워드 인수 '{}'이 (가)있는 Django Reverse (0) | 2020.07.21 |
HashMap get / put 복잡성 (0) | 2020.07.21 |
JavaScript에 유니 코드 문자 삽입 (0) | 2020.07.21 |