Python 依赖键盘中断的单元测试代码

Python 依赖键盘中断的单元测试代码,python,watchdog,Python,Watchdog,我想测试代码的一部分,它有一个无限循环,当发出键盘中断时会中断。我正在使用看门狗模块监视目录中创建的新文件。 以下是相关代码: class EventHandler(PatternMatchingEventHandler): """ Inherits from PatternMatchingEventHandler Calls on_create when a new file is added to the output folder

我想测试代码的一部分,它有一个无限循环,当发出键盘中断时会中断。我正在使用看门狗模块监视目录中创建的新文件。 以下是相关代码:

class EventHandler(PatternMatchingEventHandler):
    """
        Inherits from PatternMatchingEventHandler
        Calls on_create when a new file is added to the output
        folder
    """

    def process(self, event):
        """
            For debugging
        """
        return (event.src_path, event.event_type)

    def on_created(self, event):
        self.process(event)

class Watcher(object):
    """
        Waits for events in the directory being watched
    """

    def __init__(self, outpath):
        """
            Initialize a watcher object. outpath is the absolute path of
            the output csv folder usually provided by the config module
        """
        self.path = outpath

    def run(self):
        event_handler = EventHandler(ignore_directories=True, patterns=['*.csv'])
        observer = Observer()
        observer.schedule(event_handler, self.path)
        observer.start()
        try:
            while True:
                time.sleep(1)

        except KeyboardInterrupt:
            observer.stop()

        observer.join()
我的测试代码如下所示:

def test_watcher(self):
    """
        Test the watcher code
    """
    self.watcher.run()
    out_file = "somefile.csv"
    with open(out_file, 'w+') as fname:
        fname.write('')

    # How to stop the watcher from code?

    self.assertTrue("somefile.csv was created")

我使用的是内置的unittest

测试用例通常不依赖于任何用户输入,也不在无限循环中运行,您的两个假设似乎都不符合基本测试用例标准,您能否简要解释一下您实际想要测试什么?创建文件时应该触发一个事件。在我的测试代码中,我正在编写一个新文件“somefile.csv”。我试图测试与之相关联的事件是否真的被firedI添加了更多的代码。希望更清楚now@Ajit你找到解决办法了吗?