Skip to content

Commit

Permalink
fix: Support relative imports for submodules (#169)
Browse files Browse the repository at this point in the history
  • Loading branch information
di committed Dec 28, 2021
1 parent 6f4a360 commit 9046388
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/functions_framework/_function_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ def load_function_module(source):
directory, filename = os.path.split(realpath)
name, extension = os.path.splitext(filename)
# 2. Create a new module
spec = importlib.util.spec_from_file_location(name, realpath)
spec = importlib.util.spec_from_file_location(
name, realpath, submodule_search_locations=[directory]
)
source_module = importlib.util.module_from_spec(spec)
# 3. Add the directory of the source to sys.path to allow the function to
# load modules relative to its location
Expand Down
11 changes: 11 additions & 0 deletions tests/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,3 +604,14 @@ def tests_cloud_to_background_event_client_invalid_source(
resp = background_event_client.post("/", headers=headers, json=tempfile_payload)

assert resp.status_code == 500


def test_relative_imports():
source = TEST_FUNCTIONS_DIR / "relative_imports" / "main.py"
target = "function"

client = create_app(target, source).test_client()

resp = client.get("/")
assert resp.status_code == 200
assert resp.data == b"success"
22 changes: 22 additions & 0 deletions tests/test_functions/relative_imports/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Function used in test for relative imports."""

from .test import foo


def function(request):
"""Test HTTP function who returns a value from a relative import"""
return foo
1 change: 1 addition & 0 deletions tests/test_functions/relative_imports/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
foo = "success"

0 comments on commit 9046388

Please sign in to comment.