Example #1
0
    def test_synchronize_remote_move_while_download_file(self):
        local = self.local_1
        remote = self.remote_1

        # Create documents in the remote root workspace
        new_folder_id = remote.make_folder(self.folder_id, "New folder").uid
        self.wait_sync(wait_for_async=True)

        def callback(*_):
            """ Add delay when upload and download. """
            if self.engine_1.file_id and not self.engine_1.has_rename:
                # Rename remote file while downloading
                remote.move(self.engine_1.file_id, new_folder_id)
                self.engine_1.has_rename = True
            time.sleep(3)
            Engine.suspend_client(self.engine_1)

        self.engine_1.has_rename = False
        self.engine_1.file_id = None

        Options.set("tmp_file_limit", 0.1, "manual")
        try:
            self.engine_1.remote.download_callback = callback
            file = self.location / "resources" / "files" / "testFile.pdf"
            content = file.read_bytes()
            self.engine_1.file_id = remote.make_file(self.folder_id,
                                                     "testFile.pdf",
                                                     content=content).uid

            # Rename remote folder then synchronize
            self.wait_sync(wait_for_async=True)
            assert not local.exists("/Test folder/testFile.pdf")
            assert local.exists("/Test folder/New folder/testFile.pdf")
        finally:
            self.engine_1.remote.download_callback = Engine.suspend_client
Example #2
0
def test_error():
    with pytest.raises(RuntimeError):
        Options.set("no key", 42)

    with configure_scope() as scope:
        scope._should_capture = False
        Options.set("no key", 42, fail_on_error=False)

    with pytest.raises(TypeError) as err:
        Options.set("delay", "foo")
    msg = err.value.args[0]
    assert "delay" in msg
    assert "test.ini" not in msg
    assert "debugging" not in msg

    # Test the 'section' arg
    with pytest.raises(TypeError) as err:
        Options.set("delay", "foo", file="test.ini")
    msg = err.value.args[0]
    assert "delay" in msg
    assert "test.ini" in msg
    assert "debugging" not in msg

    # Test `file` and `section` args
    with pytest.raises(TypeError) as err:
        Options.set("delay", "foo", file="test.ini", section="debugging")
    msg = err.value.args[0]
    assert "delay" in msg
    assert "test.ini" in msg
    assert "debugging" in msg
Example #3
0
def test_validator(option, a_bad_value, a_good_value):
    # Setting a bad value is a no-op
    Options.set(option, a_bad_value)
    assert getattr(Options, option) != a_bad_value

    Options.set(option, a_good_value)
    assert getattr(Options, option) == a_good_value
Example #4
0
def test_error():
    with pytest.raises(RuntimeError):
        Options.set("no key", 42)

    with configure_scope() as scope:
        scope._should_capture = False
        Options.set("no key", 42, fail_on_error=False)

    with pytest.raises(TypeError) as err:
        Options.set("delay", "foo")
    msg = err.value.args[0]
    assert "delay" in msg
    assert "test.ini" not in msg
    assert "debugging" not in msg

    # Test the 'section' arg
    with pytest.raises(TypeError) as err:
        Options.set("delay", "foo", file="test.ini")
    msg = err.value.args[0]
    assert "delay" in msg
    assert "test.ini" in msg
    assert "debugging" not in msg

    # Test `file` and `section` args
    with pytest.raises(TypeError) as err:
        Options.set("delay", "foo", file="test.ini", section="debugging")
    msg = err.value.args[0]
    assert "delay" in msg
    assert "test.ini" in msg
    assert "debugging" in msg
Example #5
0
    def test_synchronize_remote_deletion_while_download_file(self):
        local = self.local_1
        remote = self.remote_document_client_1

        def callback(*_):
            """ Add delay when upload and download. """
            if not self.engine_1.has_delete:
                # Delete remote file while downloading
                try:
                    remote.delete("/Test folder/testFile.pdf")
                except Exception:
                    log.exception("Cannot trash")
                else:
                    self.engine_1.has_delete = True
            time.sleep(1)
            Engine.suspend_client(self.engine_1)

        self.engine_1.start()
        self.engine_1.has_delete = False

        filepath = self.location / "resources" / "testFile.pdf"

        Options.set("tmp_file_limit", 0.1, "manual")
        with patch.object(self.engine_1.remote,
                          "download_callback",
                          new=callback):
            remote.make_folder("/", "Test folder")
            remote.make_file("/Test folder", "testFile.pdf",
                             filepath.read_bytes())

            self.wait_sync(wait_for_async=True)
            # Sometimes the server does not return the document trash action in summary changes.
            # So it may fail on the next assertion.
            assert not local.exists("/Test folder/testFile.pdf")
Example #6
0
def test_cli_args(tmp):
    url = "http://*****:*****@localhost:8899"
    Options.set("proxy_server", url, setter="cli")
    with Manager(tmp()) as manager:
        proxy = manager.proxy
        assert isinstance(proxy, ManualProxy)
        assert proxy.url == url
        settings = proxy.settings()
        assert settings["http"] == settings["https"] == url
Example #7
0
def test_cli_args(tmp):
    url = "http://*****:*****@localhost:8899"
    Options.set("proxy_server", url, setter="cli")
    with Manager(tmp()) as manager:
        proxy = manager.proxy
        assert isinstance(proxy, ManualProxy)
        assert proxy.url == url
        settings = proxy.settings()
        assert settings["http"] == settings["https"] == url
Example #8
0
def test_server_and_local_config_with_default_value_forced():
    """Usecase:
    - The server defines some options.
    - The user decided to force default values for the same option.
    Result: The user choice must be the priority.
    """

    # The option is set to True by default
    assert Options.synchronization_enabled

    # The default arguments from the CLI are not taken into account
    Options.set("synchronization_enabled", True, setter="cli")
    assert str(Options) == "Options()"

    # The user has a config file setting the option to True,
    # even if this is the default value, it should be taken into account
    Options.set("synchronization_enabled", True, setter="local")
    assert str(Options) == "Options(synchronization_enabled[local]=True)"

    # Even further: the user has set the default value manually, it has the priority over all
    Options.set("synchronization_enabled", True, setter="manual")
    assert str(Options) == "Options(synchronization_enabled[manual]=True)"

    # The server's config has then no power
    Options.set("synchronization_enabled", False, setter="server")
    assert Options.synchronization_enabled
Example #9
0
def test_features(feature, feat_name, default, manager_factory):
    """Check that features are well handled."""
    manager, engine = manager_factory()
    updater = ServerOptionsUpdater(manager)
    opt_name = f"feature_{feat_name}"

    def enabled():
        return {"feature": {feature: default}}

    def toggled():
        return {"feature": {feature: not default}}

    # Check the default value
    assert getattr(Feature, feat_name) is default
    assert getattr(Options, opt_name) is default

    # Mimic the IT team toggling the feature's state
    with patch.object(engine.remote, "get_server_configuration", new=toggled):
        updater._poll()
        assert getattr(Feature, feat_name) is not default
        assert getattr(Options, opt_name) is not default

    # Mimic the IT team restoring back the feature's state
    with patch.object(engine.remote, "get_server_configuration", new=enabled):
        updater._poll()
        assert getattr(Feature, feat_name) is default
        assert getattr(Options, opt_name) is default

    # No-op
    updater._poll()
    assert getattr(Feature, feat_name) is default
    assert getattr(Options, opt_name) is default

    # Check when the feature is forced locally
    Options.set(opt_name, not default, setter="local")
    assert getattr(Feature, feat_name) is not default
    assert getattr(Options, opt_name) is not default

    # Check when the feature is forced locally (restoring the default value)
    Options.set(opt_name, default, setter="local")
    assert getattr(Feature, feat_name) is default
    assert getattr(Options, opt_name) is default

    # Then the server config has on more power on the feature state
    with patch.object(engine.remote, "get_server_configuration", new=toggled):
        updater._poll()
        assert getattr(Feature, feat_name) is default
        assert getattr(Options, opt_name) is default
