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

VSCode调试Python测试遇ImportError:模块导入路径错误求助

问题描述

项目结构

├── compute_metrics_service
│   ├── tests
│   │   ├── integration
│   │   │   ├── test_app.py
│   │   │   └── __init__.py
│   │   └── unit
│   └── utils
├── data_quality
│   ├── helpers
│   └── tests
│       ├── integration
│       └── unit
└── fetch_data_metrics
    ├── helpers
    └── tests
        ├── integration
        └── unit

错误信息

ImportError: 'test_app' module incorrectly imported from '/Users/xxxx/Documents/SOC/data-quality-tool/data_quality/tests/integration'. Expected '/Users/xxxx/Documents/SOC/data-quality-tool/compute_metrics_service/tests/integration'. Is this module globally installed?

当前PYTHONPATH设置

export PYTHONPATH="$PWD/data_quality:$PWD/compute_metrics_service:$PWD/fetch_data_metrics"

test_app.py代码结构

import unittest
import os
import logging
from datetime import datetime
from unittest import mock
from unittest.mock import MagicMock, patch, mock_open
from compute_metrics_service import app
from compute_metrics_service.utils import Helpers


class TestMainCompleteness(unittest.TestCase):
 ...
解决方法
  • 配置VSCode调试环境的PYTHONPATH
    终端设置的PYTHONPATH可能无法被VSCode调试进程继承,需要在launch.json中明确配置:

    1. 打开VSCode调试面板,点击"创建launch.json文件"并选择Python环境
    2. 修改配置为:
      {
          "version": "0.2.0",
          "configurations": [
              {
                  "name": "Python: Test App Integration",
                  "type": "python",
                  "request": "launch",
                  "program": "${file}",
                  "cwd": "${workspaceFolder}",
                  "env": {
                      "PYTHONPATH": "${workspaceFolder}/data_quality:${workspaceFolder}/compute_metrics_service:${workspaceFolder}/fetch_data_metrics"
                  },
                  "justMyCode": false
              }
          ]
      }
      
    3. 调试时选择该配置运行test_app.py
  • 限制VSCode测试发现的目录范围
    VSCode默认扫描所有子目录找测试文件,易混淆同名模块,需在.vscode/settings.json中指定测试路径:

    {
        "python.testing.unittestArgs": [
            "-v",
            "-s",
            "./compute_metrics_service/tests/integration",
            "-p",
            "test_*.py"
        ],
        "python.testing.pytestEnabled": false,
        "python.testing.unittestEnabled": true
    }
    
  • 确认VSCode工作目录为项目根目录
    确保VSCode打开的是/Users/xxxx/Documents/SOC/data-quality-tool目录,而非某个子模块文件夹,否则PYTHONPATH的相对路径会失效。

  • 检查全局安装的同名模块
    执行pip list查看是否存在test_app或compute_metrics_service相关的全局包,若有则执行pip uninstall <package-name>卸载。

内容的提问来源于stack exchange,提问作者Fares

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:50:21