3

I want to test a part of the code that has an infinite loop and break out when a keyboard interrupt is issued. I am using watchdog module to watch for new files created in a directory. Here is the relevant code :

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

My testing code looks something like this :

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

I am using built-in unittest

Ajit
  • 667
  • 2
  • 14
  • 27
  • Test cases are generally not dependent on any user input, and neither run in an infinite loop, Both of your assumptions seem to be loose on basic test case criteria, Can you briefly explain what you want to test actually ? – ZdaR Oct 17 '17 at 09:00
  • An event should be fired when a file is created. In my test code I am writing a new file "somefile.csv". I am trying to test if the event associated with it is actually being fired – Ajit Oct 17 '17 at 09:07
  • I added some more code. Hope it is clearer now – Ajit Oct 17 '17 at 09:15
  • @Ajit Did you fins a solution for this? – Lordbug Jul 04 '19 at 21:15

0 Answers0