Пример #1
0
class WebUIPluginTestCase(BaseTestCase):
    def set_up(self):
        common.set_tmp_config_dir()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        return component.start()

    def tear_down(self):
        def on_shutdown(result):
            del self.rpcserver
            del self.core

        return component.shutdown().addCallback(on_shutdown)

    def test_enable_webui(self):
        if 'WebUi' not in self.core.get_available_plugins():
            raise unittest.SkipTest('WebUi plugin not available for testing')

        d = self.core.enable_plugin('WebUi')

        def result_cb(result):
            if 'WebUi' not in self.core.get_enabled_plugins():
                self.fail('Failed to enable WebUi plugin')
            self.assertTrue(result)

        d.addBoth(result_cb)
        return d
Пример #2
0
class WebUIPluginTestCase(BaseTestCase):

    def set_up(self):
        common.set_tmp_config_dir()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        return component.start()

    def tear_down(self):

        def on_shutdown(result):
            del self.rpcserver
            del self.core
        return component.shutdown().addCallback(on_shutdown)

    def test_enable_webui(self):
        if 'WebUi' not in self.core.get_available_plugins():
            raise unittest.SkipTest('WebUi plugin not available for testing')

        d = self.core.enable_plugin('WebUi')

        def result_cb(result):
            if 'WebUi' not in self.core.get_enabled_plugins():
                self.fail('Failed to enable WebUi plugin')
            self.assertTrue(result)

        d.addBoth(result_cb)
        return d
Пример #3
0
 def set_up(self):
     self.setup_config()
     RPCServer(listen=False)
     self.core = Core()
     self.session = lt.session()
     self.torrent = None
     return component.start()
Пример #4
0
 def set_up(self):
     self.setup_config()
     self.rpcserver = RPCServer(listen=False)
     self.core = Core()
     self.core.config.config['lsd'] = False
     self.core.config.config['new_release_check'] = False
     self.session = self.core.session
     self.torrent = None
     return component.start()
Пример #5
0
 def set_up(self):
     common.set_tmp_config_dir()
     self.rpcserver = RPCServer(listen=False)
     self.core = Core()
     self.core.config.config['lsd'] = False
     self.clock = task.Clock()
     self.core.torrentmanager.callLater = self.clock.callLater
     self.listen_port = 51242
     return component.start().addCallback(self.start_web_server)
Пример #6
0
 def set_up(self):
     common.set_tmp_config_dir()
     self.rpcserver = RPCServer(listen=False)
     self.core = Core()
     self.core.config.config['lsd'] = False
     self.clock = task.Clock()
     self.tm = self.core.torrentmanager
     self.tm.callLater = self.clock.callLater
     return component.start()
Пример #7
0
 def set_up(self):
     self.setup_config()
     RPCServer(listen=False)
     self.core = Core()
     self.session = lt.session()
     self.torrent = None
     return component.start()
Пример #8
0
class TorrentmanagerTestCase(BaseTestCase):
    def set_up(self):
        common.set_tmp_config_dir()
        RPCServer(listen=False)
        self.core = Core()
        return component.start()

    def tear_down(self):
        return component.shutdown()

    @defer.inlineCallbacks
    def test_remove_torrent(self):
        filename = common.get_test_data_file('test.torrent')
        with open(filename) as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id = yield self.core.add_torrent_file(filename, filedump, {})
        self.assertTrue(self.core.torrentmanager.remove(torrent_id, False))

    @pytest.mark.todo
    def test_remove_torrent_false(self):
        """Test when remove_torrent returns False"""
        common.todo_test(self)

    def test_remove_invalid_torrent(self):
        self.assertRaises(InvalidTorrentError, self.core.torrentmanager.remove,
                          'torrentidthatdoesntexist')
Пример #9
0
    def __init__(self,
                 listen_interface=None,
                 interface=None,
                 port=None,
                 standalone=False,
                 read_only_config_keys=None):
        """
        Args:
            listen_interface (str, optional): The IP address to listen to bittorrent connections on.
            interface (str, optional): The IP address the daemon will listen for UI connections on.
            port (int, optional): The port the daemon will listen for UI connections on.
            standalone (bool, optional): If True the client is in Standalone mode otherwise, if
                False, start the daemon as separate process.
            read_only_config_keys (list of str, optional): A list of config keys that will not be
                altered by core.set_config() RPC method.
        """
        self.standalone = standalone
        self.pid_file = get_config_dir('deluged.pid')
        log.info('Deluge daemon %s', get_version())
        if is_daemon_running(self.pid_file):
            raise DaemonRunningError(
                'Deluge daemon already running with this config directory!')

        # Twisted catches signals to terminate, so just have it call the shutdown method.
        reactor.addSystemEventTrigger('before', 'shutdown', self._shutdown)

        # Catch some Windows specific signals
        if windows_check():

            def win_handler(ctrl_type):
                """Handle the Windows shutdown or close events."""
                log.debug('windows handler ctrl_type: %s', ctrl_type)
                if ctrl_type == CTRL_CLOSE_EVENT or ctrl_type == CTRL_SHUTDOWN_EVENT:
                    self._shutdown()
                    return 1

            SetConsoleCtrlHandler(win_handler)

        # Start the core as a thread and join it until it's done
        self.core = Core(listen_interface=listen_interface,
                         read_only_config_keys=read_only_config_keys)

        if port is None:
            port = self.core.config['daemon_port']
        self.port = port

        if interface and not is_ip(interface):
            log.error('Invalid UI interface (must be IP Address): %s',
                      interface)
            interface = None

        self.rpcserver = RPCServer(
            port=port,
            allow_remote=self.core.config['allow_remote'],
            listen=not standalone,
            interface=interface)

        log.debug('Listening to UI on: %s:%s and bittorrent on: %s', interface,
                  port, listen_interface)
Пример #10
0
 def setUp(self):
     self.setup_config()
     global rpcserver
     global core
     rpcserver = RPCServer(listen=False)
     core = Core()
     self.session = lt.session()
     self.torrent = None
     return component.start()
Пример #11
0
class Daemon(object):
    def __init__(self, options=None, args=None, classic=False):
        # Check for another running instance of the daemon
        if os.path.isfile(deluge.configmanager.get_config_dir("deluged.pid")):
            # Get the PID and the port of the supposedly running daemon
            try:
                (pid, port) = open(
                    deluge.configmanager.get_config_dir(
                        "deluged.pid")).read().strip().split(";")
                pid = int(pid)
                port = int(port)
            except ValueError:
                pid = None
                port = None

            def process_running(pid):
                if deluge.common.windows_check():
                    import win32process
                    return pid in win32process.EnumProcesses()
                else:
                    # We can just use os.kill on UNIX to test if the process is running
                    try:
                        os.kill(pid, 0)
                    except OSError:
                        return False
                    else:
                        return True

            if pid is not None and process_running(pid):
                # Ok, so a process is running with this PID, let's make doubly-sure
                # it's a deluged process by trying to open a socket to it's port.
                import socket
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    s.connect(("127.0.0.1", port))
                except socket.error:
                    # Can't connect, so it must not be a deluged process..
                    pass
                else:
                    # This is a deluged!
                    s.close()
                    raise deluge.error.DaemonRunningError(
                        "There is a deluge daemon running with this config directory!"
                    )

        # Initialize gettext
        try:
            locale.setlocale(locale.LC_ALL, '')
            if hasattr(locale, "bindtextdomain"):
                locale.bindtextdomain(
                    "deluge",
                    pkg_resources.resource_filename("deluge", "i18n"))
            if hasattr(locale, "textdomain"):
                locale.textdomain("deluge")
            gettext.bindtextdomain(
                "deluge", pkg_resources.resource_filename("deluge", "i18n"))
            gettext.textdomain("deluge")
            gettext.install("deluge",
                            pkg_resources.resource_filename("deluge", "i18n"))
        except Exception, e:
            log.error("Unable to initialize gettext/locale: %s", e)
            import __builtin__
            __builtin__.__dict__["_"] = lambda x: x

        # Twisted catches signals to terminate, so just have it call the shutdown
        # method.
        reactor.addSystemEventTrigger("before", "shutdown", self._shutdown)

        # Catch some Windows specific signals
        if deluge.common.windows_check():
            from win32api import SetConsoleCtrlHandler
            from win32con import CTRL_CLOSE_EVENT
            from win32con import CTRL_SHUTDOWN_EVENT

            def win_handler(ctrl_type):
                log.debug("ctrl_type: %s", ctrl_type)
                if ctrl_type == CTRL_CLOSE_EVENT or ctrl_type == CTRL_SHUTDOWN_EVENT:
                    self._shutdown()
                    return 1

            SetConsoleCtrlHandler(win_handler)

        version = deluge.common.get_version()

        log.info("Deluge daemon %s", version)
        log.debug("options: %s", options)
        log.debug("args: %s", args)
        # Set the config directory
        if options and options.config:
            deluge.configmanager.set_config_dir(options.config)

        if options and options.listen_interface:
            listen_interface = options.listen_interface
        else:
            listen_interface = ""

        from deluge.core.core import Core
        # Start the core as a thread and join it until it's done
        self.core = Core(listen_interface=listen_interface)

        port = self.core.config["daemon_port"]
        if options and options.port:
            port = options.port
        if options and options.ui_interface:
            interface = options.ui_interface
        else:
            interface = ""

        self.rpcserver = RPCServer(
            port=port,
            allow_remote=self.core.config["allow_remote"],
            listen=not classic,
            interface=interface)

        # Register the daemon and the core RPCs
        self.rpcserver.register_object(self.core)
        self.rpcserver.register_object(self)

        # Make sure we start the PreferencesManager first
        component.start("PreferencesManager")

        if not classic:
            # Write out a pid file all the time, we use this to see if a deluged is running
            # We also include the running port number to do an additional test
            open(deluge.configmanager.get_config_dir("deluged.pid"),
                 "wb").write("%s;%s\n" % (os.getpid(), port))

            component.start()
            try:
                reactor.run()
            finally:
                self._shutdown()
