50 lines
2.0 KiB
Python
50 lines
2.0 KiB
Python
"""Reject real listener conflicts and unrelated Docker mappings before startup."""
|
|
import importlib.util
|
|
from pathlib import Path
|
|
import socket
|
|
import unittest
|
|
|
|
spec = importlib.util.spec_from_file_location("local", Path(__file__).parents[1] / "scripts/local.py")
|
|
local = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(local)
|
|
|
|
|
|
class PortChecks(unittest.TestCase):
|
|
def test_free_loopback_port(self):
|
|
with socket.socket() as sock:
|
|
sock.bind(("127.0.0.1", 0))
|
|
port = sock.getsockname()[1]
|
|
local.check_port("grafana", "127.0.0.1", port, 3000, [])
|
|
|
|
def test_real_listener_rejected(self):
|
|
with socket.socket() as sock:
|
|
sock.bind(("127.0.0.1", 0))
|
|
sock.listen()
|
|
with self.assertRaisesRegex(RuntimeError, "PORT CONFLICT"):
|
|
local.check_port("grafana", "127.0.0.1", sock.getsockname()[1], 3000, [])
|
|
|
|
def container(self, project="observability-local", service="grafana", ip="127.0.0.1"):
|
|
return {"Name": "/test", "Config": {"Labels": {
|
|
"com.docker.compose.project": project,
|
|
"com.docker.compose.service": service}},
|
|
"NetworkSettings": {"Ports": {"3000/tcp": [{"HostIp": ip, "HostPort": "3001"}]}}}
|
|
|
|
def test_own_mapping_allows_update(self):
|
|
local.check_port("grafana", "127.0.0.1", 3001, 3000, [self.container()])
|
|
|
|
def test_other_project_rejected(self):
|
|
with self.assertRaisesRegex(RuntimeError, "PORT CONFLICT"):
|
|
local.check_port("grafana", "127.0.0.1", 3001, 3000, [self.container(project="other")])
|
|
|
|
def test_wildcard_mapping_rejected(self):
|
|
with self.assertRaisesRegex(RuntimeError, "PORT CONFLICT"):
|
|
local.check_port("grafana", "127.0.0.1", 3001, 3000, [self.container(project="other", ip="0.0.0.0")])
|
|
|
|
def test_wrong_service_rejected(self):
|
|
with self.assertRaisesRegex(RuntimeError, "PORT CONFLICT"):
|
|
local.check_port("tempo", "127.0.0.1", 3001, 3000, [self.container()])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|