| 1 | /* |
| 2 | * Open Chinese Convert |
| 3 | * |
| 4 | * Copyright 2015-2026 Carbo Kuo and contributors |
| 5 | * |
| 6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | * you may not use this file except in compliance with the License. |
| 8 | * You may obtain a copy of the License at |
| 9 | * |
| 10 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | * |
| 12 | * Unless required by applicable law or agreed to in writing, software |
| 13 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | * See the License for the specific language governing permissions and |
| 16 | * limitations under the License. |
| 17 | */ |
| 18 | |
| 19 | #include <fstream> |
| 20 | #include <filesystem> |
| 21 | #include <memory> |
| 22 | #include <set> |
| 23 | #include <string_view> |
| 24 | #include <utility> |
| 25 | #include <vector> |
| 26 | |
| 27 | #if defined(_WIN32) || defined(_WIN64) |
| 28 | #include <windows.h> |
| 29 | #else |
| 30 | #include <unistd.h> |
| 31 | #endif |
| 32 | |
| 33 | #include "Config.hpp" |
| 34 | #include "ConfigTestBase.hpp" |
| 35 | #include "ConversionChain.hpp" |
| 36 | #include "Converter.hpp" |
| 37 | #include "Dict.hpp" |
| 38 | #include "Segments.hpp" |
| 39 | #include "Exception.hpp" |
| 40 | #include "ResourceProvider.hpp" |
| 41 | #include "TestUtilsUTF8.hpp" |
| 42 | #include "UTF8Util.hpp" |
| 43 | |
| 44 | namespace opencc { |
| 45 | namespace { |
| 46 | |
| 47 | namespace fs = std::filesystem; |
| 48 | |
| 49 | std::string PathString(const fs::path& path) { return path.u8string(); } |
| 50 | |
| 51 | std::string NormalizePathString(std::string path) { |
| 52 | for (char& ch : path) { |
| 53 | if (ch == '\\') { |
| 54 | ch = '/'; |
| 55 | } |
| 56 | } |
| 57 | return path; |
| 58 | } |
| 59 | |
| 60 | fs::path MakeTempDir(const std::string& name) { |
| 61 | #if defined(_WIN32) || defined(_WIN64) |
| 62 | const auto suffix = std::to_string(GetCurrentProcessId()); |
| 63 | #else |
| 64 | const auto suffix = std::to_string(getpid()); |
| 65 | #endif |
| 66 | fs::path dir = fs::temp_directory_path() / (name + "-" + suffix); |
| 67 | fs::remove_all(dir); |
| 68 | fs::create_directories(dir); |
| 69 | return dir; |
| 70 | } |
| 71 | |
| 72 | void WriteFile(const fs::path& path, const std::string& content) { |
| 73 | std::ofstream ofs(path, std::ios::binary); |
| 74 | ofs << content; |
| 75 | } |
| 76 | |
| 77 | void WriteLe16(std::ofstream& output, uint16_t value) { |
| 78 | output.put(static_cast<char>(value & 0xff)); |
| 79 | output.put(static_cast<char>((value >> 8) & 0xff)); |
| 80 | } |
| 81 | |
| 82 | void WriteLe32(std::ofstream& output, uint32_t value) { |
| 83 | output.put(static_cast<char>(value & 0xff)); |
| 84 | output.put(static_cast<char>((value >> 8) & 0xff)); |
| 85 | output.put(static_cast<char>((value >> 16) & 0xff)); |
| 86 | output.put(static_cast<char>((value >> 24) & 0xff)); |
| 87 | } |
| 88 | |
| 89 | struct ZipTestEntry { |
| 90 | std::string name; |
| 91 | std::string content; |
| 92 | uint32_t localHeaderOffset; |
| 93 | }; |
| 94 | |
| 95 | void WriteStoredZip(const fs::path& path, |
| 96 | std::vector<std::pair<std::string, std::string>> entries) { |
| 97 | std::ofstream output(path, std::ios::binary); |
| 98 | std::vector<ZipTestEntry> writtenEntries; |
| 99 | for (const auto& entry : entries) { |
| 100 | const std::string& name = entry.first; |
| 101 | const std::string& content = entry.second; |
| 102 | const uint32_t localHeaderOffset = |
| 103 | static_cast<uint32_t>(output.tellp()); |
| 104 | WriteLe32(output, 0x04034b50); |
| 105 | WriteLe16(output, 20); |
| 106 | WriteLe16(output, 0); |
| 107 | WriteLe16(output, 0); |
| 108 | WriteLe16(output, 0); |
| 109 | WriteLe16(output, 0); |
| 110 | WriteLe32(output, 0); |
| 111 | WriteLe32(output, static_cast<uint32_t>(content.size())); |
| 112 | WriteLe32(output, static_cast<uint32_t>(content.size())); |
| 113 | WriteLe16(output, static_cast<uint16_t>(name.size())); |
| 114 | WriteLe16(output, 0); |
| 115 | output.write(name.data(), static_cast<std::streamsize>(name.size())); |
| 116 | output.write(content.data(), static_cast<std::streamsize>(content.size())); |
| 117 | writtenEntries.push_back(ZipTestEntry{name, content, localHeaderOffset}); |
| 118 | } |
| 119 | |
| 120 | const uint32_t centralDirectoryOffset = |
| 121 | static_cast<uint32_t>(output.tellp()); |
| 122 | for (const ZipTestEntry& entry : writtenEntries) { |
| 123 | WriteLe32(output, 0x02014b50); |
| 124 | WriteLe16(output, 20); |
| 125 | WriteLe16(output, 20); |
| 126 | WriteLe16(output, 0); |
| 127 | WriteLe16(output, 0); |
| 128 | WriteLe16(output, 0); |
| 129 | WriteLe16(output, 0); |
| 130 | WriteLe32(output, 0); |
| 131 | WriteLe32(output, static_cast<uint32_t>(entry.content.size())); |
| 132 | WriteLe32(output, static_cast<uint32_t>(entry.content.size())); |
| 133 | WriteLe16(output, static_cast<uint16_t>(entry.name.size())); |
| 134 | WriteLe16(output, 0); |
| 135 | WriteLe16(output, 0); |
| 136 | WriteLe16(output, 0); |
| 137 | WriteLe16(output, 0); |
| 138 | WriteLe32(output, 0); |
| 139 | WriteLe32(output, entry.localHeaderOffset); |
| 140 | output.write(entry.name.data(), |
| 141 | static_cast<std::streamsize>(entry.name.size())); |
| 142 | } |
| 143 | const uint32_t centralDirectorySize = |
| 144 | static_cast<uint32_t>(output.tellp()) - centralDirectoryOffset; |
| 145 | |
| 146 | WriteLe32(output, 0x06054b50); |
| 147 | WriteLe16(output, 0); |
| 148 | WriteLe16(output, 0); |
| 149 | WriteLe16(output, static_cast<uint16_t>(writtenEntries.size())); |
| 150 | WriteLe16(output, static_cast<uint16_t>(writtenEntries.size())); |
| 151 | WriteLe32(output, centralDirectorySize); |
| 152 | WriteLe32(output, centralDirectoryOffset); |
| 153 | WriteLe16(output, 0); |
| 154 | } |
| 155 | |
| 156 | std::string SingleDictConfig(const std::string& dictFile) { |
| 157 | return std::string("{\n" |
| 158 | " \"name\": \"Resource Provider Test\",\n" |
| 159 | " \"segmentation\": {\n" |
| 160 | " \"type\": \"mmseg\",\n" |
| 161 | " \"dict\": {\"type\": \"text\", \"file\": \"") + |
| 162 | dictFile + |
| 163 | "\"}\n" |
| 164 | " },\n" |
| 165 | " \"conversion_chain\": [{\n" |
| 166 | " \"dict\": {\"type\": \"text\", \"file\": \"" + |
| 167 | dictFile + |
| 168 | "\"}\n" |
| 169 | " }]\n" |
| 170 | "}\n"; |
| 171 | } |
| 172 | |
| 173 | std::string InlineSingleStepConfig(const std::string& segmentationEntries, |
| 174 | const std::string& conversionDict) { |
| 175 | return std::string("{\n" |
| 176 | " \"name\": \"Inline Dict Test\",\n" |
| 177 | " \"segmentation\": {\n" |
| 178 | " \"type\": \"mmseg\",\n" |
| 179 | " \"dict\": {\n" |
| 180 | " \"type\": \"inline\",\n" |
| 181 | " \"entries\": ") + |
| 182 | segmentationEntries + |
| 183 | "\n" |
| 184 | " }\n" |
| 185 | " },\n" |
| 186 | " \"conversion_chain\": [{\n" |
| 187 | " \"dict\": " + |
| 188 | conversionDict + |
| 189 | "\n" |
| 190 | " }]\n" |
| 191 | "}\n"; |
| 192 | } |
| 193 | |
| 194 | std::string ChainConfig(const std::vector<std::string>& dicts) { |
| 195 | std::string config = |
| 196 | "{\n" |
| 197 | " \"name\": \"Rime Compatibility Test\",\n" |
| 198 | " \"conversion_chain\": [\n"; |
| 199 | for (size_t i = 0; i < dicts.size(); i++) { |
| 200 | config += |
| 201 | " {\n" |
| 202 | " \"dict\": " + |
| 203 | dicts[i] + |
| 204 | "\n" |
| 205 | " }"; |
| 206 | config += (i + 1 == dicts.size()) ? "\n" : ",\n"; |
| 207 | } |
| 208 | config += |
| 209 | " ]\n" |
| 210 | "}\n"; |
| 211 | return config; |
| 212 | } |
| 213 | |
| 214 | bool ConvertWordLikeRime(const ConversionChainPtr& chain, |
| 215 | const std::string& input, |
| 216 | std::vector<std::string>* converted) { |
| 217 | std::vector<std::string> current{input}; |
| 218 | bool hasExactMatch = false; |
| 219 | |
| 220 | const auto AddIfNew = [](const std::string& value, |
| 221 | std::vector<std::string>* values, |
| 222 | std::set<std::string>* seen) { |
| 223 | if (seen->insert(value).second) { |
| 224 | values->push_back(value); |
| 225 | } |
| 226 | }; |
| 227 | |
| 228 | for (const ConversionPtr& conversion : chain->GetConversions()) { |
| 229 | const DictPtr dict = conversion->GetDict(); |
| 230 | std::vector<std::string> next; |
| 231 | std::set<std::string> seen; |
| 232 | |
| 233 | for (const std::string& word : current) { |
| 234 | const Optional<const DictEntry*> exact = dict->Match(word); |
| 235 | if (!exact.IsNull()) { |
| 236 | hasExactMatch = true; |
| 237 | for (const std::string& value : exact.Get()->Values()) { |
| 238 | AddIfNew(value, &next, &seen); |
| 239 | } |
| 240 | continue; |
| 241 | } |
| 242 | |
| 243 | std::string fallback; |
| 244 | for (const char* pstr = word.c_str(); *pstr != '\0';) { |
| 245 | const Optional<const DictEntry*> prefix = dict->MatchPrefix(pstr); |
| 246 | size_t matchedLength; |
| 247 | if (prefix.IsNull()) { |
| 248 | matchedLength = UTF8Util::NextCharLength(pstr); |
| 249 | fallback.append(pstr, matchedLength); |
| 250 | } else { |
| 251 | matchedLength = prefix.Get()->KeyLength(); |
| 252 | fallback += prefix.Get()->GetDefault(); |
| 253 | } |
| 254 | pstr += matchedLength; |
| 255 | } |
| 256 | AddIfNew(fallback, &next, &seen); |
| 257 | } |
| 258 | |
| 259 | current = std::move(next); |
| 260 | } |
| 261 | |
| 262 | *converted = current; |
| 263 | return hasExactMatch; |
| 264 | } |
| 265 | |
| 266 | std::string FindOcd2DictionaryDir(const std::string& configTestDirPath) { |
| 267 | std::vector<fs::path> candidates; |
| 268 | if (!PACKAGE_DATA_DIRECTORY.empty()) { |
| 269 | candidates.push_back(fs::u8path(PACKAGE_DATA_DIRECTORY)); |
| 270 | } |
| 271 | |
| 272 | const fs::path configDir = fs::u8path(configTestDirPath); |
| 273 | candidates.push_back(configDir.parent_path().parent_path() / "data" / |
| 274 | "dictionary"); |
| 275 | candidates.push_back(fs::current_path() / "data" / "dictionary"); |
| 276 | candidates.push_back(fs::current_path().parent_path() / "data" / "dictionary"); |
| 277 | |
| 278 | for (const fs::path& candidate : candidates) { |
| 279 | if (candidate.empty()) { |
| 280 | continue; |
| 281 | } |
| 282 | const fs::path phrases = candidate / "STPhrases.ocd2"; |
| 283 | const fs::path characters = candidate / "STCharacters.ocd2"; |
| 284 | if (fs::is_regular_file(phrases) && fs::is_regular_file(characters)) { |
| 285 | return PathString(candidate) + "/"; |
| 286 | } |
| 287 | } |
| 288 | return ""; |
| 289 | } |
| 290 | |
| 291 | } // namespace |
| 292 | |
| 293 | class ConfigTest : public ConfigTestBase { |
| 294 | protected: |
| 295 | ConfigTest() |
| 296 | : input(utf8("燕燕于飞差池其羽之子于归远送于野")), |
| 297 | expected(utf8("燕燕于飛差池其羽之子于歸遠送於野")) {} |
| 298 | |
| 299 | virtual void SetUp() { |
| 300 | converter = config.NewFromFile(CONFIG_TEST_JSON_PATH); |
| 301 | } |
| 302 | |
| 303 | Config config; |
| 304 | ConverterPtr converter; |
| 305 | const std::string input; |
| 306 | const std::string expected; |
| 307 | }; |
| 308 | |
| 309 | TEST_F(ConfigTest, Convert) { |
| 310 | const std::string converted = converter->Convert(std::string_view(input)); |
| 311 | EXPECT_EQ(expected, converted); |
| 312 | } |
| 313 | |
| 314 | TEST_F(ConfigTest, ConvertLength) { |
| 315 | const std::string result = converter->Convert(std::string_view(input)); |
| 316 | EXPECT_EQ(expected.length(), result.length()); |
| 317 | EXPECT_EQ(expected, result); |
| 318 | } |
| 319 | |
| 320 | TEST_F(ConfigTest, NonexistingPath) { |
| 321 | const std::string path = "/opencc/no/such/file/or/directory"; |
| 322 | try { |
| 323 | const ConverterPtr _ = config.NewFromFile(path); |
| 324 | } catch (FileNotFound& e) { |
| 325 | EXPECT_EQ(path + " not found or not accessible.", e.what()); |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | TEST_F(ConfigTest, NewFromStringWitoutTrailingSlash) { |
| 330 | std::ifstream ifs(CONFIG_TEST_JSON_PATH); |
| 331 | std::string content(std::istreambuf_iterator<char>(ifs), |
| 332 | (std::istreambuf_iterator<char>())); |
| 333 | |
| 334 | const ConverterPtr _ = config.NewFromString(content, CONFIG_TEST_DIR_PATH); |
| 335 | } |
| 336 | |
| 337 | TEST_F(ConfigTest, DefaultConfigPathFindsAdjacentResources) { |
| 338 | const fs::path tempDir = MakeTempDir("opencc-adjacent-resource-test"); |
| 339 | fs::copy_file(fs::u8path(CONFIG_TEST_DIR_PATH) / "config_test.json", |
| 340 | tempDir / "config_test.json"); |
| 341 | fs::copy_file(fs::u8path(CONFIG_TEST_DIR_PATH) / "config_test_phrases.txt", |
| 342 | tempDir / "config_test_phrases.txt"); |
| 343 | fs::copy_file(fs::u8path(CONFIG_TEST_DIR_PATH) / "config_test_characters.txt", |
| 344 | tempDir / "config_test_characters.txt"); |
| 345 | |
| 346 | try { |
| 347 | const ConverterPtr tempConverter = |
| 348 | config.NewFromFile(PathString(tempDir / "config_test.json")); |
| 349 | EXPECT_EQ(expected, tempConverter->Convert(std::string_view(input))); |
| 350 | } catch (...) { |
| 351 | fs::remove_all(tempDir); |
| 352 | throw; |
| 353 | } |
| 354 | fs::remove_all(tempDir); |
| 355 | } |
| 356 | |
| 357 | TEST_F(ConfigTest, ExplicitProviderFindsResources) { |
| 358 | const fs::path tempDir = MakeTempDir("opencc-explicit-provider-test"); |
| 359 | const fs::path configDir = tempDir / "config"; |
| 360 | const fs::path resourceDir = tempDir / "resources"; |
| 361 | fs::create_directories(configDir); |
| 362 | fs::create_directories(resourceDir); |
| 363 | WriteFile(configDir / "config.json", SingleDictConfig("dict.txt")); |
| 364 | WriteFile(resourceDir / "dict.txt", utf8("鼠标\t滑鼠\n")); |
| 365 | |
| 366 | try { |
| 367 | std::shared_ptr<ResourceProvider> provider( |
| 368 | new FilesystemResourceProvider({PathString(resourceDir)})); |
| 369 | const ConverterPtr tempConverter = |
| 370 | config.NewFromFile(PathString(configDir / "config.json"), provider); |
| 371 | EXPECT_EQ(utf8("滑鼠"), |
| 372 | tempConverter->Convert(std::string_view(utf8("鼠标")))); |
| 373 | } catch (...) { |
| 374 | fs::remove_all(tempDir); |
| 375 | throw; |
| 376 | } |
| 377 | fs::remove_all(tempDir); |
| 378 | } |
| 379 | |
| 380 | TEST_F(ConfigTest, ExplicitProviderFindsConfigNameAndResources) { |
| 381 | const fs::path tempDir = MakeTempDir("opencc-provider-config-test"); |
| 382 | const fs::path resourceDir = tempDir / "resources"; |
| 383 | fs::create_directories(resourceDir); |
| 384 | WriteFile(resourceDir / "provider_config.json", SingleDictConfig("dict.txt")); |
| 385 | WriteFile(resourceDir / "dict.txt", utf8("鼠标\t滑鼠\n")); |
| 386 | |
| 387 | try { |
| 388 | std::shared_ptr<ResourceProvider> provider( |
| 389 | new FilesystemResourceProvider({PathString(resourceDir)})); |
| 390 | const ConverterPtr tempConverter = |
| 391 | config.NewFromFile("provider_config.json", provider); |
| 392 | EXPECT_EQ(utf8("滑鼠"), |
| 393 | tempConverter->Convert(std::string_view(utf8("鼠标")))); |
| 394 | } catch (...) { |
| 395 | fs::remove_all(tempDir); |
| 396 | throw; |
| 397 | } |
| 398 | fs::remove_all(tempDir); |
| 399 | } |
| 400 | |
| 401 | TEST_F(ConfigTest, ZipProviderFindsConfigNameAndResources) { |
| 402 | const fs::path tempDir = MakeTempDir("opencc-zip-provider-test"); |
| 403 | const fs::path zipPath = tempDir / "resources.zip"; |
| 404 | WriteStoredZip(zipPath, { |
| 405 | {"config.json", SingleDictConfig("dict.txt")}, |
| 406 | {"dict.txt", utf8("鼠标\t滑鼠\n")}, |
| 407 | }); |
| 408 | |
| 409 | try { |
| 410 | std::shared_ptr<ResourceProvider> provider( |
| 411 | new ZipResourceProvider(PathString(zipPath))); |
| 412 | const ConverterPtr tempConverter = |
| 413 | config.NewFromFile("config.json", provider); |
| 414 | EXPECT_EQ(utf8("滑鼠"), |
| 415 | tempConverter->Convert(std::string_view(utf8("鼠标")))); |
| 416 | } catch (...) { |
| 417 | fs::remove_all(tempDir); |
| 418 | throw; |
| 419 | } |
| 420 | fs::remove_all(tempDir); |
| 421 | } |
| 422 | |
| 423 | TEST_F(ConfigTest, ZipProviderDoesNotOverrideAbsoluteConfigPath) { |
| 424 | const fs::path tempDir = MakeTempDir("opencc-zip-absolute-config-test"); |
| 425 | const fs::path zipPath = tempDir / "resources.zip"; |
| 426 | const fs::path configPath = tempDir / "config.json"; |
| 427 | WriteStoredZip(zipPath, { |
| 428 | {"config.json", |
| 429 | InlineSingleStepConfig( |
| 430 | "{\n" |
| 431 | " \"鼠标\": \"鼠标\"\n" |
| 432 | " }", |
| 433 | "{\n" |
| 434 | " \"type\": \"inline\",\n" |
| 435 | " \"entries\": {\n" |
| 436 | " \"鼠标\": \"乙\"\n" |
| 437 | " }\n" |
| 438 | " }")}, |
| 439 | }); |
| 440 | WriteFile(configPath, |
| 441 | InlineSingleStepConfig( |
| 442 | "{\n" |
| 443 | " \"鼠标\": \"鼠标\"\n" |
| 444 | " }", |
| 445 | "{\n" |
| 446 | " \"type\": \"inline\",\n" |
| 447 | " \"entries\": {\n" |
| 448 | " \"鼠标\": \"甲\"\n" |
| 449 | " }\n" |
| 450 | " }")); |
| 451 | |
| 452 | try { |
| 453 | std::shared_ptr<ResourceProvider> provider( |
| 454 | new ZipResourceProvider(PathString(zipPath))); |
| 455 | const ConverterPtr tempConverter = |
| 456 | config.NewFromFile(PathString(configPath), provider); |
| 457 | EXPECT_EQ(utf8("甲"), |
| 458 | tempConverter->Convert(std::string_view(utf8("鼠标")))); |
| 459 | } catch (...) { |
| 460 | fs::remove_all(tempDir); |
| 461 | throw; |
| 462 | } |
| 463 | fs::remove_all(tempDir); |
| 464 | } |
| 465 | |
| 466 | TEST_F(ConfigTest, ExplicitProviderConfigOverridesInstalledOrCwdConfigName) { |
| 467 | const fs::path tempDir = MakeTempDir("opencc-provider-config-override-test"); |
| 468 | const fs::path cwdDir = tempDir / "cwd"; |
| 469 | const fs::path resourceDir = tempDir / "resources"; |
| 470 | fs::create_directories(cwdDir); |
| 471 | fs::create_directories(resourceDir); |
| 472 | WriteFile(cwdDir / "config.json", SingleDictConfig("dict_a.txt")); |
| 473 | WriteFile(resourceDir / "config.json", SingleDictConfig("dict_b.txt")); |
| 474 | WriteFile(resourceDir / "dict_a.txt", utf8("鼠标\t甲\n")); |
| 475 | WriteFile(resourceDir / "dict_b.txt", utf8("鼠标\t乙\n")); |
| 476 | |
| 477 | const fs::path originalCwd = fs::current_path(); |
| 478 | try { |
| 479 | fs::current_path(cwdDir); |
| 480 | std::shared_ptr<ResourceProvider> provider( |
| 481 | new FilesystemResourceProvider({PathString(resourceDir)})); |
| 482 | const ConverterPtr tempConverter = |
| 483 | config.NewFromFile("config.json", provider); |
| 484 | EXPECT_EQ(utf8("乙"), |
| 485 | tempConverter->Convert(std::string_view(utf8("鼠标")))); |
| 486 | fs::current_path(originalCwd); |
| 487 | } catch (...) { |
| 488 | fs::current_path(originalCwd); |
| 489 | fs::remove_all(tempDir); |
| 490 | throw; |
| 491 | } |
| 492 | fs::remove_all(tempDir); |
| 493 | } |
| 494 | |
| 495 | TEST_F(ConfigTest, RelativeParentDictionaryPathStillWorks) { |
| 496 | const fs::path tempDir = MakeTempDir("opencc-relative-parent-resource-test"); |
| 497 | const fs::path configDir = tempDir / "config"; |
| 498 | const fs::path dictionaryDir = tempDir / "dictionary"; |
| 499 | fs::create_directories(configDir); |
| 500 | fs::create_directories(dictionaryDir); |
| 501 | WriteFile(configDir / "config.json", |
| 502 | SingleDictConfig("../dictionary/dict.txt")); |
| 503 | WriteFile(dictionaryDir / "dict.txt", utf8("鼠标\t滑鼠\n")); |
| 504 | |
| 505 | try { |
| 506 | const ConverterPtr tempConverter = |
| 507 | config.NewFromFile(PathString(configDir / "config.json")); |
| 508 | EXPECT_EQ(utf8("滑鼠"), |
| 509 | tempConverter->Convert(std::string_view(utf8("鼠标")))); |
| 510 | } catch (...) { |
| 511 | fs::remove_all(tempDir); |
| 512 | throw; |
| 513 | } |
| 514 | fs::remove_all(tempDir); |
| 515 | } |
| 516 | |
| 517 | TEST_F(ConfigTest, MultipleSearchPathsUseFirstMatch) { |
| 518 | const fs::path tempDir = MakeTempDir("opencc-provider-order-test"); |
| 519 | const fs::path configDir = tempDir / "config"; |
| 520 | const fs::path firstDir = tempDir / "first"; |
| 521 | const fs::path secondDir = tempDir / "second"; |
| 522 | fs::create_directories(configDir); |
| 523 | fs::create_directories(firstDir); |
| 524 | fs::create_directories(secondDir); |
| 525 | WriteFile(configDir / "config.json", SingleDictConfig("dict.txt")); |
| 526 | WriteFile(firstDir / "dict.txt", utf8("鼠标\t第一\n")); |
| 527 | WriteFile(secondDir / "dict.txt", utf8("鼠标\t第二\n")); |
| 528 | |
| 529 | try { |
| 530 | std::shared_ptr<ResourceProvider> provider( |
| 531 | new FilesystemResourceProvider( |
| 532 | {PathString(firstDir), PathString(secondDir)})); |
| 533 | const ConverterPtr tempConverter = |
| 534 | config.NewFromFile(PathString(configDir / "config.json"), provider); |
| 535 | EXPECT_EQ(utf8("第一"), |
| 536 | tempConverter->Convert(std::string_view(utf8("鼠标")))); |
| 537 | } catch (...) { |
| 538 | fs::remove_all(tempDir); |
| 539 | throw; |
| 540 | } |
| 541 | fs::remove_all(tempDir); |
| 542 | } |
| 543 | |
| 544 | TEST_F(ConfigTest, MissingResourceListsSearchedPaths) { |
| 545 | const fs::path tempDir = MakeTempDir("opencc-provider-missing-test"); |
| 546 | const fs::path firstDir = tempDir / "first"; |
| 547 | const fs::path secondDir = tempDir / "second"; |
| 548 | fs::create_directories(firstDir); |
| 549 | fs::create_directories(secondDir); |
| 550 | |
| 551 | try { |
| 552 | FilesystemResourceProvider provider( |
| 553 | {PathString(firstDir), PathString(secondDir)}); |
| 554 | provider.Resolve("missing.ocd2"); |
| 555 | FAIL() << "Expected FileNotFound"; |
| 556 | } catch (const FileNotFound& e) { |
| 557 | const std::string message = e.what(); |
| 558 | EXPECT_NE(std::string::npos, message.find("missing.ocd2")); |
| 559 | EXPECT_NE(std::string::npos, message.find(PathString(firstDir))); |
| 560 | EXPECT_NE(std::string::npos, message.find(PathString(secondDir))); |
| 561 | } |
| 562 | fs::remove_all(tempDir); |
| 563 | } |
| 564 | |
| 565 | TEST_F(ConfigTest, FilesystemResourceCacheKeyIncludesFreshness) { |
| 566 | const fs::path tempDir = MakeTempDir("opencc-resource-cache-key-test"); |
| 567 | const fs::path resourceDir = tempDir / "resources"; |
| 568 | fs::create_directories(resourceDir); |
| 569 | const fs::path dictPath = resourceDir / "dict.txt"; |
| 570 | WriteFile(dictPath, utf8("鼠标\t滑鼠\n")); |
| 571 | |
| 572 | try { |
| 573 | FilesystemResourceProvider provider({PathString(resourceDir)}); |
| 574 | const std::shared_ptr<const ResourceProvider::Resource> resource = |
| 575 | provider.GetResource("dict.txt"); |
| 576 | EXPECT_EQ(NormalizePathString(PathString(dictPath)), |
| 577 | NormalizePathString(resource->Name())); |
| 578 | const std::string oldKey = |
| 579 | resource->Name() + "\n" + std::to_string(resource->Size()); |
| 580 | EXPECT_NE(oldKey, resource->CacheKey()); |
| 581 | } catch (...) { |
| 582 | fs::remove_all(tempDir); |
| 583 | throw; |
| 584 | } |
| 585 | fs::remove_all(tempDir); |
| 586 | } |
| 587 | |
| 588 | TEST_F(ConfigTest, PluginLikeResourcePathSupplementsMainPath) { |
| 589 | const fs::path tempDir = MakeTempDir("opencc-plugin-resource-test"); |
| 590 | const fs::path configDir = tempDir / "config"; |
| 591 | const fs::path mainDir = tempDir / "main"; |
| 592 | const fs::path pluginDir = tempDir / "plugin"; |
| 593 | fs::create_directories(configDir); |
| 594 | fs::create_directories(mainDir); |
| 595 | fs::create_directories(pluginDir); |
| 596 | WriteFile(configDir / "config.json", SingleDictConfig("plugin_dict.txt")); |
| 597 | WriteFile(pluginDir / "plugin_dict.txt", utf8("服务器\t伺服器\n")); |
| 598 | |
| 599 | try { |
| 600 | std::shared_ptr<ResourceProvider> provider( |
| 601 | new FilesystemResourceProvider( |
| 602 | {PathString(mainDir), PathString(pluginDir)})); |
| 603 | const ConverterPtr tempConverter = |
| 604 | config.NewFromFile(PathString(configDir / "config.json"), provider); |
| 605 | EXPECT_EQ(utf8("伺服器"), |
| 606 | tempConverter->Convert(std::string_view(utf8("服务器")))); |
| 607 | } catch (...) { |
| 608 | fs::remove_all(tempDir); |
| 609 | throw; |
| 610 | } |
| 611 | fs::remove_all(tempDir); |
| 612 | } |
| 613 | |
| 614 | TEST_F(ConfigTest, InlineDictBasicConversion) { |
| 615 | const std::string json = InlineSingleStepConfig( |
| 616 | "{\n" |
| 617 | " \"麦旋风\": \"麦旋风\"\n" |
| 618 | " }", |
| 619 | "{\n" |
| 620 | " \"type\": \"inline\",\n" |
| 621 | " \"entries\": {\n" |
| 622 | " \"麦旋风\": \"冰炫風\"\n" |
| 623 | " }\n" |
| 624 | " }"); |
| 625 | |
| 626 | const ConverterPtr inlineConverter = config.NewFromString(json, ""); |
| 627 | EXPECT_EQ(utf8("我想吃冰炫風"), |
| 628 | inlineConverter->Convert(std::string_view(utf8("我想吃麦旋风")))); |
| 629 | } |
| 630 | |
| 631 | TEST_F(ConfigTest, InlineDictInGroupTakesPriorityOverFollowingFileDict) { |
| 632 | const std::string json = |
| 633 | std::string("{\n" |
| 634 | " \"name\": \"Inline Group Priority Test\",\n" |
| 635 | " \"segmentation\": {\n" |
| 636 | " \"type\": \"mmseg\",\n" |
| 637 | " \"dict\": {\"type\": \"text\", \"file\": \"config_test_phrases.txt\"}\n" |
| 638 | " },\n" |
| 639 | " \"conversion_chain\": [{\n" |
| 640 | " \"dict\": {\n" |
| 641 | " \"type\": \"group\",\n" |
| 642 | " \"match_policy\": \"short_circuit\",\n" |
| 643 | " \"dicts\": [\n" |
| 644 | " {\n" |
| 645 | " \"type\": \"inline\",\n" |
| 646 | " \"entries\": {\n" |
| 647 | " \"燕燕于飞\": \"自訂覆寫\"\n" |
| 648 | " }\n" |
| 649 | " },\n" |
| 650 | " {\"type\": \"text\", \"file\": \"config_test_phrases.txt\"}\n" |
| 651 | " ]\n" |
| 652 | " }\n" |
| 653 | " }]\n" |
| 654 | "}\n"); |
| 655 | |
| 656 | const ConverterPtr inlineConverter = |
| 657 | config.NewFromString(json, {CONFIG_TEST_DIR_PATH + "/"}); |
| 658 | EXPECT_EQ(utf8("自訂覆寫"), |
| 659 | inlineConverter->Convert(std::string_view(utf8("燕燕于飞")))); |
| 660 | } |
| 661 | |
| 662 | TEST_F(ConfigTest, GroupDictWithoutMatchPolicyDefaultsToShortCircuit) { |
| 663 | const std::string json = |
| 664 | std::string("{\n" |
| 665 | " \"name\": \"Legacy Group Policy Test\",\n" |
| 666 | " \"segmentation\": {\n" |
| 667 | " \"type\": \"mmseg\",\n" |
| 668 | " \"dict\": {\"type\": \"text\", \"file\": \"config_test_phrases.txt\"}\n" |
| 669 | " },\n" |
| 670 | " \"conversion_chain\": [{\n" |
| 671 | " \"dict\": {\n" |
| 672 | " \"type\": \"group\",\n" |
| 673 | " \"dicts\": [\n" |
| 674 | " {\n" |
| 675 | " \"type\": \"inline\",\n" |
| 676 | " \"entries\": {\n" |
| 677 | " \"燕燕于飞\": \"自訂覆寫\"\n" |
| 678 | " }\n" |
| 679 | " },\n" |
| 680 | " {\"type\": \"text\", \"file\": \"config_test_phrases.txt\"}\n" |
| 681 | " ]\n" |
| 682 | " }\n" |
| 683 | " }]\n" |
| 684 | "}\n"); |
| 685 | |
| 686 | testing::internal::CaptureStderr(); |
| 687 | const ConverterPtr legacyConverter = |
| 688 | config.NewFromString(json, {CONFIG_TEST_DIR_PATH + "/"}); |
| 689 | const std::string warning = testing::internal::GetCapturedStderr(); |
| 690 | EXPECT_NE(std::string::npos, |
| 691 | warning.find("warning: config does not conform to schema")); |
| 692 | EXPECT_EQ(utf8("自訂覆寫"), |
| 693 | legacyConverter->Convert(std::string_view(utf8("燕燕于飞")))); |
| 694 | } |
| 695 | |
| 696 | TEST_F(ConfigTest, UnionDictGroupPrefersLaterLongerMatch) { |
| 697 | const std::string json = |
| 698 | std::string("{\n" |
| 699 | " \"name\": \"Union Group Test\",\n" |
| 700 | " \"segmentation\": {\n" |
| 701 | " \"type\": \"mmseg\",\n" |
| 702 | " \"dict\": {\n" |
| 703 | " \"type\": \"inline\",\n" |
| 704 | " \"entries\": {\n" |
| 705 | " \"意大利面\": \"意大利面\"\n" |
| 706 | " }\n" |
| 707 | " }\n" |
| 708 | " },\n" |
| 709 | " \"conversion_chain\": [{\n" |
| 710 | " \"dict\": {\n" |
| 711 | " \"type\": \"group\",\n" |
| 712 | " \"match_policy\": \"union\",\n" |
| 713 | " \"dicts\": [\n" |
| 714 | " {\n" |
| 715 | " \"type\": \"inline\",\n" |
| 716 | " \"entries\": {\n" |
| 717 | " \"意大利\": \"義大利\"\n" |
| 718 | " }\n" |
| 719 | " },\n" |
| 720 | " {\n" |
| 721 | " \"type\": \"inline\",\n" |
| 722 | " \"entries\": {\n" |
| 723 | " \"意大利面\": \"義大利麵\"\n" |
| 724 | " }\n" |
| 725 | " }\n" |
| 726 | " ]\n" |
| 727 | " }\n" |
| 728 | " }]\n" |
| 729 | "}\n"); |
| 730 | |
| 731 | const ConverterPtr inlineConverter = config.NewFromString(json, ""); |
| 732 | EXPECT_EQ(utf8("義大利麵"), |
| 733 | inlineConverter->Convert(std::string_view(utf8("意大利面")))); |
| 734 | } |
| 735 | |
| 736 | TEST_F(ConfigTest, InlineDictOutputStillProcessedByLaterChainStep) { |
| 737 | const std::string json = |
| 738 | std::string("{\n" |
| 739 | " \"name\": \"Inline Chain Test\",\n" |
| 740 | " \"segmentation\": {\n" |
| 741 | " \"type\": \"mmseg\",\n" |
| 742 | " \"dict\": {\n" |
| 743 | " \"type\": \"inline\",\n" |
| 744 | " \"entries\": {\n" |
| 745 | " \"A\": \"A\",\n" |
| 746 | " \"B\": \"B\"\n" |
| 747 | " }\n" |
| 748 | " }\n" |
| 749 | " },\n" |
| 750 | " \"conversion_chain\": [\n" |
| 751 | " {\n" |
| 752 | " \"dict\": {\n" |
| 753 | " \"type\": \"inline\",\n" |
| 754 | " \"entries\": {\n" |
| 755 | " \"A\": \"B\"\n" |
| 756 | " }\n" |
| 757 | " }\n" |
| 758 | " },\n" |
| 759 | " {\n" |
| 760 | " \"dict\": {\n" |
| 761 | " \"type\": \"inline\",\n" |
| 762 | " \"entries\": {\n" |
| 763 | " \"B\": \"C\"\n" |
| 764 | " }\n" |
| 765 | " }\n" |
| 766 | " }\n" |
| 767 | " ]\n" |
| 768 | "}\n"); |
| 769 | |
| 770 | const ConverterPtr inlineConverter = config.NewFromString(json, ""); |
| 771 | EXPECT_EQ("C", inlineConverter->Convert(std::string_view("A"))); |
| 772 | } |
| 773 | |
| 774 | TEST_F(ConfigTest, InlineSegmentationDictUsesLongestMatch) { |
| 775 | const std::string json = |
| 776 | std::string("{\n" |
| 777 | " \"name\": \"Inline Segmentation Test\",\n" |
| 778 | " \"segmentation\": {\n" |
| 779 | " \"type\": \"mmseg\",\n" |
| 780 | " \"dict\": {\n" |
| 781 | " \"type\": \"inline\",\n" |
| 782 | " \"entries\": {\n" |
| 783 | " \"ABC\": \"ABC\",\n" |
| 784 | " \"AB\": \"AB\",\n" |
| 785 | " \"D\": \"D\"\n" |
| 786 | " }\n" |
| 787 | " }\n" |
| 788 | " },\n" |
| 789 | " \"conversion_chain\": [{\n" |
| 790 | " \"dict\": {\n" |
| 791 | " \"type\": \"inline\",\n" |
| 792 | " \"entries\": {\n" |
| 793 | " \"ABC\": \"X\",\n" |
| 794 | " \"AB\": \"Y\",\n" |
| 795 | " \"C\": \"Z\",\n" |
| 796 | " \"D\": \"D\"\n" |
| 797 | " }\n" |
| 798 | " }\n" |
| 799 | " }]\n" |
| 800 | "}\n"); |
| 801 | |
| 802 | const ConverterPtr inlineConverter = config.NewFromString(json, ""); |
| 803 | EXPECT_EQ("XD", inlineConverter->Convert(std::string_view("ABCD"))); |
| 804 | } |
| 805 | |
| 806 | TEST_F(ConfigTest, InlineDictPreservesExactStringSemantics) { |
| 807 | const std::string json = InlineSingleStepConfig( |
| 808 | "{\n" |
| 809 | " \"A\": \"A\",\n" |
| 810 | " \" A \": \" A \"\n" |
| 811 | " }", |
| 812 | "{\n" |
| 813 | " \"type\": \"inline\",\n" |
| 814 | " \"entries\": {\n" |
| 815 | " \" A \": \"B\"\n" |
| 816 | " }\n" |
| 817 | " }"); |
| 818 | |
| 819 | const ConverterPtr inlineConverter = config.NewFromString(json, ""); |
| 820 | EXPECT_EQ("A", inlineConverter->Convert(std::string_view("A"))); |
| 821 | EXPECT_EQ("B", inlineConverter->Convert(std::string_view(" A "))); |
| 822 | } |
| 823 | |
| 824 | TEST_F(ConfigTest, InlineDictValidationErrors) { |
| 825 | const auto ExpectInvalidFormat = [this](const std::string& json, |
| 826 | const std::string& expectedMessage) { |
| 827 | testing::internal::CaptureStderr(); |
| 828 | try { |
| 829 | const ConverterPtr _ = config.NewFromString(json, ""); |
| 830 | (void)testing::internal::GetCapturedStderr(); |
| 831 | FAIL() << "Expected InvalidFormat"; |
| 832 | } catch (const InvalidFormat& e) { |
| 833 | const std::string warning = testing::internal::GetCapturedStderr(); |
| 834 | EXPECT_NE(std::string::npos, |
| 835 | warning.find("warning: config does not conform to schema")); |
| 836 | EXPECT_NE(std::string::npos, |
| 837 | std::string(e.what()).find(expectedMessage)); |
| 838 | } |
| 839 | }; |
| 840 | |
| 841 | ExpectInvalidFormat( |
| 842 | "{\n" |
| 843 | " \"segmentation\": {\n" |
| 844 | " \"type\": \"mmseg\",\n" |
| 845 | " \"dict\": {\n" |
| 846 | " \"type\": \"inline\",\n" |
| 847 | " \"entries\": {\n" |
| 848 | " \"A\": \"A\"\n" |
| 849 | " }\n" |
| 850 | " }\n" |
| 851 | " },\n" |
| 852 | " \"conversion_chain\": [{\n" |
| 853 | " \"dict\": {\n" |
| 854 | " \"type\": \"inline\"\n" |
| 855 | " }\n" |
| 856 | " }]\n" |
| 857 | "}\n", |
| 858 | "Required property not found: entries"); |
| 859 | |
| 860 | ExpectInvalidFormat( |
| 861 | "{\n" |
| 862 | " \"segmentation\": {\n" |
| 863 | " \"type\": \"mmseg\",\n" |
| 864 | " \"dict\": {\n" |
| 865 | " \"type\": \"inline\",\n" |
| 866 | " \"entries\": {\n" |
| 867 | " \"A\": \"A\"\n" |
| 868 | " }\n" |
| 869 | " }\n" |
| 870 | " },\n" |
| 871 | " \"conversion_chain\": [{\n" |
| 872 | " \"dict\": {\n" |
| 873 | " \"type\": \"inline\",\n" |
| 874 | " \"entries\": []\n" |
| 875 | " }\n" |
| 876 | " }]\n" |
| 877 | "}\n", |
| 878 | "Property must be an object: entries"); |
| 879 | |
| 880 | ExpectInvalidFormat( |
| 881 | "{\n" |
| 882 | " \"segmentation\": {\n" |
| 883 | " \"type\": \"mmseg\",\n" |
| 884 | " \"dict\": {\n" |
| 885 | " \"type\": \"inline\",\n" |
| 886 | " \"entries\": {\n" |
| 887 | " \"A\": \"A\"\n" |
| 888 | " }\n" |
| 889 | " }\n" |
| 890 | " },\n" |
| 891 | " \"conversion_chain\": [{\n" |
| 892 | " \"dict\": {\n" |
| 893 | " \"type\": \"inline\",\n" |
| 894 | " \"entries\": {\n" |
| 895 | " \"\": \"B\"\n" |
| 896 | " }\n" |
| 897 | " }\n" |
| 898 | " }]\n" |
| 899 | "}\n", |
| 900 | "Inline dictionary key must be a non-empty string"); |
| 901 | |
| 902 | ExpectInvalidFormat( |
| 903 | "{\n" |
| 904 | " \"segmentation\": {\n" |
| 905 | " \"type\": \"mmseg\",\n" |
| 906 | " \"dict\": {\n" |
| 907 | " \"type\": \"inline\",\n" |
| 908 | " \"entries\": {\n" |
| 909 | " \"A\": \"A\"\n" |
| 910 | " }\n" |
| 911 | " }\n" |
| 912 | " },\n" |
| 913 | " \"conversion_chain\": [{\n" |
| 914 | " \"dict\": {\n" |
| 915 | " \"type\": \"inline\",\n" |
| 916 | " \"entries\": {\n" |
| 917 | " \"A\": \"\"\n" |
| 918 | " }\n" |
| 919 | " }\n" |
| 920 | " }]\n" |
| 921 | "}\n", |
| 922 | "Inline dictionary value must be a non-empty string: A"); |
| 923 | |
| 924 | ExpectInvalidFormat( |
| 925 | "{\n" |
| 926 | " \"segmentation\": {\n" |
| 927 | " \"type\": \"mmseg\",\n" |
| 928 | " \"dict\": {\n" |
| 929 | " \"type\": \"inline\",\n" |
| 930 | " \"entries\": {\n" |
| 931 | " \"A\": \"A\"\n" |
| 932 | " }\n" |
| 933 | " }\n" |
| 934 | " },\n" |
| 935 | " \"conversion_chain\": [{\n" |
| 936 | " \"dict\": {\n" |
| 937 | " \"type\": \"inline\",\n" |
| 938 | " \"entries\": {\n" |
| 939 | " \"A\": 1\n" |
| 940 | " }\n" |
| 941 | " }\n" |
| 942 | " }]\n" |
| 943 | "}\n", |
| 944 | "Inline dictionary value must be a non-empty string: A"); |
| 945 | |
| 946 | ExpectInvalidFormat( |
| 947 | "{\n" |
| 948 | " \"segmentation\": {\n" |
| 949 | " \"type\": \"mmseg\",\n" |
| 950 | " \"dict\": {\n" |
| 951 | " \"type\": \"inline\",\n" |
| 952 | " \"entries\": {\n" |
| 953 | " \"A\": \"A\"\n" |
| 954 | " }\n" |
| 955 | " }\n" |
| 956 | " },\n" |
| 957 | " \"conversion_chain\": [{\n" |
| 958 | " \"dict\": {\n" |
| 959 | " \"type\": \"inline\",\n" |
| 960 | " \"may_output_tofu\": true,\n" |
| 961 | " \"entries\": {\n" |
| 962 | " \"A\": \"B\"\n" |
| 963 | " }\n" |
| 964 | " }\n" |
| 965 | " }]\n" |
| 966 | "}\n", |
| 967 | "Inline dictionary does not support may_output_tofu"); |
| 968 | } |
| 969 | |
| 970 | TEST_F(ConfigTest, InlineDictSupportsJsoncCommentsAndTrailingComma) { |
| 971 | const std::string json = |
| 972 | std::string("{\n" |
| 973 | " \"name\": \"Inline JSONC Test\",\n" |
| 974 | " \"segmentation\": {\n" |
| 975 | " \"type\": \"mmseg\",\n" |
| 976 | " \"dict\": {\n" |
| 977 | " \"type\": \"inline\",\n" |
| 978 | " \"entries\": {\n" |
| 979 | " \"麦旋风\": \"麦旋风\"\n" |
| 980 | " }\n" |
| 981 | " }\n" |
| 982 | " },\n" |
| 983 | " \"conversion_chain\": [{\n" |
| 984 | " \"dict\": {\n" |
| 985 | " \"type\": \"inline\",\n" |
| 986 | " \"entries\": {\n" |
| 987 | " // Custom entry.\n" |
| 988 | " \"麦旋风\": \"冰炫風\",\n" |
| 989 | " }\n" |
| 990 | " }\n" |
| 991 | " }]\n" |
| 992 | "}\n"); |
| 993 | |
| 994 | const ConverterPtr inlineConverter = config.NewFromString(json, ""); |
| 995 | EXPECT_EQ(utf8("冰炫風"), |
| 996 | inlineConverter->Convert(std::string_view(utf8("麦旋风")))); |
| 997 | } |
| 998 | |
| 999 | TEST_F(ConfigTest, InlineSegmentationAndConversionWorksWithOcd2GroupDicts) { |
| 1000 | const std::string ocd2Dir = FindOcd2DictionaryDir(CONFIG_TEST_DIR_PATH); |
| 1001 | if (ocd2Dir.empty()) { |
| 1002 | GTEST_SKIP() << "STPhrases.ocd2/STCharacters.ocd2 not found"; |
| 1003 | } |
| 1004 | |
| 1005 | const std::string json = |
| 1006 | std::string("{\n" |
| 1007 | " \"name\": \"Inline Segmentation+Conversion ocd2 Test\",\n" |
| 1008 | " \"segmentation\": {\n" |
| 1009 | " \"type\": \"mmseg\",\n" |
| 1010 | " \"dict\": {\n" |
| 1011 | " \"type\": \"group\",\n" |
| 1012 | " \"match_policy\": \"short_circuit\",\n" |
| 1013 | " \"dicts\": [\n" |
| 1014 | " {\n" |
| 1015 | " \"type\": \"inline\",\n" |
| 1016 | " \"entries\": {\n" |
| 1017 | " \"台湾\": \"台灣\"\n" |
| 1018 | " }\n" |
| 1019 | " },\n" |
| 1020 | " {\"type\": \"ocd2\", \"file\": \"STPhrases.ocd2\"}\n" |
| 1021 | " ]\n" |
| 1022 | " }\n" |
| 1023 | " },\n" |
| 1024 | " \"conversion_chain\": [\n" |
| 1025 | " {\n" |
| 1026 | " \"dict\": {\n" |
| 1027 | " \"type\": \"group\",\n" |
| 1028 | " \"match_policy\": \"short_circuit\",\n" |
| 1029 | " \"dicts\": [\n" |
| 1030 | " {\n" |
| 1031 | " \"type\": \"inline\",\n" |
| 1032 | " \"entries\": {\n" |
| 1033 | " \"台灣\": \"台灣\"\n" |
| 1034 | " }\n" |
| 1035 | " },\n" |
| 1036 | " {\"type\": \"ocd2\", \"file\": \"STPhrases.ocd2\"},\n" |
| 1037 | " {\"type\": \"ocd2\", \"file\": \"STCharacters.ocd2\"}\n" |
| 1038 | " ]\n" |
| 1039 | " }\n" |
| 1040 | " }\n" |
| 1041 | " ]\n" |
| 1042 | "}\n"); |
| 1043 | |
| 1044 | const ConverterPtr inlineConverter = config.NewFromString(json, {ocd2Dir}); |
| 1045 | EXPECT_EQ(utf8("臺灣"), |
| 1046 | inlineConverter->Convert(std::string_view(utf8("台湾")))); |
| 1047 | EXPECT_EQ(utf8("台灣"), |
| 1048 | inlineConverter->Convert(std::string_view(utf8("台灣")))); |
| 1049 | } |
| 1050 | |
| 1051 | #if defined(_MSC_VER) |
| 1052 | // This case exists only to verify Windows Unicode path handling in OpenCC |
| 1053 | // itself. Other platforms do not have this specific regression, and MinGW-like |
| 1054 | // Windows environments do not provide a stable enough std::filesystem Unicode |
| 1055 | // behavior for this check to be reliable. |
| 1056 | TEST_F(ConfigTest, LoadConfigFromUnicodePath) { |
| 1057 | namespace fs = std::filesystem; |
| 1058 | |
| 1059 | const fs::path sourceDir = fs::u8path(CONFIG_TEST_DIR_PATH); |
| 1060 | const fs::path tempDir = |
| 1061 | fs::temp_directory_path() / |
| 1062 | fs::u8path("opencc-中文路径-config-test-" + |
| 1063 | std::to_string(GetCurrentProcessId())); |
| 1064 | |
| 1065 | fs::remove_all(tempDir); |
| 1066 | fs::create_directories(tempDir); |
| 1067 | fs::copy_file(sourceDir / "config_test.json", tempDir / "config_test.json", |
| 1068 | fs::copy_options::overwrite_existing); |
| 1069 | fs::copy_file(sourceDir / "config_test_phrases.txt", |
| 1070 | tempDir / "config_test_phrases.txt", |
| 1071 | fs::copy_options::overwrite_existing); |
| 1072 | fs::copy_file(sourceDir / "config_test_characters.txt", |
| 1073 | tempDir / "config_test_characters.txt", |
| 1074 | fs::copy_options::overwrite_existing); |
| 1075 | try { |
| 1076 | const ConverterPtr unicodeConverter = |
| 1077 | config.NewFromFile(tempDir.u8string() + "/config_test.json"); |
| 1078 | EXPECT_EQ(expected, unicodeConverter->Convert(std::string_view(input))); |
| 1079 | } catch (...) { |
| 1080 | fs::remove_all(tempDir); |
| 1081 | throw; |
| 1082 | } |
| 1083 | |
| 1084 | fs::remove_all(tempDir); |
| 1085 | } |
| 1086 | #endif |
| 1087 | |
| 1088 | // ── Normalization tests ────────────────────────────────────────────────────── |
| 1089 | |
| 1090 | TEST_F(ConfigTest, NormalizationRunsBeforeSegmentationAndConversion) { |
| 1091 | // normalization: 甲 → 乙 main conversion: 乙 → 丙 |
| 1092 | // Without normalization the main dict would not match 甲. |
| 1093 | const std::string config = R"({ |
| 1094 | "name": "Normalization Test", |
| 1095 | "normalization": [{"dict": {"type": "inline", "entries": {"甲": "乙"}}}], |
| 1096 | "conversion_chain": [{"dict": {"type": "inline", "entries": {"乙": "丙"}}}] |
| 1097 | })"; |
| 1098 | Config c; |
| 1099 | const ConverterPtr conv = c.NewFromString(config, CONFIG_TEST_DIR_PATH); |
| 1100 | EXPECT_EQ(utf8("丙"), conv->Convert(utf8("甲"))); |
| 1101 | } |
| 1102 | |
| 1103 | TEST_F(ConfigTest, AbsentNormalizationPreservesOriginalBehavior) { |
| 1104 | const std::string config = R"({ |
| 1105 | "name": "No Normalization Test", |
| 1106 | "conversion_chain": [{"dict": {"type": "inline", "entries": {"甲": "丙"}}}] |
| 1107 | })"; |
| 1108 | Config c; |
| 1109 | const ConverterPtr conv = c.NewFromString(config, CONFIG_TEST_DIR_PATH); |
| 1110 | EXPECT_EQ(utf8("丙"), conv->Convert(utf8("甲"))); |
| 1111 | } |
| 1112 | |
| 1113 | TEST_F(ConfigTest, NormalizationMissingFileDictThrows) { |
| 1114 | const std::string config = R"({ |
| 1115 | "name": "Bad Normalization", |
| 1116 | "normalization": [{"dict": {"type": "ocd2", "file": "nonexistent.ocd2"}}], |
| 1117 | "conversion_chain": [{"dict": {"type": "inline", "entries": {"甲": "丙"}}}] |
| 1118 | })"; |
| 1119 | Config c; |
| 1120 | EXPECT_THROW(c.NewFromString(config, CONFIG_TEST_DIR_PATH), Exception); |
| 1121 | } |
| 1122 | |
| 1123 | TEST_F(ConfigTest, NormalizationGetConversionChainIsNonNull) { |
| 1124 | // Regression: converters built from configs with a normalization field must |
| 1125 | // expose a non-null GetConversionChain() so that downstream consumers such |
| 1126 | // as librime do not crash on null-pointer dereference. |
| 1127 | // The returned chain must represent the main conversion_chain (乙→丙), not |
| 1128 | // the normalization chain (甲→乙). |
| 1129 | const std::string config = R"({ |
| 1130 | "name": "Normalization Chain Test", |
| 1131 | "normalization": [{"dict": {"type": "inline", "entries": {"甲": "乙"}}}], |
| 1132 | "conversion_chain": [{"dict": {"type": "inline", "entries": {"乙": "丙"}}}] |
| 1133 | })"; |
| 1134 | Config c; |
| 1135 | const ConverterPtr conv = c.NewFromString(config, CONFIG_TEST_DIR_PATH); |
| 1136 | const ConversionChainPtr chain = conv->GetConversionChain(); |
| 1137 | ASSERT_NE(nullptr, chain); |
| 1138 | const std::list<ConversionPtr> conversions = chain->GetConversions(); |
| 1139 | ASSERT_FALSE(conversions.empty()); |
| 1140 | ASSERT_NE(nullptr, conversions.front()->GetDict()); |
| 1141 | EXPECT_FALSE(conversions.front()->GetDict()->Match(utf8("乙")).IsNull()); |
| 1142 | EXPECT_TRUE(conversions.front()->GetDict()->Match(utf8("甲")).IsNull()); |
| 1143 | |
| 1144 | // Verify it is the main chain: 乙 → 丙 (not the normalization chain 甲 → 乙). |
| 1145 | const SegmentsPtr result = chain->Convert(SegmentsPtr(new Segments{utf8("乙")})); |
| 1146 | ASSERT_EQ(1u, result->Length()); |
| 1147 | EXPECT_EQ(utf8("丙"), result->At(0)); |
| 1148 | } |
| 1149 | |
| 1150 | TEST_F(ConfigTest, RimeConvertWordExactExpansionThreadsThroughChain) { |
| 1151 | const fs::path tempDir = MakeTempDir("opencc-rime-exact-expansion-test"); |
| 1152 | WriteFile(tempDir / "first.txt", utf8("里\t裏 里 哩\n")); |
| 1153 | |
| 1154 | const std::string config = ChainConfig({ |
| 1155 | "{\"type\": \"text\", \"file\": \"first.txt\"}", |
| 1156 | "{\n" |
| 1157 | " \"type\": \"inline\",\n" |
| 1158 | " \"entries\": {\"裏\": \"裡\"}\n" |
| 1159 | " }", |
| 1160 | }); |
| 1161 | Config c; |
| 1162 | const ConverterPtr conv = c.NewFromString(config, PathString(tempDir)); |
| 1163 | |
| 1164 | std::vector<std::string> converted; |
| 1165 | EXPECT_TRUE(ConvertWordLikeRime(conv->GetConversionChain(), utf8("里"), |
| 1166 | &converted)); |
| 1167 | EXPECT_EQ((std::vector<std::string>{utf8("裡"), utf8("里"), utf8("哩")}), |
| 1168 | converted); |
| 1169 | |
| 1170 | fs::remove_all(tempDir); |
| 1171 | } |
| 1172 | |
| 1173 | TEST_F(ConfigTest, RimeConvertWordPartialFallbackContinuesToNextStage) { |
| 1174 | const std::string config = ChainConfig({ |
| 1175 | "{\n" |
| 1176 | " \"type\": \"inline\",\n" |
| 1177 | " \"entries\": {\"内\": \"內\"}\n" |
| 1178 | " }", |
| 1179 | "{\n" |
| 1180 | " \"type\": \"inline\",\n" |
| 1181 | " \"entries\": {\"內存\": \"記憶體\"}\n" |
| 1182 | " }", |
| 1183 | }); |
| 1184 | Config c; |
| 1185 | const ConverterPtr conv = c.NewFromString(config, CONFIG_TEST_DIR_PATH); |
| 1186 | |
| 1187 | std::vector<std::string> converted; |
| 1188 | EXPECT_TRUE(ConvertWordLikeRime(conv->GetConversionChain(), utf8("内存"), |
| 1189 | &converted)); |
| 1190 | EXPECT_EQ((std::vector<std::string>{utf8("記憶體")}), converted); |
| 1191 | } |
| 1192 | |
| 1193 | TEST_F(ConfigTest, RimeConvertWordReturnsFalseWithoutAnyExactMatch) { |
| 1194 | const std::string config = ChainConfig({ |
| 1195 | "{\n" |
| 1196 | " \"type\": \"inline\",\n" |
| 1197 | " \"entries\": {\"a\": \"A\"}\n" |
| 1198 | " }", |
| 1199 | "{\n" |
| 1200 | " \"type\": \"inline\",\n" |
| 1201 | " \"entries\": {\"z\": \"Z\"}\n" |
| 1202 | " }", |
| 1203 | }); |
| 1204 | Config c; |
| 1205 | const ConverterPtr conv = c.NewFromString(config, CONFIG_TEST_DIR_PATH); |
| 1206 | |
| 1207 | std::vector<std::string> converted; |
| 1208 | EXPECT_FALSE(ConvertWordLikeRime(conv->GetConversionChain(), "abc", |
| 1209 | &converted)); |
| 1210 | EXPECT_EQ((std::vector<std::string>{"Abc"}), converted); |
| 1211 | } |
| 1212 | |
| 1213 | } // namespace opencc |