开发者

Python - Extend an API client class or pass instance

开发者 https://www.devze.com 2023-03-26 09:06 出处:网络
I\'m interacting with an API for which I have a Python library. The library provides an APIClient class which provides all the functionality of the API. I want to interact with this API according to s

I'm interacting with an API for which I have a Python library. The library provides an APIClient class which provides all the functionality of the API. I want to interact with this API according to some logic, and I would like to be able to test the logic wihtout making API calls (i.e. a mock) as it is transactional.

Clearly I need to mock out (at some stage) some of the API client's functionality, but I'm unsure how best to go about this.

Should I simply extend the APIClient class, implement my logic and then extend my class again to create a mock version:

class MyClass(APIClient):
   pass #Lots of interesting things actually happen here

class MyTestClass(MyClass):

   def an_overridden_method(self):
      pass #here I implement a method for testing

Or should I pass an APIClient instance to my class and, when I want to test, should I pass i开发者_开发知识库n a mocked out version of the APIClient class?

class MyClass(object):

   def __init__(self, api_client):
      self.api_client = api_client

class MockAPIClient(APIClient):

   def an_overwritten_method(self):
      pass

Or is there an alernative, 'best practice' way for me to implement this?


You would normally not mock parts of the unit under test. If you're testing MyClass, one of the things you would like to test is that it creates and executes transactions when it's really supposed to do that. The overridden method, in your example, would go un-tested.

Instead, you should mock the layer that would actually cause transactions to occur; arrange for SomeDatabaseApi.connect, SomeDatabaseApi.Connection.startTransaction and so on to actually be mock stubs, so that the unit under tests still calls them, but then you can see how they were called afterwards.

There's probably more more mock testing frameworks for python than you could possibly need, but I've made good use of MiniMock, it's simple, effective and expressive.


+1 for passing in the api_client instance; keeps thinks loosely coupled.

Also, depending on the APIClient class, I would create a completely new class, without inheriting from the original APIClient.

0

精彩评论

暂无评论...
验证码 换一张
取 消