beannetworktester 1.1.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. beannetworktester/__init__.py +20 -0
  2. beannetworktester/_aim.py +245 -0
  3. beannetworktester/_lock.py +135 -0
  4. beannetworktester/_program.py +134 -0
  5. beannetworktester/_session.py +281 -0
  6. beannetworktester/program/BeanNetworkTester/BeanNetworkTester.exe +0 -0
  7. beannetworktester/program/BeanNetworkTester/_internal/LICENSE +675 -0
  8. beannetworktester/program/BeanNetworkTester/_internal/THIRD-PARTY-NOTICES.md +336 -0
  9. beannetworktester/program/BeanNetworkTester/_internal/VCRUNTIME140.dll +0 -0
  10. beannetworktester/program/BeanNetworkTester/_internal/VCRUNTIME140_1.dll +0 -0
  11. beannetworktester/program/BeanNetworkTester/_internal/VERSION.txt +1 -0
  12. beannetworktester/program/BeanNetworkTester/_internal/_asyncio.pyd +0 -0
  13. beannetworktester/program/BeanNetworkTester/_internal/_bz2.pyd +0 -0
  14. beannetworktester/program/BeanNetworkTester/_internal/_ctypes.pyd +0 -0
  15. beannetworktester/program/BeanNetworkTester/_internal/_decimal.pyd +0 -0
  16. beannetworktester/program/BeanNetworkTester/_internal/_lzma.pyd +0 -0
  17. beannetworktester/program/BeanNetworkTester/_internal/_multiprocessing.pyd +0 -0
  18. beannetworktester/program/BeanNetworkTester/_internal/_overlapped.pyd +0 -0
  19. beannetworktester/program/BeanNetworkTester/_internal/_queue.pyd +0 -0
  20. beannetworktester/program/BeanNetworkTester/_internal/_socket.pyd +0 -0
  21. beannetworktester/program/BeanNetworkTester/_internal/_ssl.pyd +0 -0
  22. beannetworktester/program/BeanNetworkTester/_internal/_tkinter.pyd +0 -0
  23. beannetworktester/program/BeanNetworkTester/_internal/_wmi.pyd +0 -0
  24. beannetworktester/program/BeanNetworkTester/_internal/_zstd.pyd +0 -0
  25. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-console-l1-1-0.dll +0 -0
  26. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-datetime-l1-1-0.dll +0 -0
  27. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-debug-l1-1-0.dll +0 -0
  28. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-errorhandling-l1-1-0.dll +0 -0
  29. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-fibers-l1-1-0.dll +0 -0
  30. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-fibers-l1-1-1.dll +0 -0
  31. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-file-l1-1-0.dll +0 -0
  32. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-file-l1-2-0.dll +0 -0
  33. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-file-l2-1-0.dll +0 -0
  34. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-handle-l1-1-0.dll +0 -0
  35. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-heap-l1-1-0.dll +0 -0
  36. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-interlocked-l1-1-0.dll +0 -0
  37. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-kernel32-legacy-l1-1-1.dll +0 -0
  38. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-libraryloader-l1-1-0.dll +0 -0
  39. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-localization-l1-2-0.dll +0 -0
  40. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-memory-l1-1-0.dll +0 -0
  41. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-namedpipe-l1-1-0.dll +0 -0
  42. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-processenvironment-l1-1-0.dll +0 -0
  43. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-processthreads-l1-1-0.dll +0 -0
  44. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-processthreads-l1-1-1.dll +0 -0
  45. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-profile-l1-1-0.dll +0 -0
  46. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-rtlsupport-l1-1-0.dll +0 -0
  47. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-string-l1-1-0.dll +0 -0
  48. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-synch-l1-1-0.dll +0 -0
  49. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-synch-l1-2-0.dll +0 -0
  50. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-sysinfo-l1-1-0.dll +0 -0
  51. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-sysinfo-l1-2-0.dll +0 -0
  52. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-timezone-l1-1-0.dll +0 -0
  53. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-core-util-l1-1-0.dll +0 -0
  54. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-conio-l1-1-0.dll +0 -0
  55. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-convert-l1-1-0.dll +0 -0
  56. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-environment-l1-1-0.dll +0 -0
  57. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-filesystem-l1-1-0.dll +0 -0
  58. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-heap-l1-1-0.dll +0 -0
  59. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-locale-l1-1-0.dll +0 -0
  60. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-math-l1-1-0.dll +0 -0
  61. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-private-l1-1-0.dll +0 -0
  62. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-process-l1-1-0.dll +0 -0
  63. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-runtime-l1-1-0.dll +0 -0
  64. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-stdio-l1-1-0.dll +0 -0
  65. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-string-l1-1-0.dll +0 -0
  66. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-time-l1-1-0.dll +0 -0
  67. beannetworktester/program/BeanNetworkTester/_internal/api-ms-win-crt-utility-l1-1-0.dll +0 -0
  68. beannetworktester/program/BeanNetworkTester/_internal/base_library.zip +0 -0
  69. beannetworktester/program/BeanNetworkTester/_internal/bean.ico +0 -0
  70. beannetworktester/program/BeanNetworkTester/_internal/bean.png +0 -0
  71. beannetworktester/program/BeanNetworkTester/_internal/lang/en.json +1461 -0
  72. beannetworktester/program/BeanNetworkTester/_internal/lang/pl.json +1461 -0
  73. beannetworktester/program/BeanNetworkTester/_internal/lang/zh.json +1461 -0
  74. beannetworktester/program/BeanNetworkTester/_internal/libcrypto-3.dll +0 -0
  75. beannetworktester/program/BeanNetworkTester/_internal/libffi-8.dll +0 -0
  76. beannetworktester/program/BeanNetworkTester/_internal/libssl-3.dll +0 -0
  77. beannetworktester/program/BeanNetworkTester/_internal/libtommath.dll +0 -0
  78. beannetworktester/program/BeanNetworkTester/_internal/licenses/GPL-2.0.txt +340 -0
  79. beannetworktester/program/BeanNetworkTester/_internal/licenses/GPL-3.0.txt +675 -0
  80. beannetworktester/program/BeanNetworkTester/_internal/licenses/LGPL-2.1.txt +506 -0
  81. beannetworktester/program/BeanNetworkTester/_internal/licenses/LGPL-3.0.txt +166 -0
  82. beannetworktester/program/BeanNetworkTester/_internal/licenses/PyDivert-LICENSE.txt +15 -0
  83. beannetworktester/program/BeanNetworkTester/_internal/licenses/PyInstaller-COPYING.txt +636 -0
  84. beannetworktester/program/BeanNetworkTester/_internal/licenses/Python-LICENSE.txt +676 -0
  85. beannetworktester/program/BeanNetworkTester/_internal/licenses/Tcl-Tk-LICENSE.txt +40 -0
  86. beannetworktester/program/BeanNetworkTester/_internal/licenses/WinDivert-LICENSE.txt +1191 -0
  87. beannetworktester/program/BeanNetworkTester/_internal/licenses/X.Org-libraries.txt +1295 -0
  88. beannetworktester/program/BeanNetworkTester/_internal/licenses/elfutils-LICENSE.txt +40 -0
  89. beannetworktester/program/BeanNetworkTester/_internal/licenses/libbpf-LICENSE.txt +47 -0
  90. beannetworktester/program/BeanNetworkTester/_internal/licenses/libtommath-LICENSE.txt +26 -0
  91. beannetworktester/program/BeanNetworkTester/_internal/licenses/psutil-LICENSE.txt +29 -0
  92. beannetworktester/program/BeanNetworkTester/_internal/licenses/zlib-LICENSE.txt +30 -0
  93. beannetworktester/program/BeanNetworkTester/_internal/licenses/zstd-LICENSE.txt +40 -0
  94. beannetworktester/program/BeanNetworkTester/_internal/psutil/_psutil_windows.pyd +0 -0
  95. beannetworktester/program/BeanNetworkTester/_internal/pydivert/windivert_dll/WinDivert64.dll +0 -0
  96. beannetworktester/program/BeanNetworkTester/_internal/pydivert/windivert_dll/WinDivert64.sys +0 -0
  97. beannetworktester/program/BeanNetworkTester/_internal/pyexpat.pyd +0 -0
  98. beannetworktester/program/BeanNetworkTester/_internal/pyinstaller-6.22.3.dist-info/INSTALLER +1 -0
  99. beannetworktester/program/BeanNetworkTester/_internal/pyinstaller-6.22.3.dist-info/METADATA +213 -0
  100. beannetworktester/program/BeanNetworkTester/_internal/pyinstaller-6.22.3.dist-info/RECORD +1137 -0
  101. beannetworktester/program/BeanNetworkTester/_internal/pyinstaller-6.22.3.dist-info/REQUESTED +0 -0
  102. beannetworktester/program/BeanNetworkTester/_internal/pyinstaller-6.22.3.dist-info/WHEEL +4 -0
  103. beannetworktester/program/BeanNetworkTester/_internal/pyinstaller-6.22.3.dist-info/entry_points.txt +7 -0
  104. beannetworktester/program/BeanNetworkTester/_internal/pyinstaller-6.22.3.dist-info/licenses/COPYING.txt +648 -0
  105. beannetworktester/program/BeanNetworkTester/_internal/python3.dll +0 -0
  106. beannetworktester/program/BeanNetworkTester/_internal/python315.dll +0 -0
  107. beannetworktester/program/BeanNetworkTester/_internal/scenarios/blocked-endpoint.json +9 -0
  108. beannetworktester/program/BeanNetworkTester/_internal/scenarios/cafe-wifi.json +10 -0
  109. beannetworktester/program/BeanNetworkTester/_internal/scenarios/congested-vpn.json +9 -0
  110. beannetworktester/program/BeanNetworkTester/_internal/scenarios/failing-dns.json +11 -0
  111. beannetworktester/program/BeanNetworkTester/_internal/scenarios/mobile-lte-to-3g.json +12 -0
  112. beannetworktester/program/BeanNetworkTester/_internal/scenarios/overloaded-game-server.json +10 -0
  113. beannetworktester/program/BeanNetworkTester/_internal/scenarios/same-loss-in-runs.json +10 -0
  114. beannetworktester/program/BeanNetworkTester/_internal/scenarios/upload-drop-midway.json +12 -0
  115. beannetworktester/program/BeanNetworkTester/_internal/select.pyd +0 -0
  116. beannetworktester/program/BeanNetworkTester/_internal/tcl90.dll +0 -0
  117. beannetworktester/program/BeanNetworkTester/_internal/tcl9tk90.dll +0 -0
  118. beannetworktester/program/BeanNetworkTester/_internal/ucrtbase.dll +0 -0
  119. beannetworktester/program/BeanNetworkTester/_internal/unicodedata.pyd +0 -0
  120. beannetworktester/program/BeanNetworkTester/_internal/zlib1.dll +0 -0
  121. beannetworktester/py.typed +0 -0
  122. beannetworktester/pytest_plugin.py +57 -0
  123. beannetworktester-1.1.0.dist-info/METADATA +278 -0
  124. beannetworktester-1.1.0.dist-info/RECORD +129 -0
  125. beannetworktester-1.1.0.dist-info/WHEEL +4 -0
  126. beannetworktester-1.1.0.dist-info/entry_points.txt +3 -0
  127. beannetworktester-1.1.0.dist-info/licenses/LICENSE +373 -0
  128. beannetworktester-1.1.0.dist-info/licenses/program/LICENSE +675 -0
  129. beannetworktester-1.1.0.dist-info/licenses/program/THIRD-PARTY-NOTICES.md +336 -0
