Mocking

There is a Python AWS mocking framework called Moto (http://docs.getmoto.org/en/latest/), but I prefer to use a generic one called mock, which is much more widely supported in the Python community and from Python 3.3 is included in the Python standard library.

The following mocking code can be found at the bottom of serverless-microservice-data-api/test/test_dynamo_get.py:

from unittest import mock

mock.patch.object(lambda_query_dynamo.DynamoRepository,
"query_by_partition_key",
return_value=['item'])
def test_validid_checkstatus_status200(self,
mock_query_by_partition_key):
result = lambda_query_dynamo.Controller.get_dynamodb_records(
self.validJsonDataNoStartDate)
assert result['statusCode'] == '200'

@mock.patch.object(lambda_query_dynamo.DynamoRepository,
"query_by_partition_key",
return_value=['item'])
def test_validid_getrecord_validparamcall(self,
mock_query_by_partition_key):
lambda_query_dynamo.Controller.get_dynamodb_records(
self.validJsonDataNoStartDate) mock_query_by_partition_key.assert_called_with(
partition_key='EventId',
partition_value=u'324')

@mock.patch.object(lambda_query_dynamo.DynamoRepository,
"query_by_partition_and_sort_key",
return_value=['item'])
def test_validid_getrecorddate_validparamcall(self,
mock_query_by_partition_and_sort_key):
lambda_query_dynamo.Controller.get_dynamodb_records(
self.validJsonDataStartDate)
mock_query_by_partition_and_sort_key.assert_called_with(partition_key='
EventId',
partition_value=u'324',
sort_key='EventDay',
sort_value=20171013)

The key observations from this code are as follows:

  • @mock.patch.object() is a decorator for the query_by_partition_key() or query_by_partition_and_sort_key() method we are mocking from the DynamoRepository() class.
  • test_validid_checkstatus_status200(): We mock the calls to query_by_partition_key(). If the query is valid, we get a '200' status code back.
  • test_validid_getrecords_validparamcall(): We mock the calls to query_by_partition_key() and check the method is called with the correct parameters. Note that don't need to check that the lower-level boto3 self.db_table.query() method works.
  • test_validid_getrecordsdate_validparamcall(): We mock the calls to query_by_partition_and_sort_key() and check that the method is called with the correct parameters.
You are not here to test existing third-party libraries or Boto3, but your code and integration with them. Mocking allows you to replace parts of the code under test with mock objects and make an assertion about the method or attributes.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset