ProgramingTip

Python mock의 모의 속성?

bestdevel 2020. 12. 1. 19:12
반응형

Python mock의 모의 속성?


mockPython에서 사용하는 데 많은 어려움이 있습니다 .

def method_under_test():
    r = requests.post("http://localhost/post")

    print r.ok # prints "<MagicMock name='post().ok' id='11111111'>"

    if r.ok:
       return StartResult()
    else:
       raise Exception()

class MethodUnderTestTest(TestCase):

    def test_method_under_test(self):
        with patch('requests.post') as patched_post:
            patched_post.return_value.ok = True

            result = method_under_test()

            self.assertEqual(type(result), StartResult,
                "Failed to return a StartResult.")

시험은 올바른 값을 반환하지만 r.ok모의 목적 True. 에서는 mock라이브러리 에서 속성을 어떻게 모의 소개?


return_value다음 을을합니다 .PropertyMock

with patch('requests.post') as patched_post:
    type(patched_post.return_value).ok = PropertyMock(return_value=True)

requests.post,을 호출 할 때 해당 호출 의 반환 값 에서 값을 반환하도록 PropertyMock속성 ok대해 설정 합니다 True.


수행하는 간결이를하고 간단한 방법은 new_callable patch의 속성 을 사용하여 모의 object-를 만드는 대신 강제 patch로 사용하는 PropertyMock을 구석으로입니다 MagicMock. 전달 된 다른 인수는 개체 patch를 만드는 데 사용 PropertyMock됩니다.

with patch('requests.post', new_callable=PropertyMock, return_value=True) as mock_post:
    """Your test"""

모의 버전 '1.0.1'에서는 질문에 언급 된 더 간단한 구문이 지원되고있는 그대로 작동합니다!

업데이트 된 예제 코드 (unittest 대신 py.test가 사용됨) :

import mock
import requests


def method_under_test():
    r = requests.post("http://localhost/post")

    print r.ok

    if r.ok:
        return r.ok
    else:
        raise Exception()


def test_method_under_test():
    with mock.patch('requests.post') as patched_post:
        patched_post.return_value.ok = True

        result = method_under_test()
        assert result is True, "mock ok failed"

이 코드를 다음과 같이 실행하십시오. (pytest를 설치했는지 확인하십시오)

$ py.test -s -v mock_attributes.py 
======= test session starts =======================
platform linux2 -- Python 2.7.10 -- py-1.4.30 -- pytest-2.7.2 -- /home/developer/miniconda/bin/python
rootdir: /home/developer/projects/learn/scripts/misc, inifile: 
plugins: httpbin, cov
collected 1 items 

mock_attributes.py::test_method_under_test True
PASSED

======= 1 passed in 0.03 seconds =================

참고 URL : https://stackoverflow.com/questions/16867509/mock-attributes-in-python-mock

반응형