def test_adjacent_port_to_many_to_one(self): port_mappings = PortMappings() port_mappings.add([7000, 7002], 7000) port_mappings.add(6999) expected_result = { "6999/tcp": 6999, "7000/tcp": [7000, 7001, 7002], } result = port_mappings.to_dict() assert result == expected_result
def extract_port_flags(user_flags, port_mappings: PortMappings): regex = r"-p\s+([0-9]+)(\-([0-9]+))?:([0-9]+)(\-([0-9]+))?" matches = re.match(".*%s" % regex, user_flags) if matches: for match in re.findall(regex, user_flags): start = int(match[0]) end = int(match[2] or match[0]) start_target = int(match[3] or start) end_target = int(match[5] or end) port_mappings.add([start, end], [start_target, end_target]) user_flags = re.sub(regex, r"", user_flags) return user_flags
def test_many_to_one_adjacent_to_uniform(self): port_mappings = PortMappings() port_mappings.add(5002) port_mappings.add(5003) port_mappings.add([5004, 5006], 5004) expected_result = { "5002/tcp": 5002, "5003/tcp": 5003, "5004/tcp": [5004, 5005, 5006], } result = port_mappings.to_dict() assert result == expected_result
def test_port_ranges_with_bind_host(self): port_mappings = PortMappings(bind_host="0.0.0.0") port_mappings.add(5000) port_mappings.add(5001) port_mappings.add(5003) port_mappings.add([5004, 5006], 9000) result = port_mappings.to_str() self.assertEqual( "-p 0.0.0.0:5000-5001:5000-5001 -p 0.0.0.0:5003:5003 -p 0.0.0.0:5004-5006:9000", result )
def test_overlapping_port_ranges(self): port_mappings = PortMappings() port_mappings.add(4590) port_mappings.add(4591) port_mappings.add(4593) port_mappings.add(4592) port_mappings.add(4593) result = port_mappings.to_str() # assert that ranges are non-overlapping, i.e., no duplicate ports self.assertEqual("-p 4590-4592:4590-4592 -p 4593:4593", result)
def test_port_ranges_with_bind_host_to_dict(self): port_mappings = PortMappings(bind_host="0.0.0.0") port_mappings.add(5000, 6000) port_mappings.add(5001, 7000) port_mappings.add(5003, 8000) port_mappings.add([5004, 5006], 9000) result = port_mappings.to_dict() expected_result = { "6000/tcp": ("0.0.0.0", 5000), "7000/tcp": ("0.0.0.0", 5001), "8000/tcp": ("0.0.0.0", 5003), "9000/tcp": ("0.0.0.0", [5004, 5005, 5006]), } assert result == expected_result
def test_port_mappings(self): map = PortMappings() map.add(123) self.assertEqual("-p 123:123", map.to_str()) map.add(124) self.assertEqual("-p 123-124:123-124", map.to_str()) map.add(234) self.assertEqual("-p 123-124:123-124 -p 234:234", map.to_str()) map.add(345, 346) self.assertEqual("-p 123-124:123-124 -p 234:234 -p 345:346", map.to_str()) map.add([456, 458]) self.assertEqual( "-p 123-124:123-124 -p 234:234 -p 345:346 -p 456-458:456-458", map.to_str()) map = PortMappings() map.add([123, 124]) self.assertEqual("-p 123-124:123-124", map.to_str()) map.add([234, 237], [345, 348]) self.assertEqual("-p 123-124:123-124 -p 234-237:345-348", map.to_str())