Created
September 20, 2019 14:54
-
-
Save FFY00/1d5bf1c1b720cd7e7d941eeec3604084 to your computer and use it in GitHub Desktop.
ratbag-emu server fixture with random port
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@pytest.fixture(autouse=True, scope='session') | |
@pytest.mark.first | |
def server(self, port_range=[9000, 9999]): | |
p = port = None | |
try: | |
stdout = open('ratbag-emu-log-stdout.txt', 'w') | |
stderr = open('ratbag-emu-log-stderr.txt', 'w') | |
def try_port(port): | |
ret = False | |
try: | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock.bind(('0.0.0.0', port)) | |
ret = True | |
finally: | |
sock.close() | |
return ret | |
tries = 0 | |
found = False | |
while not found: | |
port = random.randint(port_range[0], port_range[1]) | |
found = try_port(port) | |
tries += 1 | |
assert tries < 100, 'Reached max tries when trying to find a port' | |
p = subprocess.Popen(['/usr/bin/env', 'python3', '-m', 'ratbag_emu', '-p', str(port)], | |
stdout=stdout, stderr=stderr) | |
sleep(2) | |
yield port | |
finally: | |
if p: | |
p.kill() | |
if stdout: | |
stdout.close() | |
if stderr: | |
stderr.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment