2 years ago

#69860

test-img

tg295

Mock entire client class with pytest

I have a class that inherits from another class in which we build a client:

class Client(ClientLibrary):

    def __init__(self, hosts=[{'host':<HOST_ADDRESS>, 'port':<PORT>}], **kwargs):
        ''' alternative constructor, where i'd pass in some defaults to simplify connection'''
        super().__init__(hosts, *args, **kwargs)


    def some_method(self):
        ...

I want to test this class, and already have a test server set up that I want to connect to for testing. My initial approach was to create a MockClient that inherits from the original Client but swaps out the hosts parameter for the test host like so:

# I create a mock client that inherits from the original `Client` class, but passes in the host and port of the test server.

class MockClient(Client):

    def __init__(self, hosts=[{'host':MOCK_HOST, 'port':MOCK_PORT}]):

        super().__init__(hosts=hosts)

The idea was then that i'd use this mock client in the tests, however I have faced a lot of issues where I am testing functions that encapsulate the original Client class. I have tried patching it but keep on running into issues.

Is there a better way to approach this? And can this be done using pytest fixtures?

I want to be able to perform the following sorts of tests:

class TestFunctionThatUtilisesClient:

     def test_in_which_class_is_constructed_explicitly(self):
         client = Client()
         r = client.some_method()
         assert r == 'something'

    
     def test_in_which_class_is_constructed_implicitly(self):
         r = another_method() # Client() is called somewhere in here
         assert r == 'something else'

python

pytest

python-unittest

0 Answers

Your Answer

Accepted video resources