Example #10
0
def test_cli_args():
    url = "http://*****:*****@localhost:8899"
    Options.set("proxy_server", url, setter="cli")
    manager = Manager()
    proxy = manager.proxy
    assert proxy
    assert isinstance(proxy, ManualProxy)
    assert proxy.authenticated
    assert proxy.scheme == "http"
    assert proxy.host == "localhost"
    assert proxy.port == 8899
    assert proxy.username == "username"
    assert proxy.password == "password"
    settings = proxy.settings()
    assert settings["http"] == settings["https"] == url
    manager.stop()
    manager.unbind_all()
    manager.dispose_all()
    Manager._singleton = None
Example #11
0
def test_list_conversion_and_original_values_updated():
    assert isinstance(Options.ignored_suffixes, tuple)
    assert "azerty" not in Options.ignored_suffixes
    current_len = len(Options.ignored_suffixes)

    Options.set("ignored_suffixes", ["azerty"], setter="manual")
    assert isinstance(Options.ignored_suffixes, tuple)
    assert "azerty" in Options.ignored_suffixes
    assert len(Options.ignored_suffixes) == current_len + 1

    new_values = {
        "ignored_files": ["bim", "bam", "boom", "zzzzzzzzzz"],
        "force_locale": "zh",
    }
    Options.update(new_values, setter="manual")
    assert isinstance(Options.ignored_files, tuple)
    assert "bim" in Options.ignored_files
    assert "bam" in Options.ignored_files
    assert "boom" in Options.ignored_files
    assert len(Options.ignored_files) > 4
    # Check it is sorted
    assert Options.ignored_files[-1] == "zzzzzzzzzz"
Example #12
0
def test_list_conversion_and_original_values_updated():
    assert isinstance(Options.ignored_suffixes, tuple)
    assert "azerty" not in Options.ignored_suffixes
    current_len = len(Options.ignored_suffixes)

    Options.set("ignored_suffixes", ["azerty"], setter="manual")
    assert isinstance(Options.ignored_suffixes, tuple)
    assert "azerty" in Options.ignored_suffixes
    assert len(Options.ignored_suffixes) == current_len + 1

    new_values = {
        "ignored_files": ["bim", "bam", "boom", "zzzzzzzzzz"],
        "force_locale": "zh",
    }
    Options.update(new_values, setter="manual")
    assert isinstance(Options.ignored_files, tuple)
    assert "bim" in Options.ignored_files
    assert "bam" in Options.ignored_files
    assert "boom" in Options.ignored_files
    assert len(Options.ignored_files) > 4
    # Check it is sorted
    assert Options.ignored_files[-1] == "zzzzzzzzzz"
Example #13
0
def test_error():
    with pytest.raises(RuntimeError):
        Options.set("no key", 42)

    Options.set("no key", 42, fail_on_error=False)

    with pytest.raises(TypeError):
        Options.set("delay", "foo")
Example #14
0
def test_error():
    with pytest.raises(KeyError):
        Options.set('no key', 42)

    Options.set('no key', 42, fail_on_error=False)

    with pytest.raises(TypeError):
        Options.set('delay', 'foo')
Example #15
0
def test_error():
    with pytest.raises(KeyError):
        Options.set('no key', 42)

    Options.set('no key', 42, fail_on_error=False)

    with pytest.raises(TypeError):
        Options.set('delay', '30')
Example #16
0
    def parse_cli(self, argv):
        """Parse the command line argument using argparse and protocol URL"""
        # Filter psn argument provided by OSX .app service launcher
        # https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/LaunchServicesReference.pdf
        # When run from the .app bundle generated with py2app with
        # argv_emulation=True this is already filtered out but we keep it
        # for running CLI from the source folder in development.
        argv = [a for a in argv if not a.startswith("-psn_")]

        # Preprocess the args to detect protocol handler calls and be more
        # tolerant to missing subcommand
        has_command = False

        filtered_args = []
        for arg in argv[1:]:
            if arg.startswith('nxdrive://'):
                Options.set('protocol_url', arg, setter='cli')
                continue
            if not arg.startswith('-'):
                has_command = True
            filtered_args.append(arg)

        parser = self.make_cli_parser(add_subparsers=has_command)
        # Change default value according to config.ini
        self.load_config(parser)
        options = parser.parse_args(filtered_args)
        if options.debug:
            # Install Post-Mortem debugger hook

            def info(etype, value, tb):
                traceback.print_exception(etype, value, tb)
                pdb.pm()

            sys.excepthook = info

        return options
