Some small examples of Python mocks

Source: Internet
Author: User
Tags assert

1. If I want to mock the date object in the library, but I just want to mock the Today () method, that is, today () returns the results I want, but other date initialization methods cannot be changed.

From datatime import date with
patch (' mymodule.date ') as mock_date:
    mock_date.taday.return_value = Date ( 2010,10,8)
    Mock_date.side_effect = Lambda *args, **kw:date (*args, **kw)
    
    assert mymodule.date.today () = = Date ( 2010,10,8)
    assert mymodule.date (2009,6,8) = = Date (2009,6,8)


2. Configure mocks

mock = Mock ()
attrs = {' Method.return_value ': 3, ' Other.side_effect ': Keyerror}
mock.configure_mock (**attrs)
Mock.method ()   # return 3
mock.other ()    # return Keyerror

3.mock functions used in other module

If test_fuction_uu.py to test Fuction_uu, but Fuction_uu called myfuction, I want to mock this myfuction. Finally, it was done in the patch way below.

test_module.py

Def myfuction (): Return
    2


def fuction_uu (): Return
    myfuction ()

test_mock_fuction.py

@patch (' Test_module.myfuction ', magicmock (return_value =))
def test_faction_uu ():
    print  Fuction_uu (
    
if __name__ = = ' __main__ ':
    test_faction_uu ()

4. For class patch, note that Setup and teardown, in the official mock document, say that if an exception is thrown in Setup, then teardown will not be executed, which could create a hole. The document says that using the cleanup function in Unittest2 can avoid this problem.

Class MyTest ():
    def setUp (self):
        patcher = Patch (' Package.module.Class ')
        self. Mockclass = Patcher.start ()
        self.addcleanup (patcher.stop)
    
    def test_something (self):
        assert package. Module.class is self. Mockclass   

5.patch.object can have the effect of "replace" parameters, the following

@patch. Object (SomeClass, ' Class_mothod ') 
def Test (mock_method):
    someclass.class_method (3)
    Mock_ Method.assert_called_with (3)
    
test ()   # Attention:no parameter!


6.mock Database Operations

mock = mock ()
cursor = mock.connection.cursor.return_value
cursor.execute.return_value = [' foo ']
Mock.conection.cursor (). Execute ("SELECT 1")
# return [' foo ']
expected = Call.connection.cursor (). Execute (" Select 1 ")
mock.mock_calls
#return [Call.connection.cursor (), Call.connection.cursor (). Ececute (' Select 1 ')]
mock.mock_calls = = expected
#return True





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.