def test_save_resume_preresolved_magnet(self): """ Test whether a magnet link correctly writes save-resume data before it is resolved. This can happen when a magnet link is added when the user does not have internet. """ self.ltmgr.initialize() self.ltmgr.trsession = self.tribler_session self.ltmgr.metadata_tmpdir = tempfile.mkdtemp(suffix=u'tribler_metainfo_tmpdir') mock_tdef = MockObject() mock_tdef.get_infohash = lambda: 'a' * 20 self.tribler_session.get_download = lambda _: None self.tribler_session.get_downloads_pstate_dir = lambda: self.ltmgr.metadata_tmpdir mock_lm = MockObject() mock_lm.ltmgr = self.ltmgr mock_lm.tunnel_community = None self.tribler_session.lm = mock_lm def dl_from_tdef(tdef, _): dl = LibtorrentDownloadImpl(self.tribler_session, tdef) dl.setup() dl.cancel_all_pending_tasks() return dl self.tribler_session.start_download_from_tdef = dl_from_tdef download = self.ltmgr.start_download_from_magnet("magnet:?xt=urn:btih:" + ('1'*40)) basename = hexlify(download.get_def().get_infohash()) + '.state' filename = os.path.join(download.session.get_downloads_pstate_dir(), basename) self.assertTrue(os.path.isfile(filename))
def setUp(self): """ Setup some classes and files that are used by the tests in this module. """ yield super(BaseTestChannel, self).setUp() self.fake_session = MockObject() self.fake_session.add_observer = lambda a, b, c: False self.fake_session_config = MockObject() self.fake_session_config.get_state_dir = lambda: self.session_base_dir self.fake_session.config = self.fake_session_config fake_notifier = MockObject() fake_notifier.add_observer = lambda a, b, c, d: False fake_notifier.notify = lambda a, b, c, d: False self.fake_session.notifier = fake_notifier self.fake_channel_community = MockObject() self.fake_channel_community.get_channel_id = lambda: 42 self.fake_channel_community.cid = 'a' * 20 self.fake_channel_community.get_channel_name = lambda: "my fancy channel" self.channel_db_handler = self.session.open_dbhandler(NTFY_CHANNELCAST) self.votecast_db_handler = self.session.open_dbhandler(NTFY_VOTECAST) self.session.get_dispersy = lambda: True self.session.lm.dispersy = Dispersy(ManualEnpoint(0), self.getStateDir())
def test_on_metadata_received_alert(self): """ Testing whether the right operations happen when we receive metadata """ test_deferred = Deferred() def mocked_checkpoint(): test_deferred.callback(None) mocked_file = MockObject() mocked_file.path = 'test' self.libtorrent_download_impl.handle.trackers = lambda: [] self.libtorrent_download_impl.handle.save_resume_data = lambda: None self.libtorrent_download_impl.handle.rename_file = lambda *_: None with open(os.path.join(TESTS_DATA_DIR, "bak_single.torrent"), mode='rb') as torrent_file: encoded_metainfo = torrent_file.read() decoded_metainfo = bdecode(encoded_metainfo) get_info_from_handle(self.libtorrent_download_impl.handle).metadata = lambda: bencode(decoded_metainfo['info']) get_info_from_handle(self.libtorrent_download_impl.handle).files = lambda: [mocked_file] self.libtorrent_download_impl.checkpoint = mocked_checkpoint self.libtorrent_download_impl.session = MockObject() self.libtorrent_download_impl.session.lm = MockObject() self.libtorrent_download_impl.session.lm.torrent_db = None self.libtorrent_download_impl.handle.save_path = lambda: None self.libtorrent_download_impl.handle.prioritize_files = lambda _: None self.libtorrent_download_impl.get_save_path = lambda: '' self.libtorrent_download_impl.get_share_mode = lambda: False self.libtorrent_download_impl.on_metadata_received_alert(None) return test_deferred
def test_restart_in_upload_mode(self): tdef = self.create_tdef() def mock_set_upload_mode(handle, mode): handle.status().upload_mode = mode fake_status = MockObject() fake_status.share_mode = False fake_status.upload_mode = False impl = LibtorrentDownloadImpl(self.session, tdef) impl.handle = MockObject() impl.handle.status = lambda: fake_status # impl.handle.upload_mode = False impl.handle.set_priority = lambda _: None impl.handle.set_sequential_download = lambda _: None impl.handle.set_upload_mode = lambda mode, _handle=impl.handle: mock_set_upload_mode(_handle, mode) impl.handle.get_upload_mode = lambda: impl.handle.status().upload_mode impl.handle.is_valid = lambda: True impl.handle.resume = lambda: None # Create a dummy download config impl.dlconfig = DownloadStartupConfig().dlconfig.copy() impl.session.lm.on_download_wrapper_created = lambda _: True impl.set_upload_mode(True) impl.restart() self.assertTrue(impl.get_upload_mode())
def test_selected_files_no_files(self): """ Test that no files are selected if torrent info is not available. """ def mocked_set_file_prios(_): mocked_set_file_prios.called = True mocked_set_file_prios.called = False mocked_file = MockObject() mocked_file.path = 'my/path' mock_torrent_info = MockObject() self.libtorrent_download_impl.handle.prioritize_files = mocked_set_file_prios self.libtorrent_download_impl.handle.get_torrent_info = lambda: mock_torrent_info self.libtorrent_download_impl.handle.rename_file = lambda *_: None self.libtorrent_download_impl.tdef.get_infohash = lambda: 'a' * 20 self.libtorrent_download_impl.orig_files = ['a', 'b'] self.libtorrent_download_impl.get_save_path = lambda: 'my/path' # If share mode is not enabled and everything else is fine, file priority should be set # when set_selected_files() is called. But in this test, no files attribute is set in torrent info # in order to test AttributeError, therfore, no call to set file priority is expected. self.libtorrent_download_impl.get_share_mode = lambda: False self.libtorrent_download_impl.set_selected_files(['a']) self.assertFalse(mocked_set_file_prios.called)
def create_fake_block(self): """ Create a dummy block and return it """ block = MockObject() block.hash = 'a' return block
def test_on_metadata_received_alert(self): """ Testing whether the right operations happen when we receive metadata """ test_deferred = Deferred() def mocked_checkpoint(): test_deferred.callback(None) mocked_file = MockObject() mocked_file.path = 'test' self.libtorrent_download_impl.handle.trackers = lambda: [] self.libtorrent_download_impl.handle.save_resume_data = lambda: None torrent_dict = {'name': 'test', 'piece length': 42, 'pieces': '', 'files': []} get_info_from_handle(self.libtorrent_download_impl.handle).metadata = lambda: lt.bencode(torrent_dict) get_info_from_handle(self.libtorrent_download_impl.handle).files = lambda: [mocked_file] self.libtorrent_download_impl.checkpoint = mocked_checkpoint self.libtorrent_download_impl.session = MockObject() self.libtorrent_download_impl.session.lm = MockObject() self.libtorrent_download_impl.session.lm.rtorrent_handler = None self.libtorrent_download_impl.session.lm.torrent_db = None self.libtorrent_download_impl.handle.save_path = lambda: None self.libtorrent_download_impl.handle.prioritize_files = lambda _: None self.libtorrent_download_impl.get_save_path = lambda: '' self.libtorrent_download_impl.get_share_mode = lambda: False self.libtorrent_download_impl.on_metadata_received_alert(None) return test_deferred
def test_multifile_torrent(self): tdef = TorrentDef() tdef.add_content(os.path.join(TESTS_DATA_DIR, "video.avi")) tdef.set_tracker("http://tribler.org/announce") tdef.save() impl = LibtorrentDownloadImpl(self.session, tdef) # Override the add_torrent because it will be called impl.ltmgr = MockObject() impl.ltmgr.add_torrent = lambda _, _dummy2: succeed(fake_handler) impl.set_selected_files = lambda: None fake_handler = MockObject() fake_handler.is_valid = lambda: True fake_handler.status = lambda: fake_status fake_handler.set_share_mode = lambda _: None fake_handler.set_priority = lambda _: None fake_handler.set_sequential_download = lambda _: None fake_handler.resume = lambda: None fake_handler.set_max_connections = lambda _: None fake_status = MockObject() fake_status.share_mode = False # Create a dummy download config impl.dlconfig = DownloadStartupConfig().dlconfig.copy() # Create a dummy pstate pstate = CallbackConfigParser() pstate.add_section("state") test_dict = dict() test_dict["a"] = "b" pstate.set("state", "engineresumedata", test_dict) return impl.network_create_engine_wrapper(pstate)
def on_wallet_created(_): wallet.get_balance = lambda: succeed({'available': 100000, 'pending': 0, 'currency': 'BTC', 'precision': 8}) mock_tx = MockObject() mock_tx.hash = 'a' * 20 wallet.wallet.send_to = lambda *_: mock_tx wallet.transfer(3000, '2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF').addCallback( lambda _: test_deferred.callback(None))
def test_on_socks_in(self): """ Test whether data is correctly dispatched to a circuit """ mock_socks_server = MockObject() self.dispatcher.set_socks_servers([mock_socks_server]) mock_udp_connection = MockObject() mock_udp_connection.socksconnection = MockObject() mock_udp_connection.socksconnection.socksserver = mock_socks_server mock_request = MockObject() mock_request.destination = ("0.0.0.0", 1024) mock_request.payload = 'a' # No circuit is selected self.assertFalse(self.dispatcher.on_socks5_udp_data(mock_udp_connection, mock_request)) self.selection_strategy.select = lambda *_: self.mock_circuit # Circuit is not ready self.assertFalse(self.dispatcher.on_socks5_udp_data(mock_udp_connection, mock_request)) self.mock_circuit.state = CIRCUIT_STATE_READY # Circuit ready, should be able to tunnel data self.assertTrue(self.dispatcher.on_socks5_udp_data(mock_udp_connection, mock_request))
def test_create_playlist(self): """ Testing whether the API can create a new playlist in a given channel """ mock_channel_community = MockObject() mock_channel_community.called_create = False self.create_fake_channel("channel", "") def verify_playlist_created(_): self.assertTrue(mock_channel_community.called_create) def create_playlist_called(name, description, _): self.assertEqual(name, "test1") self.assertEqual(description, "test2") mock_channel_community.called_create = True mock_channel_community.create_playlist = create_playlist_called mock_dispersy = MockObject() mock_dispersy.get_community = lambda _: mock_channel_community self.session.get_dispersy_instance = lambda: mock_dispersy expected_json = {"created": True} post_params = {"name": "test1", "description": "test2"} return self.do_request('channels/discovered/%s/playlists' % 'fakedispersyid'.encode('hex'), expected_code=200, expected_json=expected_json, post_data=post_params, request_type='PUT')\ .addCallback(verify_playlist_created)
def test_selected_files(self): """ Test whether the selected files are set correctly """ def mocked_set_file_prios(_): mocked_set_file_prios.called = True mocked_set_file_prios.called = False mocked_file = MockObject() mocked_file.path = 'my/path' mock_torrent_info = MockObject() mock_torrent_info.files = lambda: [mocked_file, mocked_file] self.libtorrent_download_impl.handle.prioritize_files = mocked_set_file_prios self.libtorrent_download_impl.handle.get_torrent_info = lambda: mock_torrent_info self.libtorrent_download_impl.handle.rename_file = lambda *_: None self.libtorrent_download_impl.get_share_mode = lambda: False self.libtorrent_download_impl.tdef.get_infohash = lambda: 'a' * 20 self.libtorrent_download_impl.orig_files = ['a', 'b'] self.libtorrent_download_impl.get_save_path = lambda: 'my/path' self.libtorrent_download_impl.set_selected_files(['a']) self.assertTrue(mocked_set_file_prios.called) self.libtorrent_download_impl.get_share_mode = lambda: False mocked_set_file_prios.called = False self.assertFalse(mocked_set_file_prios.called)
def test_edit_playlist(self): """ Testing whether a playlist is correctly modified """ mock_channel_community = MockObject() mock_channel_community.called_modify = False my_channel_id = self.create_fake_channel("channel", "") def verify_playlist_modified(_): self.assertTrue(mock_channel_community.called_modify) def modify_playlist_called(playlist_id, modifications): self.assertEqual(playlist_id, 1) self.assertEqual(modifications['name'], 'test') self.assertEqual(modifications['description'], 'test') mock_channel_community.called_modify = True mock_channel_community.modifyPlaylist = modify_playlist_called mock_dispersy = MockObject() mock_dispersy.get_community = lambda _: mock_channel_community self.session.get_dispersy_instance = lambda: mock_dispersy self.create_playlist(my_channel_id, 1234, 42, "test playlist", "test description") post_params = {'name': 'test', 'description': 'test'} return self.do_request('channels/discovered/%s/playlists/1' % 'fakedispersyid'.encode('hex'), expected_code=200, expected_json={"modified": True}, post_data=post_params, request_type='POST').addCallback(verify_playlist_modified)
def test_remove_torrent_playlist(self): """ Testing whether a torrent can be successfully removed from a playlist """ mock_channel_community = MockObject() mock_channel_community.called_remove = False my_channel_id = self.create_fake_channel("channel", "") def verify_torrent_removed(_): self.assertTrue(mock_channel_community.called_remove) def modify_remove_called(playlist_id, torrents): self.assertEqual(playlist_id, 1) self.assertEqual(torrents, [42]) mock_channel_community.called_remove = True mock_channel_community.remove_playlist_torrents = modify_remove_called mock_dispersy = MockObject() mock_dispersy.get_community = lambda _: mock_channel_community self.session.get_dispersy_instance = lambda: mock_dispersy self.create_playlist(my_channel_id, 1234, 42, "test playlist", "test description") yield self.do_request('channels/discovered/%s/playlists/1/abcd' % 'fakedispersyid'.encode('hex'), expected_code=404, request_type='DELETE') torrent_list = [[my_channel_id, 1, 1, ('a' * 40).decode('hex'), 1460000000, "ubuntu-torrent.iso", [['file1.txt', 42]], []]] self.insert_torrents_into_channel(torrent_list) self.insert_torrent_into_playlist(1234, ('a' * 40).decode('hex')) yield self.do_request('channels/discovered/%s/playlists/1/%s' % ('fakedispersyid'.encode('hex'), 'a' * 40), expected_code=200, request_type='DELETE', expected_json={'removed': True})\ .addCallback(verify_torrent_removed)
def test_encode_torrent(self): """ Test the encoding of a torrent file """ message = MockObject() message.payload = MockObject() message.payload.name = u'test' message.payload.infohash = 'a' * 20 message.payload.timestamp = 1234 message.payload.files = [(u'a', 1234)] message.payload.trackers = ['udp://tracker.openbittorrent.com:80/announce', 'http://google.com'] meta = self.channel_community.get_meta_message(u"torrent") msg = MockObject() msg.meta = meta decoded_message = self.conversion._decode_torrent(msg, 0, self.conversion._encode_torrent(message)[0])[1] self.assertEqual(len(decoded_message.files), 1) self.assertEqual(len(decoded_message.trackers), 1) message.payload.files = [(u'a', 1234)] * 1000 message.payload.trackers = ['udp://tracker.openbittorrent.com:80/announce'] * 100 decoded_message = self.conversion._decode_torrent(msg, 0, self.conversion._encode_torrent(message)[0])[1] self.assertGreaterEqual(len(decoded_message.files), 133) self.assertEqual(len(decoded_message.trackers), 10)
def test_set_proxy_settings(self): """ Test setting the proxy settings """ def on_proxy_set(settings): self.assertTrue(settings) self.assertEqual(settings.hostname, 'a') self.assertEqual(settings.port, 1234) self.assertEqual(settings.username, 'abc') self.assertEqual(settings.password, 'def') def on_set_settings(settings): self.assertTrue(settings) self.assertEqual(settings['proxy_hostname'], 'a') self.assertEqual(settings['proxy_port'], 1234) self.assertEqual(settings['proxy_username'], 'abc') self.assertEqual(settings['proxy_password'], 'def') self.assertEqual(settings['proxy_peer_connections'], True) self.assertEqual(settings['proxy_hostnames'], True) mock_lt_session = MockObject() mock_lt_session.get_settings = lambda: {} mock_lt_session.set_settings = on_set_settings mock_lt_session.set_proxy = on_proxy_set # Libtorrent < 1.1.0 uses set_proxy to set proxy settings self.ltmgr.metadata_tmpdir = tempfile.mkdtemp(suffix=u'tribler_metainfo_tmpdir') self.ltmgr.set_proxy_settings(mock_lt_session, 0, ('a', "1234"), ('abc', 'def'))
def test_get_info_from_handle(self): mock_handle = MockObject() def mock_get_torrent_file(): raise RuntimeError mock_handle.torrent_file = mock_get_torrent_file self.assertIsNone(get_info_from_handle(mock_handle))
def test_remove_invalid_torrent(self): """ Tests a successful removal status of torrents without a handle """ self.ltmgr.initialize() mock_dl = MockObject() mock_dl.handle = None self.assertTrue(self.ltmgr.remove_torrent(mock_dl).called)
def test_tracker_reply_alert(self): """ Testing the tracker reply alert in LibtorrentDownloadImpl """ mock_alert = MockObject() mock_alert.url = 'http://google.com' mock_alert.num_peers = 42 self.libtorrent_download_impl.on_tracker_reply_alert(mock_alert) self.assertEqual(self.libtorrent_download_impl.tracker_status['http://google.com'], [42, 'Working'])
def test_close_dbhandler(self): handler = MockObject() self.called = False def verify_close_called(): self.called = True handler.close = verify_close_called Session.close_dbhandler(handler) self.assertTrue(self.called)
def test_remove_invalid_handle_torrent(self): """ Tests a successful removal status of torrents with an invalid handle """ self.ltmgr.initialize() mock_handle = MockObject() mock_handle.is_valid = lambda: False mock_dl = MockObject() mock_dl.handle = mock_handle self.assertTrue(self.ltmgr.remove_torrent(mock_dl).called)
def test_download_remove(self): """ Test the effects of removing a download in the tunnel community """ self.nodes[0].overlay.num_hops_by_downloads[1] = 1 mock_download = MockObject() mock_download.get_hops = lambda: 1 self.nodes[0].overlay.on_download_removed(mock_download) self.assertEqual(self.nodes[0].overlay.num_hops_by_downloads[1], 0)
def test_get_transactions(self): """ Test whether transactions in bitcoinlib are correctly returned """ raw_tx = '02000000014bca66ebc0e3ab0c5c3aec6d0b3895b968497397752977dfd4a2f0bc67db6810000000006b483045022100fc' \ '93a034db310fbfead113283da95e980ac7d867c7aa4e6ef0aba80ef321639e02202bc7bd7b821413d814d9f7d6fc76ff46' \ 'b9cd3493173ef8d5fac40bce77a7016d01210309702ce2d5258eacc958e5a925b14de912a23c6478b8e2fb82af43d20212' \ '14f3feffffff029c4e7020000000001976a914d0115029aa5b2d2db7afb54a6c773ad536d0916c88ac90f4f70000000000' \ '1976a914f0eabff37e597b930647a3ec5e9df2e0fed0ae9888ac108b1500' wallet = BitcoinTestnetWallet(self.session_base_dir) mock_wallet = MockObject() mock_wallet.transactions_update = lambda **_: None mock_wallet._session = MockObject() mock_all = MockObject() mock_all.all = lambda *_: [(raw_tx, 3, datetime.datetime(2012, 9, 16, 0, 0), 12345)] mock_filter = MockObject() mock_filter.filter = lambda *_: mock_all mock_wallet._session.query = lambda *_: mock_filter wallet.wallet = mock_wallet wallet.wallet.wallet_id = 3 mock_key = MockObject() mock_key.address = 'n3Uogo82Tyy76ZNuxmFfhJiFqAUbJ5BPho' wallet.wallet.keys = lambda **_: [mock_key] wallet.created = True def on_transactions(transactions): self.assertTrue(transactions) self.assertEqual(transactions[0]["fee_amount"], 12345) self.assertEqual(transactions[0]["amount"], 16250000) return wallet.get_transactions().addCallback(on_transactions)
def test_tracker_warning_alert(self): """ Test whether a tracking warning alert is processed correctly """ url = "http://google.com" mock_alert = MockObject() mock_alert.category = lambda: lt.alert.category_t.error_notification mock_alert.url = url mock_alert.message = lambda: 'test' self.libtorrent_download_impl.process_alert(mock_alert, 'tracker_warning_alert') self.assertEqual(self.libtorrent_download_impl.tracker_status[url][1], 'Warning: test')
def test_remove_unregistered_torrent(self): """ Tests a successful removal status of torrents which aren't known """ self.ltmgr.initialize() mock_handle = MockObject() mock_handle.is_valid = lambda: False alert = type('torrent_removed_alert', (object, ), dict(handle=mock_handle, info_hash='0'*20)) self.ltmgr.process_alert(alert()) self.assertNotIn('0'*20, self.ltmgr.torrents)
def test_tracker_reply_alert(self): """ Testing the tracker reply alert in LibtorrentDownloadImpl """ mock_alert = MockObject() mock_alert.url = 'http://google.com' mock_alert.num_peers = 42 self.libtorrent_download_impl.on_tracker_reply_alert(mock_alert) self.assertEqual( self.libtorrent_download_impl.tracker_status['http://google.com'], [42, 'Working'])
def test_seederratio_policy(self): for i, torrent in enumerate(self.torrents): mock_ds = MockObject() mock_ds.get_num_seeds_peers = lambda index=i: (index, 1) torrent.state = mock_ds policy = SeederRatioPolicy() sorted_torrents = policy.sort(self.torrents) expected_torrents = list(reversed(self.torrents)) self.assertItemsEqual(sorted_torrents, expected_torrents, 'Arrays contains different torrents') self.assertListEqual(sorted_torrents, expected_torrents, 'Array is not sorted properly')
def test_seederratio_policy(self): for i, torrent in enumerate(self.torrents): mock_ds = MockObject() mock_ds.get_num_seeds_peers = lambda index=i: (index, 1) torrent.state = mock_ds policy = SeederRatioPolicy() sorted_torrents = policy.sort(self.torrents) expected_torrents = list(reversed(self.torrents)) self.assertCountEqual(sorted_torrents, expected_torrents, 'Arrays contains different torrents') self.assertListEqual(sorted_torrents, expected_torrents, 'Array is not sorted properly')
def test_readd_bittorrent_peers(self): """ Test the readd bittorrent peers method """ mock_torrent = MockObject() mock_torrent.add_peer = lambda _: None mock_torrent.tdef = MockObject() mock_torrent.tdef.get_infohash = lambda: 'a' * 20 self.nodes[0].overlay.bittorrent_peers = {mock_torrent: [None]} self.nodes[0].overlay.readd_bittorrent_peers() self.assertNotIn(mock_torrent, self.nodes[0].overlay.bittorrent_peers)
def test_edit_my_channel_no_cmty(self): """ Testing whether an error 404 is returned when trying to edit your channel without community """ mock_dispersy = MockObject() mock_dispersy.get_community = lambda _: None self.session.get_dispersy_instance = lambda: mock_dispersy self.create_my_channel('test', 'test') return self.do_request('mychannel', expected_code=404, request_type='POST')
def setUp(self): yield super(TestPayoutManager, self).setUp() fake_tc = MockObject() fake_tc.add_listener = lambda *_: None fake_response_peer = MockObject() fake_response_peer.public_key = MockObject() fake_response_peer.public_key.key_to_bin = lambda: 'a' * 64 fake_dht = MockObject() fake_dht.connect_peer = lambda *_: succeed([fake_response_peer]) self.payout_manager = PayoutManager(fake_tc, fake_dht)
def on_wallet_created(_): wallet.get_balance = lambda: succeed({ 'available': 100000, 'pending': 0, 'currency': 'BTC', 'precision': 8 }) mock_tx = MockObject() mock_tx.hash = 'a' * 20 wallet.wallet.send_to = lambda *_: mock_tx wallet.transfer(3000, '2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF').addCallback( lambda _: test_deferred.callback(None))
def test_get_dest_files(self): """ Testing whether the right list of files is returned when fetching files from a download """ self.libtorrent_download_impl.handle.file_priority = lambda _: 123 mocked_file = MockObject() mocked_file.path = 'test' mock_torrent_info = MockObject() mock_torrent_info.files = lambda: [mocked_file] self.libtorrent_download_impl.handle.get_torrent_info = lambda: mock_torrent_info dest_files = self.libtorrent_download_impl.get_dest_files() self.assertIsInstance(dest_files[0], tuple) self.assertEqual(dest_files[0][0], 'test')
def test_send_error_packet(self): """ Testing whether a correct error message is sent in the tftp handler """ def mocked_send_packet(_, packet): self.assertEqual(packet['session_id'], 42) self.assertEqual(packet['error_code'], 43) self.assertEqual(packet['error_msg'], "test") self.handler._send_packet = mocked_send_packet mock_session = MockObject() mock_session.session_id = 42 self.handler._send_error_packet(mock_session, 43, "test")
def setUp(self, annotate=True): super(TestResourceMonitor, self).setUp(annotate=annotate) mock_session = MockObject() mock_session.config = MockObject() mock_session.config.get_resource_monitor_history_size = lambda: 1 mock_session.config.get_resource_monitor_poll_interval = lambda: 20 mock_session.config.get_state_dir = lambda: "." mock_session.config.get_log_dir = lambda: "logs" mock_session.config.get_resource_monitor_enabled = lambda: False self.resource_monitor = ResourceMonitor(mock_session) self.resource_monitor.session.notifier = MockObject() self.resource_monitor.session.notifier.notify = lambda subject, changeType, obj_id, *args: None
def setUp(self): super(TestResourceMonitor, self).setUp() mock_session = MockObject() mock_session.config = MockObject() mock_session.config.get_resource_monitor_history_size = lambda: 1 mock_session.config.get_resource_monitor_poll_interval = lambda: 20 mock_session.config.get_state_dir = lambda: "." mock_session.config.get_log_dir = lambda: "logs" mock_session.config.get_resource_monitor_enabled = lambda: False self.resource_monitor = ResourceMonitor(mock_session) self.resource_monitor.session.notifier = MockObject() self.resource_monitor.session.notifier.notify = lambda subject, changeType, obj_id, *args: None
def test_basic_policy_run(self): """ Test running an iteration of basic policy. Scenario: There are 10 torrents with infohashes ordered as 0-9 and the torrents with odd infohashes are downloading while the rest are stopped. In the next iteration, we assume that all the torrents with infohashes as multiple of 3 are scheduled to start and the rest to be stopped. The scenario is represented in the table below: Infohash Status To Start -> Result 0 STOPPED True Started 1 DOWNLOADING False Stopped 2 STOPPED False Do Nothing 3 DOWNLOADING True Do Nothing 4 STOPPED False Do Nothing 5 DOWNLOADING False Stopped 6 STOPPED True Started 7 DOWNLOADING False Stopped 8 STOPPED False Do Nothing 9 DOWNLOADING True Do Nothing At the end of the iteration, the following result is expected: Started = 2 Stopped = 3 """ scenario = MockObject() scenario.to_start = [True, False, False, True, False, False, True, False, False, True] scenario.torrent_status = [DLSTATUS_STOPPED, DLSTATUS_DOWNLOADING, DLSTATUS_STOPPED, DLSTATUS_DOWNLOADING, DLSTATUS_STOPPED, DLSTATUS_DOWNLOADING, DLSTATUS_STOPPED, DLSTATUS_DOWNLOADING, DLSTATUS_STOPPED, DLSTATUS_DOWNLOADING] # Any BasicPolicy implementation is fine. policy = UploadPolicy() def get_status(scenario, index): return scenario.torrent_status[index] for i, torrent in enumerate(self.torrents): torrent.download = MockObject() torrent.download.state = MockObject() torrent.download.state.get_status = lambda _scenario=scenario, index=i: get_status(_scenario, index) torrent.download.get_state = lambda _torrent=torrent: _torrent.download.state torrent.download.restart = lambda: None torrent.download.stop = lambda: None policy.schedule(torrent, to_start=scenario.to_start[i]) policy.run() self.assertEqual(policy.started_in_iteration, 2) self.assertEqual(policy.stopped_in_iteration, 3)
def test_got_metainfo(self): """ Testing whether the callback is correctly invoked when we received metainfo """ test_deferred = Deferred() self.ltmgr.initialize() def metainfo_cb(metainfo): self.assertDictEqual(metainfo, {'info': {'pieces': ['a']}, 'leechers': 0, 'nodes': [], 'seeders': 0, 'initial peers': []}) test_deferred.callback(None) fake_handle = MockObject() torrent_info = MockObject() torrent_info.metadata = lambda: bencode({'pieces': ['a']}) torrent_info.trackers = lambda: [] fake_handle.get_peer_info = lambda: [] fake_handle.torrent_file = lambda: torrent_info self.ltmgr.get_session().remove_torrent = lambda *_: None self.ltmgr.metainfo_requests['a' * 20] = { 'handle': fake_handle, 'timeout_callbacks': [], 'callbacks': [metainfo_cb], 'notify': False } self.ltmgr.got_metainfo("a" * 20) return test_deferred
def test_get_files_completion(self): """ Testing whether the right completion of files is returned """ self.mocked_tdef.get_files_with_length = lambda: [("test.txt", 100)] handle = MockObject() handle.file_progress = lambda **_: [60] self.mock_download.handle = handle download_state = DownloadState(self.mock_download, MockObject(), None) self.assertEqual(download_state.get_files_completion(), [('test.txt', 0.6)]) handle.file_progress = lambda **_: [0] self.assertEqual(download_state.get_files_completion(), [('test.txt', 0.0)]) handle.file_progress = lambda **_: [100] self.assertEqual(download_state.get_files_completion(), [('test.txt', 1.0)]) self.mocked_tdef.get_files_with_length = lambda: [] handle.file_progress = lambda **_: [] self.assertEqual(download_state.get_files_completion(), []) # Test a file with a length of zero self.mocked_tdef.get_files_with_length = lambda: [("test.txt", 0)] handle.file_progress = lambda **_: [0] self.assertEqual(download_state.get_files_completion(), [('test.txt', 1.0)])
def test_update_conflicting_torrent_info(self): """ Test updating torrent info response with existing record in the database.""" torrent_info_response = MockObject() torrent_info_response.infohash = 'a' * 20 torrent_info_response.name = 'ubuntu' torrent_info_response.length = 123 torrent_info_response.creation_date = 123123123 torrent_info_response.num_files = 2 torrent_info_response.comment = 'Ubuntu ISO' self.content_repository.called_update_torrent = False def fake_update_torrent(ref): ref.called_update_torrent = True def fake_get_torrent(infohash, name): torrent = {'infohash': infohash, 'name': name} return torrent self.content_repository.torrent_db.updateTorrent = lambda infohash, **kw: fake_update_torrent( self.content_repository) self.content_repository.has_torrent = lambda infohash: True self.content_repository.get_torrent = lambda infohash: fake_get_torrent( infohash, torrent_info_response.name) self.content_repository.update_torrent_info(torrent_info_response) self.assertFalse(self.content_repository.called_update_torrent)
def setUp(self, annotate=True): TriblerCoreTest.setUp(self, annotate=annotate) self.lm = TriblerLaunchMany() self.lm.session_lock = NoDispersyRLock() self.lm.session = MockObject() self.lm.session.config = MockObject() self.lm.session.config.get_max_upload_rate = lambda: 100 self.lm.session.config.get_max_download_rate = lambda: 100 self.lm.session.config.get_default_number_hops = lambda: 0 # Ignore notifications mock_notifier = MockObject() mock_notifier.notify = lambda *_: None self.lm.session.notifier = mock_notifier
def setUp(self, annotate=True): TriblerCoreTest.setUp(self, annotate=annotate) self.mock_download = MockObject() self.mocked_tdef = MockObject() self.mocked_tdef.get_name = lambda: "test" self.mocked_tdef.get_length = lambda: 43 self.mock_download.get_def = lambda: self.mocked_tdef self.mock_transferred = MockObject() self.mock_transferred.upTotal = 5 self.mock_transferred.downTotal = 6 self.mock_transferred.numConInitiated = 10 self.mock_transferred.numSeeds = 11 self.mock_transferred.numPeers = 12
def setup_torrents(torrents): for i, torrent in enumerate(torrents): mock_status = MockObject() mock_status.total_upload = i * i mock_status.active_time = i mock_handle = MockObject() mock_handle.status = lambda status=mock_status: status mock_dl = MockObject() mock_dl.handle = mock_handle torrent.download = mock_dl return torrents
def test_set_proxy_settings(self): """ Test setting the proxy settings """ def on_proxy_set(settings): self.assertTrue(settings) self.assertEqual(settings.hostname, 'a') self.assertEqual(settings.port, 1234) self.assertEqual(settings.username, 'abc') self.assertEqual(settings.password, 'def') mock_lt_session = MockObject() mock_lt_session.set_proxy = on_proxy_set self.ltmgr.metadata_tmpdir = tempfile.mkdtemp(suffix=u'tribler_metainfo_tmpdir') self.ltmgr.set_proxy_settings(mock_lt_session, 0, ('a', "1234"), ('abc', 'def'))
def setUp(self): yield super(TestGigaChannelManager, self).setUp() self.torrent_template = { "title": "", "infohash": "", "torrent_date": datetime(1970, 1, 1), "tags": "video" } my_key = default_eccrypto.generate_key(u"curve25519") self.mock_session = MockObject() self.mock_session.lm = MockObject() self.mock_session.lm.mds = MetadataStore(":memory:", self.session_base_dir, my_key) self.chanman = GigaChannelManager(self.mock_session) self.torrents_added = 0
def test_restart(self): tdef = self.create_tdef() impl = LibtorrentDownloadImpl(self.session, tdef) impl.handle = MockObject() impl.handle.set_priority = lambda _: None impl.handle.set_sequential_download = lambda _: None impl.handle.resume = lambda: None impl.handle.status = lambda: fake_status fake_status = MockObject() fake_status.share_mode = False # Create a dummy download config impl.dlconfig = DownloadStartupConfig().dlconfig.copy() impl.session.lm.on_download_wrapper_created = lambda _: True impl.restart()
def test_update_torrent(self): """ Test updating a torrent when a circuit breaks """ self.nodes[0].overlay.active_data_circuits = lambda: True self.nodes[0].overlay.readd_bittorrent_peers = lambda *_: None mock_handle = MockObject() mock_handle.get_peer_info = lambda: {2, 3} peers = {1, 2} self.nodes[0].overlay.update_torrent(peers, mock_handle, 'a') self.assertIn('a', self.nodes[0].overlay.bittorrent_peers) # Test adding peers self.nodes[0].overlay.bittorrent_peers['a'] = {4} self.nodes[0].overlay.update_torrent(peers, mock_handle, 'a')
def setUp(self, annotate=True): yield super(TestTunnelDispatcher, self).setUp(annotate=annotate) self.mock_tunnel_community = MockObject() self.selection_strategy = MockObject() self.selection_strategy.select = lambda *_: None self.mock_tunnel_community.selection_strategy = self.selection_strategy self.mock_tunnel_community.send_data = lambda *_: None self.dispatcher = TunnelDispatcher(self.mock_tunnel_community) self.mock_circuit = MockObject() self.mock_circuit.state = CIRCUIT_STATE_EXTENDING self.mock_circuit.circuit_id = 3 self.mock_circuit.sock_addr = ("1.1.1.1", 1234) self.mock_circuit.tunnel_data = lambda *_: None
def test_remove_torrent_no_community(self): """ Testing whether an error 404 is returned when a torrent from a playlist without channel community """ def mocked_get_community(_): raise CommunityNotFoundException("abcd") mock_dispersy = MockObject() mock_dispersy.get_community = mocked_get_community self.session.get_dispersy_instance = lambda: mock_dispersy channel_cid = 'fakedispersyid'.encode('hex') my_channel_id = self.create_my_channel("my channel", "this is a short description") self.create_playlist(my_channel_id, 1234, 42, "test playlist", "test description") return self.do_request('channels/discovered/%s/playlists/1/abcd' % channel_cid, expected_code=404, request_type='DELETE')
def setUp(self): yield super(TestTorrentChecker, self).setUp() self.session.lm.torrent_checker = TorrentChecker(self.session) self.session.lm.tracker_manager = TrackerManager(self.session) self.session.lm.popularity_community = MockObject() self.torrent_checker = self.session.lm.torrent_checker self.torrent_checker.listen_on_udp = lambda: None def get_metainfo(_, callback, **__): callback({"seeders": 1, "leechers": 2}) self.session.lm.ltmgr = MockObject() self.session.lm.ltmgr.get_metainfo = get_metainfo self.session.lm.ltmgr.shutdown = lambda: None
def setUp(self): super(TestPickleConverter, self).setUp() self.mock_session = MockObject() self.mock_session.get_downloads_pstate_dir = lambda: self.session_base_dir self.mock_session.config = TriblerConfig() self.mock_session.config.get_state_dir = lambda: self.session_base_dir
def setUp(self, annotate=True): yield super(TestTftpRequester, self).setUp(annotate=annotate) self.mock_session = MockObject() self.remote_torrent_handler = RemoteTorrentHandler(self.mock_session) self.remote_torrent_handler.running = True self.tftp_requester = TftpRequester('test', self.mock_session, self.remote_torrent_handler, 1)
def test_torrent_insert_existing_download(self): self.credit_mining_manager.add_source(self.cid) self.session.lm.downloads[self.infohash_bin] = MockObject() self.credit_mining_manager.on_torrent_insert(self.cid, self.infohash, self.name) self.assertNotIn(self.infohash, self.credit_mining_manager.torrents) del self.session.lm.downloads[self.infohash_bin]
def test_decode_payload(self): """ Test decoding of a payload """ message = MockObject() meta_msg = self.market_community.get_meta_message(u"ask") offer_payload = OfferPayload.Implementation(meta_msg, TraderId('abc'), MessageNumber('3'), OrderNumber(4), Price(5, 'BTC'), Quantity(6, 'MC'), Timeout(3600), Timestamp.now(), 'a', 'b', Ttl(3), "1.2.3.4", 1234) message.payload = offer_payload packet = encode((3.14, 100)) placeholder = self.get_placeholder_msg(u"ask") self.assertRaises(DropPacket, self.conversion._decode_payload, placeholder, 0, packet, [Price]) self.assertRaises(DropPacket, self.conversion._decode_payload, placeholder, 0, "a2zz", [Price])
def test_handle_new_request_no_metadata(self): """ When the metadata_store from LaunchManyCore is not available, return from the function rather than trying to load the metadata. :return: """ self.handler.session = MockObject() # Make sure the packet appears to have the correct attributes fake_packet = { "opcode": OPCODE_RRQ, "file_name": METADATA_PREFIX + "abc", "options": { "blksize": 1, "timeout": 1 }, "session_id": 1 } self.handler._load_metadata = lambda _: self.fail( "This line should not be called") def test_function(): test_function.is_called = True return False test_function.is_called = False self.handler.session.get_enable_metadata = test_function self.handler._handle_new_request("123", "456", fake_packet) self.assertTrue(test_function.is_called)
def test_promote_torrent(self): def set_upload_mode(upload_mode, torrent): torrent.upload_mode = upload_mode torrent = self.torrents[0] torrent.download = MockObject() torrent.download.set_upload_mode = lambda upload_mode, _torrent=torrent: set_upload_mode(upload_mode, _torrent) torrent.download.restart = lambda: None # Promote from state 0 torrent.upload_mode = False torrent.mining_state['state_id'] = 0 self.policy.promote_torrent(torrent) self.assertEqual(torrent.mining_state['state_id'], 1) self.assertTrue(torrent.upload_mode) # Promote from state 1 torrent.upload_mode = True torrent.mining_state['state_id'] = 1 self.policy.promote_torrent(torrent) self.assertEqual(torrent.mining_state['state_id'], 2) self.assertFalse(torrent.upload_mode) # Promote from last state last_state = len(self.policy.investment_states) - 1 torrent.upload_mode = True # Last state is always in upload mode torrent.mining_state['state_id'] = last_state self.policy.promote_torrent(torrent) self.assertEqual(torrent.mining_state['state_id'], last_state) self.assertTrue(torrent.upload_mode)
def test_resume_data_failed(self): """ Testing whether the correct operations happen when an error is raised during resume data saving """ test_deferred = Deferred() def on_error(_): test_deferred.callback(None) mock_alert = MockObject() mock_alert.msg = "test error" self.libtorrent_download_impl.deferreds_resume.append(Deferred().addErrback( self.libtorrent_download_impl._on_resume_err).addCallback(on_error)) self.libtorrent_download_impl.on_save_resume_data_failed_alert(mock_alert) return test_deferred