toolkitx 0.0.1__tar.gz

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.
@@ -0,0 +1,174 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
@@ -0,0 +1 @@
1
+ 3.13
toolkitx-0.0.1/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: toolkitx
3
+ Version: 0.0.1
4
+ Summary: A personal Python toolkit for common tasks
5
+ Project-URL: Homepage, https://github.com/ider-zh/toolkitx
6
+ Project-URL: Bug Tracker, https://github.com/ider-zh/toolkitx/issues
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: diskcache>=5.6.3
10
+ Requires-Dist: py-transgpt>=2.0
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest; extra == 'dev'
13
+ Requires-Dist: pytest-dotenv; extra == 'dev'
14
+ Description-Content-Type: text/markdown
15
+
16
+ # toolkitx
17
+
18
+ A personal Python toolkit for common tasks. This package provides various utility functions to simplify common development workflows.
19
+
20
+ ## Features
21
+
22
+ * **Text Utilities** (`toolkitx.text_utils`):
23
+ * `truncate_text_smart`: Smartly truncates text by characters or words, with options for suffix and tolerance, attempting to preserve sentence or word boundaries.
24
+ * `split_text_by_word_count`: Splits long text into overlapping chunks based on word count.
25
+ * **Command-Line Script**:
26
+ * `hello`: A simple script accessible via `hello` command after installation, prints a greeting message.
27
+ * **Experimental Translator** (`toolkitx.lab.translator`):
28
+ * `Translator`: A class providing translation capabilities using Baidu or Tencent translation APIs, with disk-based caching for performance. (Requires API credentials)
29
+
30
+ ## Installation
31
+
32
+ 1. Clone the repository:
33
+ ```bash
34
+ git clone https://github.com/ider-zh/toolkitx.git
35
+ cd toolkitx
36
+ ```
37
+ 2. Install the package. For development, you can install it in editable mode with development dependencies:
38
+ ```bash
39
+ pip install -e ".[dev]"
40
+ ```
41
+ For regular installation:
42
+ ```bash
43
+ pip install .
44
+ ```
45
+
46
+ ## Usage
47
+
48
+ ### Text Utilities
49
+
50
+ ```python
51
+ from toolkitx import truncate_text_smart, split_text_by_word_count
52
+
53
+ # Smart Truncation
54
+ text = "This is a very long sentence that needs to be truncated."
55
+ truncated_char = truncate_text_smart(text, limit=20, mode="char", suffix="...")
56
+ print(f"Char truncated: {truncated_char}")
57
+
58
+ truncated_word = truncate_text_smart(text, limit=5, mode="word", suffix="...")
59
+ print(f"Word truncated: {truncated_word}")
60
+
61
+ # Split Text
62
+ long_text = "This is a long piece of text that we want to split into several smaller chunks with some overlap between them for context."
63
+ chunks = split_text_by_word_count(long_text, max_words=10, overlap=2)
64
+ for i, chunk in enumerate(chunks):
65
+ print(f"Chunk {i+1}: {chunk}")
66
+ ```
@@ -0,0 +1,51 @@
1
+ # toolkitx
2
+
3
+ A personal Python toolkit for common tasks. This package provides various utility functions to simplify common development workflows.
4
+
5
+ ## Features
6
+
7
+ * **Text Utilities** (`toolkitx.text_utils`):
8
+ * `truncate_text_smart`: Smartly truncates text by characters or words, with options for suffix and tolerance, attempting to preserve sentence or word boundaries.
9
+ * `split_text_by_word_count`: Splits long text into overlapping chunks based on word count.
10
+ * **Command-Line Script**:
11
+ * `hello`: A simple script accessible via `hello` command after installation, prints a greeting message.
12
+ * **Experimental Translator** (`toolkitx.lab.translator`):
13
+ * `Translator`: A class providing translation capabilities using Baidu or Tencent translation APIs, with disk-based caching for performance. (Requires API credentials)
14
+
15
+ ## Installation
16
+
17
+ 1. Clone the repository:
18
+ ```bash
19
+ git clone https://github.com/ider-zh/toolkitx.git
20
+ cd toolkitx
21
+ ```
22
+ 2. Install the package. For development, you can install it in editable mode with development dependencies:
23
+ ```bash
24
+ pip install -e ".[dev]"
25
+ ```
26
+ For regular installation:
27
+ ```bash
28
+ pip install .
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ### Text Utilities
34
+
35
+ ```python
36
+ from toolkitx import truncate_text_smart, split_text_by_word_count
37
+
38
+ # Smart Truncation
39
+ text = "This is a very long sentence that needs to be truncated."
40
+ truncated_char = truncate_text_smart(text, limit=20, mode="char", suffix="...")
41
+ print(f"Char truncated: {truncated_char}")
42
+
43
+ truncated_word = truncate_text_smart(text, limit=5, mode="word", suffix="...")
44
+ print(f"Word truncated: {truncated_word}")
45
+
46
+ # Split Text
47
+ long_text = "This is a long piece of text that we want to split into several smaller chunks with some overlap between them for context."
48
+ chunks = split_text_by_word_count(long_text, max_words=10, overlap=2)
49
+ for i, chunk in enumerate(chunks):
50
+ print(f"Chunk {i+1}: {chunk}")
51
+ ```
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "toolkitx"
3
+ version = "0.0.1"
4
+ description = "A personal Python toolkit for common tasks"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "diskcache>=5.6.3",
9
+ "py-transgpt>=2.0",
10
+ ]
11
+
12
+ [project.optional-dependencies]
13
+ dev = [
14
+ "pytest",
15
+ "pytest-dotenv",
16
+ ]
17
+
18
+ [project.scripts]
19
+ hello = "toolkitx.hello:hello"
20
+
21
+ [build-system]
22
+ requires = ["hatchling"]
23
+ build-backend = "hatchling.build"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["toolkitx"]
27
+
28
+ [project.urls]
29
+ "Homepage" = "https://github.com/ider-zh/toolkitx"
30
+ "Bug Tracker" = "https://github.com/ider-zh/toolkitx/issues"
@@ -0,0 +1,240 @@
1
+ import os
2
+ import pytest
3
+ from unittest.mock import patch, MagicMock
4
+ from toolkitx.lab.translator import Translator # 假设 Translator 类在这个路径下
5
+
6
+ # --- API Key Availability Check ---
7
+ # 这些变量将在模块加载时评估,反映环境变量的初始状态
8
+ # pytest-dotenv 应该在 pytest 收集测试之前加载 .env 文件
9
+ BAIDU_KEYS_AVAILABLE = bool(os.getenv("BAIDU_API_ID") and os.getenv("BAIDU_API_KEY"))
10
+ TENCENT_KEYS_AVAILABLE = bool(os.getenv("TENCENT_API_ID") and os.getenv("TENCENT_API_KEY"))
11
+
12
+ # --- Test API Credentials (can be overridden by .env for actual integration tests if not mocked) ---
13
+ # 这些主要用于那些不依赖 .env 文件,而是直接传递参数或使用 monkeypatch 的测试
14
+ TEST_BAIDU_API_ID_PARAM = "param_baidu_id"
15
+ TEST_BAIDU_API_KEY_PARAM = "param_baidu_key"
16
+ TEST_TENCENT_API_ID_PARAM = "param_tencent_id"
17
+ TEST_TENCENT_API_KEY_PARAM = "param_tencent_key"
18
+
19
+
20
+ @pytest.fixture
21
+ def temp_cache_path(tmp_path):
22
+ """提供一个临时的缓存路径"""
23
+ cache_dir = tmp_path / "translator_cache"
24
+ cache_dir.mkdir()
25
+ return str(cache_dir)
26
+
27
+ @pytest.fixture
28
+ def mock_baidu_engine_class():
29
+ """模拟 BaiduTranslation 类,并返回被 mock 的类本身以便检查构造函数调用"""
30
+ with patch('toolkitx.lab.translator.BaiduTranslation') as MockBaiduEngine:
31
+ mock_instance = MagicMock()
32
+ mock_instance.translate.return_value = "translated_from_baidu"
33
+ MockBaiduEngine.return_value = mock_instance
34
+ yield MockBaiduEngine
35
+
36
+ @pytest.fixture
37
+ def mock_tencent_engine_class():
38
+ """模拟 TencentTranslation 类,并返回被 mock 的类本身"""
39
+ with patch('toolkitx.lab.translator.TencentTranslation') as MockTencentEngine:
40
+ mock_instance = MagicMock()
41
+ mock_instance.translate.return_value = "translated_from_tencent"
42
+ MockTencentEngine.return_value = mock_instance
43
+ yield MockTencentEngine
44
+
45
+ # --- Initialization Tests ---
46
+
47
+ def test_translator_init_baidu_with_direct_params(temp_cache_path, mock_baidu_engine_class):
48
+ """测试使用直接参数初始化百度翻译引擎"""
49
+ translator = Translator(
50
+ engine="baidu",
51
+ cache_path=temp_cache_path,
52
+ api_id=TEST_BAIDU_API_ID_PARAM,
53
+ api_key=TEST_BAIDU_API_KEY_PARAM
54
+ )
55
+ assert translator.engine_name == "baidu"
56
+ # 验证 BaiduTranslation 构造函数是否用提供的参数被调用
57
+ mock_baidu_engine_class.assert_called_once_with(api_id=TEST_BAIDU_API_ID_PARAM, api_key=TEST_BAIDU_API_KEY_PARAM)
58
+ translator.close_cache()
59
+
60
+ def test_translator_init_baidu_with_monkeypatched_env(temp_cache_path, mock_baidu_engine_class, monkeypatch):
61
+ """测试使用 monkeypatch 设置的环境变量初始化百度翻译引擎"""
62
+ monkeypatch.setenv("BAIDU_API_ID", "env_baidu_id_monkey")
63
+ monkeypatch.setenv("BAIDU_API_KEY", "env_baidu_key_monkey")
64
+ translator = Translator(engine="baidu", cache_path=temp_cache_path)
65
+ assert translator.engine_name == "baidu"
66
+ mock_baidu_engine_class.assert_called_once_with(api_id="env_baidu_id_monkey", api_key="env_baidu_key_monkey")
67
+ translator.close_cache()
68
+
69
+ def test_translator_init_baidu_missing_keys_error(temp_cache_path, monkeypatch):
70
+ """测试当百度密钥缺失时是否抛出 ValueError"""
71
+ monkeypatch.delenv("BAIDU_API_ID", raising=False)
72
+ monkeypatch.delenv("BAIDU_API_KEY", raising=False)
73
+ with pytest.raises(ValueError, match="Baidu API ID and API Key are required"):
74
+ Translator(engine="baidu", cache_path=temp_cache_path)
75
+
76
+ def test_translator_init_tencent_with_direct_params(temp_cache_path, mock_tencent_engine_class):
77
+ """测试使用直接参数初始化腾讯翻译引擎"""
78
+ translator = Translator(
79
+ engine="tencent",
80
+ cache_path=temp_cache_path,
81
+ api_id=TEST_TENCENT_API_ID_PARAM,
82
+ api_key=TEST_TENCENT_API_KEY_PARAM
83
+ )
84
+ assert translator.engine_name == "tencent"
85
+ mock_tencent_engine_class.assert_called_once_with(api_id=TEST_TENCENT_API_ID_PARAM, api_key=TEST_TENCENT_API_KEY_PARAM)
86
+ translator.close_cache()
87
+
88
+ def test_translator_init_tencent_with_monkeypatched_env(temp_cache_path, mock_tencent_engine_class, monkeypatch):
89
+ """测试使用 monkeypatch 设置的环境变量初始化腾讯翻译引擎"""
90
+ monkeypatch.setenv("TENCENT_API_ID", "env_tencent_id_monkey")
91
+ monkeypatch.setenv("TENCENT_API_KEY", "env_tencent_key_monkey")
92
+ translator = Translator(engine="tencent", cache_path=temp_cache_path)
93
+ assert translator.engine_name == "tencent"
94
+ mock_tencent_engine_class.assert_called_once_with(api_id="env_tencent_id_monkey", api_key="env_tencent_key_monkey")
95
+ translator.close_cache()
96
+
97
+ def test_translator_init_tencent_missing_keys_error(temp_cache_path, monkeypatch):
98
+ """测试当腾讯密钥缺失时是否抛出 ValueError (根据用户代码中的错误信息)"""
99
+ monkeypatch.delenv("TENCENT_API_ID", raising=False)
100
+ monkeypatch.delenv("TENCENT_API_KEY", raising=False)
101
+ with pytest.raises(ValueError, match="Tencent Secret ID and Secret Key are required"):
102
+ Translator(engine="tencent", cache_path=temp_cache_path)
103
+
104
+ def test_translator_init_unsupported_engine(temp_cache_path):
105
+ """测试初始化不支持的引擎时是否抛出 ValueError"""
106
+ with pytest.raises(ValueError, match="Unsupported engine: unsupported_engine"):
107
+ Translator(engine="unsupported_engine", cache_path=temp_cache_path)
108
+
109
+ # --- Translation and Cache Tests (Relying on .env loaded keys) ---
110
+
111
+ @pytest.mark.skipif(not BAIDU_KEYS_AVAILABLE, reason="BAIDU_API_ID and/or BAIDU_API_KEY not set in environment (e.g., via .env)")
112
+ def test_translate_baidu_with_env_keys_cache_miss_and_hit(temp_cache_path, mock_baidu_engine_class):
113
+ """测试百度翻译(使用环境变量中的密钥),包括缓存未命中和命中"""
114
+ # 从环境变量获取预期的密钥,因为 BAIDU_KEYS_AVAILABLE 为 True
115
+ expected_api_id = os.getenv("BAIDU_API_ID")
116
+ expected_api_key = os.getenv("BAIDU_API_KEY")
117
+
118
+ translator = Translator(engine="baidu", cache_path=temp_cache_path) # 不传递 api_id/key
119
+
120
+ # 验证 BaiduTranslation 构造函数是否用环境变量中的密钥被调用
121
+ mock_baidu_engine_class.assert_called_once_with(api_id=expected_api_id, api_key=expected_api_key)
122
+
123
+ # 获取 mock 的翻译实例 (由 mock_baidu_engine_class 的 return_value 提供)
124
+ mock_baidu_engine_instance = translator.translator_instance
125
+
126
+ text = "你好"
127
+ target_lang = "en"
128
+ source_lang = "zh"
129
+
130
+ # 首次翻译 (cache miss)
131
+ result1 = translator.translate(text, target_lang=target_lang, source_lang=source_lang)
132
+ assert result1 == "translated_from_baidu" # 这是 mock_engine_instance.translate 的返回值
133
+ mock_baidu_engine_instance.translate.assert_called_once_with(text, target_lang, source_lang)
134
+
135
+ # 再次翻译 (cache hit)
136
+ mock_baidu_engine_instance.translate.reset_mock() # 重置 mock 调用计数
137
+ result2 = translator.translate(text, target_lang=target_lang, source_lang=source_lang)
138
+ assert result2 == "translated_from_baidu"
139
+ mock_baidu_engine_instance.translate.assert_not_called() # 不应再次调用实际翻译引擎的 translate
140
+
141
+ translator.close_cache()
142
+
143
+ @pytest.mark.skipif(not TENCENT_KEYS_AVAILABLE, reason="TENCENT_API_ID and/or TENCENT_API_KEY not set in environment (e.g., via .env)")
144
+ def test_translate_tencent_with_env_keys_cache_miss_and_hit(temp_cache_path, mock_tencent_engine_class):
145
+ """测试腾讯翻译(使用环境变量中的密钥),包括缓存未命中和命中"""
146
+ expected_api_id = os.getenv("TENCENT_API_ID")
147
+ expected_api_key = os.getenv("TENCENT_API_KEY")
148
+
149
+ translator = Translator(engine="tencent", cache_path=temp_cache_path)
150
+ mock_tencent_engine_class.assert_called_once_with(api_id=expected_api_id, api_key=expected_api_key)
151
+ mock_tencent_engine_instance = translator.translator_instance
152
+
153
+ text = "Hello"
154
+ target_lang = "zh"
155
+ source_lang = "en"
156
+
157
+ result1 = translator.translate(text, target_lang=target_lang, source_lang=source_lang)
158
+ assert result1 == "translated_from_tencent"
159
+ mock_tencent_engine_instance.translate.assert_called_once_with(text, target_lang, source_lang)
160
+
161
+ mock_tencent_engine_instance.translate.reset_mock()
162
+ result2 = translator.translate(text, target_lang=target_lang, source_lang=source_lang)
163
+ assert result2 == "translated_from_tencent"
164
+ mock_tencent_engine_instance.translate.assert_not_called()
165
+
166
+ translator.close_cache()
167
+
168
+ @pytest.mark.skipif(not BAIDU_KEYS_AVAILABLE, reason="Baidu keys not in .env")
169
+ def test_translate_empty_string_with_env_keys(temp_cache_path, mock_baidu_engine_class):
170
+ """测试使用环境变量密钥翻译空字符串"""
171
+ translator = Translator(engine="baidu", cache_path=temp_cache_path)
172
+ assert translator.translate("") == ""
173
+ # BaiduTranslation 构造函数会被调用,但其 translate 方法不应被调用
174
+ mock_baidu_engine_class.return_value.translate.assert_not_called()
175
+ translator.close_cache()
176
+
177
+ @pytest.mark.skipif(not BAIDU_KEYS_AVAILABLE, reason="Baidu keys not in .env")
178
+ def test_translate_uses_default_langs_with_env_keys(temp_cache_path, mock_baidu_engine_class):
179
+ """测试使用环境变量密钥时,是否使用默认语言"""
180
+ default_target = "fr"
181
+ default_source = "de"
182
+ translator = Translator(
183
+ engine="baidu",
184
+ cache_path=temp_cache_path,
185
+ target_lang=default_target,
186
+ source_lang=default_source
187
+ )
188
+ mock_engine_instance = translator.translator_instance
189
+ text = "Guten Tag"
190
+ translator.translate(text) # 不传递 target_lang/source_lang
191
+ mock_engine_instance.translate.assert_called_once_with(text, default_target, default_source)
192
+ translator.close_cache()
193
+
194
+ @pytest.mark.skipif(not BAIDU_KEYS_AVAILABLE, reason="Baidu keys not in .env")
195
+ def test_translate_api_error_with_env_keys(temp_cache_path, mock_baidu_engine_class):
196
+ """测试使用环境变量密钥时,API 错误是否正确传递"""
197
+ translator = Translator(engine="baidu", cache_path=temp_cache_path)
198
+ mock_engine_instance = translator.translator_instance
199
+ mock_engine_instance.translate.side_effect = RuntimeError("API communication error")
200
+
201
+ with pytest.raises(RuntimeError, match="API communication error"):
202
+ translator.translate("text to fail")
203
+ translator.close_cache()
204
+
205
+ # --- Cache Management Tests (Relying on .env loaded keys) ---
206
+
207
+ @pytest.mark.skipif(not BAIDU_KEYS_AVAILABLE, reason="Baidu keys not in .env")
208
+ def test_clear_cache_with_env_keys(temp_cache_path, mock_baidu_engine_class):
209
+ """测试使用环境变量密钥时,清除缓存的功能"""
210
+ translator = Translator(engine="baidu", cache_path=temp_cache_path)
211
+ mock_engine_instance = translator.translator_instance
212
+ text = "Cache me"
213
+ target_lang = "en"
214
+
215
+ # 翻译并缓存
216
+ translator.translate(text, target_lang=target_lang)
217
+ mock_engine_instance.translate.assert_called_once()
218
+
219
+ # 清除缓存
220
+ translator.clear_cache()
221
+
222
+ # 再次翻译,应该会调用API (cache miss)
223
+ mock_engine_instance.translate.reset_mock()
224
+ translator.translate(text, target_lang=target_lang)
225
+ mock_engine_instance.translate.assert_called_once()
226
+
227
+ translator.close_cache()
228
+
229
+ def test_close_cache_direct_params(temp_cache_path, mock_baidu_engine_class): # 这个测试不需要依赖环境变量
230
+ """测试 close_cache 方法(不依赖环境变量密钥)"""
231
+ translator = Translator(
232
+ engine="baidu",
233
+ cache_path=temp_cache_path,
234
+ api_id="dummy_id",
235
+ api_key="dummy_key"
236
+ )
237
+ # 模拟 Cache 对象的 close 方法
238
+ with patch.object(translator.cache, 'close', wraps=translator.cache.close) as mock_cache_close:
239
+ translator.close_cache()
240
+ mock_cache_close.assert_called_once()