示例#1
0
def createTorr(filename):

    #get the time in a convinient format
    seconds = int(config['end']) - int(config['start'])
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)

    humantime = "%02d:%02d:%02d" % (h, m, s)

    if config['debug']:
        print >>sys.stderr, "duration for the newly created torrent: ", humantime

    dcfg = DownloadStartupConfig()
#  dcfg.set_dest_dir(basename)
    tdef = TorrentDef()
    tdef.add_content( filename, playtime=humantime)
    tdef.set_tracker(SESSION.get_internal_tracker_url())
    print >>sys.stderr, tdef.get_tracker()
    tdef.finalize()

    if config['torrName'] == '':
        torrentbasename = config['videoOut']+'.torrent'
    else:
        torrentbasename = config['torrName']+'.torrent'

    torrentfilename = os.path.join(config['destdir'],torrentbasename)
    tdef.save(torrentfilename)

    if config['seedAfter']:
        if config['debug']:
            print >>sys.stderr, "Seeding the newly created torrent"
        d = SESSION.start_download(tdef,dcfg)
        d.set_state_callback(state_callback,getpeerlist=False)
示例#2
0
def createTorr(filename):

    #get the time in a convinient format
    seconds = int(config['end']) - int(config['start'])
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)

    humantime = "%02d:%02d:%02d" % (h, m, s)

    if config['debug']:
        print >> sys.stderr, "duration for the newly created torrent: ", humantime

    dcfg = DownloadStartupConfig()
    #  dcfg.set_dest_dir(basename)
    tdef = TorrentDef()
    tdef.add_content(filename, playtime=humantime)
    tdef.set_tracker(SESSION.get_internal_tracker_url())
    print >> sys.stderr, tdef.get_tracker()
    tdef.finalize()

    if config['torrName'] == '':
        torrentbasename = config['videoOut'] + '.torrent'
    else:
        torrentbasename = config['torrName'] + '.torrent'

    torrentfilename = os.path.join(config['destdir'], torrentbasename)
    tdef.save(torrentfilename)

    if config['seedAfter']:
        if config['debug']:
            print >> sys.stderr, "Seeding the newly created torrent"
        d = SESSION.start_download(tdef, dcfg)
        d.set_state_callback(state_callback, getpeerlist=False)
