# Buggy code
def network_stop(self, removestate, removecontent):
    """Called by network thread, but safe for any"""
    with self.dllock:
        self._logger.debug(
            "LibtorrentDownloadImpl: network_stop %s", self.tdef.get_name()
        )

        pstate = self.network_get_persistent_state()
        if self.handle is not None:
            self._logger.debug(
                "LibtorrentDownloadImpl: network_stop: engineresumedata from torrent handle"
            )
            self.pstate_for_restart = pstate
            if removestate:
                self.ltmgr.remove_torrent(self, removecontent)
                self.handle = None
            else:
                self.set_vod_mode(False)
                self.handle.pause()
                self.save_resume_data()
        else:
            # This method is also called at Session shutdown, where one may
            # choose to checkpoint its Download. If the Download was
            # stopped before, pstate_for_restart contains its resumedata.
            # and that should be written into the checkpoint.
            #
            if self.pstate_for_restart is not None:
                self._logger.debug(
                    "LibtorrentDownloadImpl: network_stop: Reusing previously saved engineresume data for checkpoint"
                )
                # Don't copy full pstate_for_restart, as the torrent
                # may have gone from e.g. HASHCHECK at startup to STOPPED
                # now, at shutdown. In other words, it was never active
                # in this session and the pstate_for_restart still says
                # HASHCHECK.
                pstate.set(
                    "state",
                    "engineresumedata",
                    self.pstate_for_restart.get("state", "engineresumedata"),
                )
            else:
                self._logger.debug(
                    "LibtorrentDownloadImpl: network_stop: Could not reuse engineresumedata as pstart_for_restart is None"
                )

        # Offload the removal of the dlcheckpoint to another thread
        if removestate:
            self.session.lm.remove_pstate(self.tdef.get_infohash())

        return (self.tdef.get_infohash(), pstate)


# 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 network_stop(self, removestate, removecontent):
    """Called by network thread, but safe for any"""
    with self.dllock:
        self._logger.debug(
            "LibtorrentDownloadImpl: network_stop %s", self.tdef.get_name()
        )
        self.cancel_all_pending_tasks()

        pstate = self.network_get_persistent_state()
        if self.handle is not None:
            self._logger.debug(
                "LibtorrentDownloadImpl: network_stop: engineresumedata from torrent handle"
            )
            self.pstate_for_restart = pstate
            if removestate:
                self.ltmgr.remove_torrent(self, removecontent)
                self.handle = None
            else:
                self.set_vod_mode(False)
                self.handle.pause()
                self.save_resume_data()
        else:
            # This method is also called at Session shutdown, where one may
            # choose to checkpoint its Download. If the Download was
            # stopped before, pstate_for_restart contains its resumedata.
            # and that should be written into the checkpoint.
            #
            if self.pstate_for_restart is not None:
                self._logger.debug(
                    "LibtorrentDownloadImpl: network_stop: Reusing previously saved engineresume data for checkpoint"
                )
                # Don't copy full pstate_for_restart, as the torrent
                # may have gone from e.g. HASHCHECK at startup to STOPPED
                # now, at shutdown. In other words, it was never active
                # in this session and the pstate_for_restart still says
                # HASHCHECK.
                pstate.set(
                    "state",
                    "engineresumedata",
                    self.pstate_for_restart.get("state", "engineresumedata"),
                )
            else:
                self._logger.debug(
                    "LibtorrentDownloadImpl: network_stop: Could not reuse engineresumedata as pstart_for_restart is None"
                )

        # Offload the removal of the dlcheckpoint to another thread
        if removestate:
            self.session.lm.remove_pstate(self.tdef.get_infohash())

        return (self.tdef.get_infohash(), pstate)