Coverage for src\zapy\api\connection.py: 0%

1 import socket

2 import sys

3 import json

4

5 from pathlib import Path

6

7 from .models import ServerConnection

8

9

10 def load_server_config() -> ServerConnection:

11 virtual_env_path = Path(sys.prefix)

12 zapy_etc = virtual_env_path / 'etc' / 'zapy'

13 zapy_etc.mkdir(parents=True, exist_ok=True)

14

15 conn_file = zapy_etc / 'connection.json'

16

17 if not conn_file.exists():

18 conn = create_connection(conn_file)

19 else:

20 conn = read_connection(conn_file)

21

22 return conn

23

24

25 def create_connection(conn_path) -> ServerConnection:

26 conn = ServerConnection(

27 host = '127.0.0.1',

28 port = get_random_free_port(),

29 )

30 with open(conn_path, "w") as outfile:

31 outfile.write(conn.model_dump_json())

32 return conn

33

34

35 def read_connection(conn_path) -> ServerConnection:

36 with open(conn_path, "r") as outfile:

37 raw_data = json.load(outfile)

38 return ServerConnection.model_validate(raw_data)

39

40 def get_random_free_port() -> int:

41 sock = socket.socket()

42 sock.bind(('', 0))

43 port = sock.getsockname()[1]

44 sock.close()

45 return port

46