Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

python mock what is return_value in the following

i am very new to python mock and so just trying to understand the same. In the below code what is the difference between 1 and 2 statements indicated below,because in the end i can set mock_response.status_code with either of the statements

   import requests

    def get_data():
        response = requests.get('https://www.somesite.com')
        return response.status_code

    if __name__ == '__main__':
        print get_data()

Now what is the difference between the following codes,

    from call import get_data
    import unittest
    from mock import Mock,patch
    import requests

    class TestCall(unittest.TestCase):
        def test_get_data(self):
            with patch.object(requests,'get') as get_mock:
                1.get_mock.return_value = mock_response = Mock()
                  # OR 
                2.mock_response = get_mock.return_value
                mock_response.status_code = 200
                assert get_data() == 200

    unittest.main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looking at the docs:

return_value: The value returned when the mock is called. By default this is a new Mock (created on first access). See the return_value attribute.

You are mocking the get function of the requests module. The get method is supposed to return a response object which later you assert its status_code. Therefore you're telling the get mock function to return a mock response. According to the docs, return_value by default returns a Mock object, hence there should be no difference between 1 and 2 except that 1 is explicitly creating a Mock and 2 uses the default behavior.

As a side note, that unit test is testing nothing because you set the status_code on the Mock object and then assert it. It's like:

status_code = 200
assert status_code == 200

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...