# Buggy code
def setup(
    self,
    dcfg=None,
    pstate=None,
    initialdlstatus=None,
    wrapperDelay=0,
    share_mode=False,
    checkpoint_disabled=False,
):
    """
    Create a Download object. Used internally by Session.
    @param dcfg DownloadStartupConfig or None (in which case
    a new DownloadConfig() is created and the result
    becomes the runtime config of this Download.
    :returns a Deferred to which a callback can be added which returns the result of
    network_create_engine_wrapper.
    """
    # Called by any thread, assume sessionlock is held
    self.set_checkpoint_disabled(checkpoint_disabled)

    try:
        # The deferred to be returned
        deferred = Deferred()
        with self.dllock:
            # Copy dlconfig, from default if not specified
            if dcfg is None:
                cdcfg = DownloadStartupConfig()
            else:
                cdcfg = dcfg
            self.dlconfig = cdcfg.dlconfig.copy()
            self.dlconfig.lock = self.dllock
            self.dlconfig.set_callback(self.dlconfig_changed_callback)

            if not isinstance(self.tdef, TorrentDefNoMetainfo):
                self.set_corrected_infoname()
                self.set_filepieceranges()

            self.dlstate = DLSTATUS_CIRCUITS if self.get_hops() > 0 else self.dlstate

            self._logger.debug(
                "setup: initialdlstatus %s %s",
                hexlify(self.tdef.get_infohash()),
                initialdlstatus,
            )

            def schedule_create_engine():
                self.cew_scheduled = True
                create_engine_wrapper_deferred = self.network_create_engine_wrapper(
                    self.pstate_for_restart, initialdlstatus, share_mode=share_mode
                )
                create_engine_wrapper_deferred.chainDeferred(deferred)

            can_create_engine_deferred = self.can_create_engine_wrapper()
            # Add a lambda callback that ignored the parameter of the callback which schedules
            # a task using the taskamanger with wrapperDelay as delay.
            can_create_engine_deferred.addCallback(
                lambda _: self.session.lm.threadpool.add_task(
                    schedule_create_engine, wrapperDelay
                )
            )

        self.pstate_for_restart = pstate
        return deferred

    except Exception as e:
        with self.dllock:
            self.error = e
            print_exc()


# Traceback (isError)
Regression

Tribler.Test.Core.Modules.RestApi.test_downloads_endpoint.TestDownloadsEndpoint.test_remove_download_no_remove_data_param (from nosetests)
Failing for the past 1 build (Since Failed#2109 )
Took 4.4 sec.
Error Message

Test raised 1 unhandled Twisted exceptions:
[{'log_namespace': u'log_legacy', 'log_time': 1467938979.639, 'format': '%(log_legacy)s', 'log_system': '-', 'log_legacy': <twisted.logger._stdlib.StringifiableFromEvent object at 0x06D22830>, 'log_level': <LogLevel=critical>, 'system': '-', 'isError': 1, 'failure': <twisted.python.failure.Failure exceptions.AttributeError: 'NoneType' object has no attribute 'add_task'>, 'time': 1467938979.639, 'log_text': 'Unhandled Error\nTraceback (most recent call last):\n  File "C:\\Python27\\lib\\threading.py", line 763, in run\n    self.__target(*self.__args, **self.__kwargs)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Utilities\\twisted_thread.py", line 55, in _reactor_runner\n    reactor.run(installSignalHandlers=False)\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1194, in run\n    self.mainLoop()\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1203, in mainLoop\n    self.runUntilCurrent()\n--- <exception caught here> ---\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 825, in runUntilCurrent\n    call.func(*call.args, **call.kw)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 27, in <lambda>\n    lambda_f = lambda a = args, kwa = kwargs: invoke_func(*a, **kwa)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 28, in invoke_func\n    download.session.lm.threadpool.add_task(lambda_f, 1)\nexceptions.AttributeError: \'NoneType\' object has no attribute \'add_task\'\n', 'log_format': u'{log_text}', 'message': (), 'why': None}]

# Fixed code
def setup(
    self,
    dcfg=None,
    pstate=None,
    initialdlstatus=None,
    wrapperDelay=0,
    share_mode=False,
    checkpoint_disabled=False,
):
    """
    Create a Download object. Used internally by Session.
    @param dcfg DownloadStartupConfig or None (in which case
    a new DownloadConfig() is created and the result
    becomes the runtime config of this Download.
    :returns a Deferred to which a callback can be added which returns the result of
    network_create_engine_wrapper.
    """
    # Called by any thread, assume sessionlock is held
    self.set_checkpoint_disabled(checkpoint_disabled)

    try:
        # The deferred to be returned
        deferred = Deferred()
        with self.dllock:
            # Copy dlconfig, from default if not specified
            if dcfg is None:
                cdcfg = DownloadStartupConfig()
            else:
                cdcfg = dcfg
            self.dlconfig = cdcfg.dlconfig.copy()
            self.dlconfig.lock = self.dllock
            self.dlconfig.set_callback(self.dlconfig_changed_callback)

            if not isinstance(self.tdef, TorrentDefNoMetainfo):
                self.set_corrected_infoname()
                self.set_filepieceranges()

            self.dlstate = DLSTATUS_CIRCUITS if self.get_hops() > 0 else self.dlstate

            self._logger.debug(
                "setup: initialdlstatus %s %s",
                hexlify(self.tdef.get_infohash()),
                initialdlstatus,
            )

            def schedule_create_engine():
                self.cew_scheduled = True
                create_engine_wrapper_deferred = self.network_create_engine_wrapper(
                    self.pstate_for_restart, initialdlstatus, share_mode=share_mode
                )
                create_engine_wrapper_deferred.chainDeferred(deferred)

            def schedule_create_engine_call(_):
                self.register_task(
                    "schedule_create_engine",
                    reactor.callLater(wrapperDelay, schedule_create_engine),
                )

            # Add a lambda callback that ignored the parameter of the callback which schedules
            # a task using the taskamanger with wrapperDelay as delay.
            self.can_create_engine_wrapper().addCallback(schedule_create_engine_call)

        self.pstate_for_restart = pstate
        return deferred

    except Exception as e:
        with self.dllock:
            self.error = e
            print_exc()