# ModuleNotFoundError: colcon test 期间找不到名为 'my_package' 的模块

- **ID:** `ros2/colcon-test-import-error-pkg-name`
- **领域:** ros2
- **类别:** test_error
- **错误码:** `COL-1002`
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

setup.py 或 setup.cfg 中的 Python 包名称与实际目录名称不匹配，或者由于缺少 --symlink-install 或构建路径问题，包未安装到 Python 环境中。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| ROS2 Foxy Fitzroy | active | — | — |
| ROS2 Galactic Geochelone | active | — | — |
| ROS2 Humble Hawksbill | active | — | — |

## 解决方案

1. ```
   Ensure the Python package name in setup.py matches the directory name. For example, if your package directory is 'my_package', set `name='my_package'` in setup.py. Then rebuild with `colcon build --symlink-install` and run tests with `colcon test --packages-select my_package`.
   ```
2. ```
   If using ament_python, verify that the `entry_points` in setup.py are correct and that the test directory has an `__init__.py` file. Run `colcon test --event-handlers console_direct+` to see the full error trace.
   ```

## 无效尝试

- **** — Running pip install -e . in the package root may install it temporarily, but colcon will overwrite it on next build, and it doesn't fix the root cause. (50% 失败率)
- **** — Deleting the entire build directory and rebuilding is overkill; the issue is usually a configuration mismatch, not a corrupted build. (30% 失败率)
