1 """Miscellaneous utility functions."""
5 import subprocess as subp
11 from pathlib import Path
15 from .const import EXIT_SKIP
17 _ALPHA_NUMERIC = string.ascii_lowercase + string.digits
20 def random_port() -> int:
21 """Return an unused TCP port in the unprivileged range.
22 Note that this function releases the port before returning, and it can be
23 overtaken by something else before you use it.
26 port = random.randint(1024, 65535)
28 with socket.socket() as sock:
29 sock.bind(("0.0.0.0", port))
33 log.debug("could not bind to random port %d", port, exc_info=ex)
36 def temp_file(content: str) -> str:
37 """Create a temporary file and write text content into it."""
38 file = tempfile.mktemp()
39 with open(file, "w", encoding="utf-8") as f:
44 def remove_file(path: T.Union[str, Path]) -> bool:
45 """Try to remove file without failing if it does not exist."""
49 except FileNotFoundError:
53 def random_string(k: int) -> str:
54 """Generate a random alphanumeric string of length k."""
55 return "".join(random.choices(_ALPHA_NUMERIC, k=k))
58 def find_line(filename: str, prefix: str) -> str:
59 """Find a line with the prefix in a text file.
60 Check that only one line matches.
62 with open(filename, "r", encoding="utf-8") as f:
63 keylines = [line for line in f.readlines() if line.startswith(prefix)]
64 check.equals(1, len(keylines))
65 return keylines[0].rstrip()
68 def require_root() -> None:
69 """Check that test is running with root privileges.
70 Exit with code 77 otherwise.
74 log.info("this test requires root (but running under UID %d)", euid)
78 def require_command(*args: str) -> None:
79 """Check that command args runs with exit code 0.
80 Exit with code 77 otherwise.
82 if subp.run(args, check=False).returncode:
83 log.info('this test requires command "%s" to work', " ".join(args))
87 def require_path(path: str) -> None:
88 """Check that path exists in your file system.
89 Exit with code 77 otherwise.
91 if not os.path.exists(path):
92 log.warning("this test requires path %s to be present", path)
96 # Thin wrappers around `with open(...) as f: f.do_something()`
97 # Don't do much, besides saving quite a bit of space because of how frequently they're needed.
100 def read_text(path: str) -> str:
101 """Return the text contents of a file."""
102 with open(path, encoding="utf-8") as f:
106 def write_text(path: str, text: str) -> str:
107 """Write text to a file, replacing its content. Return the text added."""
108 with open(path, "w", encoding="utf-8") as f:
113 def read_lines(path: str) -> T.List[str]:
114 """Read file as a list of lines."""
115 with open(path, encoding="utf-8") as f:
116 return f.read().splitlines()
119 def write_lines(path: str, lines: T.List[str]) -> T.List[str]:
120 """Write text lines to a file, replacing it content. Return the line added."""
121 with open(path, "w", encoding="utf-8") as f:
122 f.write(os.linesep.join(lines))
127 def append_line(path: str, line: str) -> str:
128 """Append a line to the end of the file. Return the line added."""
129 line = f"{os.linesep}{line}{os.linesep}"
130 with open(path, "a", encoding="utf-8") as f: