Skip to content

Commit cd2f3e0

Browse files
committed
test(tasks): add unit tests
1 parent 80d4116 commit cd2f3e0

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

tests/test_tasks_fn.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Copyright 2022 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
"""Task Queue function tests."""
15+
import unittest
16+
17+
from unittest.mock import MagicMock
18+
from flask import Flask, Request
19+
from werkzeug.test import EnvironBuilder
20+
from firebase_functions.tasks import on_task_dispatched, CallableRequest
21+
22+
23+
class TestTasks(unittest.TestCase):
24+
"""
25+
Task Queue function tests.
26+
"""
27+
28+
def test_on_task_dispatched_decorator(self):
29+
"""
30+
Tests the on_task_dispatched decorator functionality by checking
31+
that the __firebase_endpoint__ attribute is set properly.
32+
"""
33+
34+
func = MagicMock()
35+
func.__name__ = "testfn"
36+
decorated_func = on_task_dispatched()(func)
37+
endpoint = getattr(decorated_func, "__firebase_endpoint__")
38+
self.assertIsNotNone(endpoint)
39+
self.assertIsNotNone(endpoint.taskQueueTrigger)
40+
41+
def test_task_handler(self):
42+
"""
43+
Test the proper execution of the task handler created by the on_task_dispatched
44+
decorator. This test will create a Flask app, apply the on_task_dispatched
45+
decorator to the example function, inject a request, and then ensure that a
46+
correct response is generated.
47+
"""
48+
app = Flask(__name__)
49+
50+
@on_task_dispatched()
51+
def example(request: CallableRequest[object]) -> str:
52+
self.assertEqual(request.data, {"test": "value"})
53+
return "Hello World"
54+
55+
with app.test_request_context("/"):
56+
environ = EnvironBuilder(
57+
method="POST",
58+
json={
59+
"data": {
60+
"test": "value"
61+
},
62+
},
63+
).get_environ()
64+
request = Request(environ)
65+
response = example(request)
66+
self.assertEqual(response.status_code, 200)
67+
self.assertEqual(
68+
response.get_data(as_text=True),
69+
'{"result":"Hello World"}\n',
70+
)

0 commit comments

Comments
 (0)