Example #17
0
    def parse_cli(self, argv):
        """Parse the command line argument using argparse and protocol URL"""
        # Filter psn argument provided by OSX .app service launcher
        # https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/LaunchServicesReference.pdf
        # When run from the .app bundle generated with py2app with
        # argv_emulation=True this is already filtered out but we keep it
        # for running CLI from the source folder in development.
        argv = [a for a in argv if not a.startswith("-psn_")]

        # Preprocess the args to detect protocol handler calls and be more
        # tolerant to missing subcommand
        has_command = False

        filtered_args = []
        for arg in argv[1:]:
            if arg.startswith('nxdrive://'):
                Options.set('protocol_url', arg, setter='cli')
                continue
            if not arg.startswith('-'):
                has_command = True
            filtered_args.append(arg)

        parser = self.make_cli_parser(add_subparsers=has_command)
        # Change default value according to config.ini
        self.load_config(parser)
        options = parser.parse_args(filtered_args)
        if options.debug:
            # Install Post-Mortem debugger hook

            def info(etype, value, tb):
                traceback.print_exception(etype, value, tb)
                pdb.pm()

            sys.excepthook = info

        return options
Example #18
0
def test_setters():
    """ Check setters level. """

    Options.set('delay', 1)
    assert Options.delay == 1

    Options.set('delay', 2, setter='server')
    assert Options.delay == 2

    Options.set('delay', 1)
    assert Options.delay == 2

    Options.set('delay', 3, setter='local')
    assert Options.delay == 3

    Options.set('delay', 2, setter='server')
    assert Options.delay == 3

    Options.set('delay', 42, setter='manual')
    assert Options.delay == 42

    Options.set('delay', 0, setter='local')
    assert Options.delay == 42

    Options.delay = 222
    assert Options.delay == 222
Example #19
0
def test_setters():
    """ Check setters level. """

    Options.set("delay", 1)
    assert Options.delay == 1

    Options.set("delay", 2, setter="server")
    assert Options.delay == 2

    Options.set("delay", 1)
    assert Options.delay == 2

    Options.set("delay", 3, setter="local")
    assert Options.delay == 3

    Options.set("delay", 2, setter="server")
    assert Options.delay == 3

    Options.set("delay", 42, setter="manual")
    assert Options.delay == 42

    Options.set("delay", 0, setter="local")
    assert Options.delay == 42

    Options.delay = 222
    assert Options.delay == 222
Example #20
0
def test_setters():
    """ Check setters level. """

    Options.set('delay', 1)
    assert Options.delay == 1

    Options.set('delay', 2, setter='server')
    assert Options.delay == 2

    Options.set('delay', 1)
    assert Options.delay == 2

    Options.set('delay', 3, setter='local')
    assert Options.delay == 3

    Options.set('delay', 2, setter='server')
    assert Options.delay == 3

    Options.set('delay', 42, setter='manual')
    assert Options.delay == 42

    Options.set('delay', 0, setter='local')
    assert Options.delay == 42

    Options.delay = 222
    assert Options.delay == 222
Example #21
0
def test_setters():
    """ Check setters level. """

    Options.set("delay", 1)
    assert Options.delay == 1

    Options.set("delay", 2, setter="server")
    assert Options.delay == 2

    Options.set("delay", 1)
    assert Options.delay == 2

    Options.set("delay", 3, setter="local")
    assert Options.delay == 3

    Options.set("delay", 2, setter="server")
    assert Options.delay == 3

    Options.set("delay", 42, setter="manual")
    assert Options.delay == 42

    Options.set("delay", 0, setter="local")
    assert Options.delay == 42

    Options.delay = 222
    assert Options.delay == 222