微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:在单元测试期间,请在使用另一个模块之前先对其进行替换

如何解决Python:在单元测试期间,请在使用另一个模块之前先对其进行替换

我有以下模块:

  1. 导入课程
  2. 实例化类并使用它

我想在实例化/使用之前用另一个类替换该类。

这怎么办?


这是我的用例的一个类似物。

thread_import.py

from threading import Thread

def foo() -> None:
    pass

def run_thread() -> Thread:
    hello = Thread(target=foo,daemon=True)
    hello.start()
    hello.join()
    return hello

test_thread_import.py

from threading import Thread
from typing import Optional
from unittest import TestCase
from unittest.mock import patch

from thread_import import run_thread

class ExcCatchingThread(Thread):
    """Thread that when run,its exception is caught.

    SEE: https://stackoverflow.com/questions/12484175/make-python-unittest-fail-on-exception-from-any-thread#12651449

    """

    exc: Optional[Exception]

    def run(self):
        try:
            Thread.run(self)
        except Exception as exc:
            self.exc = exc
        else:
            self.exc = None

class TestThreadImport(TestCase):
    def test_run_thread(self) -> None:
        planned_exc = Exception("Planned exc.")
        with patch("thread_import.foo",side_effect=planned_exc):
            thread = run_thread()
            # how can I swap Thread in thread_import with ExcCatchingThread?
            self.assertEqual(thread.exc,planned_exc)

使用Python 3.8.5完成

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。