title: Unit test for Python AWS Lambda: mock function before module is imported
body: <p>I'm trying to write unit tests for my aws lambda function written in python <code>3.9</code>. I tried different things to mock the <code>get_object</code> function that makes calls to the <code>S3</code>. I wanted to focus only on the <code>calculate</code> method, to verify if I'm getting correct results of an calculation.</p>
  <p>When I try to run the following approach I'm getting credential errors about <code>boto3</code></p>
  <pre class="lang-sh prettyprint-override"><code>python -m unittest tests/app-test.py
  ...
  botocore.exceptions.NoCredentialsError: Unable to locate credentials
  </code></pre>
  <p>Is there a way to import the <code>calculate</code> method from <code>app.py</code> and mock call to the <code>get_object</code> fn?</p>
  <p>directory:</p>
  <pre><code>functions:
  - __init__.py
  - app.py
  tests:
  - __init__.py
  - app-test.py
  </code></pre>
  <p>lambda function <code>app.py</code>:</p>
  <pre class="lang-py prettyprint-override"><code>import json
  import boto3
  
  def get_object():
      s3 = boto3.client('s3')
      response = s3.get_object(Bucket='mybucket', Key='object.json')
      content = response['Body'].read().decode('utf-8')
      return json.loads(content)
  
  
  stops = get_object()
  
  
  def lambda_handler(event, context): 
      params = event['queryStringParameters']
      a = int(params['a'])
      b = int(params['b'])
     
      result = calculate(a, b)
      return {
          'statusCode': 200,
          'body': json.dumps(result)
      }
  
  
  def calculate(a, b):
      return a + b
  </code></pre>
  <p>unit test <code>app-test.py</code>:</p>
  <pre class="lang-py prettyprint-override"><code>import unittest
  from unittest import mock
  
  with mock.patch('functions.app.get_object', return_value={}):
      from functions.app import calculate
  
  class TestCalculation(unittest.TestCase):
     def test_should_return_correct_calculation(self):
       # when
       result = calculate(1, 2)
  
       # then
       self.assertEqual(3, result)     
  
  </code></pre>