Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I'm getting started writing Google Cloud http Functions using Python and I would like to include unit tests. My function only responds to POST requests so the basic outline of my function is:

def entry_point(request):

    if request.method == 'POST':

        # do something

    else:

        # throw error or similar

I want to write a simple unit test to ensure that if the function receives a GET request the response has a 405 status.

Hence in my unit test I need to pass in a value for the request parameter:

def test_call(self):

    req = #need a way of constructing a request

    response = entry_point(req)

    assert response.status  == 405 # or something like this

Basically I need to construct a request then check that the response status is what I expect it to be. I've googled around and found loads of pages that talk about mocking and all sorts of stuff that I frankly don't understand (I'm not a crash hot developer) so I'm hoping someone can help me with an idiot's guide of doing what I need to do.

I did find this: https://cloud.google.com/functions/docs/bestpractices/testing#unit_tests_2:

from unittest.mock import Mock

import main

def test_print_name():

    name = 'test'

    data = {'name': name}

    req = Mock(get_json=Mock(return_value=data), args=data)

    # Call tested function

    assert main.hello_http(req) == 'Hello {}!'.format(name)

def test_print_hello_world():

    data = {}

    req = Mock(get_json=Mock(return_value=data), args=data)

    # Call tested function

    assert main.hello_http(req) == 'Hello World!'

which kinda helped but it doesn't explain how I can specify the request method (i.e. GET, POST etc...).

1 Answer

0 votes
by (25.1k points)

You can just pass an objectthat has the attributes your code refers to. For me, this will do:

import unittest

from main import entry_point

class Request:

    def __init__(self, method):

        self.method = method

class MyTestClass(unittest.TestCase):

    def test_call_with_request(self):

        request = Request("GET")

        response = entry_point(request)

        assert response.status_code == 405

Related questions

0 votes
1 answer
asked Jun 26, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...