Search code examples
python-3.xamazon-web-servicesaws-lambdaserverlessaws-sam

Testing Lambda Functions that reference modules included in a layer


I've been working a on a CRUD SAM application using a Python 3.8 runtime. My lambda functions reference a lambda layer that has code shared amongst the functions. My application builds/deploys and I can invoke the functions locally, however, in composing unit tests (using pytest), I'm not sure how to get around my imports referencing a layer in line that doesn't match the file structure.

File structure:

.
├── template.yaml
├── _layer-folder
│   └── _python
│       └── shared_code.py 
├── _lambda
│   ├── some_function.py
│   └── _tests
│       └── test-some-function.py

When running my tests for my lambda functions, I get an import error when I reference a module in that lives in the shared layer. For example:

from some_module_in_a_layer import some_layer_function

Is there a way to configure pytest to reference the correct file directory when running the tests?


Solution

  • I ended up resolving this by appending to the system path when testing or running locally within my __init__.py file.

    if os.environ.get("ENVIRONMENT") == "test":
        sys.path.append(os.getcwd() + '/path/to/layer')