systemdebt
systemdebt

Reputation: 4941

update a mocked object in python

I have a mocked object created as follows:

    with patch('requests.get') as request:
      self.request = request
      self.request.session = MockSession()
      self.request.cookies = {}

How can it be updated through another function

Upvotes: 1

Views: 907

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16815

If you want to save a patched object, you have to start and stop patching manually. If you use the context manager (e.g. with patch), the patching will be reverted at exiting the scope.
Here is what you can do:

class TestSomething(unittest.TestCase):
    def setUp(self):
      self.patcher = patch('requests.get')  # returns the patcher object
      self.request = self.patcher.start()  # returns the patched object
      self.request.session = MockSession()
      self.request.cookies = {}

    def tearDown(self):
        sef.patcher.stop()

    def test_03_set_nonce(self):
        self.web_session.set_nonce(self.request)
        self.assertTrue(len(self.request.cookies) > 0, 'set_nonce failed.')

Note that I didn't check the actual test - this depends on your application logic.

You can also do the patching directly in the test:

    @patch('requests.get')
    def test_03_set_nonce(self, request):
        request.session = MockSession()
        request.cookies = {}
        self.web_session.set_nonce(request)
        self.assertTrue(len(request.cookies) > 0, 'set_nonce failed.')

Upvotes: 2

Related Questions