无法修补另一个模块中使用的软件包

时间:2019-05-14 11:15:44

标签: python unit-testing testing mocking

我想修补正在测试的模块中使用的一些外部软件包。请看看我的代码:

src / Notifiers.py

from abc import ABC, abstractmethod
from pathlib import PureWindowsPath
from smtplib import *
from datetime import datetime
from email.mime.text import MIMEText
import logging
import schedule


class Notifier(ABC):

    def __init__(self, name):
        self._logger = logging.getLogger(__name__)
        self._name = name

    @abstractmethod
    def send_notification(self, msg):
        pass

    def set_logger(self, root_name):
        my_logger_name = root_name + '.' + self._name
        self._logger = logging.getLogger(my_logger_name)
        self._logger.setLevel(logging.DEBUG)


class EmailNotifier(Notifier):

    def __init__(self, name, host, port, user, passwd, receivers):
        super().__init__(name)
        self._host = host
        self._port = port
        self._username = user
        self._password = passwd
        self._receivers = receivers

    def send_notification(self, lines):
        self._logger.debug('Rozpoczynam wysylanie maila')
        msg = MIMEText('\n'.join(lines))
        msg['Subject'] = 'SIMail powiadomienie'
        msg['From'] = 'SIMail kontrola routerow'
        msg['To'] = ", ".join(self._receivers)
        msg['Date'] = datetime.now().strftime('%a, %b %d, %Y at %I:%M %p')
        try:
            smtp_obj = SMTP(self._host,
                            self._port)
            smtp_obj.starttls()
            smtp_obj.login(self._username,
                           self._password)
            smtp_obj.send_message(msg)
            self._logger.info('Sent notification emails')
        except SMTPRecipientsRefused:
            print("Nobody was an email sent to")
        except SMTPHeloError:
            print("Server didnt respond for hello")
        except SMTPSenderRefused:
            print("Server refused sender")

上面的代码包含我要测试的模块。请注意,EmailNotifier使用的是MIMEText和SMTP之类的库,在测试期间我需要进行模拟。

现在,我将向您展示我的测试用例: tests / unit / Notifiers_test.py

from mock import patch
from unittest import TestCase
from Notifiers import *


class EmailNotifierTest(TestCase):

    @patch('Notifiers.email.mime.text.MIMEText')
    @patch('Notifiers.smtplib.SMTP')
    def test_send_notification(self, mock_smtp, mock_mime):
        """
        Case:
        Send email notification
        Excpected:
        EmailNotifier cannot crush
        """
        mock_smtp.side_effect = lambda: None
        name = 'test_name'
        host = 'test_host'
        port = 123
        user = 'test-user'
        passwd = 'test-passwd'
        receivers = ('abc@def.gh', 'ijk@lmn.op')

        notifier = EmailNotifier(name, host, port, user, passwd, receivers)
        lines = ('1. This is line number one', '2. This is line number two')
        notifier.send_notification(lines)
        mock_mime.assert_called_with('\n'.join(lines))

问题是我需要修补MIMEText中使用的EmailNotifier,我在另一个模块Notifiers_test中对此进行了测试。 但是当我尝试打补丁时,出现错误:

  

F Notifiers_test.py:7(EmailNotifierTest.test_send_notification)   ........ \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ mock \ mock.py:1297:   在打补丁       arg = patching。 enter ()........ \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ mock \ mock.py:1353:   在输入中       self.target = self.getter()........ \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ mock \ mock.py:1523:   在       getter = lambda:_importer(目标)........ \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ mock \ mock.py:1210:   在_importer中       事= _dot_lookup(事物,补偿,导入路径)

     
     

thing =,comp ='smtplib'   import_path ='Notifiers.EmailNotifier.smtplib'

def _dot_lookup(thing, comp, import_path):
    try:
        return getattr(thing, comp)
    except AttributeError:
       __import__(import_path)            
     

E ModuleNotFoundError:否   名为“ Notifiers.EmailNotifier”的模块; “通知者”不是   包装

     

........ \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ mock \ mock.py:1199:ModuleNotFoundError

我试图跳过我的补丁src中的Notifiers,但是,我的对象根本没有被补丁。你能告诉我怎么做吗?我正在使用PyCharm,并且src设置为Source目录。

我还附加了目录树:

Directories tree

0 个答案:

没有答案