简体   繁体   中英

How to mock a Django internal library using patch decorator

I'm mocking an internal library class (Server) of python that provides connection to HTTP JSON-RPC server. But when running the test the class is not mocking. The class is used calling a project class that is a wrapper for other class that effectively instantiates the Server class.

I extract here the parts of the code that give sense for what I'm talking about.

Unit test :

@patch('jsonrpc_requests.jsonrpc.Server')
def test_get_question_properties(self, mockServer):
    lime_survey = Questionnaires()
    # ...

Class Questionnaires :

class Questionnaires(ABCSearchEngine):
    """ Wrapper class for LimeSurvey API"""

    def get_question_properties(self, question_id, language):
        return super(Questionnaires, self).get_question_properties(question_id, language)

Class Questionnaires calls the method get_question_properties from class ABCSearchEnginge(ABC) . This class initializes the Server class to provide the connection to the external API.

Class ABCSearchEnginge :

class ABCSearchEngine(ABC):
    session_key = None
    server = None

    def __init__(self):
        self.get_session_key()

    def get_session_key(self):
        # HERE the self.server keep getting real Server class instead the mocked one
        self.server = Server(
            settings.LIMESURVEY['URL_API'] + '/index.php/admin/remotecontrol')

As the test is mocking Server class why it's not mocking? What is the missing parts?

From what i see you didnt add a return value.

Were did you put the mocked value in : @patch('jsonrpc_requests.jsonrpc.Server') ?

If you try to add a MagicMock what happend (Dont forget to add from mock import patch, MagicMock )?

@patch('jsonrpc_requests.Server', MagicMock('RETURN VALUE HERE'))

You also need to Mock the __init__ method (Where Server is this one from jsonrpc_requests import Server ):

@patch.object(Server, '__init__', MagicMock(return_value=None))

I extrapolated your problem from my own understanding, maybe you need to fix some path ( Mock need the exact path to do the job).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM