def wait():
    """
    Wait long enough for file/folder mtime to change. This is needed
    to be able to detected modifications.
    """
    if platform.is_darwin() or platform.is_windows():
         # on osx resolution of stat.mtime is only 1 second
        time.sleep(1.5)
    else:
        time.sleep(0.5)
Example #2
0
def test_move_from():
    mkdir(p('dir1'))
    mkdir(p('dir2'))
    touch(p('dir1', 'a'))
    start_watching(p('dir1'))
    mv(p('dir1', 'a'), p('dir2', 'b'))

    event = event_queue.get(timeout=5)[0]
    assert isinstance(event, FileDeletedEvent)
    assert event.src_path == p('dir1', 'a')

    if not platform.is_windows():
        event = event_queue.get(timeout=5)[0]
        assert event.src_path == p('dir1')
        assert isinstance(event, DirModifiedEvent)
Example #3
0
def test_recursive_on():
    mkdir(p('dir1', 'dir2', 'dir3'), True)
    start_watching()
    touch(p('dir1', 'dir2', 'dir3', 'a'))

    event = event_queue.get(timeout=5)[0]
    assert event.src_path == p('dir1', 'dir2', 'dir3', 'a')
    assert isinstance(event, FileCreatedEvent)

    if not platform.is_windows():
        event = event_queue.get(timeout=5)[0]
        assert event.src_path == p('dir1', 'dir2', 'dir3')
        assert isinstance(event, DirModifiedEvent)

        event = event_queue.get(timeout=5)[0]
        assert event.src_path == p('dir1', 'dir2', 'dir3', 'a')
        assert isinstance(event, FileModifiedEvent)
Example #4
0
def test_create():
    start_watching()
    open(p('a'), 'a').close()

    event = event_queue.get(timeout=5)[0]
    assert event.src_path == p('a')
    assert isinstance(event, FileCreatedEvent)

    if not platform.is_windows():
        event = event_queue.get(timeout=5)[0]
        assert os.path.normpath(event.src_path) == os.path.normpath(p(''))
        assert isinstance(event, DirModifiedEvent)

    if platform.is_linux():
        event = event_queue.get(timeout=5)[0]
        assert event.src_path == p('a')
        assert isinstance(event, FileClosedEvent)
Example #5
0
    def _get_native_observer():
        """
        Return native observer... or fail.
        """
        from watchdog.utils import platform

        if platform.is_linux():
            from watchdog.observers.inotify import InotifyObserver
            return InotifyObserver

        if platform.is_windows():
            # TODO: find a reliable way of checking Windows version and import
            # polling explicitly for Windows XP
            try:
                from watchdog.observers.read_directory_changes import (
                    WindowsApiObserver)
                return WindowsApiObserver
            except:
                raise AssertionError('Native observer not supported.')

        raise AssertionError('Native observer not supported.')
Example #6
0
    def _get_native_observer():
        """
        Return native observer... or fail.
        """
        from watchdog.utils import platform

        if platform.is_linux():
            from watchdog.observers.inotify import InotifyObserver
            return InotifyObserver

        if platform.is_windows():
            # TODO: find a reliable way of checking Windows version and import
            # polling explicitly for Windows XP
            try:
                from watchdog.observers.read_directory_changes import (
                    WindowsApiObserver)
                return WindowsApiObserver
            except:
                raise AssertionError('Native observer not supported.')

        raise AssertionError('Native observer not supported.')
Example #7
0
def test_recursive_off():
    mkdir(p('dir1'))
    start_watching(recursive=False)
    touch(p('dir1', 'a'))

    with pytest.raises(Empty):
        event_queue.get(timeout=5)

    mkfile(p('b'))
    expect_event(FileCreatedEvent(p('b')))
    if not platform.is_windows():
        expect_event(DirModifiedEvent(p()))

        if platform.is_linux():
            expect_event(FileClosedEvent(p('b')))

    # currently limiting these additional events to macOS only, see https://github.com/gorakhargosh/watchdog/pull/779
    if platform.is_darwin():
        mkdir(p('dir1', 'dir2'))
        with pytest.raises(Empty):
            event_queue.get(timeout=5)
        mkfile(p('dir1', 'dir2', 'somefile'))
        with pytest.raises(Empty):
            event_queue.get(timeout=5)

        mkdir(p('dir3'))
        expect_event(DirModifiedEvent(
            p()))  # the contents of the parent directory changed

        mv(p('dir1', 'dir2', 'somefile'), p('somefile'))
        expect_event(
            FileMovedEvent(p('dir1', 'dir2', 'somefile'), p('somefile')))
        expect_event(DirModifiedEvent(p()))

        mv(p('dir1', 'dir2'), p('dir2'))
        expect_event(DirMovedEvent(p('dir1', 'dir2'), p('dir2')))
        expect_event(DirModifiedEvent(p()))
Example #8
0
def test_separate_consecutive_moves():
    mkdir(p('dir1'))
    mkfile(p('dir1', 'a'))
    mkfile(p('b'))
    start_watching(p('dir1'))
    mv(p('dir1', 'a'), p('c'))
    mv(p('b'), p('dir1', 'd'))

    dir_modif = DirModifiedEvent(p('dir1'))
    a_deleted = FileDeletedEvent(p('dir1', 'a'))
    d_created = FileCreatedEvent(p('dir1', 'd'))

    expected_events = [a_deleted, dir_modif, d_created, dir_modif]

    if platform.is_windows():
        expected_events = [a_deleted, d_created]

    if platform.is_bsd():
        # Due to the way kqueue works, we can't really order
        # 'Created' and 'Deleted' events in time, so creation queues first
        expected_events = [d_created, a_deleted, dir_modif, dir_modif]

    for expected_event in expected_events:
        expect_event(expected_event)
Example #9
0
Classes
-------
.. autoclass:: BaseThread
   :members:
   :show-inheritance:
   :inherited-members:

"""
import os
import sys
import threading
import watchdog.utils.platform
from watchdog.utils.compat import Event
from collections import namedtuple

if sys.version_info[0] == 2 and platform.is_windows():
    # st_ino is not implemented in os.stat on this platform
    import win32stat
    stat = win32stat.stat
else:
    stat = os.stat


def has_attribute(ob, attribute):
    """
    :func:`hasattr` swallows exceptions. :func:`has_attribute` tests a Python object for the
    presence of an attribute.

    :param ob:
        object to inspect
    :param attribute:
Example #10
0
def rerun_filter(exc, *args):
    time.sleep(5)
    return issubclass(exc[0], Empty) and platform.is_windows()
Example #11
0
from watchdog.utils import platform
from watchdog.utils.unicode_paths import str_cls
from watchdog.events import (FileDeletedEvent, FileModifiedEvent,
                             FileCreatedEvent, FileMovedEvent, DirDeletedEvent,
                             DirModifiedEvent, DirCreatedEvent, DirMovedEvent)
from watchdog.observers.api import ObservedWatch

if platform.is_linux():
    from watchdog.observers.inotify import (
        InotifyEmitter as Emitter,
        InotifyFullEmitter,
    )
elif platform.is_darwin():
    pytestmark = pytest.mark.skip("FIXME: issue #546.")
    from watchdog.observers.fsevents2 import FSEventsEmitter as Emitter
elif platform.is_windows():
    from watchdog.observers.read_directory_changes import (WindowsApiEmitter as
                                                           Emitter)
elif platform.is_bsd():
    from watchdog.observers.kqueue import (KqueueEmitter as Emitter)

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)


@pytest.fixture(autouse=True)
def setup_teardown(tmpdir):
    global p, emitter, event_queue
    p = partial(os.path.join, tmpdir)
    event_queue = Queue()
Example #12
0
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from watchdog.utils import platform
from functools import reduce

if platform.is_windows():
  import ctypes

  from watchdog.observers.winapi import\
    FILE_FLAG_BACKUP_SEMANTICS,\
    FILE_FLAG_OVERLAPPED,\
    FILE_SHARE_READ,\
    FILE_SHARE_WRITE,\
    FILE_SHARE_DELETE,\
    FILE_NOTIFY_CHANGE_FILE_NAME,\
    FILE_NOTIFY_CHANGE_DIR_NAME,\
    FILE_NOTIFY_CHANGE_ATTRIBUTES,\
    FILE_NOTIFY_CHANGE_SIZE,\
    FILE_NOTIFY_CHANGE_LAST_WRITE,\
    FILE_NOTIFY_CHANGE_SECURITY,\
    FILE_NOTIFY_CHANGE_LAST_ACCESS,\
Example #13
0
def rerun_filter(exc, *args):
    time.sleep(5)
    if issubclass(exc[0], Empty) and platform.is_windows():
        return True

    return False
Example #14
0
from tests import Queue
from functools import partial
from .shell import mkdir, touch, mv, rm, mkdtemp
from watchdog.utils import platform
from watchdog.utils.unicode_paths import str_cls
from watchdog.events import *
from watchdog.observers.api import ObservedWatch

