def test___eq__(self):
        watch1 = ObservedWatch('/foobar', True)
        watch2 = ObservedWatch('/foobar', True)
        watch_ne1 = ObservedWatch('/foo', True)
        watch_ne2 = ObservedWatch('/foobar', False)

        assert_true(watch1.__eq__(watch2))
        assert_false(watch1.__eq__(watch_ne1))
        assert_false(watch1.__eq__(watch_ne2))
Exemplo n.º 2
0
def test_observer__ne__():
    watch1 = ObservedWatch('/foobar', True)
    watch2 = ObservedWatch('/foobar', True)
    watch_ne1 = ObservedWatch('/foo', True)
    watch_ne2 = ObservedWatch('/foobar', False)

    assert not watch1.__ne__(watch2)
    assert watch1.__ne__(watch_ne1)
    assert watch1.__ne__(watch_ne2)
  def test___ne__(self):
    watch1 = ObservedWatch('/foobar', True)
    watch2 = ObservedWatch('/foobar', True)
    watch_ne1 = ObservedWatch('/foo', True)
    watch_ne2 = ObservedWatch('/foobar', False)

    self.assertFalse(watch1.__ne__(watch2))
    self.assertTrue(watch1.__ne__(watch_ne1))
    self.assertTrue(watch1.__ne__(watch_ne2))
Exemplo n.º 4
0
def start_watching(path=None, use_full_emitter=False):
    path = p('') if path is None else path
    global emitter
    if platform.is_linux() and use_full_emitter:
        emitter = InotifyFullEmitter(event_queue, ObservedWatch(path, recursive=True))
    else:
        emitter = Emitter(event_queue, ObservedWatch(path, recursive=True))

    if platform.is_darwin():
        # FSEvents will report old evens (like create for mkdtemp in test
        # setup. Waiting for a considerable time seems to 'flush' the events.
        time.sleep(10)
    emitter.start()
Exemplo n.º 5
0
def start_watching(path=None, use_full_emitter=False, recursive=True):
    # todo: check if other platforms expect the trailing slash (e.g. `p('')`)
    path = p() if path is None else path
    global emitter
    if platform.is_linux() and use_full_emitter:
        emitter = InotifyFullEmitter(event_queue, ObservedWatch(path, recursive=recursive))
    else:
        emitter = Emitter(event_queue, ObservedWatch(path, recursive=recursive))

    if platform.is_darwin():
        emitter.suppress_history = True

    emitter.start()
Exemplo n.º 6
0
def start_watching(path=None, use_full_emitter=False):
    global emitter
    path = p("") if path is None else path
    emitter = FSEventsEmitter(event_queue,
                              ObservedWatch(path, recursive=True),
                              suppress_history=True)
    emitter.start()
Exemplo n.º 7
0
def emitter(event_queue):
    watch = ObservedWatch(temp_dir, True)
    em = Emitter(event_queue, watch, timeout=0.2)
    em.start()
    yield em
    em.stop()
    em.join(5)
Exemplo n.º 8
0
    def test_schedule_with(self):
        # This provides more readable traceback message for ObservedWatch.
        def ow_repr(self):
            return str((self.path, self.is_recursive))

        setattr(ObservedWatch, '__repr__', ow_repr)

        # mock open so that files other than '.gitignore' raise exception
        m = mock_open(read_data='*.py[cod]\n__pycache__/\n')
        patcher = patch('builtins.open', m)
        patcher.start()

        # reset gitignore path to '.gitignore' (a file that exists)
        self.parser.gitignore_path = '.gitignore'
        observer = Observer()
        result = self.parser.schedule_with(observer, self.HandlerClass)
        # expected
        handlers = []
        for dog in self.dogs:
            handler = dog.create_handler(self.HandlerClass)
            handlers.append(handler)
        watches = []
        for dog in self.dogs:
            watch = ObservedWatch(*dog.watch_info)
            watches.append(watch)
        handler_for_watch = {
            watches[0]: set([handlers[0], handlers[1]]),
            watches[2]: set([handlers[2]]),
            watches[3]: set([handlers[3]]),
        }

        self.maxDiff = None
        # self.fail((result, handler_for_watch))
        self.assertEqual(result, handler_for_watch)
        patcher.stop()
 def start(self):
     sleep(0.5)
     self.event_queue = queue.Queue()
     global temp_dir
     self.watch = ObservedWatch(temp_dir, True)
     self.emitter = Emitter(self.event_queue, self.watch, timeout=0.2)
     self.emitter.start()
     sleep(0.5)