Пример #12
0
 def set_up(self):
     common.set_tmp_config_dir()
     self.rpcserver = RPCServer(listen=False)
     self.core = Core()
     self.listen_port = 51242
     return component.start().addCallback(self.start_web_server)
Пример #13
0
class CoreTestCase(BaseTestCase):
    def set_up(self):
        common.set_tmp_config_dir()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        self.core.config.config['lsd'] = False
        self.clock = task.Clock()
        self.core.torrentmanager.callLater = self.clock.callLater
        self.listen_port = 51242
        return component.start().addCallback(self.start_web_server)

    def start_web_server(self, result):
        website = Site(TopLevelResource())
        for dummy in range(10):
            try:
                self.webserver = reactor.listenTCP(self.listen_port, website)
            except CannotListenError as ex:
                error = ex
                self.listen_port += 1
            else:
                break
        else:
            raise error

        return result

    def tear_down(self):
        def on_shutdown(result):
            del self.rpcserver
            del self.core
            return self.webserver.stopListening()

        return component.shutdown().addCallback(on_shutdown)

    def add_torrent(self, filename, paused=False):
        if not paused:
            # Patch libtorrent flags starting torrents paused
            self.patch(deluge.core.torrentmanager,
                       'LT_DEFAULT_ADD_TORRENT_FLAGS', 592)
        options = {'add_paused': paused, 'auto_managed': False}
        filepath = common.get_test_data_file(filename)
        with open(filepath, 'rb') as _file:
            filedump = b64encode(_file.read())
        torrent_id = self.core.add_torrent_file(filename, filedump, options)
        return torrent_id

    @defer.inlineCallbacks
    def test_add_torrent_files(self):
        options = {}
        filenames = ['test.torrent', 'test_torrent.file.torrent']
        files_to_add = []
        for f in filenames:
            filename = common.get_test_data_file(f)
            with open(filename, 'rb') as _file:
                filedump = b64encode(_file.read())
            files_to_add.append((filename, filedump, options))
        errors = yield self.core.add_torrent_files(files_to_add)
        self.assertEqual(len(errors), 0)

    @defer.inlineCallbacks
    def test_add_torrent_files_error_duplicate(self):
        options = {}
        filenames = ['test.torrent', 'test.torrent']
        files_to_add = []
        for f in filenames:
            filename = common.get_test_data_file(f)
            with open(filename, 'rb') as _file:
                filedump = b64encode(_file.read())
            files_to_add.append((filename, filedump, options))
        errors = yield self.core.add_torrent_files(files_to_add)
        self.assertEqual(len(errors), 1)
        self.assertTrue(
            str(errors[0]).startswith('Torrent already in session'))

    @defer.inlineCallbacks
    def test_add_torrent_file(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = b64encode(_file.read())
        torrent_id = yield self.core.add_torrent_file_async(
            filename, filedump, options)

        # Get the info hash from the test.torrent
        from deluge.bencode import bdecode, bencode

        with open(filename, 'rb') as _file:
            info_hash = sha(bencode(bdecode(
                _file.read())[b'info'])).hexdigest()
        self.assertEqual(torrent_id, info_hash)

    def test_add_torrent_file_invalid_filedump(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        self.assertRaises(AddTorrentError, self.core.add_torrent_file,
                          filename, False, options)

    @defer.inlineCallbacks
    def test_add_torrent_url(self):
        url = ('http://localhost:%d/ubuntu-9.04-desktop-i386.iso.torrent' %
               self.listen_port)
        options = {}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        torrent_id = yield self.core.add_torrent_url(url, options)
        self.assertEqual(torrent_id, info_hash)

    def test_add_torrent_url_with_cookie(self):
        url = 'http://localhost:%d/cookie' % self.listen_port
        options = {}
        headers = {'Cookie': 'password=deluge'}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        d = self.core.add_torrent_url(url, options)
        d.addCallbacks(self.fail,
                       self.assertIsInstance,
                       errbackArgs=(Failure, ))

        d = self.core.add_torrent_url(url, options, headers)
        d.addCallbacks(self.assertEqual, self.fail, callbackArgs=(info_hash, ))

        return d

    def test_add_torrent_url_with_redirect(self):
        url = 'http://localhost:%d/redirect' % self.listen_port
        options = {}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEqual, info_hash)
        return d

    def test_add_torrent_url_with_partial_download(self):
        url = 'http://localhost:%d/partial' % self.listen_port
        options = {}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEqual, info_hash)
        return d

    @defer.inlineCallbacks
    def test_add_torrent_magnet(self):
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'
        uri = deluge.common.create_magnet_uri(info_hash)
        options = {}
        torrent_id = yield self.core.add_torrent_magnet(uri, options)
        self.assertEqual(torrent_id, info_hash)

    def test_resume_torrent(self):
        tid1 = self.add_torrent('test.torrent', paused=True)
        tid2 = self.add_torrent('test_torrent.file.torrent', paused=True)
        # Assert paused
        r1 = self.core.get_torrent_status(tid1, ['paused'])
        self.assertTrue(r1['paused'])
        r2 = self.core.get_torrent_status(tid2, ['paused'])
        self.assertTrue(r2['paused'])

        self.core.resume_torrent(tid2)
        r1 = self.core.get_torrent_status(tid1, ['paused'])
        self.assertTrue(r1['paused'])
        r2 = self.core.get_torrent_status(tid2, ['paused'])
        self.assertFalse(r2['paused'])

    def test_resume_torrent_list(self):
        """Backward compatibility for list of torrent_ids."""
        torrent_id = self.add_torrent('test.torrent', paused=True)
        self.core.resume_torrent([torrent_id])
        result = self.core.get_torrent_status(torrent_id, ['paused'])
        self.assertFalse(result['paused'])

    def test_resume_torrents(self):
        tid1 = self.add_torrent('test.torrent', paused=True)
        tid2 = self.add_torrent('test_torrent.file.torrent', paused=True)
        self.core.resume_torrents([tid1, tid2])
        r1 = self.core.get_torrent_status(tid1, ['paused'])
        self.assertFalse(r1['paused'])
        r2 = self.core.get_torrent_status(tid2, ['paused'])
        self.assertFalse(r2['paused'])

    def test_resume_torrents_all(self):
        """With no torrent_ids param, resume all torrents"""
        tid1 = self.add_torrent('test.torrent', paused=True)
        tid2 = self.add_torrent('test_torrent.file.torrent', paused=True)
        self.core.resume_torrents()
        r1 = self.core.get_torrent_status(tid1, ['paused'])
        self.assertFalse(r1['paused'])
        r2 = self.core.get_torrent_status(tid2, ['paused'])
        self.assertFalse(r2['paused'])

    def test_pause_torrent(self):
        tid1 = self.add_torrent('test.torrent')
        tid2 = self.add_torrent('test_torrent.file.torrent')
        # Assert not paused
        r1 = self.core.get_torrent_status(tid1, ['paused'])
        self.assertFalse(r1['paused'])
        r2 = self.core.get_torrent_status(tid2, ['paused'])
        self.assertFalse(r2['paused'])

        self.core.pause_torrent(tid2)
        r1 = self.core.get_torrent_status(tid1, ['paused'])
        self.assertFalse(r1['paused'])
        r2 = self.core.get_torrent_status(tid2, ['paused'])
        self.assertTrue(r2['paused'])

    def test_pause_torrent_list(self):
        """Backward compatibility for list of torrent_ids."""
        torrent_id = self.add_torrent('test.torrent')
        result = self.core.get_torrent_status(torrent_id, ['paused'])
        self.assertFalse(result['paused'])
        self.core.pause_torrent([torrent_id])
        result = self.core.get_torrent_status(torrent_id, ['paused'])
        self.assertTrue(result['paused'])

    def test_pause_torrents(self):
        tid1 = self.add_torrent('test.torrent')
        tid2 = self.add_torrent('test_torrent.file.torrent')

        self.core.pause_torrents([tid1, tid2])
        r1 = self.core.get_torrent_status(tid1, ['paused'])
        self.assertTrue(r1['paused'])
        r2 = self.core.get_torrent_status(tid2, ['paused'])
        self.assertTrue(r2['paused'])

    def test_pause_torrents_all(self):
        """With no torrent_ids param, pause all torrents"""
        tid1 = self.add_torrent('test.torrent')
        tid2 = self.add_torrent('test_torrent.file.torrent')

        self.core.pause_torrents()
        r1 = self.core.get_torrent_status(tid1, ['paused'])
        self.assertTrue(r1['paused'])
        r2 = self.core.get_torrent_status(tid2, ['paused'])
        self.assertTrue(r2['paused'])

    def test_prefetch_metadata_existing(self):
        """Check another call with same magnet returns existing deferred."""
        magnet = 'magnet:?xt=urn:btih:ab570cdd5a17ea1b61e970bb72047de141bce173'
        expected = ('ab570cdd5a17ea1b61e970bb72047de141bce173', None)

        def on_result(result):
            self.assertEqual(result, expected)

        d = self.core.prefetch_magnet_metadata(magnet)
        d.addCallback(on_result)
        d2 = self.core.prefetch_magnet_metadata(magnet)
        d2.addCallback(on_result)
        self.clock.advance(30)
        return defer.DeferredList([d, d2])

    @defer.inlineCallbacks
    def test_remove_torrent(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = b64encode(_file.read())
        torrent_id = yield self.core.add_torrent_file_async(
            filename, filedump, options)
        removed = self.core.remove_torrent(torrent_id, True)
        self.assertTrue(removed)
        self.assertEqual(len(self.core.get_session_state()), 0)

    def test_remove_torrent_invalid(self):
        self.assertRaises(
            InvalidTorrentError,
            self.core.remove_torrent,
            'torrentidthatdoesntexist',
            True,
        )

    @defer.inlineCallbacks
    def test_remove_torrents(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = b64encode(_file.read())
        torrent_id = yield self.core.add_torrent_file_async(
            filename, filedump, options)

        filename2 = common.get_test_data_file('unicode_filenames.torrent')
        with open(filename2, 'rb') as _file:
            filedump = b64encode(_file.read())
        torrent_id2 = yield self.core.add_torrent_file_async(
            filename2, filedump, options)
        d = self.core.remove_torrents([torrent_id, torrent_id2], True)

        def test_ret(val):
            self.assertTrue(val == [])

        d.addCallback(test_ret)

        def test_session_state(val):
            self.assertEqual(len(self.core.get_session_state()), 0)

        d.addCallback(test_session_state)
        yield d

    @defer.inlineCallbacks
    def test_remove_torrents_invalid(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = b64encode(_file.read())
            torrent_id = yield self.core.add_torrent_file_async(
                filename, filedump, options)
        val = yield self.core.remove_torrents(
            ['invalidid1', 'invalidid2', torrent_id], False)
        self.assertEqual(len(val), 2)
        self.assertEqual(
            val[0], ('invalidid1', 'torrent_id invalidid1 not in session.'))
        self.assertEqual(
            val[1], ('invalidid2', 'torrent_id invalidid2 not in session.'))

    def test_get_session_status(self):
        status = self.core.get_session_status(
            ['net.recv_tracker_bytes', 'net.sent_tracker_bytes'])
        self.assertIsInstance(status, dict)
        self.assertEqual(status['net.recv_tracker_bytes'], 0)
        self.assertEqual(status['net.sent_tracker_bytes'], 0)

    def test_get_session_status_all(self):
        status = self.core.get_session_status([])
        self.assertIsInstance(status, dict)
        self.assertIn('upload_rate', status)
        self.assertIn('net.recv_bytes', status)

    def test_get_session_status_depr(self):
        status = self.core.get_session_status(['num_peers', 'num_unchoked'])
        self.assertIsInstance(status, dict)
        self.assertEqual(status['num_peers'], 0)
        self.assertEqual(status['num_unchoked'], 0)

    def test_get_session_status_rates(self):
        status = self.core.get_session_status(['upload_rate', 'download_rate'])
        self.assertIsInstance(status, dict)
        self.assertEqual(status['upload_rate'], 0)

    def test_get_session_status_ratio(self):
        status = self.core.get_session_status(
            ['write_hit_ratio', 'read_hit_ratio'])
        self.assertIsInstance(status, dict)
        self.assertEqual(status['write_hit_ratio'], 0.0)
        self.assertEqual(status['read_hit_ratio'], 0.0)

    def test_get_free_space(self):
        space = self.core.get_free_space('.')
        # get_free_space returns long on Python 2 (32-bit).
        self.assertTrue(isinstance(space, integer_types))
        self.assertTrue(space >= 0)
        self.assertEqual(self.core.get_free_space('/someinvalidpath'), -1)

    @pytest.mark.slow
    def test_test_listen_port(self):
        d = self.core.test_listen_port()

        def result(r):
            self.assertTrue(r in (True, False))

        d.addCallback(result)
        return d

    def test_sanitize_filepath(self):
        pathlist = {
            '\\backslash\\path\\': 'backslash/path',
            ' single_file ': 'single_file',
            '..': '',
            '/../..../': '',
            '  Def ////ad./ / . . /b  d /file': 'Def/ad./. ./b  d/file',
            '/ test /\\.. /.file/': 'test/.file',
            'mytorrent/subfold/file1': 'mytorrent/subfold/file1',
            'Torrent/folder/': 'Torrent/folder',
        }

        for key in pathlist:
            self.assertEqual(
                deluge.core.torrent.sanitize_filepath(key, folder=False),
                pathlist[key])
            self.assertEqual(
                deluge.core.torrent.sanitize_filepath(key, folder=True),
                pathlist[key] + '/',
            )

    def test_get_set_config_values(self):
        self.assertEqual(self.core.get_config_values(['abc', 'foo']), {
            'foo': None,
            'abc': None
        })
        self.assertEqual(self.core.get_config_value('foobar'), None)
        self.core.set_config({'abc': 'def', 'foo': 10, 'foobar': 'barfoo'})
        self.assertEqual(self.core.get_config_values(['foo', 'abc']), {
            'foo': 10,
            'abc': 'def'
        })
        self.assertEqual(self.core.get_config_value('foobar'), 'barfoo')

    def test_read_only_config_keys(self):
        key = 'max_upload_speed'
        self.core.read_only_config_keys = [key]

        old_value = self.core.get_config_value(key)
        self.core.set_config({key: old_value + 10})
        new_value = self.core.get_config_value(key)
        self.assertEqual(old_value, new_value)

        self.core.read_only_config_keys = None

    def test__create_peer_id(self):
        self.assertEqual(self.core._create_peer_id('2.0.0'), '-DE200s-')
        self.assertEqual(self.core._create_peer_id('2.0.0.dev15'), '-DE200D-')
        self.assertEqual(self.core._create_peer_id('2.0.1rc1'), '-DE201r-')
        self.assertEqual(self.core._create_peer_id('2.11.0b2'), '-DE2B0b-')
        self.assertEqual(self.core._create_peer_id('2.4.12b2.dev3'),
                         '-DE24CD-')
Пример #14
0
    def __init__(self, options=None, args=None, classic=False):
        # Check for another running instance of the daemon
        if os.path.isfile(deluge.configmanager.get_config_dir("deluged.pid")):
            # Get the PID and the port of the supposedly running daemon
            try:
                (pid, port) = open(
                    deluge.configmanager.get_config_dir(
                        "deluged.pid")).read().strip().split(";")
                pid = int(pid)
                port = int(port)
            except ValueError:
                pid = None
                port = None

            def process_running(pid):
                if deluge.common.windows_check():
                    # Do some fancy WMI junk to see if the PID exists in Windows
                    from win32com.client import GetObject

                    def get_proclist():
                        WMI = GetObject('winmgmts:')
                        processes = WMI.InstancesOf('Win32_Process')
                        return [
                            process.Properties_('ProcessID').Value
                            for process in processes
                        ]

                    return pid in get_proclist()
                else:
                    # We can just use os.kill on UNIX to test if the process is running
                    try:
                        os.kill(pid, 0)
                    except OSError:
                        return False
                    else:
                        return True

            if pid is not None and process_running(pid):
                # Ok, so a process is running with this PID, let's make doubly-sure
                # it's a deluged process by trying to open a socket to it's port.
                import socket
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    s.connect(("127.0.0.1", port))
                except socket.error:
                    # Can't connect, so it must not be a deluged process..
                    pass
                else:
                    # This is a deluged!
                    s.close()
                    raise deluge.error.DaemonRunningError(
                        "There is a deluge daemon running with this config "
                        "directory!")

        # Initialize gettext
        deluge.common.setup_translations()

        # Twisted catches signals to terminate, so just have it call the shutdown
        # method.
        reactor.addSystemEventTrigger("after", "shutdown", self.shutdown)

        # Catch some Windows specific signals
        if deluge.common.windows_check():
            from win32api import SetConsoleCtrlHandler
            from win32con import CTRL_CLOSE_EVENT
            from win32con import CTRL_SHUTDOWN_EVENT

            def win_handler(ctrl_type):
                log.debug("ctrl_type: %s", ctrl_type)
                if ctrl_type == CTRL_CLOSE_EVENT or ctrl_type == CTRL_SHUTDOWN_EVENT:
                    self.__shutdown()
                    return 1

            SetConsoleCtrlHandler(win_handler)

        version = deluge.common.get_version()

        log.info("Deluge daemon %s", version)
        log.debug("options: %s", options)
        log.debug("args: %s", args)
        # Set the config directory
        if options and options.config:
            deluge.configmanager.set_config_dir(options.config)

        from deluge.core.core import Core
        # Start the core as a thread and join it until it's done
        self.core = Core()

        port = self.core.config["daemon_port"]
        if options and options.port:
            port = options.port
        if options and options.ui_interface:
            interface = options.ui_interface
        else:
            interface = ""

        self.rpcserver = RPCServer(
            port=port,
            allow_remote=self.core.config["allow_remote"],
            listen=not classic,
            interface=interface)

        # Register the daemon and the core RPCs
        self.rpcserver.register_object(self.core)
        self.rpcserver.register_object(self)

        # Make sure we start the PreferencesManager first
        component.start("PreferencesManager")

        if not classic:
            # Write out a pid file all the time, we use this to see if a deluged is running
            # We also include the running port number to do an additional test
            open(deluge.configmanager.get_config_dir("deluged.pid"),
                 "wb").write("%s;%s\n" % (os.getpid(), port))

            component.start()
            try:
                reactor.run()
            finally:
                self._shutdown()
Пример #15
0
class CoreTestCase(unittest.TestCase):
    def setUp(self):
        common.set_tmp_config_dir()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        return component.start().addCallback(self.startWebserver)

    def startWebserver(self, result):
        self.website = Site(TopLevelResource())
        self.webserver = reactor.listenTCP(51242, self.website)
        return result

    def tearDown(self):
        def on_shutdown(result):
            component._ComponentRegistry.components = {}
            del self.rpcserver
            del self.core
            return self.webserver.stopListening()

        return component.shutdown().addCallback(on_shutdown)

    def test_add_torrent_file(self):
        options = {}
        filename = os.path.join(os.path.dirname(__file__), "test.torrent")
        import base64
        torrent_id = self.core.add_torrent_file(
            filename, base64.encodestring(open(filename).read()), options)

        # Get the info hash from the test.torrent
        from deluge.bencode import bdecode, bencode
        info_hash = sha(bencode(bdecode(
            open(filename).read())["info"])).hexdigest()

        self.assertEquals(torrent_id, info_hash)

    def test_add_torrent_url(self):
        url = "http://localhost:51242/ubuntu-9.04-desktop-i386.iso.torrent"
        options = {}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEquals, info_hash)
        return d

    def test_add_torrent_url_with_cookie(self):
        url = "http://localhost:51242/cookie"
        options = {}
        headers = {"Cookie": "password=deluge"}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallbacks(self.fail,
                       self.assertIsInstance,
                       errbackArgs=(Failure, ))

        d = self.core.add_torrent_url(url, options, headers)
        d.addCallbacks(self.assertEquals,
                       self.fail,
                       callbackArgs=(info_hash, ))

        return d

    def test_add_torrent_url_with_redirect(self):
        url = "http://localhost:51242/redirect"
        options = {}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEquals, info_hash)

        return d

    def test_add_torrent_url_with_partial_download(self):
        url = "http://localhost:51242/partial"
        options = {}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEquals, info_hash)

        return d

    def test_add_magnet(self):
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"
        import deluge.common
        uri = deluge.common.create_magnet_uri(info_hash)
        options = {}

        torrent_id = self.core.add_torrent_magnet(uri, options)
        self.assertEquals(torrent_id, info_hash)

    def test_remove_torrent(self):
        options = {}
        filename = os.path.join(os.path.dirname(__file__), "test.torrent")
        import base64
        torrent_id = self.core.add_torrent_file(
            filename, base64.encodestring(open(filename).read()), options)

        self.assertRaises(deluge.error.InvalidTorrentError,
                          self.core.remove_torrent, "torrentidthatdoesntexist",
                          True)

        ret = self.core.remove_torrent(torrent_id, True)

        self.assertTrue(ret)
        self.assertEquals(len(self.core.get_session_state()), 0)

    def test_get_session_status(self):
        status = self.core.get_session_status(["upload_rate", "download_rate"])
        self.assertEquals(type(status), dict)
        self.assertEquals(status["upload_rate"], 0.0)

    def test_get_cache_status(self):
        status = self.core.get_cache_status()
        self.assertEquals(type(status), dict)
        self.assertEquals(status["write_hit_ratio"], 0.0)
        self.assertEquals(status["read_hit_ratio"], 0.0)

    def test_get_free_space(self):
        space = self.core.get_free_space(".")
        self.assertTrue(type(space) in (int, long))
        self.assertTrue(space >= 0)
        self.assertEquals(self.core.get_free_space("/someinvalidpath"), 0)

    def test_test_listen_port(self):
        d = self.core.test_listen_port()

        def result(r):
            self.assertTrue(r in (True, False))

        d.addCallback(result)
        return d
