Search code examples
pythondjangomockingamazon-product-api

How can I test the amazon api?


I have the following code.

How can I test the function create_items_by_parent_asin?

def get_amazon():
    return AmazonAPI(settings.AMAZON_ACCESS_KEY, settings.AMAZON_SECRET_KEY, settings.AMAZON_ASSOC_TAG)

def get_item_by_asin(asin: str, response_group='Large'):
    amazon = get_amazon()
    product = amazon.lookup(ItemId=asin, ResponseGroup=response_group)
    return product

def create_items_by_parent_asin(self, asin: str):
    amazon_item = get_item_by_asin(asin, response_group='Large')
    ....

Solution

  • You don't test the API, you mock the interactions with amazon away with a different implementation of AmazonAPI.

    In python this can be done using unittest.mock: https://docs.python.org/3/library/unittest.mock.html

    It's been a long time since I've done this in python, but iirc you can just do something like this in your testclasses (untested, I adapted the example from the docs):

    testproduct = ... # static product you will use in your tests
    with patch('AmazonAPI') as mock:
        instance = mock.return_value
        instance.lookup.return_value = testproduct
        product = x.create_items_by_parent_asin("...") # this should now be your testproduct
    

    If product is a non-trivial thing to create an instance of you can also mock this away by doing:

    testproduct = Mock()
    testproduct.<method you want to mock>.return_value = ...