Debian Codegraph @

tests/test_idna_cli.py

raw
1 import io
2 import subprocess
3 import sys
4 import unittest
5 from contextlib import contextmanager, redirect_stderr, redirect_stdout
6 from unittest import mock
7
8 from idna import cli, unicode_version
9 from idna.package_data import __version__
10
11
12 def run_cli(*argv, stdin=None):
13 """Invoke ``cli.main`` with ``argv`` and capture (rc, stdout, stderr).
14
15 Pass ``stdin`` as a string to simulate a piped stdin; omit it to
16 simulate an interactive terminal.
17 """
18 out = io.StringIO()
19 err = io.StringIO()
20 with redirect_stdout(out), redirect_stderr(err), _patched_stdin(stdin):
21 rc = cli.main(list(argv))
22 return rc, out.getvalue(), err.getvalue()
23
24
25 class _FakeStdin(io.StringIO):
26 """``io.StringIO`` with a configurable ``isatty`` result."""
27
28 def __init__(self, data: str, is_tty: bool) -> None:
29 super().__init__(data)
30 self._is_tty = is_tty
31
32 def isatty(self) -> bool:
33 return self._is_tty
34
35
36 @contextmanager
37 def _patched_stdin(data):
38 """Replace ``sys.stdin`` with a fake stream and isatty() result."""
39 stream = _FakeStdin("" if data is None else data, is_tty=data is None)
40 with mock.patch.object(sys, "stdin", stream):
41 yield
42
43
44 class CLIAutoDetectTests(unittest.TestCase):
45 def test_autodetect_encodes_unicode_input(self):
46 rc, out, err = run_cli("пример.рф")
47 self.assertEqual(rc, 0)
48 self.assertEqual(out.strip(), "xn--e1afmkfd.xn--p1ai")
49 self.assertEqual(err, "")
50
51 def test_autodetect_decodes_alabel(self):
52 rc, out, _ = run_cli("xn--e1afmkfd.xn--p1ai")
53 self.assertEqual(rc, 0)
54 self.assertEqual(out.strip(), "пример.рф")
55
56 def test_autodetect_decodes_when_any_label_is_alabel(self):
57 # Mixed label: at least one xn-- label triggers decode mode.
58 rc, out, _ = run_cli("xn--11b5bs3a9aj6g.example")
59 self.assertEqual(rc, 0)
60 self.assertEqual(out.strip(), "परीक्षा.example")
61
62 def test_autodetect_encodes_plain_ascii_input(self):
63 rc, out, _ = run_cli("example.com")
64 self.assertEqual(rc, 0)
65 self.assertEqual(out.strip(), "example.com")
66
67 def test_looks_like_alabel_is_case_insensitive(self):
68 self.assertTrue(cli._looks_like_alabel("XN--ZCKZAH"))
69 self.assertTrue(cli._looks_like_alabel("foo.Xn--ZcKzAh"))
70 self.assertFalse(cli._looks_like_alabel("example.com"))
71 self.assertFalse(cli._looks_like_alabel("xnfoo.example"))
72
73 def test_looks_like_alabel_handles_unicode_dots(self):
74 # IDEOGRAPHIC FULL STOP should split labels for the purpose of
75 # spotting an A-label, matching the behavior of idna.encode/decode.
76 self.assertTrue(cli._looks_like_alabel("foo。xn--zckzah"))
77
78
79 class CLIExplicitModeTests(unittest.TestCase):
80 def test_encode_flag_forces_encode(self):
81 rc, out, _ = run_cli("-e", "παράδειγμα")
82 self.assertEqual(rc, 0)
83 self.assertEqual(out.strip(), "xn--hxajbheg2az3al")
84
85 def test_long_encode_flag_forces_encode(self):
86 rc, out, _ = run_cli("--encode", "한국")
87 self.assertEqual(rc, 0)
88 self.assertEqual(out.strip(), "xn--3e0b707e")
89
90 def test_decode_flag_forces_decode(self):
91 rc, out, _ = run_cli("-d", "xn--hxajbheg2az3al")
92 self.assertEqual(rc, 0)
93 self.assertEqual(out.strip(), "παράδειγμα")
94
95 def test_long_decode_flag_forces_decode(self):
96 rc, out, _ = run_cli("--decode", "xn--3e0b707e")
97 self.assertEqual(rc, 0)
98 self.assertEqual(out.strip(), "한국")
99
100 def test_encode_and_decode_are_mutually_exclusive(self):
101 # argparse exits via SystemExit (code 2) for mutually-exclusive errors.
102 with self.assertRaises(SystemExit) as ctx, redirect_stderr(io.StringIO()):
103 cli.main(["-e", "-d", "example.com"])
104 self.assertEqual(ctx.exception.code, 2)
105
106
107 class CLIUTS46Tests(unittest.TestCase):
108 def test_uts46_is_applied_by_default(self):
109 # Uppercase Greek is not PVALID under IDNA 2008 alone; UTS #46
110 # case-folds it so encoding succeeds.
111 rc, out, _ = run_cli("ΠΑΡΆΔΕΙΓΜΑ.ΕΛ")
112 self.assertEqual(rc, 0)
113 self.assertEqual(out.strip(), "xn--hxajbheg2az3al.xn--qxam")
114
115 def test_strict_disables_uts46(self):
116 rc, out, err = run_cli("--strict", "ΠΑΡΆΔΕΙΓΜΑ.ΕΛ")
117 self.assertEqual(rc, 1)
118 self.assertEqual(out, "")
119 self.assertIn("encode failed", err)
120 self.assertIn("U+03A0", err)
121
122 def test_strict_does_not_affect_valid_inputs(self):
123 rc, out, _ = run_cli("--strict", "пример.рф")
124 self.assertEqual(rc, 0)
125 self.assertEqual(out.strip(), "xn--e1afmkfd.xn--p1ai")
126
127 def test_uts46_applies_to_explicit_decode(self):
128 # Trailing FULLWIDTH FULL STOP (U+FF0E) is mapped to "." by UTS #46
129 # so the input still decodes as a single A-label.
130 rc, out, _ = run_cli("-d", "xn--zckzah.")
131 self.assertEqual(rc, 0)
132 self.assertEqual(out.strip(), "テスト.")
133
134
135 class CLIErrorHandlingTests(unittest.TestCase):
136 def test_invalid_input_returns_nonzero_and_writes_to_stderr(self):
137 rc, out, err = run_cli("foo_bar")
138 self.assertEqual(rc, 1)
139 self.assertEqual(out, "")
140 self.assertTrue(err.startswith("idna: encode failed for 'foo_bar':"))
141
142 def test_invalid_alabel_decode_returns_nonzero(self):
143 # Trailing hyphen after the xn-- prefix is rejected by ulabel().
144 rc, out, err = run_cli("-d", "xn--")
145 self.assertEqual(rc, 1)
146 self.assertEqual(out, "")
147 self.assertIn("decode failed", err)
148
149 def test_missing_argument_with_tty_stdin_is_an_argparse_error(self):
150 # Interactive shell (no piped stdin) and no domain arg → argparse exits 2.
151 with self.assertRaises(SystemExit) as ctx, redirect_stderr(io.StringIO()), _patched_stdin(None):
152 cli.main([])
153 self.assertEqual(ctx.exception.code, 2)
154
155
156 class CLIVersionTests(unittest.TestCase):
157 def test_version_flag(self):
158 buf = io.StringIO()
159 with self.assertRaises(SystemExit) as ctx, redirect_stdout(buf):
160 cli.main(["--version"])
161 self.assertEqual(ctx.exception.code, 0)
162 self.assertIn(__version__, buf.getvalue())
163 self.assertIn(f"Unicode {unicode_version}", buf.getvalue())
164
165
166 class CLIMultipleDomainsTests(unittest.TestCase):
167 def test_multiple_unicode_positional_domains_are_all_encoded(self):
168 rc, out, _ = run_cli("пример.рф", "παράδειγμα", "한국")
169 self.assertEqual(rc, 0)
170 self.assertEqual(
171 out.splitlines(),
172 ["xn--e1afmkfd.xn--p1ai", "xn--hxajbheg2az3al", "xn--3e0b707e"],
173 )
174
175 def test_multiple_alabel_positional_domains_are_all_decoded(self):
176 rc, out, _ = run_cli("xn--e1afmkfd.xn--p1ai", "xn--hxajbheg2az3al", "xn--3e0b707e")
177 self.assertEqual(rc, 0)
178 self.assertEqual(out.splitlines(), ["пример.рф", "παράδειγμα", "한국"])
179
180 def test_mode_flag_applies_to_every_positional_domain(self):
181 rc, out, _ = run_cli("-e", "한국", "παράδειγμα")
182 self.assertEqual(rc, 0)
183 self.assertEqual(
184 out.splitlines(),
185 ["xn--3e0b707e", "xn--hxajbheg2az3al"],
186 )
187
188 def test_failures_are_reported_per_domain_and_processing_continues(self):
189 rc, out, err = run_cli("пример.рф", "foo_bar", "παράδειγμα")
190 self.assertEqual(rc, 1)
191 self.assertEqual(
192 out.splitlines(),
193 ["xn--e1afmkfd.xn--p1ai", "xn--hxajbheg2az3al"],
194 )
195 self.assertIn("encode failed for 'foo_bar'", err)
196
197
198 class CLIModeLockTests(unittest.TestCase):
199 """The first input picks the mode; the rest of the stream follows."""
200
201 def test_first_unicode_input_locks_subsequent_inputs_to_encode(self):
202 # 'foo_bar' is invalid in either direction; the stderr mode word
203 # reveals which mode the second input was processed in.
204 rc, out, err = run_cli("пример.рф", "foo_bar")
205 self.assertEqual(rc, 1)
206 self.assertEqual(out.splitlines(), ["xn--e1afmkfd.xn--p1ai"])
207 self.assertIn("encode failed for 'foo_bar'", err)
208
209 def test_first_alabel_input_locks_subsequent_inputs_to_decode(self):
210 rc, out, err = run_cli("xn--zckzah", "foo_bar")
211 self.assertEqual(rc, 1)
212 self.assertEqual(out.splitlines(), ["テスト"])
213 self.assertIn("decode failed for 'foo_bar'", err)
214
215 def test_explicit_mode_flag_overrides_first_input_heuristic(self):
216 # First input looks like an A-label but -e forces encode for everything.
217 rc, out, err = run_cli("-e", "xn--zckzah", "foo_bar")
218 self.assertEqual(rc, 1)
219 self.assertEqual(out.splitlines(), ["xn--zckzah"])
220 self.assertIn("encode failed for 'foo_bar'", err)
221
222 def test_stdin_first_line_locks_mode_for_the_stream(self):
223 rc, out, err = run_cli(stdin="xn--zckzah\nfoo_bar\n")
224 self.assertEqual(rc, 1)
225 self.assertEqual(out.splitlines(), ["テスト"])
226 self.assertIn("decode failed for 'foo_bar'", err)
227
228
229 class CLIStdinTests(unittest.TestCase):
230 def test_reads_one_domain_per_line_from_piped_stdin(self):
231 rc, out, _ = run_cli(stdin="пример.рф\nπαράδειγμα\n한국\n")
232 self.assertEqual(rc, 0)
233 self.assertEqual(
234 out.splitlines(),
235 ["xn--e1afmkfd.xn--p1ai", "xn--hxajbheg2az3al", "xn--3e0b707e"],
236 )
237
238 def test_blank_lines_in_stdin_are_skipped(self):
239 rc, out, _ = run_cli(stdin="\nпример.рф\n\n \nπαράδειγμα\n")
240 self.assertEqual(rc, 0)
241 self.assertEqual(
242 out.splitlines(),
243 ["xn--e1afmkfd.xn--p1ai", "xn--hxajbheg2az3al"],
244 )
245
246 def test_empty_stdin_exits_cleanly_with_no_output(self):
247 rc, out, err = run_cli(stdin="")
248 self.assertEqual(rc, 0)
249 self.assertEqual(out, "")
250 self.assertEqual(err, "")
251
252 def test_positional_domains_take_precedence_over_piped_stdin(self):
253 rc, out, _ = run_cli("example.com", stdin="ignored.example\n")
254 self.assertEqual(rc, 0)
255 self.assertEqual(out.splitlines(), ["example.com"])
256
257 def test_stdin_errors_continue_processing_and_set_exit_code(self):
258 rc, out, err = run_cli(stdin="пример.рф\nfoo_bar\nπαράδειγμα\n")
259 self.assertEqual(rc, 1)
260 self.assertEqual(
261 out.splitlines(),
262 ["xn--e1afmkfd.xn--p1ai", "xn--hxajbheg2az3al"],
263 )
264 self.assertIn("encode failed for 'foo_bar'", err)
265
266 def test_decode_flag_applies_to_every_stdin_line(self):
267 rc, out, _ = run_cli("-d", stdin="xn--hxajbheg2az3al\nxn--3e0b707e\n")
268 self.assertEqual(rc, 0)
269 self.assertEqual(out.splitlines(), ["παράδειγμα", "한국"])
270
271
272 class CLIModuleEntryTests(unittest.TestCase):
273 def test_python_dash_m_idna_runs_cli(self):
274 # End-to-end: spawn ``python -m idna`` and check the round trip.
275 result = subprocess.run(
276 [sys.executable, "-m", "idna", "xn--zckzah"],
277 check=False,
278 capture_output=True,
279 text=True,
280 )
281 self.assertEqual(result.returncode, 0)
282 self.assertEqual(result.stdout.strip(), "テスト")
283 self.assertEqual(result.stderr, "")
284
285 def test_python_dash_m_idna_reads_piped_stdin(self):
286 # End-to-end: pipe a list of A-labels and confirm they all decode.
287 result = subprocess.run(
288 [sys.executable, "-m", "idna"],
289 input="xn--e1afmkfd.xn--p1ai\nxn--zckzah\n",
290 check=False,
291 capture_output=True,
292 text=True,
293 )
294 self.assertEqual(result.returncode, 0)
295 self.assertEqual(
296 result.stdout.splitlines(),
297 ["пример.рф", "テスト"],
298 )
299 self.assertEqual(result.stderr, "")
300
301 def test_python_dash_m_idna_reports_errors(self):
302 result = subprocess.run(
303 [sys.executable, "-m", "idna", "foo_bar"],
304 check=False,
305 capture_output=True,
306 text=True,
307 )
308 self.assertEqual(result.returncode, 1)
309 self.assertEqual(result.stdout, "")
310 self.assertIn("encode failed", result.stderr)
311
312
313 if __name__ == "__main__":
314 unittest.main()