|
| 1 | +import unittest |
| 2 | + |
| 3 | +from hypothesis import assume, given, settings |
| 4 | +from hypothesis.strategies import integers |
| 5 | +import os |
| 6 | +import socket |
| 7 | +import random |
| 8 | + |
| 9 | +import lib.utils as utils |
| 10 | + |
| 11 | + |
| 12 | +class TestUtils(unittest.TestCase): |
| 13 | + def test_extract_schema_from_snapshot(self): |
| 14 | + snapshot_path = '00000000000000000003.snap' |
| 15 | + v = utils.extract_schema_from_snapshot(snapshot_path) |
| 16 | + self.assertEqual(v, [u'version', 2, 3, 1]) |
| 17 | + |
| 18 | + @settings(max_examples=5) |
| 19 | + @given(port=integers(65000, 65535)) |
| 20 | + def test_check_port(self, port): |
| 21 | + def open_socket(p): |
| 22 | + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 23 | + s.bind(('localhost', p)) |
| 24 | + s.listen() |
| 25 | + return s |
| 26 | + status = utils.check_port(port, False, ipv4=True, ipv6=False) |
| 27 | + self.assertEqual(status, True) |
| 28 | + s = open_socket(port) |
| 29 | + status = utils.check_port(port, False, ipv4=True, ipv6=False) |
| 30 | + s.close() |
| 31 | + self.assertEqual(status, False) |
| 32 | + |
| 33 | + @settings(max_examples=2) |
| 34 | + @given(start_port=integers(65000, 65535), end_port=integers(65000, 65535)) |
| 35 | + def test_find_port(self, start_port, end_port): |
| 36 | + assume(start_port < end_port) |
| 37 | + is_open_port_found = False |
| 38 | + open_port = start_port |
| 39 | + for p in range(start_port, end_port): |
| 40 | + open_port = random.randint(start_port, end_port) |
| 41 | + if utils.check_port(open_port, False, ipv4=True, ipv6=False): |
| 42 | + is_open_port_found = True |
| 43 | + break |
| 44 | + if not is_open_port_found: |
| 45 | + self.fail("Failed to found open port in range {}-{}".format(start_port, end_port)) |
| 46 | + |
| 47 | + os.environ['TEST_RUN_TCP_PORT_START'] = str(start_port) |
| 48 | + os.environ['TEST_RUN_TCP_PORT_END'] = str(end_port) |
| 49 | + open_sockets = [] |
| 50 | + for p in range(start_port, end_port): |
| 51 | + if p != open_port: |
| 52 | + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 53 | + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 54 | + s.bind(('localhost', p)) |
| 55 | + s.listen() |
| 56 | + open_sockets.append(s) |
| 57 | + found_open_port = utils.find_port() |
| 58 | + for s in open_sockets: |
| 59 | + s.close() |
| 60 | + self.assertEqual(found_open_port, open_port) |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + unittest.main() |
0 commit comments