0

I have been trying to figure out how do I create a mock for an object I am initializing in the init method of the class. I have been using pytest and mockito to try and do the same, but with least amount of luck.

I have 2 questions here:

  1. How do I initialize the object i have defined in the init method
  2. If the object is a boto3 client, will mock work and is it the most efficient way

The code snipped I am trying to mock is as given below:

../glue.py

class GlueClient():
    def __init__(self):
        self.glue_client = boto3.client("glue")

    def get_databases(self):
        ...
        response = self.glue_client.get_databases(
                    NextToken=next_token
                )
        ...

Could someone please help?

  • this is why you should use dependency injection. – juanpa.arrivillaga Jul 20 '20 at 12:11
  • @juanpa.arrivillaga, can you give me an example? So i can relate? – user2381538 Jul 20 '20 at 13:20
  • You should pass dependencies as arguments to your constructor, not instantiate them directly in the constructor – juanpa.arrivillaga Jul 20 '20 at 13:28
  • Ok.. yes, that is something that i was hoping to avoid since there are multiple such classes and every time we need to perform something, it would become the callers responsibility to create the glue object and pass it.Instead, by creating the object in __init__ the caller does not need to care about managing the object. Keeps things decoupled. – user2381538 Jul 20 '20 at 13:58
  • Um, no, **it does the exact opposite of that**. Now your classes are *tightly coupled*. Again, that is what dependency injection is all about. Write factory functions to do the gluing together for you. Or use a dependancy injection framework (these are popular in Java, but not python, in python that is just usually done by hand, for better or for worse) – juanpa.arrivillaga Jul 20 '20 at 14:25

0 Answers0