
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):
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.id)
return team.id
if __name__ == "__main__":
client = GetTeamId()
team = sys.argv[1]
print("Going to get team", team)
client.handle(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):
self.id = 4444444
self.name = "foo-team"
class TestGetTeamId(TestCase):
@patch("src.get_team_id.Github.get_organization")
def test_can_get_id(self, mock_github):
mock_github.return_value.get_teams.return_value = [
Team()
]
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):
@patch("src.jira_ticket.JIRA.create_issue")
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)
mock_jira.assert_called_once()
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
self.auth()
def auth(self):
load_dotenv()
username = os.getenv("JIRA_USERNAME")
password = os.getenv("JIRA_PASSWORD")
self.jira = JIRA(server="https://foo.atlassian.net",
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:
print(issue)
return False