class TestSeeding(TestAsServer):
    """
    Testing seeding via new tribler API:
    """
    def setUp(self):
        """ override TestAsServer """
        TestAsServer.setUp(self)
        print >> sys.stderr, "test: Giving Session time to startup"
        time.sleep(5)
        print >> sys.stderr, "test: Session should have started up"

    def setUpPreSession(self):
        """ override TestAsServer """
        TestAsServer.setUpPreSession(self)

        self.config.set_megacache(False)
        self.config.set_internal_tracker(True)
        #self.config.set_tracker_nat_check(0)

        self.mylistenport = 4810

    def setUpPostSession(self):
        pass

    def setup_seeder(self, merkle):
        self.tdef = TorrentDef()
        self.sourcefn = os.path.join(os.getcwd(), "file.wmv")
        self.tdef.add_content(self.sourcefn)
        self.tdef.set_create_merkle_torrent(merkle)
        self.tdef.set_tracker(self.session.get_internal_tracker_url())
        self.tdef.finalize()

        self.torrentfn = os.path.join(self.session.get_state_dir(),
                                      "gen.torrent")
        self.tdef.save(self.torrentfn)

        print >> sys.stderr, "test: setup_seeder: name is", self.tdef.metainfo[
            'info']['name']

        self.dscfg = DownloadStartupConfig()
        self.dscfg.set_dest_dir(os.getcwd())
        d = self.session.start_download(self.tdef, self.dscfg)

        d.set_state_callback(self.seeder_state_callback)

        print >> sys.stderr, "test: Giving Download time to startup"
        time.sleep(5)

    def seeder_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: seeder:", ` d.get_def().get_name(
        ) `, dlstatus_strings[ds.get_status()], ds.get_progress()
        return (1.0, False)

    def test_normal_torrent(self):
        """
            I want to start a Tribler client once and then connect to
            it many times. So there must be only one test method
            to prevent setUp() from creating a new client every time.

            The code is constructed so unittest will show the name of the
            (sub)test where the error occured in the traceback it prints.
        """
        self.setup_seeder(False)
        self.subtest_is_seeding()
        self.subtest_download()

    def test_merkle_torrent(self):
        self.setup_seeder(True)
        self.subtest_is_seeding()
        self.subtest_download()

    def subtest_is_seeding(self):
        infohash = self.tdef.get_infohash()
        print >> sys.stderr, "test: Connect to see if seeding this infohash"
        myid = '*' * 20
        s = BTConnection('localhost',
                         self.hisport,
                         myid=myid,
                         user_infohash=infohash)
        s.read_handshake_medium_rare()

        s.send(CHOKE)
        try:
            s.s.settimeout(10.0)
            print >> sys.stderr, "test: Receive to see if seeding this infohash"
            resp = s.recv()
            self.assert_(len(resp) > 0)
            self.assert_(resp[0] == EXTEND)
        except socket.timeout:
            print >> sys.stderr, "test: Timeout, peer didn't reply"
            self.assert_(False)
        s.close()

    def subtest_download(self):
        """ Now download the file via another Session """

        self.config2 = self.config.copy()  # not really necess
        self.config_path2 = tempfile.mkdtemp()
        self.config2.set_state_dir(self.config_path2)
        self.config2.set_listen_port(self.mylistenport)
        self.session2 = Session(self.config2, ignore_singleton=True)

        # Allow session2 to start
        print >> sys.stderr, "test: Sleeping 3 secs to let Session2 start"
        time.sleep(3)

        tdef2 = TorrentDef.load(self.torrentfn)

        dscfg2 = DownloadStartupConfig()
        dscfg2.set_dest_dir(self.config_path2)

        d = self.session2.start_download(tdef2, dscfg2)
        d.set_state_callback(self.downloader_state_callback)
        time.sleep(20)

    def downloader_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: download:", ` d.get_def().get_name(
        ) `, dlstatus_strings[ds.get_status()], ds.get_progress()

        if ds.get_status() == DLSTATUS_SEEDING:
            # File is in
            destfn = os.path.join(self.config_path2, "file.wmv")
            f = open(destfn, "rb")
            realdata = f.read()
            f.close()
            f = open(self.sourcefn, "rb")
            expdata = f.read()
            f.close()

            self.assert_(realdata == expdata)
            return (1.0, True)

        return (1.0, False)
示例#4
0
class TestSeeding(TestAsServer):
    """
    Testing seeding via new tribler API:
    """

    def setUp(self):
        """ override TestAsServer """
        TestAsServer.setUp(self)
        print >>sys.stderr,"test: Giving Session time to startup"
        time.sleep(5)
        print >>sys.stderr,"test: Session should have started up"

    def setUpPreSession(self):
        """ override TestAsServer """
        TestAsServer.setUpPreSession(self)

        self.config.set_megacache(False)
        self.config.set_internal_tracker(True)
        #self.config.set_tracker_nat_check(0)

        self.mylistenport = 4810

    def setUpPostSession(self):
        pass

    def setup_seeder(self,merkle):
        self.tdef = TorrentDef()
        self.sourcefn = os.path.join(os.getcwd(),"file.wmv")
        self.tdef.add_content(self.sourcefn)
        self.tdef.set_create_merkle_torrent(merkle)
        self.tdef.set_tracker(self.session.get_internal_tracker_url())
        self.tdef.finalize()

        self.torrentfn = os.path.join(self.session.get_state_dir(),"gen.torrent")
        self.tdef.save(self.torrentfn)

        print >>sys.stderr,"test: setup_seeder: name is",self.tdef.metainfo['info']['name']

        self.dscfg = DownloadStartupConfig()
        self.dscfg.set_dest_dir(os.getcwd())
        d = self.session.start_download(self.tdef,self.dscfg)

        d.set_state_callback(self.seeder_state_callback)

        print >>sys.stderr,"test: Giving Download time to startup"
        time.sleep(5)


    def seeder_state_callback(self,ds):
        d = ds.get_download()
        print >>sys.stderr,"test: seeder:",`d.get_def().get_name()`,dlstatus_strings[ds.get_status()],ds.get_progress()
        return (1.0,False)


    def test_normal_torrent(self):
        """
            I want to start a Tribler client once and then connect to
            it many times. So there must be only one test method
            to prevent setUp() from creating a new client every time.

            The code is constructed so unittest will show the name of the
            (sub)test where the error occured in the traceback it prints.
        """
        self.setup_seeder(False)
        self.subtest_is_seeding()
        self.subtest_download()

    def test_merkle_torrent(self):
        self.setup_seeder(True)
        self.subtest_is_seeding()
        self.subtest_download()

    def subtest_is_seeding(self):
        infohash = self.tdef.get_infohash()
        print >> sys.stderr,"test: Connect to see if seeding this infohash"
        myid = '*' * 20
        s = BTConnection('localhost',self.hisport,myid=myid,user_infohash=infohash)
        s.read_handshake_medium_rare()

        s.send(CHOKE)
        try:
            s.s.settimeout(10.0)
            print >> sys.stderr,"test: Receive to see if seeding this infohash"
            resp = s.recv()
            self.assert_(len(resp) > 0)
            self.assert_(resp[0] == EXTEND)
        except socket.timeout:
            print >> sys.stderr,"test: Timeout, peer didn't reply"
            self.assert_(False)
        s.close()


    def subtest_download(self):
        """ Now download the file via another Session """

        self.config2 = self.config.copy() # not really necess
        self.config_path2 = tempfile.mkdtemp()
        self.config2.set_state_dir(self.config_path2)
        self.config2.set_listen_port(self.mylistenport)
        self.session2 = Session(self.config2,ignore_singleton=True)

        # Allow session2 to start
        print >>sys.stderr,"test: Sleeping 3 secs to let Session2 start"
        time.sleep(3)

        tdef2 = TorrentDef.load(self.torrentfn)

        dscfg2 = DownloadStartupConfig()
        dscfg2.set_dest_dir(self.config_path2)

        d = self.session2.start_download(tdef2,dscfg2)
        d.set_state_callback(self.downloader_state_callback)
        time.sleep(20)

    def downloader_state_callback(self,ds):
        d = ds.get_download()
        print >>sys.stderr,"test: download:",`d.get_def().get_name()`,dlstatus_strings[ds.get_status()],ds.get_progress()

        if ds.get_status() == DLSTATUS_SEEDING:
            # File is in
            destfn = os.path.join(self.config_path2,"file.wmv")
            f = open(destfn,"rb")
            realdata = f.read()
            f.close()
            f = open(self.sourcefn,"rb")
            expdata = f.read()
            f.close()

            self.assert_(realdata == expdata)
            return (1.0,True)

        return (1.0,False)
示例#5
0
class TestSeeding(TestAsServer):
    """
    Testing seeding via new tribler API:
    """
    def setUp(self):
        """ override TestAsServer """
        TestAsServer.setUp(self)
        print >> sys.stderr, "test: Giving Session time to startup"
        time.sleep(5)
        print >> sys.stderr, "test: Session should have started up"

    def setUpPreSession(self):
        """ override TestAsServer """
        TestAsServer.setUpPreSession(self)

        self.config.set_overlay(False)
        self.config.set_internal_tracker(True)

        self.mylistenport = 4810

    def setUpPostSession(self):
        pass

    @skip("We need to migrate this to swift")
    def test_live_torrent(self):
        """
            I want to start a Tribler client once and then connect to
            it many times. So there must be only one test method
            to prevent setUp() from creating a new client every time.

            The code is constructed so unittest will show the name of the
            (sub)test where the error occured in the traceback it prints.
        """
        self.setup_seeder()
        time.sleep(10)
        # self.subtest_connect2downloader()
        self.subtest_download()

    def setup_seeder(self):
        self.tdef = TorrentDef()
        # semi automatic
        self.bitrate = 6144
        piecesize = 32768
        self.npieces = 12
        playtime = ((self.npieces - 1) * piecesize) / self.bitrate
        playtimestr = '0:' + str(playtime)  # DON'T WORK IF > 60 secs
        self.tdef.create_live("Test Live", self.bitrate, playtimestr)
        self.tdef.set_tracker(self.session.get_internal_tracker_url())
        self.tdef.set_piece_length(piecesize)
        self.tdef.finalize()

        print >> sys.stderr, "test: setup_seeder: name is", self.tdef.metainfo[
            'info']['name']

        self.dscfg = DownloadStartupConfig()
        self.dscfg.set_dest_dir(self.getDestDir())

        # File source
        source = InfiniteSource(piecesize)
        self.dscfg.set_video_ratelimit(self.bitrate)
        self.dscfg.set_video_source(source)

        d = self.session.start_download(self.tdef, self.dscfg)

        d.set_state_callback(self.seeder_state_callback)

    def seeder_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: seeder:", dlstatus_strings[
            ds.get_status()], ds.get_progress()
        return (1.0, False)

    def subtest_download(self):
        """ Now download the file via another Session """

        self.config2 = self.config.copy()  # not really necess
        self.config2.set_state_dir(self.getStateDir(2))
        self.config2.set_listen_port(self.mylistenport)
        self.session2 = Session(self.config2, ignore_singleton=True)

        # Allow session2 to start
        print >> sys.stderr, "test: downloader: Sleeping 3 secs to let Session2 start"
        time.sleep(3)

        tdef2 = TorrentDef.load(self.torrentfn)

        dscfg2 = DownloadStartupConfig()
        dscfg2.set_dest_dir(self.getDestDir(2))
        dscfg2.set_video_event_callback(self.downloader_vod_ready_callback)

        d = self.session2.start_download(tdef2, dscfg2)
        d.set_state_callback(self.downloader_state_callback)

        time.sleep(40)
        # To test if BITFIELD is indeed wrapping around.
        self.subtest_connect2downloader()
        time.sleep(80)

    def downloader_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: download:", dlstatus_strings[
            ds.get_status()], ds.get_progress()

        return (1.0, False)

    def downloader_vod_ready_callback(self, d, event, params):
        """ Called by SessionThread """
        if event == VODEVENT_START:
            stream = params["stream"]
            while True:
                # Fake video playback
                data = stream.read(self.bitrate)
                if len(data) == 0:
                    break
                time.sleep(1)

    def subtest_connect2downloader(self):

        print >> sys.stderr, "test: verifier: Connecting to seeder to check bitfield"

        infohash = self.tdef.get_infohash()
        s = BTConnection('localhost',
                         self.mylistenport,
                         user_infohash=infohash)
        s.read_handshake_medium_rare()

        try:
            s.s.settimeout(10.0)
            resp = s.recv()
            self.assert_(len(resp) > 0)
            print >> sys.stderr, "test: verifier: Got message", getMessageName(
                resp[0])
            self.assert_(resp[0] == EXTEND)
            resp = s.recv()
            self.assert_(len(resp) > 0)
            print >> sys.stderr, "test: verifier: Got 2nd message", getMessageName(
                resp[0])
            self.assert_(resp[0] == BITFIELD)
            b = Bitfield(self.npieces, resp[1:])
            print >> sys.stderr, "test: verifier: Bitfield is", repr(
                b.toboollist())

            b2 = Bitfield(self.npieces)
            b2[0] = True
            msg = BITFIELD + b2.tostring()
            s.send(msg)

            time.sleep(5)

        except socket.timeout:
            print >> sys.stderr, "test: verifier: Timeout, peer didn't reply"
            self.assert_(False)
        s.close()
示例#6
0
class TestSeeding(TestAsServer):

    """
    Testing seeding via new tribler API:
    """

    def setUp(self):
        """ override TestAsServer """
        TestAsServer.setUp(self)
        print >> sys.stderr, "test: Giving Session time to startup"
        time.sleep(5)
        print >> sys.stderr, "test: Session should have started up"

    def setUpPreSession(self):
        """ override TestAsServer """
        TestAsServer.setUpPreSession(self)

        self.config.set_overlay(False)
        self.config.set_internal_tracker(True)

        self.mylistenport = 4810

    def setUpPostSession(self):
        pass

    @skip("We need to migrate this to swift")
    def test_live_torrent(self):
        """
            I want to start a Tribler client once and then connect to
            it many times. So there must be only one test method
            to prevent setUp() from creating a new client every time.

            The code is constructed so unittest will show the name of the
            (sub)test where the error occured in the traceback it prints.
        """
        self.setup_seeder()
        time.sleep(10)
        # self.subtest_connect2downloader()
        self.subtest_download()

    def setup_seeder(self):
        self.tdef = TorrentDef()
        # semi automatic
        self.bitrate = 6144
        piecesize = 32768
        self.npieces = 12
        playtime = ((self.npieces - 1) * piecesize) / self.bitrate
        playtimestr = '0:' + str(playtime)  # DON'T WORK IF > 60 secs
        self.tdef.create_live("Test Live", self.bitrate, playtimestr)
        self.tdef.set_tracker(self.session.get_internal_tracker_url())
        self.tdef.set_piece_length(piecesize)
        self.tdef.finalize()

        print >> sys.stderr, "test: setup_seeder: name is", self.tdef.metainfo['info']['name']

        self.dscfg = DownloadStartupConfig()
        self.dscfg.set_dest_dir(self.getDestDir())

        # File source
        source = InfiniteSource(piecesize)
        self.dscfg.set_video_ratelimit(self.bitrate)
        self.dscfg.set_video_source(source)

        d = self.session.start_download(self.tdef, self.dscfg)

        d.set_state_callback(self.seeder_state_callback)

    def seeder_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: seeder:", dlstatus_strings[ds.get_status()], ds.get_progress()
        return (1.0, False)

    def subtest_download(self):
        """ Now download the file via another Session """

        self.config2 = self.config.copy()  # not really necess
        self.config2.set_state_dir(self.getStateDir(2))
        self.config2.set_listen_port(self.mylistenport)
        self.session2 = Session(self.config2, ignore_singleton=True)

        # Allow session2 to start
        print >> sys.stderr, "test: downloader: Sleeping 3 secs to let Session2 start"
        time.sleep(3)

        tdef2 = TorrentDef.load(self.torrentfn)

        dscfg2 = DownloadStartupConfig()
        dscfg2.set_dest_dir(self.getDestDir(2))
        dscfg2.set_video_event_callback(self.downloader_vod_ready_callback)

        d = self.session2.start_download(tdef2, dscfg2)
        d.set_state_callback(self.downloader_state_callback)

        time.sleep(40)
        # To test if BITFIELD is indeed wrapping around.
        self.subtest_connect2downloader()
        time.sleep(80)

    def downloader_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: download:", dlstatus_strings[ds.get_status()], ds.get_progress()

        return (1.0, False)

    def downloader_vod_ready_callback(self, d, event, params):
        """ Called by SessionThread """
        if event == VODEVENT_START:
            stream = params["stream"]
            while True:
                # Fake video playback
                data = stream.read(self.bitrate)
                if len(data) == 0:
                    break
                time.sleep(1)

    def subtest_connect2downloader(self):

        print >> sys.stderr, "test: verifier: Connecting to seeder to check bitfield"

        infohash = self.tdef.get_infohash()
        s = BTConnection('localhost', self.mylistenport, user_infohash=infohash)
        s.read_handshake_medium_rare()

        try:
            s.s.settimeout(10.0)
            resp = s.recv()
            self.assert_(len(resp) > 0)
            print >> sys.stderr, "test: verifier: Got message", getMessageName(resp[0])
            self.assert_(resp[0] == EXTEND)
            resp = s.recv()
            self.assert_(len(resp) > 0)
            print >> sys.stderr, "test: verifier: Got 2nd message", getMessageName(resp[0])
            self.assert_(resp[0] == BITFIELD)
            b = Bitfield(self.npieces, resp[1:])
            print >> sys.stderr, "test: verifier: Bitfield is", repr(b.toboollist())

            b2 = Bitfield(self.npieces)
            b2[0] = True
            msg = BITFIELD + b2.tostring()
            s.send(msg)

            time.sleep(5)

        except socket.timeout:
            print >> sys.stderr, "test: verifier: Timeout, peer didn't reply"
            self.assert_(False)
        s.close()
示例#7
0
class TestSeeding(TestAsServer):

    """
    Testing seeding via new tribler API:
    """
    def setUp(self):
        """ override TestAsServer """
        TestAsServer.setUp(self)

        self.session2 = None
        self.seeding_event = threading.Event()
        self.downloading_event = threading.Event()

    def setUpPreSession(self):
        """ override TestAsServer """
        TestAsServer.setUpPreSession(self)
        self.config.set_libtorrent(True)

        self.config2 = self.config.copy()  # not really necess
        self.config2.set_state_dir(self.getStateDir(2))
        self.config2.set_listen_port(4810)

        self.dscfg2 = DownloadStartupConfig()
        self.dscfg2.set_dest_dir(self.getDestDir(2))

    def setUpPostSession(self):
        pass

    def tearDown(self):
        if self.session2:
            self._shutdown_session(self.session2)
            time.sleep(10)

        TestAsServer.tearDown(self)

    def setup_seeder(self, merkle, filename='file.wmv'):
        self.tdef = TorrentDef()
        self.sourcefn = os.path.join(BASE_DIR, "API", filename)
        self.tdef.add_content(self.sourcefn)
        self.tdef.set_tracker("http://fake.net/announce")
        self.tdef.set_create_merkle_torrent(merkle)
        self.tdef.finalize()

        self.torrentfn = os.path.join(self.session.get_state_dir(), "gen.torrent")
        self.tdef.save(self.torrentfn)

        print >> sys.stderr, "test: setup_seeder: name is", self.tdef.metainfo['info']['name']

        self.dscfg = DownloadStartupConfig()
        self.dscfg.set_dest_dir(os.path.join(BASE_DIR, "API"))  # basedir of the file we are seeding
        d = self.session.start_download(self.tdef, self.dscfg)
        d.set_state_callback(self.seeder_state_callback)

        print >> sys.stderr, "test: setup_seeder: starting to wait for download to reach seeding state"
        assert self.seeding_event.wait(60)

    def seeder_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: seeder:", repr(d.get_def().get_name()), dlstatus_strings[ds.get_status()], ds.get_progress()

        if ds.get_status() == DLSTATUS_SEEDING:
            self.seeding_event.set()

        return (1.0, False)

    def test_normal_torrent(self):
        self.setup_seeder(False)
        self.subtest_is_seeding()
        self.subtest_download()

#     def test_merkle_torrent(self):
#         self.setup_seeder(True)
#         self.subtest_is_seeding()
#         self.subtest_download()

    def subtest_is_seeding(self):
        infohash = self.tdef.get_infohash()
        s = BTConnection('localhost', self.hisport, user_infohash=infohash)
        s.read_handshake_medium_rare()

        s.send(CHOKE)
        try:
            s.s.settimeout(10.0)
            resp = s.recv()
            self.assert_(len(resp) > 0)
            self.assert_(resp[0] == EXTEND)
        except socket.timeout:
            print >> sys.stderr, "test: Timeout, peer didn't reply"
            self.assert_(False)
        s.close()

    def subtest_download(self):
        """ Now download the file via another Session """
        self.session2 = Session(self.config2, ignore_singleton=True)
        self.session2.start()

        time.sleep(5)

        tdef2 = TorrentDef.load(self.torrentfn)

        d = self.session2.start_download(tdef2, self.dscfg2)
        d.set_state_callback(self.downloader_state_callback)

        time.sleep(5)

        d.add_peer(("127.0.0.1", self.hisport))
        assert self.downloading_event.wait(60)

    def downloader_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: download:", repr(d.get_def().get_name()), dlstatus_strings[ds.get_status()], ds.get_progress()

        if ds.get_status() == DLSTATUS_SEEDING:
            # File is in
            destfn = os.path.join(self.getDestDir(2), "file.wmv")
            f = open(destfn, "rb")
            realdata = f.read()
            f.close()
            f = open(self.sourcefn, "rb")
            expdata = f.read()
            f.close()

            self.assert_(realdata == expdata)
            self.downloading_event.set()
            return (1.0, True)
        return (1.0, False)
示例#8
0
class TestSeeding(TestAsServer):
    """
    Testing seeding via new tribler API:
    """
    def setUp(self):
        """ override TestAsServer """
        TestAsServer.setUp(self)

        self.session2 = None
        self.seeding_event = threading.Event()
        self.downloading_event = threading.Event()

    def setUpPreSession(self):
        """ override TestAsServer """
        TestAsServer.setUpPreSession(self)
        self.config.set_libtorrent(True)

        self.config2 = self.config.copy()  # not really necess
        self.config2.set_state_dir(self.getStateDir(2))
        self.config2.set_listen_port(4810)

        self.dscfg2 = DownloadStartupConfig()
        self.dscfg2.set_dest_dir(self.getDestDir(2))

    def setUpPostSession(self):
        pass

    def tearDown(self):
        if self.session2:
            self._shutdown_session(self.session2)
            time.sleep(10)

        TestAsServer.tearDown(self)

    def setup_seeder(self, merkle, filename='file.wmv'):
        self.tdef = TorrentDef()
        self.sourcefn = os.path.join(BASE_DIR, "API", filename)
        self.tdef.add_content(self.sourcefn)
        self.tdef.set_tracker("http://fake.net/announce")
        self.tdef.set_create_merkle_torrent(merkle)
        self.tdef.finalize()

        self.torrentfn = os.path.join(self.session.get_state_dir(),
                                      "gen.torrent")
        self.tdef.save(self.torrentfn)

        print >> sys.stderr, "test: setup_seeder: name is", self.tdef.metainfo[
            'info']['name']

        self.dscfg = DownloadStartupConfig()
        self.dscfg.set_dest_dir(os.path.join(
            BASE_DIR, "API"))  # basedir of the file we are seeding
        d = self.session.start_download(self.tdef, self.dscfg)
        d.set_state_callback(self.seeder_state_callback)

        print >> sys.stderr, "test: setup_seeder: starting to wait for download to reach seeding state"
        assert self.seeding_event.wait(60)

    def seeder_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: seeder:", repr(
            d.get_def().get_name()), dlstatus_strings[
                ds.get_status()], ds.get_progress()

        if ds.get_status() == DLSTATUS_SEEDING:
            self.seeding_event.set()

        return (1.0, False)

    def test_normal_torrent(self):
        self.setup_seeder(False)
        self.subtest_is_seeding()
        self.subtest_download()

#     def test_merkle_torrent(self):
#         self.setup_seeder(True)
#         self.subtest_is_seeding()
#         self.subtest_download()

    def subtest_is_seeding(self):
        infohash = self.tdef.get_infohash()
        s = BTConnection('localhost', self.hisport, user_infohash=infohash)
        s.read_handshake_medium_rare()

        s.send(CHOKE)
        try:
            s.s.settimeout(10.0)
            resp = s.recv()
            self.assert_(len(resp) > 0)
            self.assert_(resp[0] == EXTEND)
        except socket.timeout:
            print >> sys.stderr, "test: Timeout, peer didn't reply"
            self.assert_(False)
        s.close()

    def subtest_download(self):
        """ Now download the file via another Session """
        self.session2 = Session(self.config2, ignore_singleton=True)
        self.session2.start()

        time.sleep(5)

        tdef2 = TorrentDef.load(self.torrentfn)

        d = self.session2.start_download(tdef2, self.dscfg2)
        d.set_state_callback(self.downloader_state_callback)

        time.sleep(5)

        d.add_peer(("127.0.0.1", self.hisport))
        assert self.downloading_event.wait(60)

    def downloader_state_callback(self, ds):
        d = ds.get_download()
        print >> sys.stderr, "test: download:", repr(
            d.get_def().get_name()), dlstatus_strings[
                ds.get_status()], ds.get_progress()

        if ds.get_status() == DLSTATUS_SEEDING:
            # File is in
            destfn = os.path.join(self.getDestDir(2), "file.wmv")
            f = open(destfn, "rb")
            realdata = f.read()
            f.close()
            f = open(self.sourcefn, "rb")
            expdata = f.read()
            f.close()

            self.assert_(realdata == expdata)
            self.downloading_event.set()
            return (1.0, True)
        return (1.0, False)