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: downloader: Sleeping 3 secs to let Session2 start" time.sleep(3) tdef2 = TorrentDef.load(self.torrentfn) dscfg2 = DownloadStartupConfig() dscfg2.set_dest_dir(self.config_path2) 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)
class TestAsServer(unittest.TestCase): """ Parent class for testing the server-side of Tribler """ def setUp(self): """ unittest test setup code """ self.setUpPreSession() self.session = Session(self.config) self.hisport = self.session.get_listen_port() self.setUpPostSession() def setUpPreSession(self): """ Should set self.config_path and self.config """ self.config_path = tempfile.mkdtemp() self.config = SessionStartupConfig() self.config.set_state_dir(self.config_path) self.config.set_listen_port(random.randint(10000, 60000)) self.config.set_buddycast(False) self.config.set_start_recommender(False) self.config.set_torrent_checking(False) self.config.set_superpeer(False) self.config.set_dialback(False) self.config.set_social_networking(False) self.config.set_remote_query(False) self.config.set_internal_tracker(False) self.config.set_bartercast(False) self.config.set_multicast_local_peer_discovery(False) # Assume all test scripts are run from Tribler/Test self.config.set_install_dir(os.path.abspath(os.path.join('..','..'))) self.my_keypair = EC.gen_params(EC.NID_sect233k1) self.my_keypair.gen_key() def setUpPostSession(self): """ Should set self.his_keypair """ keypair_filename = os.path.join(self.config_path,'ec.pem') self.his_keypair = EC.load_key(keypair_filename) def tearDown(self): """ unittest test tear down code """ if self.session is not None: self.session.shutdown() print >>sys.stderr,"test_as_server: sleeping after session shutdown" time.sleep(2) try: shutil.rmtree(self.config_path) except: # Not fatal if something goes wrong here, and Win32 often gives # spurious Permission Denied errors. print_exc()
class TestAsServer(unittest.TestCase): """ Parent class for testing the server-side of Tribler """ def setUp(self): """ unittest test setup code """ self.setUpPreSession() self.session = Session(self.config) self.hisport = self.session.get_listen_port() self.setUpPostSession() def setUpPreSession(self): """ Should set self.config_path and self.config """ self.config_path = tempfile.mkdtemp() self.config = SessionStartupConfig() self.config.set_state_dir(self.config_path) self.config.set_listen_port(random.randint(10000, 60000)) self.config.set_buddycast(False) self.config.set_start_recommender(False) self.config.set_torrent_checking(False) self.config.set_superpeer(False) self.config.set_dialback(False) self.config.set_social_networking(False) self.config.set_remote_query(False) self.config.set_internal_tracker(False) self.config.set_bartercast(False) self.config.set_multicast_local_peer_discovery(False) # Assume all test scripts are run from Tribler/Test self.config.set_install_dir(os.path.abspath(os.path.join('..','..'))) self.my_keypair = EC.gen_params(EC.NID_sect233k1) self.my_keypair.gen_key() def setUpPostSession(self): """ Should set self.his_keypair """ keypair_filename = os.path.join(self.config_path,'ec.pem') self.his_keypair = EC.load_key(keypair_filename) def tearDown(self): """ unittest test tear down code """ if self.session is not None: self.session.shutdown() print >>sys.stderr,time.asctime(),'-', "test_as_server: sleeping after session shutdown" time.sleep(2) try: shutil.rmtree(self.config_path) except: # Not fatal if something goes wrong here, and Win32 often gives # spurious Permission Denied errors. print_exc()
def setUp(self): """ override TestAsServer """ # From TestAsServer.setUp(self): ignore singleton on self.setUpPreSession() self.session = Session(self.config, ignore_singleton=True) self.hisport = self.session.get_listen_port() self.setUpPostSession() # New code self.channelcastdb = ChannelCastDBHandler.getInstance() self.channelcastdb.registerSession(self.session) self.votecastdb = VoteCastDBHandler.getInstance() self.votecastdb.registerSession(self.session)
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: downloader: Sleeping 3 secs to let Session2 start" time.sleep(3) tdef2 = TorrentDef.load(self.torrentfn) dscfg2 = DownloadStartupConfig() dscfg2.set_dest_dir(self.config_path2) 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 __init__(self): self.peer_db = PeerDBHandler.getInstance() self.superpeer_db = SuperPeerDBHandler.getInstance() self.torrent_db = TorrentDBHandler.getInstance() self.mypref_db = MyPreferenceDBHandler.getInstance() self.pref_db = PreferenceDBHandler.getInstance() self.friend_db = FriendDBHandler.getInstance() self.listen_port = 6881 self.session = Session()
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(1400)
def setUp(self): """ override TestAsServer """ # From TestAsServer.setUp(self): ignore singleton on self.setUpPreSession() self.session = Session(self.config,ignore_singleton=True) self.hisport = self.session.get_listen_port() self.setUpPostSession() # New code self.channelcastdb = ChannelCastDBHandler.getInstance() self.channelcastdb.registerSession(self.session) self.votecastdb = VoteCastDBHandler.getInstance() self.votecastdb.registerSession(self.session)
def setUp(self): """ unittest test setup code """ self.setUpPreSession() self.session = Session(self.config) self.hisport = self.session.get_listen_port() self.setUpPostSession()
class TestChannelCast(TestAsServer): """ Testing ChannelCast message """ def setUp(self): """ override TestAsServer """ # From TestAsServer.setUp(self): ignore singleton on self.setUpPreSession() self.session = Session(self.config, ignore_singleton=True) self.hisport = self.session.get_listen_port() self.setUpPostSession() # New code self.channelcastdb = ChannelCastDBHandler.getInstance() self.channelcastdb.registerSession(self.session) self.votecastdb = VoteCastDBHandler.getInstance() self.votecastdb.registerSession(self.session) def setUpPreSession(self): """ override TestAsServer """ TestAsServer.setUpPreSession(self) # BuddyCast self.config.set_buddycast(True) self.config.set_start_recommender(True) fd, self.superpeerfilename = tempfile.mkstemp() os.write(fd, '') os.close(fd) self.config.set_superpeer_file(self.superpeerfilename) def setUpPostSession(self): """ override TestAsServer """ TestAsServer.setUpPostSession(self) self.mypermid = str(self.my_keypair.pub().get_der()) self.hispermid = str(self.his_keypair.pub().get_der()) self.myhash = sha(self.mypermid).digest() def tearDown(self): """ override TestAsServer """ TestAsServer.tearDown(self) try: os.remove(self.superpeerfilename) except: print_exc() def test_channel_subscription(self): self.votecastdb.unsubscribe(bin2str(self.mypermid)) self.assertEqual( self.votecastdb.getVote(bin2str(self.mypermid), bin2str(self.hispermid)), None) print >> sys.stderr, self.votecastdb.getAll() self.votecastdb.spam(bin2str(self.mypermid)) self.assertEqual( self.votecastdb.getVote(bin2str(self.mypermid), bin2str(self.hispermid)), -1) print >> sys.stderr, self.votecastdb.getAll() self.votecastdb.subscribe(bin2str(self.mypermid)) self.assertEqual( self.votecastdb.getVote(bin2str(self.mypermid), bin2str(self.hispermid)), 2) print >> sys.stderr, self.votecastdb.getAll() self.votecastdb.unsubscribe(bin2str(self.mypermid)) self.assertEqual( self.votecastdb.getVote(bin2str(self.mypermid), bin2str(self.hispermid)), 0) print >> sys.stderr, self.votecastdb.getAll() self.votecastdb.spam(bin2str(self.mypermid)) self.assertEqual( self.votecastdb.getVote(bin2str(self.mypermid), bin2str(self.hispermid)), -1) print >> sys.stderr, self.votecastdb.getAll() def check_chquery_reply(self, data): d = bdecode(data) self.assert_(type(d) == DictType) self.assert_(d.has_key('a')) self.assert_(d.has_key('id')) id = d['id'] self.assert_(type(id) == StringType) def test_channelcast(self): torrent_data = { 'announce': "http://localhost", 'info': { 'name': 'Hello 123', 'files': [{ 'length': 100, 'path': ['license.txt'] }] } } infohash = bin2str(sha(bencode(torrent_data['info'])).digest()) self.channelcastdb.addOwnTorrent(infohash, torrent_data) s = OLConnection(self.my_keypair, 'localhost', self.hisport) chcast = ChannelCastCore(None, s, self.session, None, log='', dnsindb=None) # Good message chdata = chcast.createChannelCastMessage() if chdata is None or len(chdata) == 0: print "test: no subscriptions for us.. hence do not send" else: msg = CHANNELCAST + bencode(chdata) print "test: channelcast msg created", repr(chdata) s.send(msg) time.sleep(3) # Bad message if chdata is None or len(chdata) == 0: pass else: pub_id, pub_name, infohash, torrenthash, name, timestamp, signature = chdata[ 0] chdata = [(pub_id, pub_name, infohash, torrenthash, name, 12343, signature)] msg = CHANNELCAST + bencode(chdata) print "test: channelcast msg created", repr(chdata) s.send(msg) time.sleep(20) # the other side should have closed the connection, as it is invalid message s.close() def test_channel_query(self): s = OLConnection(self.my_keypair, 'localhost', self.hisport) msg = CHANNEL_QUERY + bencode({'q': 'k:dutiet', 'id': 'a' * 20}) s.send(msg) resp = s.recv() if len(resp) > 0: print >> sys.stderr, "test: good CH_QUERY: got", getMessageName( resp[0]) self.assert_(resp[0] == CHANNEL_QUERY_REPLY) self.check_chquery_reply(resp[1:]) time.sleep(10) # the other side should not have closed the connection, as # this is all valid, so this should not throw an exception: #s.send('bla') s.close() def test_channel_update(self): s = OLConnection(self.my_keypair, 'localhost', self.hisport) msg = CHANNEL_QUERY + bencode({ 'q': 'p:345fsdf34fe345ed344g5', 'id': 'a' * 20 }) s.send(msg) resp = s.recv() if len(resp) > 0: print >> sys.stderr, "test: good CH_QUERY: got", getMessageName( resp[0]) self.assert_(resp[0] == CHANNEL_QUERY_REPLY) self.check_chquery_reply(resp[1:]) time.sleep(10) # the other side should not have closed the connection, as # this is all valid, so this should not throw an exception: s.send('bla') s.close() def test_votecast(self): self.votecastdb.subscribe('nitin') s = OLConnection(self.my_keypair, 'localhost', self.hisport) votecast = VoteCastCore(None, s, self.session, None, log='', dnsindb=None) data = votecast.createVoteCastMessage() if data is None and len(data) == 0: print >> sys.stderr, "test: no votes" else: msg = VOTECAST + bencode(data) s.send(msg) s.close()
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 def setup_seeder(self,merkle): self.tdef = TorrentDef() self.sourcefn = os.path.join(os.getcwd(),"big.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'] # set upload limitation rateManager = UserDefinedMaxAlwaysOtherwiseEquallyDividedRateManager() uploadLimitation = TotalUploadLimitation(self.session,rateManager) self.dscfg = DownloadStartupConfig() self.dscfg.set_dest_dir(os.getcwd()) self.dscfg.set_max_rate_period(4.0) 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:",`d.get_def().get_name()`,dlstatus_strings[ds.get_status()],ds.get_progress(), "up",ds.get_current_speed(UPLOAD),"down",ds.get_current_speed(DOWNLOAD) 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() 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.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(1400) 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(), "up",ds.get_current_speed(UPLOAD),"down",ds.get_current_speed(DOWNLOAD) if ds.get_status() == DLSTATUS_SEEDING: # File is in destfn = os.path.join(self.config_path2,"big.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 (2.0,True) return (2.0,False)
class TestSeeding(TestAsServer): """ Testing seeding via new tribler API: """ def setUp(self): """ override TestAsServer """ TestAsServer.setUp(self) print >>sys.stderr,time.asctime(),'-', "test: Giving Session time to startup" time.sleep(5) print >>sys.stderr,time.asctime(),'-', "test: Session should have started up" self.vod_started = False 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 def tearDown(self): TestAsServer.tearDown(self) self.assert_(self.vod_started) def setup_seeder(self,merkle): self.tdef = TorrentDef() self.sourcefn = os.path.join(os.getcwd(),"file2.wmv") self.tdef.add_content(self.sourcefn,playtime='1:00') # 60 secs 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,time.asctime(),'-', "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) def seeder_state_callback(self,ds): d = ds.get_download() print >>sys.stderr,time.asctime(),'-', "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() 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,time.asctime(),'-', "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,time.asctime(),'-', "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) 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(20) def downloader_state_callback(self,ds): d = ds.get_download() print >>sys.stderr,time.asctime(),'-', "test: download:",`d.get_def().get_name()`,dlstatus_strings[ds.get_status()],ds.get_progress() return (1.0,False) def downloader_vod_ready_callback(self,d,event,params): if event == VODEVENT_START: self.vod_started = True
class TestChannelCast(TestAsServer): """ Testing ChannelCast message """ def setUp(self): """ override TestAsServer """ # From TestAsServer.setUp(self): ignore singleton on self.setUpPreSession() self.session = Session(self.config,ignore_singleton=True) self.hisport = self.session.get_listen_port() self.setUpPostSession() # New code self.channelcastdb = ChannelCastDBHandler.getInstance() self.channelcastdb.registerSession(self.session) self.votecastdb = VoteCastDBHandler.getInstance() self.votecastdb.registerSession(self.session) def setUpPreSession(self): """ override TestAsServer """ TestAsServer.setUpPreSession(self) # BuddyCast self.config.set_buddycast(True) self.config.set_start_recommender(True) fd,self.superpeerfilename = tempfile.mkstemp() os.write(fd,'') os.close(fd) self.config.set_superpeer_file(self.superpeerfilename) def setUpPostSession(self): """ override TestAsServer """ TestAsServer.setUpPostSession(self) self.mypermid = str(self.my_keypair.pub().get_der()) self.hispermid = str(self.his_keypair.pub().get_der()) self.myhash = sha(self.mypermid).digest() def tearDown(self): """ override TestAsServer """ TestAsServer.tearDown(self) try: os.remove(self.superpeerfilename) except: print_exc() def test_channel_subscription(self): self.votecastdb.unsubscribe(bin2str(self.mypermid)) self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),None) print >> sys.stderr, self.votecastdb.getAll() self.votecastdb.spam(bin2str(self.mypermid)) self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),-1) print >> sys.stderr, self.votecastdb.getAll() self.votecastdb.subscribe(bin2str(self.mypermid)) self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),2) print >> sys.stderr, self.votecastdb.getAll() self.votecastdb.unsubscribe(bin2str(self.mypermid)) self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),0) print >> sys.stderr, self.votecastdb.getAll() self.votecastdb.spam(bin2str(self.mypermid)) self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),-1) print >> sys.stderr, self.votecastdb.getAll() def check_chquery_reply(self,data): d = bdecode(data) self.assert_(type(d) == DictType) self.assert_(d.has_key('a')) self.assert_(d.has_key('id')) id = d['id'] self.assert_(type(id) == StringType) def test_channelcast(self): torrent_data = {'announce':"http://localhost", 'info':{'name':'Hello 123', 'files':[{'length':100, 'path':['license.txt']}]}} infohash = bin2str(sha(bencode(torrent_data['info'])).digest()) self.channelcastdb.addOwnTorrent(infohash,torrent_data) s = OLConnection(self.my_keypair,'localhost',self.hisport) chcast = ChannelCastCore(None, s, self.session, None, log = '', dnsindb = None) # Good message chdata = chcast.createChannelCastMessage() if chdata is None or len(chdata) ==0: print "test: no subscriptions for us.. hence do not send" else: msg = CHANNELCAST + bencode(chdata) print "test: channelcast msg created", repr(chdata) s.send(msg) time.sleep(3) # Bad message if chdata is None or len(chdata)==0: pass else: pub_id, pub_name, infohash, torrenthash, name, timestamp, signature = chdata[0] chdata = [(pub_id, pub_name, infohash, torrenthash, name, 12343, signature)] msg = CHANNELCAST + bencode(chdata) print "test: channelcast msg created", repr(chdata) s.send(msg) time.sleep(20) # the other side should have closed the connection, as it is invalid message s.close() def test_channel_query(self): s = OLConnection(self.my_keypair,'localhost',self.hisport) msg = CHANNEL_QUERY+bencode({'q':'k:dutiet', 'id': 'a' * 20}) s.send(msg) resp = s.recv() if len(resp) > 0: print >>sys.stderr,"test: good CH_QUERY: got",getMessageName(resp[0]) self.assert_(resp[0] == CHANNEL_QUERY_REPLY) self.check_chquery_reply(resp[1:]) time.sleep(10) # the other side should not have closed the connection, as # this is all valid, so this should not throw an exception: #s.send('bla') s.close() def test_channel_update(self): s = OLConnection(self.my_keypair,'localhost',self.hisport) msg = CHANNEL_QUERY+bencode({'q':'p:345fsdf34fe345ed344g5', 'id': 'a' * 20}) s.send(msg) resp = s.recv() if len(resp) > 0: print >>sys.stderr,"test: good CH_QUERY: got",getMessageName(resp[0]) self.assert_(resp[0] == CHANNEL_QUERY_REPLY) self.check_chquery_reply(resp[1:]) time.sleep(10) # the other side should not have closed the connection, as # this is all valid, so this should not throw an exception: s.send('bla') s.close() def test_votecast(self): self.votecastdb.subscribe('nitin') s = OLConnection(self.my_keypair,'localhost',self.hisport) votecast = VoteCastCore(None, s, self.session, None, log = '', dnsindb = None) data = votecast.createVoteCastMessage() if data is None and len(data)==0: print >>sys.stderr, "test: no votes" else: msg = VOTECAST + bencode(data) s.send(msg) s.close()
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 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() 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()) # 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.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: downloader: Sleeping 3 secs to let Session2 start" time.sleep(3) tdef2 = TorrentDef.load(self.torrentfn) dscfg2 = DownloadStartupConfig() dscfg2.set_dest_dir(self.config_path2) 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", ` 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()
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" self.vod_started = False 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 def tearDown(self): TestAsServer.tearDown(self) self.assert_(self.vod_started) def setup_seeder(self,merkle): self.tdef = TorrentDef() self.sourcefn = os.path.join(os.getcwd(),"file2.wmv") self.tdef.add_content(self.sourcefn,playtime='1:00') # 60 secs 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) 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() 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.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) 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(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() return (1.0,False) def downloader_vod_ready_callback(self,d,event,params): if event == VODEVENT_START: self.vod_started = True
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 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() 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()) # 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.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: downloader: Sleeping 3 secs to let Session2 start" time.sleep(3) tdef2 = TorrentDef.load(self.torrentfn) dscfg2 = DownloadStartupConfig() dscfg2.set_dest_dir(self.config_path2) 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",`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()