Exemplo n.º 10
0
def watching(path=None, use_full_emitter=False):
    path = p("") if path is None else path
    global emitter
    Emitter = InotifyFullEmitter if use_full_emitter else InotifyEmitter
    emitter = Emitter(event_queue, ObservedWatch(path, recursive=True))
    emitter.start()
    yield
    emitter.stop()
    emitter.join(5)
Exemplo n.º 11
0
    def ObservedWatch(self, path=None, recursive=False):
        """
        Return an ObservedWatch instance.
        """
        if path is None:
            path = mk.fs.temp_path
        path = mk.fs.getEncodedPath(path)

        return ObservedWatch(path=path, recursive=recursive)
Exemplo n.º 12
0
def start_watching(path=None, use_full_emitter=False, recursive=True):
    # todo: check if other platforms expect the trailing slash (e.g. `p('')`)
    path = p() if path is None else path
    global emitter
    if platform.is_linux() and use_full_emitter:
        emitter = InotifyFullEmitter(event_queue,
                                     ObservedWatch(path, recursive=recursive))
    else:
        emitter = Emitter(event_queue, ObservedWatch(path,
                                                     recursive=recursive))

    emitter.start()

    if platform.is_darwin():
        # FSEvents _may_ report the event for the creation of `tmpdir`,
        # however, we're racing with fseventd there - if other filesystem
        # events happened _after_ `tmpdir` was created, but _before_ we
        # created the emitter then we won't get this event.
        # As such, let's create a sentinel event that tells us that we are
        # good to go.
        sentinel_file = os.path.join(
            path,
            '.sentinel' if isinstance(path, str) else '.sentinel'.encode())
        touch(sentinel_file)
        sentinel_events = [
            FileCreatedEvent(sentinel_file),
            DirModifiedEvent(path),
            FileModifiedEvent(sentinel_file)
        ]
        next_sentinel_event = sentinel_events.pop(0)
        now = time.monotonic()
        while time.monotonic() <= now + 30.0:
            try:
                event = event_queue.get(timeout=0.5)[0]
                if event == next_sentinel_event:
                    if not sentinel_events:
                        break
                    next_sentinel_event = sentinel_events.pop(0)
            except Empty:
                pass
            time.sleep(0.1)
        else:
            assert False, "Sentinel event never arrived!"
Exemplo n.º 13
0
 def schedule(self, event_handler, path, emitter_cls=None):
     with self._lock:
         watch = ObservedWatch(path, True)
         emitter = emitter_cls(self.event_queue, watch, self.timeout)
         if self.is_alive():
             emitter.start()
         self._add_handler_for_watch(event_handler, watch)
         self._add_emitter(emitter)
         self._watches.add(watch)
         return watch
Exemplo n.º 14
0
    def test___ne__(self):
        watch1 = ObservedWatch("/foobar", True)
        watch2 = ObservedWatch("/foobar", True)
        watch_ne1 = ObservedWatch("/foo", True)
        watch_ne2 = ObservedWatch("/foobar", False)

        self.assertFalse(watch1.__ne__(watch2))
        self.assertTrue(watch1.__ne__(watch_ne1))
        self.assertTrue(watch1.__ne__(watch_ne2))
Exemplo n.º 15
0
    def test___eq__(self):
        watch1 = ObservedWatch('/foobar', True)
        watch2 = ObservedWatch('/foobar', True)
        watch_ne1 = ObservedWatch('/foo', True)
        watch_ne2 = ObservedWatch('/foobar', False)

        self.assertTrue(watch1.__eq__(watch2))
        self.assertFalse(watch1.__eq__(watch_ne1))
        self.assertFalse(watch1.__eq__(watch_ne2))
Exemplo n.º 16
0
    def test___ne__(self):
        watch1 = ObservedWatch('/foobar', True)
        watch2 = ObservedWatch('/foobar', True)
        watch_ne1 = ObservedWatch('/foo', True)
        watch_ne2 = ObservedWatch('/foobar', False)

        assert_false(watch1.__ne__(watch2))
        assert_true(watch1.__ne__(watch_ne1))
        assert_true(watch1.__ne__(watch_ne2))
