samedi 16 mars 2019

Why does python mock.patch work differently when arguments are used vs return_value?

I'm trying to mock out the return value of a dependent method but the return value is different between using the return_value and adding an additional argument to the mock.patch. Please help me figure out why. I tried searching online but couldn't find an answer to this.

library/abc.py:

from tools.operating_system import os_name

class ABC(object):    
    def get_os_info(self):
        return os_name()

tools/operating_system.py:

import os

def os_name():
    return os.name

library/test_abc.py:

from unittest import TestCase, mock
from library.abc import ABC

class TestMain(TestCase):
    # This works
    def test_mocking_os_name(self):
        with mock.patch('tools.operating_system.os.name', 'test'):
            abc = ABC()
            res = abc.get_os_info()
            self.assertEqual(res, 'test')

    # The test fails because this is does not work. 
    # The return value is: <MagicMock name='name' id='4515046400'>
    def test_mocking_os_name(self):
        with mock.patch('tools.operating_system.os.name') as mock_name:
            mock_name.return_value = 'test'
            abc = ABC()
            res = abc.get_os_info()
            self.assertEqual(res, 'test')

Aucun commentaire:

Enregistrer un commentaire