'Test the restriction of max_torrents in a source.'

@deferred(timeout=30)
def test_chn_max_torrents(self):

    self.create_fake_allchannel_community()
    self.create_torrents_in_channel(self.dispersy_cid_hex)
    pioneer_file = os.path.join(TESTS_DATA_DIR, 'Pioneer.One.S01E06.720p.x264-VODO.torrent')
    pioneer_tdef = TorrentDef.load(pioneer_file)
    pioneer_ihash = binascii.unhexlify('66ED7F30E3B30FA647ABAA19A36E7503AA071535')
    torrent_list = [[self.channel_id, 1, 1, pioneer_ihash, 1460000001, pioneer_file, pioneer_tdef.get_files_with_length(), pioneer_tdef.get_trackers_as_single_tuple()]]
    self.insert_torrents_into_channel(torrent_list)
    self.boosting_manager.add_source(self.dispersy_cid)
    chn_obj = self.boosting_manager.get_source_object(self.dispersy_cid)
    chn_obj.max_torrents = 2
    chn_obj._load_torrent = (lambda _: defer.Deferred())
    def _load(infohash):
        defer_ret = defer.Deferred()
        defer_ret.callback((self.tdef if binascii.hexlify(infohash).startswith('fc') else pioneer_tdef))
        return defer_ret
    def activate_mgr():
        '\n                                                activate    ltmgr    and    adjust    max    torrents    to    emulate    overflow    torrents\n                                                '
        chn_obj.max_torrents = 1
        chn_obj._load_torrent = _load
    reactor.callLater(5, activate_mgr)
    def check_torrents_channel(src, defer_param=None):
        '\n                                                check    if    a    torrent    already    in    channel    and    ready    to    download\n                                                '
        if (defer_param is None):
            defer_param = defer.Deferred()
        src_obj = self.boosting_manager.get_source_object(src)
        success = True
        if (len(src_obj.unavail_torrent) == 0):
            self.assertLessEqual(len(src_obj.torrents), src_obj.max_torrents)
        else:
            success = False
            reactor.callLater(1, check_torrents_channel, src, defer_param)
        if success:
            src_obj.community.cancel_all_pending_tasks()
            src_obj.kill_tasks()
            defer_param.callback(src)
        return defer_param
    d = self.check_source(self.dispersy_cid)
    d.addCallback(check_torrents_channel)
    return d
