在AWS CodeBuild中执行pytest报错:NameError: name 'add_numbers'未定义
I’ve run into similar import-related issues with Python tests in CodeBuild before, and based on your code and scenario, here are the most likely fixes to get your tests running correctly:
1. Rename Your Module to Avoid Conflicts with Python’s Built-ins
This is the most probable root cause. Your code file is named code.py, but Python has a built-in standard library module also called code (used for interactive code sessions).
Locally, Python prioritizes files in your current working directory over built-in modules, so your import works. But in CodeBuild’s environment, the sys.path order or execution context might cause Python to load the built-in code module instead of your custom one—hence the NameError when trying to access add_numbers.
Fix Steps:
- Rename your
code.pyto something unique, likecalculator_functions.py - Update your test file’s import statement to match:
import calculator_functions def test_adding_module(): result = calculator_functions.add_numbers(12, 8) assert result == 20
2. Verify Your CodeBuild Working Directory & Buildspec
Make sure your CodeBuild project is executing tests from the correct directory where both code.py and your test file live. Check your buildspec.yml to ensure the pytest command targets the right files and runs from the project root.
Example buildspec that should work:
version: 0.2 phases: install: runtime-versions: python: 3.11 # Use a version matching your local environment commands: - pip install pytest build: commands: - pytest your_test_file.py -v # Replace with your actual test filename
If your files are in a subdirectory, adjust the path (e.g., pytest tests/your_test_file.py) or add a cd command to switch to the right directory first.
3. Force Python to Load Your Local Module (If You Don’t Want to Rename)
If renaming isn’t an option, explicitly add your project directory to Python’s module search path at the top of your test file. This ensures your custom code.py takes priority over the built-in module:
import sys import os # Add the current file's directory to the start of sys.path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import code def test_adding_module(): result = code.add_numbers(12, 8) assert result == 20
Start with the first fix (renaming the module)—it’s the cleanest solution and avoids future conflicts with other built-ins.
内容的提问来源于stack exchange,提问作者Sadeel Anjum

