import ipaddress import random import subprocess from ward import test, fixture from ports.commands.base import BaseCommand def _get_random_number_between_1_and_254() -> int: return random.randint(1, 254) @fixture def dev_null_pid(): p = subprocess.Popen(["tail", "-f", "/dev/null"]) yield p.pid p.kill() @test( "`_get_name_of_pid` of non-existing process should return empty string instead of " "raising `NoSuchProcess`" ) def _(): assert not BaseCommand._get_name_of_pid(10000000) @test("`_get_name_of_pid` should return `tail` ") def _(dnp: int = dev_null_pid): assert BaseCommand._get_name_of_pid(dnp) == "tail" @test("`_normalize_interface` of `::`, `::1` and `0.0.0.0` should return `localhost`") def _(): assert ( BaseCommand._normalize_interface("::") == BaseCommand._normalize_interface("::1") == BaseCommand._normalize_interface("0.0.0.0") == BaseCommand._normalize_interface("localhost") == "localhost" ) @test("`_normalize_interface` of any `127.0.0.0/8` ip should return `localhost`") def _(): # iterating over the real /8 range would take a bit too much # so let's randomize 32 IPs random_second_block = _get_random_number_between_1_and_254() random_third_block = _get_random_number_between_1_and_254() for ip in ipaddress.IPv4Network( f"127.{random_second_block}.{random_third_block}.0/24" ): assert BaseCommand._normalize_interface(str(ip)) == "localhost"