func icon indicating copy to clipboard operation
func copied to clipboard

The test_func.py unit test template for Python Knative functions in invalid

Open the-gigi opened this issue 7 months ago • 0 comments

The generated test code invoke sthe function's main() entrypoint with an empty dictionary:

import unittest

func = __import__("func")

class TestFunc(unittest.TestCase):

  def test_func_empty_request(self):
    resp, code = func.main({})
    self.assertEqual(resp, "{}")
    self.assertEqual(code, 200)

if __name__ == "__main__":
  unittest.main()

See code here

But, the main() function expects a a parliament Context that contains a Flask request

from parliament import Context
from flask import Request

...

def main(context: Context):
    """
    Function template
    The context parameter contains the Flask request object and any
    CloudEvent received with the request.
    """
   ...

It should probably generate a context with some mock request. This is what I did for my function, which expects to be invoked with a parameter named descriptions:

import unittest
from parliament import Context


func = __import__("func")


class DummyRequest:
    def __init__(self, descriptions):
        self.descriptions = descriptions

    @property
    def args(self):
        return dict(descriptions=self.descriptions)


class TestFunc(unittest.TestCase):
    def test_func(self):

        result, code = func.main(Context(DummyRequest('flame,confused')))
        expected = """{"flame": "('fire', '🔥')", "confused": "('confused_face', '😕')"}"""
        self.assertEqual(expected, result)
        self.assertEqual(code, 200)


if __name__ == "__main__":
    unittest.main()

the-gigi avatar Jul 28 '24 21:07 the-gigi