How to mock and test a django view including external api call
I want to test a django view which includes a call to an external API. The API call is wrapped up by another package (jira). When the view is called a jira ticket is created for a Project (model). How would I properly test the view while preventing that the external API is called. The view looks like this:
class RequestHelp(View):
def get(self, context, pk=None, **response_kwargs):
# get the project to create the ticket for
project = Project.objects.get(id=pk)
# initialize the jira client
jira = JIRA(
server=settings.JIRA_URL,
basic_auth=(settings.JIRA_USERNAME, settings.JIRA_PASS),
)
# create the ticket in jira
new_issue = jira.create_issue(
project=settings.JIRA_PROJECT,
summary= project.title ,
description="Would you please be so nice and help me",
reporter={"name": "My User"},
issuetype={"name": "An Issue"},
)
return HttpResponseRedirect("/")
The test at the moment looks like this:
class TestRequestHelp(TestCase):
@classmethod
def setUpTestData(cls):
cls.std_user = User.objects.create_user(
username="john",
email="john@doe.de",
password="secret",
is_staff=False,
is_superuser=True,
)
def test_get_help_logged_in(self):
self.client.login(username="john", password="secret")
project, status = Project.objects.get_or_create(title="Test")
response = self.client.get(f"/project/help/{project.pk}", follow=True)
self.assertEqual(200, response.status_code)
A "normal" test of the view works but always creates a ticket which is not desirable. Any help with this would be appreciated.