def get_ports(param): rstate = random.getstate() random.seed() ports = [] for _ in range(param): selected_port = get_random_port(min_port=1024, max_port=50000) while selected_port in selected_ports: selected_port = get_random_port(min_port=1024, max_port=50000) selected_ports.add(selected_port) ports.append(selected_port) random.setstate(rstate) return ports
async def test_perform_http_request_multipart(self): """ Test whether getting a large HTTP response works """ self.add_node_to_experiment(self.create_node()) self.nodes[1].overlay.settings.peer_flags.add(PEER_FLAG_EXIT_HTTP) await self.introduce_nodes() http_port = get_random_port() http_tracker = HTTPTracker(http_port) http_tracker.tracker_info.add_info_about_infohash('0', 0, 0) http_tracker.tracker_info.infohashes['0']['downloaded'] = os.urandom( 10000) await http_tracker.start() response = await self.nodes[0].overlay.perform_http_request( ('127.0.0.1', http_tracker.port), b'GET /scrape?info_hash=0 HTTP/1.1\r\n\r\n') self.assertEqual(response.split(b'\r\n')[0], b'HTTP/1.1 200 OK') self.assertEqual( response.split(b'\r\n\r\n')[1], (await http_tracker.handle_scrape_request(Mock(query={'info_hash': '0'}) )).body) await http_tracker.stop()
def test_get_random_port_tcp(): rand_port_num = random.randint(1000, 10000) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: attempts = 0 while attempts < 20: try: sock.bind(('', rand_port_num)) random_port = get_random_port(socket_type='tcp', min_port=rand_port_num, max_port=rand_port_num) assert random_port > rand_port_num # It should have picked a higher port return except OSError: attempts += 1 rand_port_num += 1 assert False
async def test_perform_http_request_not_allowed(self): """ Test whether we can make HTTP requests that don't have a bencoded response """ self.add_node_to_experiment(self.create_node()) self.nodes[1].overlay.settings.peer_flags.add(PEER_FLAG_EXIT_HTTP) await self.introduce_nodes() http_port = get_random_port() http_tracker = HTTPTracker(http_port) await http_tracker.start() with self.assertRaises(AsyncTimeoutError): await wait_for(self.nodes[0].overlay.perform_http_request( ('127.0.0.1', http_tracker.port), b'GET /scrape?info_hash=0 HTTP/1.1\r\n\r\n'), timeout=.3) await http_tracker.stop()
def test_get_random_port_invalid_type(): with pytest.raises(AssertionError): get_random_port(socket_type="http")
def test_get_random_port_udp(): random_port = get_random_port(socket_type='udp') assert isinstance(random_port, int) assert random_port
def test_get_random_port(): random_port = get_random_port() assert isinstance(random_port, int) assert random_port
def api_port(): return get_random_port()
def _get_random_port(self, path): """Get a random port which is not already selected.""" if path not in self.selected_ports: self.selected_ports[path] = get_random_port() self._logger.debug("Get random port %d for [%s]", self.selected_ports[path], path) return self.selected_ports[path]