upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tests/winbatch.py
diff options
context:
space:
mode:
Diffstat (limited to 'tests/winbatch.py')
-rw-r--r--tests/winbatch.py44
1 files changed, 44 insertions, 0 deletions
diff --git a/tests/winbatch.py b/tests/winbatch.py
new file mode 100644
index 000000000..55d302853
--- /dev/null
+++ b/tests/winbatch.py
@@ -0,0 +1,44 @@
1"""Write a one-line Windows batch file (a fake tool for a test) that cmd.exe can run from any user folder.
2
3cmd.exe decodes a batch file with the console's OEM code page, not UTF-8, so a path with non-ASCII letters (a
4user folder named in Cyrillic, say) written as UTF-8 becomes "The system cannot find the path specified".
5Standard library only.
6"""
7
8
9def batch_path(path):
10 """A spelling of path that cmd.exe reads correctly from a batch file: as is when ASCII, else its 8.3 short name
11 (ASCII). Falls back to the long path where the volume has 8.3 names turned off."""
12 if path.isascii():
13 return path
14 import ctypes
15 buf = ctypes.create_unicode_buffer(32768)
16 n = ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf))
17 return buf.value if 0 < n < len(buf) else path
18
19
20def _encodes(char):
21 try:
22 char.encode("oem")
23 return True
24 except UnicodeEncodeError:
25 return False
26
27
28def write_python_cmd(cmd_path, python, script):
29 """Write cmd_path as a batch file that runs `python script` with the batch file's arguments.
30
31 Raises unittest.SkipTest when a path has no 8.3 name and letters outside the OEM code page (Cyrillic on a
32 cp850 machine with 8.3 names off, say): cmd.exe couldn't run such a file in any encoding."""
33 line = f'@"{batch_path(python)}" "{batch_path(script)}" %*\n'
34 try:
35 data = line.encode("oem") # the code page cmd.exe reads a batch file with
36 except UnicodeEncodeError:
37 import unittest
38 # Windows' "oem" codec doesn't report a useful position, so name the letters it can't encode here.
39 letters = "".join(sorted({c for c in line if not _encodes(c)}))
40 raise unittest.SkipTest(f"{letters!r} in a path has no 8.3 name and is outside the OEM code page,"
41 " so cmd.exe can't run a batch file that names it; use an ASCII TEMP") from None
42 with open(cmd_path, "wb") as f:
43 f.write(data)
44 return cmd_path