Home:ALL Converter>How to mock and test a django view including external api call

How to mock and test a django view including external api call

Ask Time:2021-12-08T21:46:44         Author:Claas-Thido Pfaff

Json Formatter

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="[email protected]",
            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.

The folder structure is simple. Both files live in the same directory (a django app). So it is:

jira_integration
   - views.py
   - tests.py

Author:Claas-Thido Pfaff,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70276057/how-to-mock-and-test-a-django-view-including-external-api-call
yy