@@ -0,0 +1,20 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+
5
+ """Slow down, break or cut the network for a test: pytest, Playwright for Python, any code.
6
+
7
+ from beannetworktester import bad_network
8
+
9
+ with bad_network(server="http://localhost:3000", latency=300, loss=2):
10
+ ... # every connection to that server is slowed, on a real network
11
+
12
+ In pytest the ``bad_network`` fixture does the same and stops the session when the
13
+ test ends. It runs Bean Network Tester's own program, which this package carries for
14
+ Windows x64 and Linux x64.
15
+ """
16
+
17
+ from ._program import BadNetworkError
18
+ from ._session import BadNetwork, BadNetworkWarning, bad_network
19
+
20
+ __all__ = ["BadNetwork", "BadNetworkError", "BadNetworkWarning", "bad_network"]
@@ -0,0 +1,245 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+
5
+ """What a session aims at, and its settings, as the program's flags.
6
+
7
+ A session always aims at something. ``server=`` (one or more servers) and ``process=``
8
+ (this test, or a process it started) are exact, and they are what the helper promises: a
9
+ scenario may not change what they set while it runs, or it could widen the aim to the
10
+ whole machine. The program's own aim flags (``target``, ``dst_ip``, ``dst_port``) are an
11
+ aim too, in the program's own syntax, for what those two cannot say: an API on a port, a
12
+ range of addresses, a process by name. They reach as far as they match, which the package
13
+ READMEs spell out (``dst_port=443`` is every HTTPS connection of the machine).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ import socket
22
+ from collections.abc import Mapping, Sequence
23
+ from urllib.parse import urlsplit
24
+
25
+ from ._program import BadNetworkError
26
+
27
+ # Flags the helper sets itself, or that would turn the run into something else.
28
+ RESERVED = frozenset({
29
+ "format", "stop_on_stdin_close", "duration", "simulate", "gui", "doctor", "dry_run",
30
+ "print_config", "save_config", "license", "install_desktop", "remove_desktop",
31
+ "cleanup_driver", "version", "help",
32
+ })
33
+ # The program's aim flags: an aim of their own, or a narrowing of server= / process=,
34
+ # which set some of them.
35
+ AIM_KEYS = ("target", "dst_ip", "dst_port")
36
+ SERVER_KEYS = frozenset({"dst_ip", "dst_port"})
37
+ PROCESS_KEYS = frozenset({"target"})
38
+ _KEY = re.compile(r"^[a-z][a-z0-9_]*$")
39
+ _DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}
40
+ # The two shapes the program accepts for a scenario it ships (paths.shipped_scenario).
41
+ _SHIPPED_FOLDERS = (("scenarios",), ("_internal", "scenarios"))
42
+ _SCENARIO_ADVICE = {
43
+ SERVER_KEYS: "Aim with process= instead, and the scenario then narrows that process's "
44
+ "traffic.",
45
+ PROCESS_KEYS: "Aim with server= instead, or take target out of the scenario.",
46
+ }
47
+
48
+
49
+ def server_address(server: object) -> tuple[str, int]:
50
+ """``(host, port)`` from a URL, ``host:port`` or a ``(host, port)`` pair."""
51
+ if isinstance(server, tuple) and len(server) == 2:
52
+ host, port = server
53
+ try:
54
+ return str(host), int(port)
55
+ except (TypeError, ValueError) as exc:
56
+ raise BadNetworkError(f"server={server!r} has a port that is not a number.") from exc
57
+ text = str(server).strip()
58
+ if "://" not in text:
59
+ text = "tcp://" + text
60
+ parts = urlsplit(text)
61
+ host = parts.hostname
62
+ try:
63
+ port = parts.port or _DEFAULT_PORTS.get(parts.scheme)
64
+ except ValueError as exc:
65
+ raise BadNetworkError(f"server={server!r} has a port that is not a number.") from exc
66
+ if not host or not port:
67
+ raise BadNetworkError(
68
+ f"server={server!r} names no host and port. Give a URL such as "
69
+ "'http://localhost:3000', a 'host:port' pair or a (host, port) tuple.")
70
+ return host, int(port)
71
+
72
+
73
+ def servers(server: object) -> list[tuple[str, int]]:
74
+ """Every ``(host, port)`` that ``server=`` names: one, or a list of them."""
75
+ if isinstance(server, list):
76
+ if not server:
77
+ raise BadNetworkError("server=[] names no server.")
78
+ return [server_address(one) for one in server]
79
+ return [server_address(server)]
80
+
81
+
82
+ def server_ips(host: str, port: int, *, resolve=socket.getaddrinfo) -> list[str]:
83
+ """Every address the host has, IPv4 and IPv6, in the order the system gives them."""
84
+ try:
85
+ infos = resolve(host, port, proto=socket.IPPROTO_TCP)
86
+ except OSError as exc:
87
+ raise BadNetworkError(f"server host {host!r} has no address: {exc}") from exc
88
+ out: list[str] = []
89
+ for info in infos:
90
+ address = str(info[4][0]).split("%")[0] # an IPv6 zone is not part of the aim
91
+ if address not in out:
92
+ out.append(address)
93
+ if not out:
94
+ raise BadNetworkError(f"server host {host!r} has no address.")
95
+ return out
96
+
97
+
98
+ def _running_child(process: object) -> int | None:
99
+ """The PID of a process object this test started, while it runs; None for anything else.
100
+
101
+ An object and not a number: a number may name any process of the machine (PID 1 on
102
+ Linux, whose tree is every process), or one that took over the number of a process
103
+ that ended.
104
+ """
105
+ import asyncio.subprocess
106
+ import subprocess
107
+ if isinstance(process, subprocess.Popen):
108
+ running = process.poll() is None
109
+ elif isinstance(process, asyncio.subprocess.Process):
110
+ running = process.returncode is None
111
+ else:
112
+ return None
113
+ if not running:
114
+ raise BadNetworkError(f"process={process!r} has already ended, so there is nothing of "
115
+ "it to slow, and its number may belong to another process now.")
116
+ return int(process.pid)
117
+
118
+
119
+ def _process(process: object) -> str:
120
+ if isinstance(process, str) and process == "self":
121
+ return str(os.getpid())
122
+ pid = _running_child(process)
123
+ if pid is None:
124
+ raise BadNetworkError(
125
+ f"process={process!r}: give 'self' (this test and everything it started), or the "
126
+ "process object your test started, such as a subprocess.Popen (process=proc, not "
127
+ "proc.pid). For a process ID or a program name, use target=, the program's own "
128
+ "aim: a name there matches every program whose name contains it, and a process ID "
129
+ "covers every process it started.")
130
+ return str(pid)
131
+
132
+
133
+ def _value(value: object) -> str:
134
+ if isinstance(value, (list, tuple, set, frozenset)):
135
+ return ",".join(str(v) for v in value)
136
+ return str(value)
137
+
138
+
139
+ def _given(value: object) -> bool:
140
+ return value is not None and value is not False and value != ""
141
+
142
+
143
+ def _shipped(path: str, folders: Sequence[str]) -> str | None:
144
+ """The file a scenario name the program ships stands for, as the program finds it."""
145
+ if os.path.isabs(path):
146
+ return None
147
+ parts = os.path.normpath(path).replace("\\", "/").split("/")
148
+ if tuple(os.path.normcase(part) for part in parts[:-1]) not in _SHIPPED_FOLDERS:
149
+ return None
150
+ for folder in folders:
151
+ candidate = os.path.join(folder, parts[-1])
152
+ if os.path.isfile(candidate):
153
+ return candidate
154
+ return None
155
+
156
+
157
+ def checked_scenario(path: object, aim_keys: frozenset[str], shipped: Sequence[str]) -> str:
158
+ """The scenario's file as an absolute path, once no step of it changes ``aim_keys``.
159
+
160
+ The program is handed this path, so it reads the file that was checked. A file this
161
+ cannot read is refused here: the program could not read it either.
162
+ """
163
+ given = os.fspath(path) if isinstance(path, os.PathLike) else str(path)
164
+ found = given if os.path.isfile(given) else _shipped(given, shipped)
165
+ if found is None:
166
+ raise BadNetworkError(f"scenario={given!r}: there is no such file. A scenario the "
167
+ "program ships is named 'scenarios/<file>.json'.")
168
+ try:
169
+ with open(found, encoding="utf-8-sig") as handle:
170
+ data = json.load(handle)
171
+ except (OSError, ValueError, RecursionError) as exc: # RecursionError: nesting too deep
172
+ raise BadNetworkError(f"scenario={given!r} could not be read as JSON: {exc}") from exc
173
+ steps = data.get("steps") if isinstance(data, dict) else data
174
+ if not isinstance(steps, list):
175
+ raise BadNetworkError(f"scenario={given!r} is not a scenario: it has no list of steps.")
176
+ for number, step in enumerate(steps, 1):
177
+ settings = step.get("settings") if isinstance(step, dict) else None
178
+ if not isinstance(settings, dict):
179
+ continue
180
+ changed = sorted(key for key in settings if key in aim_keys)
181
+ if changed:
182
+ raise BadNetworkError(
183
+ f"scenario={given!r}: step {number} changes {', '.join(changed)}, which is "
184
+ "what this session aims at. A scenario may change how the network behaves, "
185
+ "not what the session aims at, or it could widen it to the whole machine. "
186
+ + _SCENARIO_ADVICE.get(aim_keys, "Take those settings out of the scenario."))
187
+ return os.path.abspath(found)
188
+
189
+
190
+ def session_flags(*, server: object = None, process: object = None, simulate: bool = False,
191
+ settings: Mapping[str, object], resolve=socket.getaddrinfo,
192
+ shipped_scenarios: Sequence[str] = ()) -> list[str]:
193
+ """The program's flags for one session, without the ones the session adds itself."""
194
+ for key in settings:
195
+ if not _KEY.match(key):
196
+ raise BadNetworkError(f"{key!r} is not a setting name. Settings are the program's "
197
+ "flags with _ for -, such as latency or loss_burst.")
198
+ if key in RESERVED:
199
+ raise BadNetworkError(f"{key} is set by beannetworktester itself and cannot be "
200
+ "passed as a setting.")
201
+ for key in AIM_KEYS:
202
+ value = settings.get(key)
203
+ # An empty aim reaches the program as an empty flag, which aims at nothing in
204
+ # particular: every connection of the machine, or, after server=, every address.
205
+ if value is None or isinstance(value, bool):
206
+ continue
207
+ if not _value(value).replace(",", "").strip():
208
+ raise BadNetworkError(
209
+ f"{key}={value!r} names nothing, and an empty aim would reach every connection "
210
+ f"of this machine. Give an address, a port or a name, or leave {key} out.")
211
+ aims = [key for key in AIM_KEYS if _given(settings.get(key))]
212
+ if server is None and process is None and not aims and not simulate:
213
+ raise BadNetworkError(
214
+ "bad_network needs an aim: server= (a URL, 'host:port', or a list of them), "
215
+ "process= ('self', or a process your test started), or one of the program's own "
216
+ "target=, dst_ip=, dst_port=. Without one it would slow every connection of this "
217
+ "machine, the test runner's own included.")
218
+ flags: list[str] = []
219
+ aim_keys: frozenset[str] = frozenset()
220
+ if server is not None:
221
+ if SERVER_KEYS & set(aims):
222
+ raise BadNetworkError("server= sets dst_ip and dst_port: give one or the other.")
223
+ # Several servers are every address of them with every port of them: the
224
+ # program's two aim flags are matched apart, not as pairs.
225
+ ips: list[str] = []
226
+ ports: list[str] = []
227
+ for host, port in servers(server):
228
+ ips += [ip for ip in server_ips(host, port, resolve=resolve) if ip not in ips]
229
+ if str(port) not in ports:
230
+ ports.append(str(port))
231
+ flags += ["--dst-ip", ",".join(ips), "--dst-port", ",".join(ports)]
232
+ aim_keys |= SERVER_KEYS
233
+ if process is not None:
234
+ if "target" in aims:
235
+ raise BadNetworkError("process= sets target: give one or the other.")
236
+ flags += ["--target", _process(process)]
237
+ aim_keys |= PROCESS_KEYS
238
+ for key, value in settings.items():
239
+ if value is None or value is False:
240
+ continue
241
+ if key == "scenario":
242
+ value = checked_scenario(value, aim_keys, shipped_scenarios)
243
+ flag = "--" + key.replace("_", "-")
244
+ flags += [flag] if value is True else [flag, _value(value)]
245
+ return flags
@@ -0,0 +1,135 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+
5
+ """One session at a time.
6
+
7
+ Two sessions that see the same traffic add up: two of 100 ms each slowed a server
8
+ by 200 ms (measured 2026-11-25). Parallel test workers would then slow each other's
9
+ tests, so a session takes this lock for as long as it runs, and a second one waits.
10
+ The system drops the lock when the process that holds it ends, however it ends.
11
+
12
+ The file is in /tmp on Linux, the machine's own and not $TMPDIR, so every user and
13
+ every environment shares the lock. On Windows it is in the user's temporary folder.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import errno
19
+ import os
20
+ import stat
21
+ import sys
22
+ import tempfile
23
+ import time
24
+
25
+ from ._program import BadNetworkError
26
+
27
+ LOCK_NAME = "beannetworktester.lock"
28
+
29
+ # Never a link or a FIFO: on Linux the path is the same for every user of the machine,
30
+ # a link planted there would point the lock at another file, and a FIFO would block the
31
+ # open. Windows has neither flag, and the folder there is the user's own.
32
+ _SAFE = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
33
+
34
+
35
+ def lock_path() -> str:
36
+ folder = tempfile.gettempdir() if sys.platform == "win32" else "/tmp" # noqa: S108
37
+ return os.path.join(folder, LOCK_NAME)
38
+
39
+
40
+ def _not_a_lock(path: str) -> BadNetworkError:
41
+ return BadNetworkError(f"{path} is not a plain file, so it is not a lock this package "
42
+ "made. Remove it, and run the tests again.")
43
+
44
+
45
+ def _open(path: str):
46
+ """The lock file, opened for reading when it is there, and made when it is not.
47
+
48
+ For reading, because the file may be another user's: a test run under sudo leaves
49
+ one owned by root, which this user may lock but not write, and which Linux does not
50
+ let a create-or-open in /tmp touch at all. Both locks work on a file open for reading.
51
+ """
52
+ mode = "rb"
53
+ try:
54
+ fd = os.open(path, os.O_RDONLY | _SAFE)
55
+ except FileNotFoundError:
56
+ mode = "r+b"
57
+ # Readable by every user on purpose: a session of another user, or one under sudo,
58
+ # opens this file to wait on it. It holds nothing, and only its maker may write it.
59
+ try:
60
+ fd = os.open(path, os.O_RDWR | os.O_CREAT | _SAFE, 0o644)
61
+ except OSError as exc:
62
+ if exc.errno == errno.ELOOP:
63
+ raise _not_a_lock(path) from exc
64
+ raise BadNetworkError(f"The lock file {path} cannot be made: {exc}") from exc
65
+ except OSError as exc:
66
+ if exc.errno == errno.ELOOP:
67
+ raise _not_a_lock(path) from exc
68
+ raise BadNetworkError(f"The lock file {path} cannot be opened: {exc}") from exc
69
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
70
+ os.close(fd)
71
+ raise _not_a_lock(path)
72
+ return os.fdopen(fd, mode)
73
+
74
+
75
+ def _try_lock(handle) -> bool:
76
+ if sys.platform == "win32":
77
+ import msvcrt
78
+ handle.seek(0)
79
+ try:
80
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
81
+ except OSError:
82
+ return False
83
+ return True
84
+ import fcntl
85
+ try:
86
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
87
+ except OSError:
88
+ return False
89
+ return True
90
+
91
+
92
+ def _unlock(handle) -> None:
93
+ if sys.platform == "win32":
94
+ import msvcrt
95
+ handle.seek(0)
96
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
97
+ else:
98
+ import fcntl
99
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
100
+
101
+
102
+ class MachineLock:
103
+ """Held from a session's start to its stop. ``path`` is for the tests."""
104
+
105
+ def __init__(self, path: str | None = None):
106
+ self.path = lock_path() if path is None else path
107
+ self._handle = None
108
+
109
+ def acquire(self, wait: float, *, sleep=time.sleep, clock=time.monotonic) -> None:
110
+ handle = _open(self.path)
111
+ deadline = clock() + max(0.0, wait)
112
+ while not _try_lock(handle):
113
+ if clock() >= deadline:
114
+ handle.close()
115
+ raise BadNetworkError(
116
+ f"Another bad_network session has been running on this machine for the "
117
+ f"{wait:g} s this one waited. Sessions run one at a time, because two would "
118
+ "add up: with parallel test workers (pytest-xdist, Playwright workers), the "
119
+ "tests that slow the network wait for each other. Give a longer wait=, or "
120
+ "run those tests in one worker.")
121
+ sleep(0.2)
122
+ self._handle = handle
123
+
124
+ def release(self) -> None:
125
+ handle, self._handle = self._handle, None
126
+ if handle is None:
127
+ return
128
+ try:
129
+ _unlock(handle)
130
+ finally:
131
+ handle.close()
132
+
133
+ @property
134
+ def held(self) -> bool:
135
+ return self._handle is not None
@@ -0,0 +1,134 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+
5
+ """Which program a session runs, and with what rights.
6
+
7
+ The wheel for Windows x64 and the one for Linux x64 carry the release's own program,
8
+ unchanged, in ``program/BeanNetworkTester``: on Windows that is the signed exe. The
9
+ wheel for every other system carries none, and says so when a session starts.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ from collections.abc import Mapping
19
+
20
+ # Set it to run another copy of the program: an installed BeanNetworkTester, or
21
+ # bean_network_tester.py from a checkout (a .py file runs with this Python). PATH is
22
+ # never searched - a different copy found there would be a different version, with
23
+ # other flags, and nothing would say so.
24
+ PROGRAM_ENV = "BEANNETWORKTESTER_PROGRAM"
25
+ SYSTEMS = ("Windows x64", "Linux x64")
26
+
27
+ _HERE = os.path.dirname(os.path.abspath(__file__))
28
+ _NAMES = {"win32": "BeanNetworkTester.exe", "linux": "BeanNetworkTester"}
29
+
30
+
31
+ class BadNetworkError(RuntimeError):
32
+ """A session could not start, or could not stop the way it should."""
33
+
34
+
35
+ def _system(platform: str) -> str:
36
+ return "linux" if platform.startswith("linux") else platform
37
+
38
+
39
+ def _sixty_four_bit_x86(machine: str) -> bool:
40
+ return machine.lower() in ("amd64", "x86_64")
41
+
42
+
43
+ def program_command(*, env: Mapping[str, str] | None = None, platform: str | None = None,
44
+ machine: str | None = None, here: str | None = None) -> list[str]:
45
+ """The command that starts the program, before its flags.
46
+
47
+ Everything is passed in, so the tests can ask about a system they are not on.
48
+ """
49
+ env = os.environ if env is None else env
50
+ given = env.get(PROGRAM_ENV)
51
+ if given:
52
+ if not os.path.isfile(given):
53
+ raise BadNetworkError(f"{PROGRAM_ENV} is set to {given}, and there is no file there. "
54
+ "Point it at the program, or unset it to use the one this "
55
+ "package installs.")
56
+ return [sys.executable, given] if given.endswith(".py") else [given]
57
+ system = _system(sys.platform if platform is None else platform)
58
+ if machine is None:
59
+ import platform as _platform
60
+ machine = _platform.machine()
61
+ here = _HERE if here is None else here
62
+ name = _NAMES.get(system)
63
+ if name is None or not _sixty_four_bit_x86(machine):
64
+ raise BadNetworkError(
65
+ f"beannetworktester runs the network on Windows x64 and Linux x64 only, and this is "
66
+ f"{system} {machine}. On a Mac, run the tests in a Linux x86_64 container or virtual "
67
+ f"machine, or on a CI runner with Windows or Linux.")
68
+ found = os.path.join(here, "program", "BeanNetworkTester", name)
69
+ if os.path.isfile(found):
70
+ return [found]
71
+ if not os.path.isdir(os.path.join(here, "program")):
72
+ raise BadNetworkError(
73
+ "This install of beannetworktester has no program in it: pip took the wheel without "
74
+ "one, which happens with a 32-bit Python or with an old pip that does not know the "
75
+ "wheel's platform tag. Install it with a 64-bit Python and a current pip, or set "
76
+ f"{PROGRAM_ENV} to the path of BeanNetworkTester.")
77
+ raise BadNetworkError(
78
+ f"The program of this install is not at {found}, where the package puts it: something "
79
+ "removed it. Run pip install --force-reinstall beannetworktester, or set "
80
+ f"{PROGRAM_ENV} to the path of BeanNetworkTester.")
81
+
82
+
83
+ def shipped_scenarios(command: list[str]) -> list[str]:
84
+ """The folders the program keeps the scenarios it ships in: built, or a checkout."""
85
+ folder = os.path.dirname(os.path.abspath(command[-1]))
86
+ return [os.path.join(folder, "_internal", "scenarios"), os.path.join(folder, "scenarios")]
87
+
88
+
89
+ def _is_admin() -> bool:
90
+ import ctypes
91
+ try:
92
+ return bool(ctypes.windll.shell32.IsUserAnAdmin()) # type: ignore[attr-defined]
93
+ except (AttributeError, OSError):
94
+ return False
95
+
96
+
97
+ def _sudo_works() -> bool:
98
+ if shutil.which("sudo") is None:
99
+ return False
100
+ try:
101
+ done = subprocess.run(["sudo", "-n", "true"], stdin=subprocess.DEVNULL, # noqa: S603, S607
102
+ capture_output=True, timeout=30)
103
+ except (OSError, subprocess.SubprocessError):
104
+ return False
105
+ return done.returncode == 0
106
+
107
+
108
+ def rights_prefix(*, simulate: bool, platform: str | None = None) -> list[str]:
109
+ """What goes in front of the program so that it may capture: ``[]`` or sudo.
110
+
111
+ A real capture needs administrator rights on Windows and root on Linux. Asked
112
+ here, before anything starts, so a test fails with a sentence that says what to
113
+ do, instead of with an exit code. ``simulate`` needs no rights at all.
114
+ """
115
+ if simulate:
116
+ return []
117
+ system = _system(sys.platform if platform is None else platform)
118
+ if system == "win32":
119
+ if _is_admin():
120
+ return []
121
+ raise BadNetworkError(
122
+ "Slowing the network needs administrator rights on Windows. Run the tests from a "
123
+ "terminal opened with Run as administrator. GitHub's Windows runners already run "
124
+ "elevated.")
125
+ if system == "linux":
126
+ if hasattr(os, "geteuid") and os.geteuid() == 0:
127
+ return []
128
+ if _sudo_works():
129
+ return ["sudo", "-n"]
130
+ raise BadNetworkError(
131
+ "Slowing the network needs root on Linux. Run the tests as root, or as a user who "
132
+ "may run sudo without a password, as on GitHub's Ubuntu runners. The program runs "
133
+ "under sudo, and the tests themselves do not.")
134
+ raise BadNetworkError(f"beannetworktester runs the network on {' and '.join(SYSTEMS)} only.")