# pytestmark = pytest.mark.skipif(not platform.is_linux() and not platform.is_darwin(),
# reason="")
if platform.is_linux():
    from watchdog.observers.inotify import InotifyEmitter as Emitter
    from watchdog.observers.inotify import InotifyFullEmitter
elif platform.is_darwin():
    from watchdog.observers.fsevents2 import FSEventsEmitter as Emitter
elif platform.is_windows():
    from watchdog.observers.read_directory_changes import WindowsApiEmitter as Emitter

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)

def setup_function(function):
    global p, event_queue
    tmpdir = os.path.realpath(mkdtemp())
    p = partial(os.path.join, tmpdir)
    event_queue = Queue()


def start_watching(path=None, use_full_emitter=False):
    path = p('') if path is None else path
Example #15
0
#Embedded file name: e:\jenkins\workspace\client_SERENITY\branches\release\SERENITY\packages\watchdog\utils\__init__.py
import os
import sys
import threading
import watchdog.utils.platform
from watchdog.utils.compat import Event
from collections import namedtuple
if sys.version_info[0] == 2 and platform.is_windows():
    import win32stat
    stat = win32stat.stat
else:
    stat = os.stat

def has_attribute(ob, attribute):
    return getattr(ob, attribute, None) is not None


class UnsupportedLibc(Exception):
    pass


class BaseThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        if has_attribute(self, 'daemon'):
            self.daemon = True
        else:
            self.setDaemon(True)
        self._stopped_event = Event()
        if not has_attribute(self._stopped_event, 'is_set'):
Example #16
0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest
from watchdog.utils import platform

if not platform.is_windows():  # noqa
    pytest.skip("Windows only.", allow_module_level=True)

import os
import os.path
from time import sleep

from watchdog.events import (
    DirCreatedEvent,
    DirMovedEvent,
)
from watchdog.observers.api import ObservedWatch
from watchdog.observers.read_directory_changes import WindowsApiEmitter

from . import Empty, Queue
from .shell import (mkdir, mkdtemp, mv, rm)
Example #17
0
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from watchdog.utils import platform
from functools import reduce

if not platform.is_windows():
    raise ImportError

import ctypes

from watchdog.observers.winapi import (
    FILE_FLAG_BACKUP_SEMANTICS,
    FILE_FLAG_OVERLAPPED,
    FILE_SHARE_READ,
    FILE_SHARE_WRITE,
    FILE_SHARE_DELETE,
    FILE_NOTIFY_CHANGE_FILE_NAME,
    FILE_NOTIFY_CHANGE_DIR_NAME,
    FILE_NOTIFY_CHANGE_ATTRIBUTES,
    FILE_NOTIFY_CHANGE_SIZE,
    FILE_NOTIFY_CHANGE_LAST_WRITE,
Example #18
0
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Portions of this code were taken from pyfilesystem, which uses the above
# new BSD license.

from __future__ import with_statement
from watchdog.utils import platform

if platform.is_windows():
    import ctypes.wintypes
    import struct

    try:
        LPVOID = ctypes.wintypes.LPVOID
    except AttributeError:
        # LPVOID wasn't defined in Py2.5, guess it was introduced in Py2.6
        LPVOID = ctypes.c_void_p

    # Invalid handle value.
    INVALID_HANDLE_VALUE = 0xFFFFFFFF     # -1

    # File notification contants.
    FILE_NOTIFY_CHANGE_FILE_NAME = 0x01
    FILE_NOTIFY_CHANGE_DIR_NAME = 0x02
Example #19
0
    DirDeletedEvent,
    DirModifiedEvent,
    DirCreatedEvent,
)
from watchdog.observers.api import ObservedWatch

if platform.is_linux():
    from watchdog.observers.inotify import (
        InotifyEmitter as Emitter,
        InotifyFullEmitter,
    )
elif platform.is_darwin():
    pytestmark = pytest.mark.skip(
        "FIXME: It is a matter of bad comparisons between bytes and str.")
    from watchdog.observers.fsevents2 import FSEventsEmitter as Emitter
elif platform.is_windows():
    from watchdog.observers.read_directory_changes import (WindowsApiEmitter as
                                                           Emitter)

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)


@pytest.fixture(autouse=True)
def setup_teardown(tmpdir):
    global p, emitter, event_queue
    p = partial(os.path.join, tmpdir)
    event_queue = Queue()

    yield