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

时间:2017-10-17 08:58:53

标签: python watchdog

我想测试一部分具有无限循环的代码,并在发出键盘中断时突破。我正在使用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()

我的测试代码如下所示:

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

0 个答案:

没有答案
相关问题