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

2024-10-03 23:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

我的测试代码如下所示:

^{pr2}$

我正在使用内置的unittest


Tags: thepathselfeventoutputisondef