You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在AWS CodeBuild中执行pytest报错:NameError: name 'add_numbers'未定义

Fixing "NameError: name 'add_numbers' is not defined" in AWS CodeBuild Python Tests

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.py to something unique, like calculator_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:41:03