python 🚀
mocking 🚀
tdd 🚀
unittest 🚀
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):
        self.team_id = 5555
        self.token = os.environ.get("GITHUB_TOKEN")
        self.client = Github(self.token) = self.client.get_organization('FooBar')

    def handle(self, team_name):
        teams =
        for team in teams:
            if team_name ==
                print("Team id",

if __name__ == "__main__":
    client = GetTeamId()
    team = sys.argv[1]
    print("Going to get team", team)

But I need test coverage on this so I made this test.

from unittest import TestCase
import unittest
from unittest.mock import patch, Mock
import json
from src.get_team_id import GetTeamId

class Team:
    def __init__(self): = 4444444 = "foo-team"

class TestGetTeamId(TestCase):
    def test_can_get_id(self, mock_github):
        mock_github.return_value.get_teams.return_value = [
        client = GetTeamId()
        results = client.handle("foo-team")    

        self.assertEqual(4444444, results)

Know how long that took!

Example Two

Mocking JIRA:

from unittest import TestCase
import unittest
from unittest.mock import patch, Mock
import json
from src.jira_ticket import JiraTicket

class TestJiraCreateTicket(TestCase):

    def test_can_make_ticket(self, mock_jira):
        mock_jira.return_value.create_issue.return_value.update.return_value = True
        client = JiraTicket()
        title = "(RENOVATE PR OPEN) Update dependency @ionic/core to v4.6.0 292416206"
        project = "PENG"
        message = "\nTitle: Foo Bar\nIssue Url: https://boo.baz\nState: open\n"
        label = "renovate"
        client.create_ticket(title, message, project, label)

and the class:

import json
from dotenv import load_dotenv
from collections import Counter
from jira import JIRA
import os

class JiraTicket:
    def __init__(self):
        self.jira = None

    def auth(self):
        username = os.getenv("JIRA_USERNAME")
        password = os.getenv("JIRA_PASSWORD")
        self.jira = JIRA(server="",
                         basic_auth=(username, password))

    def handle(self, title, message=None, label=None, project="FOO"):
        """ see if exists if does update """

    def see_if_exists(self, title, project):
        results = self.jira.search_issues("title ~ \"%s\" and project= \"%s\"" % (title, project))
        if len(results) > 0:
            for issue in results:
        return False

Good reads