Exemplo n.º 17
0
def test_observer__ne__():
    watch1 = ObservedWatch('/foobar', True)
    watch2 = ObservedWatch('/foobar', True)
    watch_ne1 = ObservedWatch('/foo', True)
    watch_ne2 = ObservedWatch('/foobar', False)

    assert not watch1.__ne__(watch2)
    assert watch1.__ne__(watch_ne1)
    assert watch1.__ne__(watch_ne2)
Exemplo n.º 18
0
def test_passing_bytes_should_give_bytes(p):
    from watchdog.utils.unicode_paths import bytes_cls
    path = bytes_cls(p(''), 'ascii')
    assert isinstance(p(''), bytes_cls)

    event_queue = Queue()
    emitter = Emitter(event_queue, ObservedWatch(path, recursive=True))
    emitter.start()
    touch(p('a'))
    event = event_queue.get(timeout=5)[0]
    assert isinstance(event.src_path, bytes_cls)
Exemplo n.º 19
0
def _setup_emitter(path):
    event_queue = Queue()

    if platform.is_darwin():
        # FSEvents will report old evens (like create for mkdtemp in test
        # setup. Waiting for a considerable time seems to 'flush' the events.
        time.sleep(10)

    emitter = Emitter(event_queue, ObservedWatch(path, recursive=True))
    emitter.start()
    return event_queue, emitter
Exemplo n.º 20
0
    def test_dispatch_event(self):
        event = FileModifiedEvent("/foobar")
        watch = ObservedWatch("/path", True)

        class TestableEventDispatcher(EventDispatcher):
            def dispatch_event(self, event, watch):
                assert True

        event_dispatcher = TestableEventDispatcher()
        event_dispatcher.event_queue.put((event, watch))
        event_dispatcher.start()
        time.sleep(1)
        event_dispatcher.stop()
Exemplo n.º 21
0
    def _set_root(self, root):
        """Set up watching `root` or closest existing parent."""
        if self.root_watch is not None and self.root_watch.path == root:
            # already watching the specified root, return early
            return

        # schedule new root watch
        while True:
            try:
                watch = self.root_observer.schedule(
                    event_handler=self, path=root, recursive=False
                )
            except OSError as sched_err:
                # root doesn't exist, move up one directory and try again
                try:
                    # clean up from failed scheduling
                    self.root_observer.unschedule(ObservedWatch(root, False))
                except KeyError:
                    pass
                newroot = os.path.dirname(root)
                if newroot == root:
                    # we've gotten to system root and still failed
                    raise sched_err
                else:
                    root = newroot
            else:
                # watch was set, break out of while loop
                break

        # add regex for root and next subdirectory
        regexes = []
        regexes.append("^" + re.escape(root) + "$")
        nextdir = self._get_next_dir_in_path(root)
        if nextdir != root:
            regexes.append("^" + re.escape(nextdir) + "$")

        # update handler (self) with regexes
        RegexMatchingEventHandler.__init__(
            self, regexes=regexes, ignore_directories=False
        )

        # unschedule old root watch
        if self.root_watch is not None:
            try:
                self.root_observer.unschedule(self.root_watch)
            except KeyError:
                # emitter already stopped
                pass

        self.root_watch = watch
Exemplo n.º 22
0
def test_close_clean(tmpdir):
    """
    On InotifyBuffer.close() InotifyBuffer.read_event() is un-blocked so that
    Inotify thread waiting for it can be closed.

    This is also a test for Inotify.queue_events handling of STOP_EVENT and
    InotifyBuffer.close() is test as side effect of Inotify.stop()
    """
    watch = ObservedWatch(path=tmpdir, recursive=False)
    emitter = InotifyEmitter([], watch)
    emitter.start()

    emitter.stop()
    emitter.join(1)
    assert not emitter.isAlive()
Exemplo n.º 23
0
    def schedule(self, event_handler, path, recursive=False, initial_state=None):
        """
        Schedules watching a path and calls appropriate methods specified
        in the given event handler in response to file system events.

        :param initial_state:
            The previous state of the directory. Files changes happened after the initial_state will be considered,
            previous events will be ignored.
        :type initial_state:
            :class:`DirectorySnapshot`
        :param from_scratch:
            If True will consider all files in path as new
        :type from_scratch:
            ``bool``
        :param event_handler:
            An event handler instance that has appropriate event handling
            methods which will be called by the observer in response to
            file system events.
        :type event_handler:
            :class:`watchdog.events.FileSystemEventHandler` or a subclass
        :param path:
            Directory path that will be monitored.
        :type path:
            ``str``
        :param recursive:
            ``True`` if events will be emitted for sub-directories
            traversed recursively; ``False`` otherwise.
        :type recursive:
            ``bool``
        :return:
            An :class:`ObservedWatch` object instance representing
            a watch.
        """
        with self._lock:
            watch = ObservedWatch(path, recursive)
            self._add_handler_for_watch(event_handler, watch)

            # If we don't have an emitter for this watch already, create it.
            if self._emitter_for_watch.get(watch) is None:
                emitter = self._emitter_class(event_queue=self.event_queue,
                                              watch=watch,
                                              timeout=self.timeout,
                                              initial_state=initial_state)
                self._add_emitter(emitter)
                if self.is_alive():
                    emitter.start()
            self._watches.add(watch)
        return watch
Exemplo n.º 24
0
def test_add_watch_twice(observer):
    """ Adding the same watch twice used to result in a null pointer return without an exception.

    See https://github.com/gorakhargosh/watchdog/issues/765
    """

    a = p("a")
    mkdir(a)
    h = FileSystemEventHandler()
    w = ObservedWatch(a, recursive=False)

    def callback(path, inodes, flags, ids):
        pass

    _fsevents.add_watch(h, w, callback, [w.path])
    with pytest.raises(RuntimeError):
        _fsevents.add_watch(h, w, callback, [w.path])
    _fsevents.remove_watch(w)
    rmdir(a)
Exemplo n.º 25
0
def emitter(event_queue):
    watch = ObservedWatch(temp_dir, True)
    em = WindowsApiEmitter(event_queue, watch, timeout=0.2)
    yield em
    em.stop()
Exemplo n.º 26
0
def test_event_emitter():
    event_queue = EventQueue()
    watch = ObservedWatch('/foobar', True)
    event_emitter = EventEmitter(event_queue, watch, timeout=1)
    event_emitter.queue_event(FileModifiedEvent('/foobar/blah'))
Exemplo n.º 27
0
def test_observer__repr__():
    observed_watch = ObservedWatch('/foobar', True)
    repr_str = '<ObservedWatch: path=/foobar, is_recursive=True>'
    assert observed_watch.__repr__() == repr(observed_watch)
    assert repr(observed_watch) == repr_str
Exemplo n.º 28
0
def test_observer__repr__():
    observed_watch = ObservedWatch('/foobar', True)
    repr_str = '<ObservedWatch: path=/foobar, is_recursive=True>'
    assert observed_watch.__repr__() == repr(observed_watch)
    assert repr(observed_watch) == repr_str
 def test___repr__(self):
     observed_watch = ObservedWatch('/foobar', True)
     assert_equal('<ObservedWatch: path=/foobar, is_recursive=True>', observed_watch.__repr__())
Exemplo n.º 30
0
def emitter(event_queue):
    watch = ObservedWatch(temp_dir, True)
    yield Emitter(event_queue, watch, timeout=0.2)
Exemplo n.º 31
0
 def test___init__(self):
     event_queue = EventQueue()
     watch = ObservedWatch("/foobar", True)
     event_emitter = EventEmitter(event_queue, watch, timeout=1)
     event_emitter.queue_event(FileModifiedEvent("/foobar/blah"))
Exemplo n.º 32
0
 def test___repr__(self):
     observed_watch = ObservedWatch("/foobar", True)
     self.assertEqual(
         "<ObservedWatch: path=" + "/foobar" + ", is_recursive=True>",
         observed_watch.__repr__(),
     )
Exemplo n.º 33
0
 def test___repr__(self):
     observed_watch = ObservedWatch('/foobar', True)
     self.assertEqual(
         '<ObservedWatch: path=' + '/foobar' + ', is_recursive=True>',
         observed_watch.__repr__())
 def setUp(self):
   self.event_queue = queue.Queue()
   self.watch = ObservedWatch(temp_dir, True)
   self.emitter = Emitter(self.event_queue, self.watch, timeout=0.2)
Exemplo n.º 35
0
 def test___repr__(self):
   observed_watch = ObservedWatch('/foobar', True)
   self.assertEqual('<ObservedWatch: path=' + absolute_path('/foobar') + ', is_recursive=True>',
                    observed_watch.__repr__())
Exemplo n.º 36
0
 def setUp(self):
     super(TestEventEmitter, self).setUp()
     self.queue = []
     watch = ObservedWatch(path=tempfile.tempdir, recursive=False)
     self.sut = DummyEventEmitter(self.queue, watch, timeout=0)