Пример #16
0
class CoreTestCase(BaseTestCase):

    def set_up(self):
        common.set_tmp_config_dir()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        self.listen_port = 51242
        return component.start().addCallback(self.start_web_server)

    def start_web_server(self, result):
        website = Site(TopLevelResource())
        for dummy in range(10):
            try:
                self.webserver = reactor.listenTCP(self.listen_port, website)
            except CannotListenError as ex:
                error = ex
                self.listen_port += 1
            else:
                break
        else:
            raise error

        return result

    def tear_down(self):

        def on_shutdown(result):
            del self.rpcserver
            del self.core
            return self.webserver.stopListening()

        return component.shutdown().addCallback(on_shutdown)

    @defer.inlineCallbacks
    def test_add_torrent_files(self):
        options = {}
        filenames = ['test.torrent', 'test_torrent.file.torrent']
        files_to_add = []
        for f in filenames:
            filename = common.get_test_data_file(f)
            with open(filename, 'rb') as _file:
                filedump = base64.encodestring(_file.read())
            files_to_add.append((filename, filedump, options))
        errors = yield self.core.add_torrent_files(files_to_add)
        self.assertEqual(len(errors), 0)

    @defer.inlineCallbacks
    def test_add_torrent_files_error_duplicate(self):
        options = {}
        filenames = ['test.torrent', 'test.torrent']
        files_to_add = []
        for f in filenames:
            filename = common.get_test_data_file(f)
            with open(filename, 'rb') as _file:
                filedump = base64.encodestring(_file.read())
            files_to_add.append((filename, filedump, options))
        errors = yield self.core.add_torrent_files(files_to_add)
        self.assertEqual(len(errors), 1)
        self.assertTrue(str(errors[0]).startswith('Torrent already in session'))

    @defer.inlineCallbacks
    def test_add_torrent_file(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id = yield self.core.add_torrent_file(filename, filedump, options)

        # Get the info hash from the test.torrent
        from deluge.bencode import bdecode, bencode
        with open(filename, 'rb') as _file:
            info_hash = sha(bencode(bdecode(_file.read())[b'info'])).hexdigest()
        self.assertEquals(torrent_id, info_hash)

    def test_add_torrent_file_invalid_filedump(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        self.assertRaises(AddTorrentError, self.core.add_torrent_file, filename, False, options)

    @defer.inlineCallbacks
    def test_add_torrent_url(self):
        url = 'http://localhost:%d/ubuntu-9.04-desktop-i386.iso.torrent' % self.listen_port
        options = {}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        torrent_id = yield self.core.add_torrent_url(url, options)
        self.assertEqual(torrent_id, info_hash)

    def test_add_torrent_url_with_cookie(self):
        url = 'http://localhost:%d/cookie' % self.listen_port
        options = {}
        headers = {'Cookie': 'password=deluge'}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        d = self.core.add_torrent_url(url, options)
        d.addCallbacks(self.fail, self.assertIsInstance, errbackArgs=(Failure,))

        d = self.core.add_torrent_url(url, options, headers)
        d.addCallbacks(self.assertEqual, self.fail, callbackArgs=(info_hash,))

        return d

    def test_add_torrent_url_with_redirect(self):
        url = 'http://localhost:%d/redirect' % self.listen_port
        options = {}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEqual, info_hash)
        return d

    def test_add_torrent_url_with_partial_download(self):
        url = 'http://localhost:%d/partial' % self.listen_port
        options = {}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEqual, info_hash)
        return d

    @defer.inlineCallbacks
    def test_add_torrent_magnet(self):
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'
        uri = deluge.common.create_magnet_uri(info_hash)
        options = {}
        torrent_id = yield self.core.add_torrent_magnet(uri, options)
        self.assertEqual(torrent_id, info_hash)

    @defer.inlineCallbacks
    def test_remove_torrent(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
        removed = self.core.remove_torrent(torrent_id, True)
        self.assertTrue(removed)
        self.assertEqual(len(self.core.get_session_state()), 0)

    def test_remove_torrent_invalid(self):
        self.assertRaises(InvalidTorrentError, self.core.remove_torrent, 'torrentidthatdoesntexist', True)

    @defer.inlineCallbacks
    def test_remove_torrents(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id = yield self.core.add_torrent_file(filename, filedump, options)

        filename2 = common.get_test_data_file('unicode_filenames.torrent')
        with open(filename2, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id2 = yield self.core.add_torrent_file(filename2, filedump, options)
        d = self.core.remove_torrents([torrent_id, torrent_id2], True)

        def test_ret(val):
            self.assertTrue(val == [])
        d.addCallback(test_ret)

        def test_session_state(val):
            self.assertEqual(len(self.core.get_session_state()), 0)
        d.addCallback(test_session_state)
        yield d

    @defer.inlineCallbacks
    def test_remove_torrents_invalid(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
            torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
        val = yield self.core.remove_torrents(['invalidid1', 'invalidid2', torrent_id], False)
        self.assertEqual(len(val), 2)
        self.assertEqual(val[0], ('invalidid1', 'torrent_id invalidid1 not in session.'))
        self.assertEqual(val[1], ('invalidid2', 'torrent_id invalidid2 not in session.'))

    def test_get_session_status(self):
        status = self.core.get_session_status(['upload_rate', 'download_rate'])
        self.assertEqual(type(status), dict)
        self.assertEqual(status['upload_rate'], 0.0)

    def test_get_session_status_ratio(self):
        status = self.core.get_session_status(['write_hit_ratio', 'read_hit_ratio'])
        self.assertEqual(type(status), dict)
        self.assertEqual(status['write_hit_ratio'], 0.0)
        self.assertEqual(status['read_hit_ratio'], 0.0)

    def test_get_free_space(self):
        space = self.core.get_free_space('.')
        # get_free_space returns long on Python 2 (32-bit).
        self.assertTrue(isinstance(space, int if not PY2 else (int, long)))
        self.assertTrue(space >= 0)
        self.assertEqual(self.core.get_free_space('/someinvalidpath'), -1)

    @pytest.mark.slow
    def test_test_listen_port(self):
        d = self.core.test_listen_port()

        def result(r):
            self.assertTrue(r in (True, False))

        d.addCallback(result)
        return d

    def test_sanitize_filepath(self):
        pathlist = {
            '\\backslash\\path\\': 'backslash/path',
            ' single_file ': 'single_file',
            '..': '',
            '/../..../': '',
            '  Def ////ad./ / . . /b  d /file': 'Def/ad./. ./b  d/file',
            '/ test /\\.. /.file/': 'test/.file',
            'mytorrent/subfold/file1': 'mytorrent/subfold/file1',
            'Torrent/folder/': 'Torrent/folder',
        }

        for key in pathlist:
            self.assertEqual(deluge.core.torrent.sanitize_filepath(key, folder=False), pathlist[key])
            self.assertEqual(deluge.core.torrent.sanitize_filepath(key, folder=True), pathlist[key] + '/')

    def test_get_set_config_values(self):
        self.assertEqual(self.core.get_config_values(['abc', 'foo']), {'foo': None, 'abc': None})
        self.assertEqual(self.core.get_config_value('foobar'), None)
        self.core.set_config({'abc': 'def', 'foo': 10, 'foobar': 'barfoo'})
        self.assertEqual(self.core.get_config_values(['foo', 'abc']), {'foo': 10, 'abc': 'def'})
        self.assertEqual(self.core.get_config_value('foobar'), 'barfoo')

    def test_read_only_config_keys(self):
        key = 'max_upload_speed'
        self.core.read_only_config_keys = [key]

        old_value = self.core.get_config_value(key)
        self.core.set_config({key: old_value + 10})
        new_value = self.core.get_config_value(key)
        self.assertEqual(old_value, new_value)

        self.core.read_only_config_keys = None
Пример #17
0
class CoreTestCase(BaseTestCase):
    def set_up(self):
        common.set_tmp_config_dir()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        self.listen_port = 51242
        return component.start().addCallback(self.start_web_server)

    def start_web_server(self, result):
        website = Site(TopLevelResource())
        for dummy in range(10):
            try:
                self.webserver = reactor.listenTCP(self.listen_port, website)
            except CannotListenError as ex:
                error = ex
                self.listen_port += 1
            else:
                break
        else:
            raise error

        return result

    def tear_down(self):
        def on_shutdown(result):
            del self.rpcserver
            del self.core
            return self.webserver.stopListening()

        return component.shutdown().addCallback(on_shutdown)

    @defer.inlineCallbacks
    def test_add_torrent_files(self):
        options = {}
        filenames = ['test.torrent', 'test_torrent.file.torrent']
        files_to_add = []
        for f in filenames:
            filename = common.get_test_data_file(f)
            with open(filename, 'rb') as _file:
                filedump = base64.encodestring(_file.read())
            files_to_add.append((filename, filedump, options))
        errors = yield self.core.add_torrent_files(files_to_add)
        self.assertEqual(len(errors), 0)

    @defer.inlineCallbacks
    def test_add_torrent_files_error_duplicate(self):
        options = {}
        filenames = ['test.torrent', 'test.torrent']
        files_to_add = []
        for f in filenames:
            filename = common.get_test_data_file(f)
            with open(filename, 'rb') as _file:
                filedump = base64.encodestring(_file.read())
            files_to_add.append((filename, filedump, options))
        errors = yield self.core.add_torrent_files(files_to_add)
        self.assertEqual(len(errors), 1)
        self.assertTrue(
            str(errors[0]).startswith('Torrent already in session'))

    @defer.inlineCallbacks
    def test_add_torrent_file(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id = yield self.core.add_torrent_file(filename, filedump,
                                                      options)

        # Get the info hash from the test.torrent
        from deluge.bencode import bdecode, bencode
        with open(filename, 'rb') as _file:
            info_hash = sha(bencode(bdecode(
                _file.read())[b'info'])).hexdigest()
        self.assertEquals(torrent_id, info_hash)

    def test_add_torrent_file_invalid_filedump(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        self.assertRaises(AddTorrentError, self.core.add_torrent_file,
                          filename, False, options)

    @defer.inlineCallbacks
    def test_add_torrent_url(self):
        url = 'http://localhost:%d/ubuntu-9.04-desktop-i386.iso.torrent' % self.listen_port
        options = {}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        torrent_id = yield self.core.add_torrent_url(url, options)
        self.assertEqual(torrent_id, info_hash)

    def test_add_torrent_url_with_cookie(self):
        url = 'http://localhost:%d/cookie' % self.listen_port
        options = {}
        headers = {'Cookie': 'password=deluge'}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        d = self.core.add_torrent_url(url, options)
        d.addCallbacks(self.fail,
                       self.assertIsInstance,
                       errbackArgs=(Failure, ))

        d = self.core.add_torrent_url(url, options, headers)
        d.addCallbacks(self.assertEqual, self.fail, callbackArgs=(info_hash, ))

        return d

    def test_add_torrent_url_with_redirect(self):
        url = 'http://localhost:%d/redirect' % self.listen_port
        options = {}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEqual, info_hash)
        return d

    def test_add_torrent_url_with_partial_download(self):
        url = 'http://localhost:%d/partial' % self.listen_port
        options = {}
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEqual, info_hash)
        return d

    @defer.inlineCallbacks
    def test_add_torrent_magnet(self):
        info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'
        uri = deluge.common.create_magnet_uri(info_hash)
        options = {}
        torrent_id = yield self.core.add_torrent_magnet(uri, options)
        self.assertEqual(torrent_id, info_hash)

    @defer.inlineCallbacks
    def test_remove_torrent(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id = yield self.core.add_torrent_file(filename, filedump,
                                                      options)
        removed = self.core.remove_torrent(torrent_id, True)
        self.assertTrue(removed)
        self.assertEqual(len(self.core.get_session_state()), 0)

    def test_remove_torrent_invalid(self):
        self.assertRaises(InvalidTorrentError, self.core.remove_torrent,
                          'torrentidthatdoesntexist', True)

    @defer.inlineCallbacks
    def test_remove_torrents(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id = yield self.core.add_torrent_file(filename, filedump,
                                                      options)

        filename2 = common.get_test_data_file('unicode_filenames.torrent')
        with open(filename2, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id2 = yield self.core.add_torrent_file(filename2, filedump,
                                                       options)
        d = self.core.remove_torrents([torrent_id, torrent_id2], True)

        def test_ret(val):
            self.assertTrue(val == [])

        d.addCallback(test_ret)

        def test_session_state(val):
            self.assertEqual(len(self.core.get_session_state()), 0)

        d.addCallback(test_session_state)
        yield d

    @defer.inlineCallbacks
    def test_remove_torrents_invalid(self):
        options = {}
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = base64.encodestring(_file.read())
            torrent_id = yield self.core.add_torrent_file(
                filename, filedump, options)
        val = yield self.core.remove_torrents(
            ['invalidid1', 'invalidid2', torrent_id], False)
        self.assertEqual(len(val), 2)
        self.assertEqual(
            val[0], ('invalidid1', 'torrent_id invalidid1 not in session.'))
        self.assertEqual(
            val[1], ('invalidid2', 'torrent_id invalidid2 not in session.'))

    def test_get_session_status(self):
        status = self.core.get_session_status(['upload_rate', 'download_rate'])
        self.assertEqual(type(status), dict)
        self.assertEqual(status['upload_rate'], 0.0)

    def test_get_session_status_ratio(self):
        status = self.core.get_session_status(
            ['write_hit_ratio', 'read_hit_ratio'])
        self.assertEqual(type(status), dict)
        self.assertEqual(status['write_hit_ratio'], 0.0)
        self.assertEqual(status['read_hit_ratio'], 0.0)

    def test_get_free_space(self):
        space = self.core.get_free_space('.')
        # get_free_space returns long on Python 2 (32-bit).
        self.assertTrue(isinstance(space, int if not PY2 else (int, long)))
        self.assertTrue(space >= 0)
        self.assertEqual(self.core.get_free_space('/someinvalidpath'), -1)

    @pytest.mark.slow
    def test_test_listen_port(self):
        d = self.core.test_listen_port()

        def result(r):
            self.assertTrue(r in (True, False))

        d.addCallback(result)
        return d

    def test_sanitize_filepath(self):
        pathlist = {
            '\\backslash\\path\\': 'backslash/path',
            ' single_file ': 'single_file',
            '..': '',
            '/../..../': '',
            '  Def ////ad./ / . . /b  d /file': 'Def/ad./. ./b  d/file',
            '/ test /\\.. /.file/': 'test/.file',
            'mytorrent/subfold/file1': 'mytorrent/subfold/file1',
            'Torrent/folder/': 'Torrent/folder',
        }

        for key in pathlist:
            self.assertEqual(
                deluge.core.torrent.sanitize_filepath(key, folder=False),
                pathlist[key])
            self.assertEqual(
                deluge.core.torrent.sanitize_filepath(key, folder=True),
                pathlist[key] + '/')

    def test_get_set_config_values(self):
        self.assertEqual(self.core.get_config_values(['abc', 'foo']), {
            'foo': None,
            'abc': None
        })
        self.assertEqual(self.core.get_config_value('foobar'), None)
        self.core.set_config({'abc': 'def', 'foo': 10, 'foobar': 'barfoo'})
        self.assertEqual(self.core.get_config_values(['foo', 'abc']), {
            'foo': 10,
            'abc': 'def'
        })
        self.assertEqual(self.core.get_config_value('foobar'), 'barfoo')

    def test_read_only_config_keys(self):
        key = 'max_upload_speed'
        self.core.read_only_config_keys = [key]

        old_value = self.core.get_config_value(key)
        self.core.set_config({key: old_value + 10})
        new_value = self.core.get_config_value(key)
        self.assertEqual(old_value, new_value)

        self.core.read_only_config_keys = None
Пример #18
0
    def setUp(self):
        self.core = Core()

        self.am = component.get("AlertManager")
        component.start(["AlertManager"])
Пример #19
0
 def setUp(self):
     common.set_tmp_config_dir()
     self.rpcserver = RPCServer(listen=False)
     self.core = Core()
     d = component.start()
     return d
Пример #20
0
 def set_up(self):
     common.set_tmp_config_dir()
     RPCServer(listen=False)
     self.core = Core()
     return component.start()
Пример #21
0
class CoreTestCase(unittest.TestCase):
    def setUp(self):
        common.set_tmp_config_dir()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        return component.start().addCallback(self.startWebserver)

    def startWebserver(self, result):
        self.website = Site(TopLevelResource())
        self.webserver = reactor.listenTCP(51242, self.website)
        return result

    def tearDown(self):

        def on_shutdown(result):
            component._ComponentRegistry.components = {}
            del self.rpcserver
            del self.core
            return self.webserver.stopListening()

        return component.shutdown().addCallback(on_shutdown)

    def test_add_torrent_file(self):
        options = {}
        filename = os.path.join(os.path.dirname(__file__), "test.torrent")
        import base64
        torrent_id = self.core.add_torrent_file(filename, base64.encodestring(open(filename).read()), options)

        # Get the info hash from the test.torrent
        from deluge.bencode import bdecode, bencode
        info_hash = sha(bencode(bdecode(open(filename).read())["info"])).hexdigest()

        self.assertEquals(torrent_id, info_hash)

    def test_add_torrent_url(self):
        url = "http://localhost:51242/ubuntu-9.04-desktop-i386.iso.torrent"
        options = {}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEquals, info_hash)
        return d

    def test_add_torrent_url_with_cookie(self):
        url = "http://localhost:51242/cookie"
        options = {}
        headers = { "Cookie" : "password=deluge" }
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallbacks(self.fail, self.assertIsInstance, errbackArgs=(Failure,))

        d = self.core.add_torrent_url(url, options, headers)
        d.addCallbacks(self.assertEquals, self.fail, callbackArgs=(info_hash,))

        return d

    def test_add_torrent_url_with_redirect(self):
        url = "http://localhost:51242/redirect"
        options = {}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEquals, info_hash)

        return d

    def test_add_torrent_url_with_partial_download(self):
        url = "http://localhost:51242/partial"
        options = {}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEquals, info_hash)

        return d

    def test_add_magnet(self):
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"
        import deluge.common
        uri = deluge.common.create_magnet_uri(info_hash)
        options = {}

        torrent_id = self.core.add_torrent_magnet(uri, options)
        self.assertEquals(torrent_id, info_hash)

    def test_remove_torrent(self):
        options = {}
        filename = os.path.join(os.path.dirname(__file__), "test.torrent")
        import base64
        torrent_id = self.core.add_torrent_file(filename, base64.encodestring(open(filename).read()), options)

        self.assertRaises(deluge.error.InvalidTorrentError, self.core.remove_torrent, "torrentidthatdoesntexist", True)

        ret = self.core.remove_torrent(torrent_id, True)

        self.assertTrue(ret)
        self.assertEquals(len(self.core.get_session_state()), 0)

    def test_get_session_status(self):
        status = self.core.get_session_status(["upload_rate", "download_rate"])
        self.assertEquals(type(status), dict)
        self.assertEquals(status["upload_rate"], 0.0)

    def test_get_cache_status(self):
        status = self.core.get_cache_status()
        self.assertEquals(type(status), dict)
        self.assertEquals(status["write_hit_ratio"], 0.0)
        self.assertEquals(status["read_hit_ratio"], 0.0)

    def test_get_free_space(self):
        space = self.core.get_free_space(".")
        self.assertTrue(type(space) in (int, long))
        self.assertTrue(space >= 0)
        self.assertEquals(self.core.get_free_space("/someinvalidpath"), 0)

    def test_test_listen_port(self):
        d = self.core.test_listen_port()

        def result(r):
            self.assertTrue(r in (True, False))

        d.addCallback(result)
        return d

    def test_sanitize_filepath(self):
        pathlist = {
            '\\backslash\\path\\' : 'backslash/path',
            ' single_file ': 'single_file',
            '..' : '',
            '/../..../': '',
            '  Def ////ad./ / . . /b  d /file': 'Def/ad./. ./b  d/file',
            '/ test /\\.. /.file/': 'test/.file',
            'mytorrent/subfold/file1': 'mytorrent/subfold/file1',
            'Torrent/folder/': 'Torrent/folder',
        }

        for key in pathlist:
            self.assertEquals(deluge.core.torrent.sanitize_filepath(key, folder=False), pathlist[key])
            self.assertEquals(deluge.core.torrent.sanitize_filepath(key, folder=True), pathlist[key] + '/')
Пример #22
0
 def set_up(self):
     self.core = Core()
     self.core.config.config['lsd'] = False
     self.am = component.get('AlertManager')
     return component.start(['AlertManager'])
Пример #23
0
 def setUp(self):
     common.set_tmp_config_dir()
     self.rpcserver = RPCServer(listen=False)
     self.core = Core()
     return component.start().addCallback(self.startWebserver)
Пример #24
0
 def set_up(self):
     self.core = Core()
     self.am = component.get('AlertManager')
     return component.start(['AlertManager'])
Пример #25
0
class TorrentTestCase(BaseTestCase):
    def setup_config(self):
        config_dir = common.set_tmp_config_dir()
        core_config = deluge.config.Config(
            'core.conf',
            defaults=deluge.core.preferencesmanager.DEFAULT_PREFS,
            config_dir=config_dir,
        )
        core_config.save()

    def set_up(self):
        self.setup_config()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        self.core.config.config['lsd'] = False
        self.session = lt.session()
        self.torrent = None
        return component.start()

    def tear_down(self):
        def on_shutdown(result):
            del self.rpcserver
            del self.core

        return component.shutdown().addCallback(on_shutdown)

    def print_priority_list(self, priorities):
        tmp = ''
        for i, p in enumerate(priorities):
            if i % 100 == 0:
                print(tmp)
                tmp = ''
            tmp += '%s' % p
        print(tmp)

    def assert_state(self, torrent, state):
        torrent.update_state()
        self.assertEqual(torrent.state, state)

    def get_torrent_atp(self, filename):
        filename = common.get_test_data_file(filename)
        with open(filename, 'rb') as _file:
            info = lt.torrent_info(lt.bdecode(_file.read()))
        atp = {'ti': info}
        atp['save_path'] = os.getcwd()
        atp['storage_mode'] = lt.storage_mode_t.storage_mode_sparse
        atp['add_paused'] = False
        atp['auto_managed'] = True
        atp['duplicate_is_error'] = True
        return atp

    def test_set_prioritize_first_last_pieces(self):
        piece_indexes = [
            0,
            1,
            50,
            51,
            52,
            110,
            111,
            112,
            113,
            200,
            201,
            202,
            212,
            213,
            214,
            215,
            216,
            217,
            457,
            458,
            459,
            460,
            461,
            462,
        ]
        self.run_test_set_prioritize_first_last_pieces(
            'dir_with_6_files.torrent', piece_indexes)

    def run_test_set_prioritize_first_last_pieces(self, torrent_file,
                                                  prioritized_piece_indexes):
        atp = self.get_torrent_atp(torrent_file)
        handle = self.session.add_torrent(atp)

        self.torrent = Torrent(handle, {})
        priorities_original = handle.piece_priorities()
        self.torrent.set_prioritize_first_last_pieces(True)
        priorities = handle.piece_priorities()

        # The length of the list of new priorites is the same as the original
        self.assertEqual(len(priorities_original), len(priorities))

        # Test the priority of all the pieces against the calculated indexes.
        for idx, priority in enumerate(priorities):
            if idx in prioritized_piece_indexes:
                self.assertEqual(priorities[idx], 7)
            else:
                self.assertEqual(priorities[idx], 4)

        # self.print_priority_list(priorities)

    def test_set_prioritize_first_last_pieces_false(self):
        atp = self.get_torrent_atp('dir_with_6_files.torrent')
        handle = self.session.add_torrent(atp)
        self.torrent = Torrent(handle, {})
        # First set some pieces prioritized
        self.torrent.set_prioritize_first_last_pieces(True)
        # Reset pirorities
        self.torrent.set_prioritize_first_last_pieces(False)
        priorities = handle.piece_priorities()

        # Test the priority of the prioritized pieces
        for i in priorities:
            self.assertEqual(priorities[i], 4)

        # self.print_priority_list(priorities)

    def test_torrent_error_data_missing(self):
        if windows_check():
            raise unittest.SkipTest(
                'unexpected end of file in bencoded string')
        options = {'seed_mode': True}
        filename = common.get_test_data_file('test_torrent.file.torrent')
        with open(filename, 'rb') as _file:
            filedump = b64encode(_file.read())
        torrent_id = self.core.add_torrent_file(filename, filedump, options)
        torrent = self.core.torrentmanager.torrents[torrent_id]

        time.sleep(0.5)  # Delay to wait for lt to finish check on Travis.
        self.assert_state(torrent, 'Seeding')

        # Force an error by reading (non-existant) piece from disk
        torrent.handle.read_piece(0)
        time.sleep(0.2)  # Delay to wait for alert from lt
        self.assert_state(torrent, 'Error')

    def test_torrent_error_resume_original_state(self):
        if windows_check():
            raise unittest.SkipTest(
                'unexpected end of file in bencoded string')
        options = {'seed_mode': True, 'add_paused': True}
        filename = common.get_test_data_file('test_torrent.file.torrent')
        with open(filename, 'rb') as _file:
            filedump = b64encode(_file.read())
        torrent_id = self.core.add_torrent_file(filename, filedump, options)
        torrent = self.core.torrentmanager.torrents[torrent_id]

        orig_state = 'Paused'
        self.assert_state(torrent, orig_state)

        # Force an error by reading (non-existant) piece from disk
        torrent.handle.read_piece(0)
        time.sleep(0.2)  # Delay to wait for alert from lt
        self.assert_state(torrent, 'Error')

        # Clear error and verify returned to original state
        torrent.force_recheck()

    def test_torrent_error_resume_data_unaltered(self):
        if windows_check():
            raise unittest.SkipTest(
                'unexpected end of file in bencoded string')
        resume_data = {
            'active_time': 13399,
            'num_incomplete': 16777215,
            'announce_to_lsd': 1,
            'seed_mode': 0,
            'pieces':
            '\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01',
            'paused': 0,
            'seeding_time': 13399,
            'last_scrape': 13399,
            'info-hash': '-\xc5\xd0\xe7\x1af\xfeid\x9ad\r9\xcb\x00\xa2YpIs',
            'max_uploads': 16777215,
            'max_connections': 16777215,
            'num_downloaders': 16777215,
            'total_downloaded': 0,
            'file-format': 'libtorrent resume file',
            'peers6': '',
            'added_time': 1411826665,
            'banned_peers6': '',
            'file_priority': [1],
            'last_seen_complete': 0,
            'total_uploaded': 0,
            'piece_priority':
            '\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01',
            'file-version': 1,
            'announce_to_dht': 1,
            'auto_managed': 1,
            'upload_rate_limit': 0,
            'completed_time': 1411826665,
            'allocation': 'sparse',
            'blocks per piece': 2,
            'download_rate_limit': 0,
            'libtorrent-version': '0.16.17.0',
            'banned_peers': '',
            'num_seeds': 16777215,
            'sequential_download': 0,
            'announce_to_trackers': 1,
            'peers': '\n\x00\x02\x0f=\xc6SC\x17]\xd8}\x7f\x00\x00\x01=\xc6',
            'finished_time': 13399,
            'last_upload': 13399,
            'trackers': [[]],
            'super_seeding': 0,
            'file sizes': [[512000, 1411826586]],
            'last_download': 13399,
        }
        torrent_state = TorrentState(
            torrent_id='2dc5d0e71a66fe69649a640d39cb00a259704973',
            filename='test_torrent.file.torrent',
            name='',
            save_path='/home/ubuntu/Downloads',
            file_priorities=[1],
            is_finished=True,
        )

        filename = common.get_test_data_file('test_torrent.file.torrent')
        with open(filename, 'rb') as _file:
            filedump = _file.read()
        resume_data = utf8_encode_structure(resume_data)
        torrent_id = self.core.torrentmanager.add(
            state=torrent_state,
            filedump=filedump,
            resume_data=lt.bencode(resume_data))
        torrent = self.core.torrentmanager.torrents[torrent_id]

        def assert_resume_data():
            self.assert_state(torrent, 'Error')
            tm_resume_data = lt.bdecode(
                self.core.torrentmanager.resume_data[torrent.torrent_id])
            self.assertEqual(tm_resume_data, resume_data)

        return deferLater(reactor, 0.5, assert_resume_data)

    def test_get_eta_seeding(self):
        atp = self.get_torrent_atp('test_torrent.file.torrent')
        handle = self.session.add_torrent(atp)
        self.torrent = Torrent(handle, {})
        self.assertEqual(self.torrent.get_eta(), 0)
        self.torrent.status = mock.MagicMock()

        self.torrent.status.upload_payload_rate = 5000
        self.torrent.status.download_payload_rate = 0
        self.torrent.status.all_time_download = 10000
        self.torrent.status.all_time_upload = 500
        self.torrent.is_finished = True
        self.torrent.options = {'stop_at_ratio': False}
        # Test finished and uploading but no stop_at_ratio set.
        self.assertEqual(self.torrent.get_eta(), 0)

        self.torrent.options = {'stop_at_ratio': True, 'stop_ratio': 1.5}
        result = self.torrent.get_eta()
        self.assertEqual(result, 2)
        self.assertIsInstance(result, int)

    def test_get_eta_downloading(self):
        atp = self.get_torrent_atp('test_torrent.file.torrent')
        handle = self.session.add_torrent(atp)
        self.torrent = Torrent(handle, {})
        self.assertEqual(self.torrent.get_eta(), 0)

        self.torrent.status = mock.MagicMock()
        self.torrent.status.download_payload_rate = 50
        self.torrent.status.total_wanted = 10000
        self.torrent.status.total_wanted_done = 5000

        result = self.torrent.get_eta()
        self.assertEqual(result, 100)
        self.assertIsInstance(result, int)
Пример #26
0
class TorrentmanagerTestCase(BaseTestCase):
    def set_up(self):
        common.set_tmp_config_dir()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        self.core.config.config['lsd'] = False
        self.clock = task.Clock()
        self.tm = self.core.torrentmanager
        self.tm.callLater = self.clock.callLater
        return component.start()

    def tear_down(self):
        def on_shutdown(result):
            del self.rpcserver
            del self.core

        return component.shutdown().addCallback(on_shutdown)

    @defer.inlineCallbacks
    def test_remove_torrent(self):
        filename = common.get_test_data_file('test.torrent')
        with open(filename, 'rb') as _file:
            filedump = _file.read()
        torrent_id = yield self.core.add_torrent_file_async(
            filename, b64encode(filedump), {}
        )
        self.assertTrue(self.tm.remove(torrent_id, False))

    def test_prefetch_metadata(self):
        from deluge._libtorrent import lt

        with open(common.get_test_data_file('test.torrent'), 'rb') as _file:
            t_info = lt.torrent_info(lt.bdecode(_file.read()))
        mock_alert = mock.MagicMock()
        mock_alert.handle.info_hash = mock.MagicMock(
            return_value='ab570cdd5a17ea1b61e970bb72047de141bce173'
        )
        mock_alert.handle.get_torrent_info = mock.MagicMock(return_value=t_info)

        magnet = 'magnet:?xt=urn:btih:ab570cdd5a17ea1b61e970bb72047de141bce173'
        d = self.tm.prefetch_metadata(magnet, 30)
        self.tm.on_alert_metadata_received(mock_alert)

        expected = (
            'ab570cdd5a17ea1b61e970bb72047de141bce173',
            bencode(
                {
                    'piece length': 32768,
                    'sha1': (
                        b'2\xce\xb6\xa8"\xd7\xf0\xd4\xbf\xdc^K\xba\x1bh'
                        b'\x9d\xc5\xb7\xac\xdd'
                    ),
                    'name': 'azcvsupdater_2.6.2.jar',
                    'private': 0,
                    'pieces': (
                        b'\xdb\x04B\x05\xc3\'\xdab\xb8su97\xa9u'
                        b'\xca<w\\\x1ef\xd4\x9b\x16\xa9}\xc0\x9f:\xfd'
                        b'\x97qv\x83\xa2"\xef\x9d7\x0by!\rl\xe5v\xb7'
                        b'\x18{\xf7/"P\xe9\x8d\x01D\x9e8\xbd\x16\xe3'
                        b'\xfb-\x9d\xaa\xbcM\x11\xba\x92\xfc\x13F\xf0'
                        b'\x1c\x86x+\xc8\xd0S\xa9\x90`\xa1\xe4\x82\xe8'
                        b'\xfc\x08\xf7\xe3\xe5\xf6\x85\x1c%\xe7%\n\xed'
                        b'\xc0\x1f\xa1;\x9a\xea\xcf\x90\x0c/F>\xdf\xdagA'
                        b'\xc42|\xda\x82\xf5\xa6b\xa1\xb8#\x80wI\xd8f'
                        b'\xf8\xbd\xacW\xab\xc3s\xe0\xbbw\xf2K\xbe\xee'
                        b'\xa8rG\xe1W\xe8\xb7\xc2i\xf3\xd8\xaf\x9d\xdc'
                        b'\xd0#\xf4\xc1\x12u\xcd\x0bE?:\xe8\x9c\x1cu'
                        b'\xabb(oj\r^\xd5\xd5A\x83\x88\x9a\xa1J\x1c?'
                        b'\xa1\xd6\x8c\x83\x9e&'
                    ),
                    'length': 307949,
                    'name.utf-8': b'azcvsupdater_2.6.2.jar',
                    'ed2k': b'>p\xefl\xfa]\x95K\x1b^\xc2\\;;e\xb7',
                }
            ),
        )
        self.assertEqual(expected, self.successResultOf(d))

    def test_prefetch_metadata_timeout(self):
        magnet = 'magnet:?xt=urn:btih:ab570cdd5a17ea1b61e970bb72047de141bce173'
        d = self.tm.prefetch_metadata(magnet, 30)
        self.clock.advance(30)
        expected = ('ab570cdd5a17ea1b61e970bb72047de141bce173', '')
        return d.addCallback(self.assertEqual, expected)

    @pytest.mark.todo
    def test_remove_torrent_false(self):
        """Test when remove_torrent returns False"""
        common.todo_test(self)

    def test_remove_invalid_torrent(self):
        self.assertRaises(
            InvalidTorrentError, self.tm.remove, 'torrentidthatdoesntexist'
        )
Пример #27
0
class TorrentTestCase(BaseTestCase):

    def setup_config(self):
        config_dir = common.set_tmp_config_dir()
        core_config = deluge.config.Config('core.conf', defaults=deluge.core.preferencesmanager.DEFAULT_PREFS,
                                           config_dir=config_dir)
        core_config.save()

    def set_up(self):
        self.setup_config()
        RPCServer(listen=False)
        self.core = Core()
        self.session = lt.session()
        self.torrent = None
        return component.start()

    def tear_down(self):
        return component.shutdown()

    def print_priority_list(self, priorities):
        tmp = ''
        for i, p in enumerate(priorities):
            if i % 100 == 0:
                print(tmp)
                tmp = ''
            tmp += '%s' % p
        print(tmp)

    def assert_state(self, torrent, state):
        torrent.update_state()
        self.assertEqual(torrent.state, state)

    def get_torrent_atp(self, filename):
        filename = common.get_test_data_file(filename)
        with open(filename, 'rb') as _file:
            info = lt.torrent_info(lt.bdecode(_file.read()))
        atp = {'ti': info}
        atp['save_path'] = os.getcwd()
        atp['storage_mode'] = lt.storage_mode_t.storage_mode_sparse
        atp['add_paused'] = False
        atp['auto_managed'] = True
        atp['duplicate_is_error'] = True
        return atp

    def test_set_prioritize_first_last_pieces(self):
        piece_indexes = [0, 1, 50, 51, 52, 110, 111, 112, 113, 200, 201, 202, 212,
                         213, 214, 215, 216, 217, 457, 458, 459, 460, 461, 462]
        self.run_test_set_prioritize_first_last_pieces('dir_with_6_files.torrent', piece_indexes)

    def run_test_set_prioritize_first_last_pieces(self, torrent_file, prioritized_piece_indexes):
        atp = self.get_torrent_atp(torrent_file)
        handle = self.session.add_torrent(atp)

        self.torrent = Torrent(handle, {})
        priorities_original = handle.piece_priorities()
        self.torrent.set_prioritize_first_last_pieces(True)
        priorities = handle.piece_priorities()

        # The length of the list of new priorites is the same as the original
        self.assertEqual(len(priorities_original), len(priorities))

        # Test the priority of all the pieces against the calculated indexes.
        for idx, priority in enumerate(priorities):
            if idx in prioritized_piece_indexes:
                self.assertEqual(priorities[idx], 7)
            else:
                self.assertEqual(priorities[idx], 4)

        # self.print_priority_list(priorities)

    def test_set_prioritize_first_last_pieces_false(self):
        atp = self.get_torrent_atp('dir_with_6_files.torrent')
        handle = self.session.add_torrent(atp)
        self.torrent = Torrent(handle, {})
        # First set some pieces prioritized
        self.torrent.set_prioritize_first_last_pieces(True)
        # Reset pirorities
        self.torrent.set_prioritize_first_last_pieces(False)
        priorities = handle.piece_priorities()

        # Test the priority of the prioritized pieces
        for i in priorities:
            self.assertEqual(priorities[i], 4)

        # self.print_priority_list(priorities)

    @defer.inlineCallbacks
    def test_torrent_error_data_missing(self):
        options = {'seed_mode': True}
        filename = common.get_test_data_file('test_torrent.file.torrent')
        with open(filename) as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
        torrent = self.core.torrentmanager.torrents[torrent_id]

        self.assert_state(torrent, 'Seeding')

        # Force an error by reading (non-existant) piece from disk
        torrent.handle.read_piece(0)
        time.sleep(0.2)  # Delay to wait for alert from lt
        self.assert_state(torrent, 'Error')

    @defer.inlineCallbacks
    def test_torrent_error_resume_original_state(self):
        options = {'seed_mode': True, 'add_paused': True}
        filename = common.get_test_data_file('test_torrent.file.torrent')
        with open(filename) as _file:
            filedump = base64.encodestring(_file.read())
        torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
        torrent = self.core.torrentmanager.torrents[torrent_id]

        orig_state = 'Paused'
        self.assert_state(torrent, orig_state)

        # Force an error by reading (non-existant) piece from disk
        torrent.handle.read_piece(0)
        time.sleep(0.2)  # Delay to wait for alert from lt
        self.assert_state(torrent, 'Error')

        # Clear error and verify returned to original state
        torrent.force_recheck()
        yield deferLater(reactor, 0.1, self.assert_state, torrent, orig_state)
        return

    @defer.inlineCallbacks
    def test_torrent_error_resume_data_unaltered(self):
        resume_data = {'active_time': 13399, 'num_incomplete': 16777215, 'announce_to_lsd': 1, 'seed_mode': 0,
                       'pieces': '\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01', 'paused': 0,
                       'seeding_time': 13399, 'last_scrape': 13399,
                       'info-hash': '-\xc5\xd0\xe7\x1af\xfeid\x9ad\r9\xcb\x00\xa2YpIs', 'max_uploads': 16777215,
                       'max_connections': 16777215, 'num_downloaders': 16777215, 'total_downloaded': 0,
                       'file-format': 'libtorrent resume file', 'peers6': '', 'added_time': 1411826665,
                       'banned_peers6': '', 'file_priority': [1], 'last_seen_complete': 0, 'total_uploaded': 0,
                       'piece_priority': '\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01',
                       'file-version': 1, 'announce_to_dht': 1, 'auto_managed': 1, 'upload_rate_limit': 0,
                       'completed_time': 1411826665, 'allocation': 'sparse', 'blocks per piece': 2,
                       'download_rate_limit': 0, 'libtorrent-version': '0.16.17.0', 'banned_peers': '',
                       'num_seeds': 16777215, 'sequential_download': 0, 'announce_to_trackers': 1,
                       'peers': '\n\x00\x02\x0f=\xc6SC\x17]\xd8}\x7f\x00\x00\x01=\xc6', 'finished_time': 13399,
                       'last_upload': 13399, 'trackers': [[]], 'super_seeding': 0,
                       'file sizes': [[512000, 1411826586]], 'last_download': 13399}
        torrent_state = TorrentState(
            torrent_id='2dc5d0e71a66fe69649a640d39cb00a259704973',
            filename='test_torrent.file.torrent',
            name='',
            save_path='/home/ubuntu/Downloads',
            file_priorities=[1],
            is_finished=True,
        )

        filename = common.get_test_data_file('test_torrent.file.torrent')
        with open(filename) as _file:
            filedump = _file.read()
        resume_data = utf8_encode_structure(resume_data)
        torrent_id = yield self.core.torrentmanager.add(state=torrent_state, filedump=filedump,
                                                        resume_data=lt.bencode(resume_data))
        torrent = self.core.torrentmanager.torrents[torrent_id]

        def assert_resume_data():
            self.assert_state(torrent, 'Error')
            tm_resume_data = lt.bdecode(self.core.torrentmanager.resume_data[torrent.torrent_id])
            self.assertEqual(tm_resume_data, resume_data)

        yield deferLater(reactor, 0.5, assert_resume_data)
        return
Пример #28
0
class CoreTestCase(unittest.TestCase):
    def setUp(self):
        common.set_tmp_config_dir()
        self.rpcserver = RPCServer(listen=False)
        self.core = Core()
        d = component.start()
        return d

    def tearDown(self):
        def on_shutdown(result):
            component._ComponentRegistry.components = {}
            del self.rpcserver
            del self.core

        return component.shutdown().addCallback(on_shutdown)

    def test_add_torrent_file(self):
        options = {}
        filename = "../test.torrent"
        import base64
        torrent_id = self.core.add_torrent_file(
            filename, base64.encodestring(open(filename).read()), options)

        # Get the info hash from the test.torrent
        from deluge.bencode import bdecode, bencode
        info_hash = sha(bencode(bdecode(
            open(filename).read())["info"])).hexdigest()

        self.assertEquals(torrent_id, info_hash)

    def test_add_torrent_url(self):
        url = "http://deluge-torrent.org/ubuntu-9.04-desktop-i386.iso.torrent"
        options = {}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEquals, info_hash)
        return d

    def test_add_torrent_url_with_cookie(self):
        url = "http://deluge-torrent.org/test_torrent.php?test=cookie"
        options = {}
        headers = {"Cookie": "password=deluge"}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallbacks(self.fail,
                       self.assertIsInstance,
                       errbackArgs=(Failure, ))

        d = self.core.add_torrent_url(url, options, headers)
        d.addCallback(self.assertEquals, info_hash)

        return d

    def test_add_torrent_url_with_redirect(self):
        url = "http://deluge-torrent.org/test_torrent.php?test=redirect"
        options = {}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEquals, info_hash)

        return d

    def test_add_torrent_url_with_partial_download(self):
        url = "http://deluge-torrent.org/test_torrent.php?test=partial"
        options = {}
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"

        d = self.core.add_torrent_url(url, options)
        d.addCallback(self.assertEquals, info_hash)

        return d

    def test_add_magnet(self):
        info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"
        import deluge.common
        uri = deluge.common.create_magnet_uri(info_hash)
        options = {}

        torrent_id = self.core.add_torrent_magnet(uri, options)
        self.assertEquals(torrent_id, info_hash)

    def test_remove_torrent(self):
        options = {}
        filename = "../test.torrent"
        import base64
        torrent_id = self.core.add_torrent_file(
            filename, base64.encodestring(open(filename).read()), options)

        self.assertRaises(deluge.error.InvalidTorrentError,
                          self.core.remove_torrent, "torrentidthatdoesntexist",
                          True)

        ret = self.core.remove_torrent(torrent_id, True)

        self.assertTrue(ret)
        self.assertEquals(len(self.core.get_session_state()), 0)

    def test_get_session_status(self):
        status = self.core.get_session_status(["upload_rate", "download_rate"])
        self.assertEquals(type(status), dict)
        self.assertEquals(status["upload_rate"], 0.0)

    def test_get_cache_status(self):
        status = self.core.get_cache_status()
        self.assertEquals(type(status), dict)
        self.assertEquals(status["write_hit_ratio"], 0.0)
        self.assertEquals(status["read_hit_ratio"], 0.0)

    def test_get_free_space(self):
        space = self.core.get_free_space(".")
        self.assertTrue(type(space) in (int, long))
        self.assertTrue(space >= 0)
        self.assertEquals(self.core.get_free_space("/someinvalidpath"), 0)

    def test_test_listen_port(self):
        d = self.core.test_listen_port()

        def result(r):
            self.assertTrue(r in (True, False))

        d.addCallback(result)
        return d

    def test_sanitize_filepath(self):
        pathlist = {
            '\\backslash\\path\\': 'backslash/path',
            ' single_file ': 'single_file',
            '..': '',
            '/../..../': '',
            '  Def ////ad./ / . . /b  d /file': 'Def/ad./. ./b  d/file',
            '/ test /\\.. /.file/': 'test/.file',
            'mytorrent/subfold/file1': 'mytorrent/subfold/file1',
            'Torrent/folder/': 'Torrent/folder',
        }

        for key in pathlist:
            self.assertEquals(
                deluge.core.torrent.sanitize_filepath(key, folder=False),
                pathlist[key])
            self.assertEquals(
                deluge.core.torrent.sanitize_filepath(key, folder=True),
                pathlist[key] + '/')
Пример #29
0
 def set_up(self):
     common.set_tmp_config_dir()
     self.rpcserver = RPCServer(listen=False)
     self.core = Core()
     self.listen_port = 51242
     return component.start().addCallback(self.start_web_server)
Пример #30
0
 def setUp(self):
     common.set_tmp_config_dir()
     self.rpcserver = RPCServer(listen=False)
     self.core = Core()
     return component.start().addCallback(self.startWebserver)
Пример #31
0
 def setUp(self):
     common.set_tmp_config_dir()
     self.rpcserver = RPCServer(listen=False)
     self.core = Core()
     d = component.start()
     return d