Skip to content

Commit 534b3b0

Browse files
fix: bug where init isn't called with cors enabled (#272)
1 parent a4eb8fa commit 534b3b0

2 files changed

Lines changed: 40 additions & 6 deletions

File tree

src/firebase_functions/https_fn.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -432,14 +432,19 @@ def example(request: Request) -> Response:
432432
options = HttpsOptions(**kwargs)
433433

434434
def on_request_inner_decorator(func: _C1):
435+
func_with_init = _core._with_init(func)
436+
437+
if options.cors is not None:
438+
wrapped_function = _cross_origin(
439+
methods=options.cors.cors_methods,
440+
origins=options.cors.cors_origins,
441+
)(func_with_init)
442+
else:
443+
wrapped_function = func_with_init
444+
435445
@_functools.wraps(func)
436446
def on_request_wrapped(request: Request) -> Response:
437-
if options.cors is not None:
438-
return _cross_origin(
439-
methods=options.cors.cors_methods,
440-
origins=options.cors.cors_origins,
441-
)(func)(request)
442-
return _core._with_init(func)(request)
447+
return wrapped_function(request)
443448

444449
_util.set_func_endpoint_attr(
445450
on_request_wrapped,

tests/test_https_fn.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from werkzeug.test import EnvironBuilder
1010

1111
from firebase_functions import core, https_fn
12+
from firebase_functions.options import CorsOptions
1213

1314

1415
class TestHttps(unittest.TestCase):
@@ -42,6 +43,34 @@ def init():
4243

4344
self.assertEqual(hello, "world")
4445

46+
def test_on_request_calls_init_function_with_cors(self):
47+
app = Flask(__name__)
48+
49+
hello = None
50+
51+
@core.init
52+
def init():
53+
nonlocal hello
54+
hello = "world"
55+
56+
func = Mock(__name__="example_func", return_value="OK")
57+
58+
with app.test_request_context("/"):
59+
environ = EnvironBuilder(
60+
method="POST",
61+
json={
62+
"data": {"test": "value"},
63+
},
64+
).get_environ()
65+
request = Request(environ)
66+
decorated_func = https_fn.on_request(
67+
cors=CorsOptions(cors_origins="*", cors_methods="GET")
68+
)(func)
69+
70+
decorated_func(request)
71+
72+
self.assertEqual(hello, "world")
73+
4574
def test_on_call_calls_init_function(self):
4675
app = Flask(__name__)
4776

0 commit comments

Comments
 (0)