Mocking, Python, Pytest
Ok this is going to be a collection of notes to self. This post does a good job of summing up some mock patterns with PyTest. I then had to mock the Snyk client which depended on the Requests library. I chose not to mock the requests library but the methods in the snyk library. The thing was the method I mocked returned the “Response” object and I wanted to use the json() feature of that object/class to return the results.
@WIP Taking advantage of a running Lambda function and it’s state https://aws.amazon.com/blogs/compute/sharing-secrets-with-aws-lambda-using-aws-systems-manager-parameter-store/ under the section Lambda function has a nice “trick” of setting above the class app = None then later on it will see if that is set def lambda_handler(event, context): global app # Initialize app if it doesn't yet exist if app is None: print("Loading config and creating new MyApp...") config = load_config(full_config_path) app = MyApp(config) return "MyApp config is " + str(app.
Mocking in Python
Serious note to self. I wanted to mock the Github module for python. My simple class will get the ID of the team. from github import Github, Team from dotenv import load_dotenv import os import sys import json class GetTeamId: def __init__(self): load_dotenv() self.team_id = 5555 self.token = os.environ.get("GITHUB_TOKEN") self.client = Github(self.token) self.org = self.client.get_organization('FooBar') def handle(self, team_name): teams = self.org.get_teams() for team in teams: if team_name == team.name: print("Team id", team.
Serverless Python and Example App WIP
There are good docs on this http://serverless.com platform. For Python https://serverless.com/framework/docs/providers/aws/examples/hello-world/python/#hello-world-python-example https://github.com/serverless/examples I will cover some items here I need to do time after time. Tagging ENV settings Testing Testing Example file test_cf_backuper.py: import unittest import mock from mock import MagicMock from get_buckets import GetBuckets import boto3 real_client = boto3.client('cloudformation') import logging import json from CFBackuper import CFBackuper logging.basicConfig() log = logging.getLogger() log.setLevel(logging.DEBUG) class TestHandler(unittest.TestCase): def test_get_one_template(self): client = CFBackuper() results = client.