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

Django项目中Pytest运行测试出现ModuleNotFoundError: No module named 'tasks'

解决Django+pytest导入'tasks'模块失败问题

问题现象

运行pytest测试时触发ModuleNotFoundError: No module named 'tasks',具体报错如下:

name = 'tasks', package = None

    def import_module(name, package=None):
        """Import a module.
    
        The 'package' argument is required when performing a relative import. It
        specifies the package to use as the anchor point from which to resolve the
        relative import to an absolute import.
    
        """
        level = 0
        if name.startswith('.'):
            if not package:
                msg = ("the 'package' argument is required to perform a relative "
                       "import for {!r}")
                raise TypeError(msg.format(name))
            for character in name:
                if character != '.':
                    break
                level += 1
>       return _bootstrap._gcd_import(name[level:], package, level)
E       ModuleNotFoundError: No module named 'tasks'

/usr/local/lib/python3.11/importlib/__init__.py:126: ModuleNotFoundError
================================================================================= short test summary info =================================================================================
FAILED core_apps/tracker/tests/test_tasks.py::FetchAndStoreVehicleModelsTest::test_existing_models_are_updated - ModuleNotFoundError: No module named 'tasks'
FAILED core_apps/tracker/tests/test_tasks.py::FetchAndStoreVehicleModelsTest::test_new_models_are_created - ModuleNotFoundError: No module named 'tasks'

项目目录结构

core_apps
├── __init__.py
├── tracker
│	├── admin.py
│	├── apps.py
│	├── __init__.py
│	├── migrations
│	│	├── 0001_initial.py
│	│	└── __init__.py
│	├── models.py
│	├── services
│	│	├── coopart.py
│	│	└── __init__.py
│	├── tasks.py
│	├── tests
│	│	├── __init__.py
│	│	└── test_tasks.py
│	└── views.py
└── users
    ├── admin.py
    ├── apps.py
    ├── forms.py
    ├── __init__.py
    ├── managers.py
    ├── migrations
    │	├── 0001_initial.py
    │	└── __init__.py
    ├── models.py
    ├── tests.py
    └── views.py

问题根源

测试文件中@patch('tasks.CopartIaaiService.get_values')的路径错误:

  • tasks并非Python全局模块,而是属于core_apps.tracker下的子模块,完整路径为core_apps.tracker.tasks
  • pytest运行时以项目根目录为Python路径起点,找不到全局的tasks模块,因此报错

IDE自动提示的路径仅适用于当前文件相对路径,但pytest执行时的模块解析规则要求使用完整绝对导入路径。

解决方案

1. 修正测试文件中的patch路径

将test_tasks.py中所有@patch('tasks.CopartIaaiService.get_values')替换为@patch('core_apps.tracker.tasks.CopartIaaiService.get_values'),修改后的测试代码如下:

from django.test import TestCase
from unittest.mock import patch

from core_apps.tracker.models import VehicleModel
from core_apps.tracker.tasks import fetch_and_store_vehicle_makes


class FetchAndStoreVehicleModelsTest(TestCase):
    @patch('core_apps.tracker.tasks.CopartIaaiService.get_values')
    def test_new_models_are_created(self, mock_get_values):
        mock_get_values.return_value = {
            "result": [
                {"id": 1, "model": "Model1", "model_slug": "model1", "make_id": 1},
                {"id": 2, "model": "Model2", "model_slug": "model2", "make_id": 2},
            ]
        }

        fetch_and_store_vehicle_makes()

        self.assertEqual(VehicleModel.objects.count(), 2)
        self.assertEqual(VehicleModel.objects.get(make_id=1).model, "Model1")
        self.assertEqual(VehicleModel.objects.get(make_id=2).model, "Model2")

    @patch('core_apps.tracker.tasks.CopartIaaiService.get_values')
    def test_existing_models_are_updated(self, mock_get_values):
        VehicleModel.objects.create(model="Old Model1", model_slug="old_model1", make_id=1)
        VehicleModel.objects.create(model="Old Model2", model_slug="old_model2", make_id=2)

        mock_get_values.return_value = {
            "result": [
                {"id": 1, "model": "New Model1", "model_slug": "new_model1", "make_id": 1},
                {"id": 2, "model": "New Model2", "model_slug": "new_model2", "make_id": 2},
            ]
        }

        fetch_and_store_vehicle_makes()

        self.assertEqual(VehicleModel.objects.count(), 2)
        self.assertEqual(VehicleModel.objects.get(make_id=1).model, "New Model1")
        self.assertEqual(VehicleModel.objects.get(make_id=2).model, "New Model2")

2. 确认项目根目录在Python路径中

确保运行pytest时处于包含core_apps的项目根目录下,pytest默认会自动将当前工作目录加入sys.path,无需额外配置。如果仍有问题,可以手动设置环境变量:

export PYTHONPATH=/path/to/your/project/root:$PYTHONPATH

3. 检查必要配置文件

确认项目根目录下存在pytest.ini或pyproject.toml,并配置正确的Django设置模块:
pytest.ini示例:

[pytest]
DJANGO_SETTINGS_MODULE = core.settings
python_files = tests.py test_*.py *_tests.py

额外验证

  • 检查core_apps/tracker/tasks.py中的导入路径是否正确(当前代码中的from core_apps.tracker.services.coopart import CopartIaaiService是正确的)
  • 确保所有目录下的__init__.py文件存在且为空(项目结构中已包含,无需修改)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 20:15:00