One annoying problem I encountered while testing AWS CDK Constructs using pytest

Saravanan Marimuthu
1 min readMay 30, 2022

Module not found error

AWS has released the “assertions” library to test the cloud formation template generated from CDK. This blog post covers one annoying problem I encountered using pytest when I want to run tests and deploy using an AzureDevops multi-stage pipeline.

more information can be found at this official link https://docs.aws.amazon.com/cdk/v2/guide/testing.html

I kept all my test files in a separate test folder and ran tests on that particular folder using the below command from a pipeline.

cd <test directory>: python -m pytest or pytest /

I kept all the other stack files in the root directory. I used the below command to deploy my stacks to AWS cloud

cd <root directory/projects/my_project>: cdk deploy

Problem:

Pytest wants me to specify the imports with an absolute path, if not I will get Module not found error

Pytest wants like: from rootdirectory.projects.my_project.file import func

whereas CDK does not want me to specify the absolute path, if I specify I will get Module not found error.

CDK wants like: from file import func

Solution:

We need to tell the virtual environment about the folder structure in the project.

After the virtual environment is activated, we need to specify the PYTHONPATH value. In my case, I was using a bash task inside Azure DevOps so I have to specify

export PYTHONPATH=”${PYTHONPATH}:$(System.DefaultWorkingDirectory)”

Now I have informed pytest and cdk about my folder structure so I can specify from rootdirectory.projects.my_project.file import func

which is working for both the tests and deployment from the multi-stage pipeline.

--

--