ModuleNotFoundError: No module named 'clients'

Рейтинг: 0Ответов: 1Опубликовано: 23.08.2023

Пишу проект на питоне. Разбил проект на папки bot и tests. Если запускаю тесты через пайчарм, то все работает, если запускаю через консоль то выдает ошибку:

return _bootstrap._gcd_import(name[level:], package, level)
test_commands.py:4: in <module>
    from bot.clients.tg import TgClient, Update, Message, MessageFrom, Chat
..\bot\clients\tg\__init__.py:2: in <module>
    from .api import *
..\bot\clients\tg\api.py:6: in <module>
    from clients.tg.dcs import GetUpdatesResponse, SendMessageResponse, SendAudioResponse, SendPhotoResponse, \
E   ModuleNotFoundError: No module named 'clients'

Вот код теста

import pytest

from unittest.mock import AsyncMock
from clients.tg import TgClient, Update, Message, MessageFrom, Chat
from engine.commands import HelpCommand


class TestHelpCommand:
    @pytest.fixture
    def setup(self, monkeypatch):
        self.mock_tg_client = AsyncMock(spec=TgClient)
        self.command = HelpCommand(tg_client=self.mock_tg_client)
        return self

    @pytest.mark.asyncio
    async def test_is_for_true(self, setup):
        # arrange
        update = Update(update_id=12)
        message_from = MessageFrom(id=1, first_name="John", last_name="Doe", username="johndoe")
        chat = Chat(id=1, type="private", first_name="John", last_name="Doe", username="johndoe")
        update.message = Message(message_id=1, from_=message_from, chat=chat, text="/help")
        # act
        result = self.command.is_for(update)
        # assert
        assert result == True

    @pytest.mark.asyncio
    async def test_is_for_false(self, setup):
        # arrange
        update = Update(update_id=12)
        message_from = MessageFrom(id=1, first_name="John", last_name="Doe", username="johndoe")
        chat = Chat(id=1, type="private", first_name="John", last_name="Doe", username="johndoe")
        update.message = Message(message_id=1, from_=message_from, chat=chat, text="/telp")
        # act
        result = self.command.is_for(update)
        # assert
        assert result == False

Вот структура приложения

введите сюда описание изображения

Пытался и PYTHONPATH устанавливать и sys.path. Ничего не помогло. Пытался добавлять bot.clients.tg ошибка ушла в сам bot.

Помогало только прописать везде где можно bot. но это потом мешает собирать в докере проект, да и как я понял так делать не очень хорошо и в определенных проектах это может аукнуться.

Ответы

▲ 0

Мне помогло:

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../bot')))

создайте файл conftest и впишите это туда. Замените /bot на название вашего модуля.