|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Tests that the CLI reads and writes text files as UTF-8. |
| 16 | +
|
| 17 | +`open()` without an explicit `encoding` uses the platform's locale encoding, |
| 18 | +which is not UTF-8 on a large share of Windows installs (`cp936` for zh-CN, |
| 19 | +`cp932` for ja-JP, `cp1252` for much of the West). The CLI's JSON and Markdown |
| 20 | +files carry agent prompts, model responses and display names, so they routinely |
| 21 | +hold non-ASCII text -- and JSON is defined as UTF-8 for interchange (RFC 8259 |
| 22 | +§8.1). Reading those files under a non-UTF-8 locale either raises |
| 23 | +`UnicodeDecodeError` or, when the UTF-8 bytes happen to form a valid sequence in |
| 24 | +the locale codec, silently yields mojibake. |
| 25 | +
|
| 26 | +CI runs on a UTF-8 default, so a test that merely reads a UTF-8 file cannot |
| 27 | +catch a missing `encoding=`. `_non_utf8_default_locale` therefore simulates the |
| 28 | +locale by forcing a non-UTF-8 codec onto every `open()` call that omits |
| 29 | +`encoding`, which makes these tests fail on any platform if the argument is |
| 30 | +dropped again. |
| 31 | +""" |
| 32 | + |
| 33 | +from __future__ import annotations |
| 34 | + |
| 35 | +import ast |
| 36 | +import builtins |
| 37 | +import contextlib |
| 38 | +import pathlib |
| 39 | +from typing import Iterator |
| 40 | + |
| 41 | +import google.adk.cli as adk_cli |
| 42 | +from google.adk.cli.cli_deploy import _get_ignore_patterns_func |
| 43 | +import pytest |
| 44 | + |
| 45 | +_NON_ASCII = "北京天气-café-🌤" |
| 46 | + |
| 47 | + |
| 48 | +@contextlib.contextmanager |
| 49 | +def _non_utf8_default_locale(codec: str = "ascii") -> Iterator[None]: |
| 50 | + """Forces `codec` onto text-mode `open()` calls that omit `encoding`. |
| 51 | +
|
| 52 | + Patching `locale.getpreferredencoding` does not work: CPython resolves the |
| 53 | + default text encoding internally, so `open()` ignores it. Wrapping |
| 54 | + `builtins.open` is what actually reproduces a non-UTF-8 locale on a UTF-8 CI |
| 55 | + machine. |
| 56 | +
|
| 57 | + `ascii` is the default because it rejects every non-ASCII byte, so a missing |
| 58 | + `encoding=` fails deterministically. A real locale codec is laxer: cp936 |
| 59 | + accepts most UTF-8 byte pairs and yields mojibake instead of raising, which |
| 60 | + `test_locale_codec_can_corrupt_silently` covers separately. |
| 61 | + """ |
| 62 | + real_open = builtins.open |
| 63 | + |
| 64 | + def patched_open( # pylint: disable=redefined-builtin |
| 65 | + file, mode="r", buffering=-1, encoding=None, *args, **kwargs |
| 66 | + ): |
| 67 | + if "b" not in mode and encoding is None: |
| 68 | + encoding = codec |
| 69 | + return real_open(file, mode, buffering, encoding, *args, **kwargs) |
| 70 | + |
| 71 | + builtins.open = patched_open |
| 72 | + try: |
| 73 | + yield |
| 74 | + finally: |
| 75 | + builtins.open = real_open |
| 76 | + |
| 77 | + |
| 78 | +def test_non_utf8_default_locale_helper_actually_bites(tmp_path): |
| 79 | + """Guards the guard: the helper must really change `open()`'s behavior.""" |
| 80 | + path = tmp_path / "probe.txt" |
| 81 | + path.write_text(_NON_ASCII, encoding="utf-8") |
| 82 | + |
| 83 | + with _non_utf8_default_locale(): |
| 84 | + with pytest.raises(UnicodeDecodeError): |
| 85 | + with open(path) as f: # no encoding= -> forced cp936 |
| 86 | + f.read() |
| 87 | + |
| 88 | + # An explicit encoding still wins over the simulated locale. |
| 89 | + with open(path, encoding="utf-8") as f: |
| 90 | + assert f.read() == _NON_ASCII |
| 91 | + |
| 92 | + |
| 93 | +def test_locale_codec_can_corrupt_silently(tmp_path): |
| 94 | + """Documents the quieter failure mode: no exception, wrong text. |
| 95 | +
|
| 96 | + cp936 decodes most UTF-8 byte pairs without complaint, so a missing |
| 97 | + `encoding=` on a zh-CN Windows box can persist mojibake into an eval set |
| 98 | + instead of raising. |
| 99 | + """ |
| 100 | + path = tmp_path / "probe.txt" |
| 101 | + path.write_text(_NON_ASCII, encoding="utf-8") |
| 102 | + |
| 103 | + with _non_utf8_default_locale("cp936"): |
| 104 | + with open(path) as f: |
| 105 | + decoded = f.read() |
| 106 | + |
| 107 | + assert decoded != _NON_ASCII # silently wrong, and no error was raised |
| 108 | + |
| 109 | + |
| 110 | +def test_get_ignore_patterns_reads_utf8_ignore_file(tmp_path): |
| 111 | + """`.gitignore` entries with non-ASCII names survive a non-UTF-8 locale.""" |
| 112 | + (tmp_path / ".gitignore").write_text( |
| 113 | + f"# comment\n{_NON_ASCII}/\n__pycache__\n", encoding="utf-8" |
| 114 | + ) |
| 115 | + |
| 116 | + with _non_utf8_default_locale(): |
| 117 | + ignore_func = _get_ignore_patterns_func(str(tmp_path)) |
| 118 | + |
| 119 | + patterns = ignore_func(str(tmp_path), [f"{_NON_ASCII}", "__pycache__"]) |
| 120 | + assert _NON_ASCII in patterns |
| 121 | + assert "__pycache__" in patterns |
| 122 | + |
| 123 | + |
| 124 | +def _text_mode_open_calls_without_encoding(root: pathlib.Path) -> list[str]: |
| 125 | + """Returns `file:line` for each text-mode `open()` that omits `encoding`.""" |
| 126 | + offenders = [] |
| 127 | + for path in sorted(root.rglob("*.py")): |
| 128 | + tree = ast.parse(path.read_text(encoding="utf-8")) |
| 129 | + for node in ast.walk(tree): |
| 130 | + # Bare `open(...)` only: `ZipFile.open`/`z.open` are binary and take no |
| 131 | + # `encoding`, and `os.fdopen` sites here are binary too. |
| 132 | + if ( |
| 133 | + not isinstance(node, ast.Call) |
| 134 | + or getattr(node.func, "id", None) != "open" |
| 135 | + ): |
| 136 | + continue |
| 137 | + if any(kw.arg == "encoding" for kw in node.keywords): |
| 138 | + continue |
| 139 | + mode = "r" |
| 140 | + if len(node.args) >= 2 and isinstance(node.args[1], ast.Constant): |
| 141 | + mode = node.args[1].value |
| 142 | + for kw in node.keywords: |
| 143 | + if kw.arg == "mode" and isinstance(kw.value, ast.Constant): |
| 144 | + mode = kw.value.value |
| 145 | + if isinstance(mode, str) and "b" not in mode: |
| 146 | + offenders.append(f"{path}:{node.lineno}") |
| 147 | + return offenders |
| 148 | + |
| 149 | + |
| 150 | +def test_cli_package_has_no_implicit_encoding_open(): |
| 151 | + """Every text-mode `open()` under `cli/` must pass `encoding` explicitly. |
| 152 | +
|
| 153 | + Ensures all text file operations across the CLI package use an explicit |
| 154 | + encoding rather than relying on the host platform's default locale. |
| 155 | + """ |
| 156 | + root = pathlib.Path(adk_cli.__file__).parent |
| 157 | + offenders = _text_mode_open_calls_without_encoding(root) |
| 158 | + assert not offenders, ( |
| 159 | + "text-mode open() without encoding= (locale-dependent, breaks on" |
| 160 | + f" non-UTF-8 locales): {offenders}" |
| 161 | + ) |
0 commit comments