| 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 <iostream> |
| 21 | #include <cstdlib> |
| 22 | #include <filesystem> |
| 23 | #include <map> |
| 24 | #include <sstream> |
| 25 | #include <unordered_map> |
| 26 | #include <vector> |
| 27 | |
| 28 | #include "test/PortableUtil.hpp" |
| 29 | |
| 30 | #include "src/Common.hpp" |
| 31 | #include "rapidjson/document.h" |
| 32 | #include "gtest/gtest.h" |
| 33 | |
| 34 | #ifdef _WIN32 |
| 35 | #ifndef NOMINMAX |
| 36 | #define NOMINMAX |
| 37 | #endif |
| 38 | #include <windows.h> |
| 39 | #else |
| 40 | #include <sys/stat.h> |
| 41 | #endif |
| 42 | |
| 43 | #ifdef BAZEL |
| 44 | #include "tools/cpp/runfiles/runfiles.h" |
| 45 | using bazel::tools::cpp::runfiles::Runfiles; |
| 46 | #endif |
| 47 | |
| 48 | namespace opencc { |
| 49 | |
| 50 | namespace fs = std::filesystem; |
| 51 | |
| 52 | #ifdef _WIN32 |
| 53 | std::wstring WideFromUtf8(const std::string& utf8) { |
| 54 | if (utf8.empty()) { |
| 55 | return L""; |
| 56 | } |
| 57 | const int required = |
| 58 | MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, nullptr, 0); |
| 59 | if (required <= 1) { |
| 60 | return L""; |
| 61 | } |
| 62 | std::wstring wide(static_cast<size_t>(required), L'\0'); |
| 63 | MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, wide.data(), required); |
| 64 | wide.resize(static_cast<size_t>(required - 1)); |
| 65 | return wide; |
| 66 | } |
| 67 | #endif |
| 68 | |
| 69 | class CommandLineConvertTest : public ::testing::Test { |
| 70 | protected: |
| 71 | CommandLineConvertTest() { GetCurrentWorkingDirectory(); } |
| 72 | |
| 73 | virtual ~CommandLineConvertTest() { free(originalWorkingDirectory); } |
| 74 | |
| 75 | virtual void SetUp() { |
| 76 | #ifdef BAZEL |
| 77 | runfiles_.reset(Runfiles::CreateForTest()); |
| 78 | #else |
| 79 | ASSERT_NE("", PROJECT_BINARY_DIR); |
| 80 | ASSERT_NE("", PROJECT_SOURCE_DIR); |
| 81 | ASSERT_EQ(0, portable_chdir(PROJECT_BINARY_DIR "/data")); |
| 82 | #endif |
| 83 | } |
| 84 | |
| 85 | virtual void TearDown() { ASSERT_EQ(0, portable_chdir(originalWorkingDirectory)); } |
| 86 | |
| 87 | std::string GetFileContents(const std::string& fileName) const { |
| 88 | std::ifstream fs(fileName, std::ios::binary); |
| 89 | EXPECT_TRUE(fs.is_open()) << fileName; |
| 90 | const std::string content((std::istreambuf_iterator<char>(fs)), |
| 91 | (std::istreambuf_iterator<char>())); |
| 92 | fs.close(); |
| 93 | return content; |
| 94 | } |
| 95 | |
| 96 | std::string GetFileContents(const fs::path& fileName) const { |
| 97 | std::ifstream stream(fileName, std::ios::binary); |
| 98 | EXPECT_TRUE(stream.is_open()) << fileName.u8string(); |
| 99 | const std::string content((std::istreambuf_iterator<char>(stream)), |
| 100 | (std::istreambuf_iterator<char>())); |
| 101 | stream.close(); |
| 102 | return content; |
| 103 | } |
| 104 | |
| 105 | void GetCurrentWorkingDirectory() { |
| 106 | originalWorkingDirectory = portable_getcwd(); |
| 107 | } |
| 108 | |
| 109 | std::string OpenccCommand() const { |
| 110 | #ifdef BAZEL |
| 111 | #ifdef _WIN32 |
| 112 | // On Windows, cc_binary executables have .exe extension in the runfiles manifest |
| 113 | std::string path = runfiles_->Rlocation("_main/src/tools/command_line.exe"); |
| 114 | if (path.empty()) { |
| 115 | path = runfiles_->Rlocation("_main/src/tools/command_line"); |
| 116 | } |
| 117 | return path; |
| 118 | #else |
| 119 | return runfiles_->Rlocation("_main/src/tools/command_line"); |
| 120 | #endif |
| 121 | #else |
| 122 | #ifndef _MSC_VER |
| 123 | return PROJECT_BINARY_DIR "/src/tools/opencc"; |
| 124 | #else |
| 125 | #ifdef NDEBUG |
| 126 | return PROJECT_BINARY_DIR "/src/tools/Release/opencc.exe"; |
| 127 | #else |
| 128 | return PROJECT_BINARY_DIR "/src/tools/Debug/opencc.exe"; |
| 129 | #endif |
| 130 | #endif |
| 131 | #endif |
| 132 | } |
| 133 | |
| 134 | // Quote a path for use in a shell command, in case the path contains spaces. |
| 135 | static std::string QuotePath(const std::string& path) { |
| 136 | return "\"" + path + "\""; |
| 137 | } |
| 138 | |
| 139 | std::string OutputDirectory() const { |
| 140 | #ifdef BAZEL |
| 141 | return ::testing::TempDir() + "/"; |
| 142 | #else |
| 143 | return PROJECT_BINARY_DIR "/test/"; |
| 144 | #endif |
| 145 | } |
| 146 | |
| 147 | #if defined(BAZEL) && defined(OPENCC_ENABLE_RESOURCE_ZIP_TEST) |
| 148 | std::string ResourceZipFile() const { |
| 149 | return runfiles_->Rlocation("_main/data/opencc-resources.zip"); |
| 150 | } |
| 151 | |
| 152 | std::string ResourceOcd2ZipFile() const { |
| 153 | return runfiles_->Rlocation("_main/data/opencc-resources-ocd2.zip"); |
| 154 | } |
| 155 | #endif |
| 156 | |
| 157 | std::string ConfigurationDirectory() const { |
| 158 | #ifdef BAZEL |
| 159 | return ""; |
| 160 | #else |
| 161 | return PROJECT_SOURCE_DIR "/data/config/"; |
| 162 | #endif |
| 163 | } |
| 164 | |
| 165 | std::string InputFile(const char* config) const { |
| 166 | return OutputDirectory() + config + ".in"; |
| 167 | } |
| 168 | |
| 169 | std::string OutputFile(const char* config) const { |
| 170 | return OutputDirectory() + config + ".out"; |
| 171 | } |
| 172 | |
| 173 | std::string TestCommand(const std::string& config, |
| 174 | const std::string& inputFile, |
| 175 | const std::string& outputFile, |
| 176 | const std::string& measuredResultFile = "", |
| 177 | const std::string& extraFlags = "") const { |
| 178 | std::string cmd = QuotePath(OpenccCommand()) + " -i " + |
| 179 | QuotePath(inputFile) + " -o " + |
| 180 | QuotePath(outputFile) + " -c " + |
| 181 | QuotePath(ConfigurationDirectory() + config + ".json"); |
| 182 | if (!extraFlags.empty()) { |
| 183 | cmd += " " + extraFlags; |
| 184 | } |
| 185 | if (!measuredResultFile.empty()) { |
| 186 | cmd += " --measured_result " + QuotePath(measuredResultFile); |
| 187 | } |
| 188 | #ifdef BAZEL |
| 189 | const std::string dictFile = |
| 190 | runfiles_->Rlocation("_main/data/dictionary/STCharacters.ocd2"); |
| 191 | const std::string dictDir = |
| 192 | dictFile.substr(0, dictFile.find_last_of("/\\")); |
| 193 | const std::string configFile = |
| 194 | runfiles_->Rlocation("_main/data/config/s2t.json"); |
| 195 | const std::string configDir = |
| 196 | configFile.substr(0, configFile.find_last_of("/\\")); |
| 197 | cmd += " --path " + QuotePath(dictDir + "/") + |
| 198 | " --path " + QuotePath(configDir + "/"); |
| 199 | #endif |
| 200 | #ifdef _WIN32 |
| 201 | // On Windows, cmd.exe /C strips the first and last quote characters when |
| 202 | // the command starts with a quoted path, corrupting the command. Wrapping |
| 203 | // the entire command in an extra pair of outer quotes causes cmd.exe to |
| 204 | // strip only those outer quotes, leaving the inner quoted paths intact. |
| 205 | return "\"" + cmd + "\""; |
| 206 | #else |
| 207 | return cmd; |
| 208 | #endif |
| 209 | } |
| 210 | |
| 211 | static int RunCommand(const std::string& cmd) { |
| 212 | #ifdef _WIN32 |
| 213 | return _wsystem(WideFromUtf8(cmd).c_str()); |
| 214 | #else |
| 215 | return system(cmd.c_str()); |
| 216 | #endif |
| 217 | } |
| 218 | |
| 219 | #if defined(BAZEL) && defined(OPENCC_ENABLE_RESOURCE_ZIP_TEST) |
| 220 | std::string TestResourceZipCommand(const std::string& config, |
| 221 | const std::string& inputFile, |
| 222 | const std::string& outputFile) const { |
| 223 | std::string cmd = QuotePath(OpenccCommand()) + " -i " + |
| 224 | QuotePath(inputFile) + " -o " + QuotePath(outputFile) + |
| 225 | " -c " + QuotePath(config + ".json") + |
| 226 | " --resource-zip " + QuotePath(ResourceZipFile()); |
| 227 | #ifdef _WIN32 |
| 228 | return "\"" + cmd + "\""; |
| 229 | #else |
| 230 | return cmd; |
| 231 | #endif |
| 232 | } |
| 233 | #endif |
| 234 | |
| 235 | std::string TestCommandWithFlags(const std::string& config, |
| 236 | const std::string& inputFile, |
| 237 | const std::string& outputFile, |
| 238 | const std::string& extraFlags, |
| 239 | const std::string& measuredResultFile = "") |
| 240 | const { |
| 241 | return TestCommand(config, inputFile, outputFile, measuredResultFile, |
| 242 | extraFlags); |
| 243 | } |
| 244 | |
| 245 | std::string TestStdinCommand(const std::string& config, |
| 246 | const std::string& inputFile, |
| 247 | const std::string& outputFile) const { |
| 248 | std::string cmd = QuotePath(OpenccCommand()) + " -c " + |
| 249 | QuotePath(ConfigurationDirectory() + config + ".json"); |
| 250 | #ifdef BAZEL |
| 251 | const std::string dictFile = |
| 252 | runfiles_->Rlocation("_main/data/dictionary/STCharacters.ocd2"); |
| 253 | const std::string dictDir = |
| 254 | dictFile.substr(0, dictFile.find_last_of("/\\")); |
| 255 | const std::string configFile = |
| 256 | runfiles_->Rlocation("_main/data/config/s2t.json"); |
| 257 | const std::string configDir = |
| 258 | configFile.substr(0, configFile.find_last_of("/\\")); |
| 259 | cmd += " --path " + QuotePath(dictDir + "/") + |
| 260 | " --path " + QuotePath(configDir + "/"); |
| 261 | #endif |
| 262 | cmd += " < " + QuotePath(inputFile) + " > " + QuotePath(outputFile); |
| 263 | #ifdef _WIN32 |
| 264 | return "\"" + cmd + "\""; |
| 265 | #else |
| 266 | return cmd; |
| 267 | #endif |
| 268 | } |
| 269 | |
| 270 | #ifndef _WIN32 |
| 271 | std::string TestPipeCommand(const std::string& config, |
| 272 | const std::string& outputFile) const { |
| 273 | std::string cmd = "(printf '后台'; sleep 0.1; printf '老板') | " + |
| 274 | QuotePath(OpenccCommand()) + " -c " + |
| 275 | QuotePath(ConfigurationDirectory() + config + ".json"); |
| 276 | #ifdef BAZEL |
| 277 | const std::string dictFile = |
| 278 | runfiles_->Rlocation("_main/data/dictionary/STCharacters.ocd2"); |
| 279 | const std::string dictDir = |
| 280 | dictFile.substr(0, dictFile.find_last_of("/\\")); |
| 281 | const std::string configFile = |
| 282 | runfiles_->Rlocation("_main/data/config/s2t.json"); |
| 283 | const std::string configDir = |
| 284 | configFile.substr(0, configFile.find_last_of("/\\")); |
| 285 | cmd += " --path " + QuotePath(dictDir + "/") + |
| 286 | " --path " + QuotePath(configDir + "/"); |
| 287 | #endif |
| 288 | cmd += " > " + QuotePath(outputFile); |
| 289 | return cmd; |
| 290 | } |
| 291 | #endif |
| 292 | |
| 293 | char* originalWorkingDirectory; |
| 294 | |
| 295 | #ifdef BAZEL |
| 296 | std::unique_ptr<Runfiles> runfiles_; |
| 297 | #endif |
| 298 | }; |
| 299 | |
| 300 | struct CaseInput { |
| 301 | std::string input; |
| 302 | std::string expected; |
| 303 | }; |
| 304 | |
| 305 | using CasesByConfig = std::unordered_map<std::string, std::vector<CaseInput>>; |
| 306 | |
| 307 | CasesByConfig LoadCases(const std::string& jsonPath) { |
| 308 | CasesByConfig cases; |
| 309 | std::string content; |
| 310 | { |
| 311 | std::ifstream ifs(jsonPath); |
| 312 | if (!ifs.is_open()) { |
| 313 | throw std::runtime_error("Cannot open " + jsonPath); |
| 314 | } |
| 315 | std::stringstream buffer; |
| 316 | buffer << ifs.rdbuf(); |
| 317 | content = buffer.str(); |
| 318 | } |
| 319 | |
| 320 | rapidjson::Document doc; |
| 321 | doc.Parse<rapidjson::kParseCommentsFlag | |
| 322 | rapidjson::kParseTrailingCommasFlag>(content.c_str()); |
| 323 | if (doc.HasParseError() || !doc.IsObject() || !doc.HasMember("cases") || |
| 324 | !doc["cases"].IsArray()) { |
| 325 | throw std::runtime_error("Invalid testcases.json format"); |
| 326 | } |
| 327 | |
| 328 | for (auto& entry : doc["cases"].GetArray()) { |
| 329 | if (!entry.IsObject() || !entry.HasMember("input") || |
| 330 | !entry["input"].IsString() || !entry.HasMember("expected") || |
| 331 | !entry["expected"].IsObject()) { |
| 332 | continue; |
| 333 | } |
| 334 | const std::string input = entry["input"].GetString(); |
| 335 | for (auto itr = entry["expected"].MemberBegin(); |
| 336 | itr != entry["expected"].MemberEnd(); ++itr) { |
| 337 | if (!itr->value.IsString()) { |
| 338 | continue; |
| 339 | } |
| 340 | const std::string config = itr->name.GetString(); |
| 341 | cases[config].push_back({input, itr->value.GetString()}); |
| 342 | } |
| 343 | } |
| 344 | return cases; |
| 345 | } |
| 346 | |
| 347 | TEST_F(CommandLineConvertTest, ConvertFromJson) { |
| 348 | #ifdef BAZEL |
| 349 | const std::string casesPath = |
| 350 | runfiles_->Rlocation("_main/test/testcases/testcases.json"); |
| 351 | #else |
| 352 | const std::string casesPath = PROJECT_SOURCE_DIR "/test/testcases/testcases.json"; |
| 353 | #endif |
| 354 | const CasesByConfig cases = LoadCases(casesPath); |
| 355 | |
| 356 | for (const auto& entry : cases) { |
| 357 | const std::string& config = entry.first; |
| 358 | const std::string inputFile = InputFile(config.c_str()); |
| 359 | const std::string outputFile = OutputFile(config.c_str()); |
| 360 | |
| 361 | // Write inputs into a temp file (one per line). |
| 362 | { |
| 363 | std::ofstream ofs(inputFile, std::ios::binary); |
| 364 | ASSERT_TRUE(ofs.is_open()) << "Failed to open input file for writing: " |
| 365 | << inputFile; |
| 366 | for (const auto& item : entry.second) { |
| 367 | ofs << item.input << "\n"; |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | ASSERT_EQ(0, |
| 372 | system(TestCommandWithFlags( |
| 373 | config, inputFile, outputFile, |
| 374 | "--include-tofu-risk-dictionaries") |
| 375 | .c_str())); |
| 376 | |
| 377 | // Read outputs and compare line by line. |
| 378 | std::ifstream ifs(outputFile, std::ios::binary); |
| 379 | ASSERT_TRUE(ifs.is_open()); |
| 380 | std::string line; |
| 381 | size_t idx = 0; |
| 382 | while (std::getline(ifs, line)) { |
| 383 | if (!line.empty() && line.back() == '\r') { |
| 384 | line.pop_back(); // normalize Windows CRLF |
| 385 | } |
| 386 | ASSERT_LT(idx, entry.second.size()); |
| 387 | EXPECT_EQ(entry.second[idx].expected, line) |
| 388 | << "config=" << config << " index=" << idx; |
| 389 | idx++; |
| 390 | } |
| 391 | EXPECT_EQ(idx, entry.second.size()) << "config=" << config; |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | TEST_F(CommandLineConvertTest, SkipsTofuRiskDictionariesByDefault) { |
| 396 | const std::string inputFile = InputFile("tofu_risk_default"); |
| 397 | const std::string outputFile = OutputFile("tofu_risk_default"); |
| 398 | |
| 399 | { |
| 400 | std::ofstream ofs(inputFile, std::ios::binary); |
| 401 | ASSERT_TRUE(ofs.is_open()); |
| 402 | ofs << "㑮"; |
| 403 | } |
| 404 | |
| 405 | ASSERT_EQ(0, system(TestCommand("t2s", inputFile, outputFile).c_str())); |
| 406 | EXPECT_EQ("㑮", GetFileContents(outputFile)); |
| 407 | } |
| 408 | |
| 409 | TEST_F(CommandLineConvertTest, IncludeTofuRiskDictionariesFlagRestoresLegacy) { |
| 410 | const std::string inputFile = InputFile("tofu_risk_include"); |
| 411 | const std::string outputFile = OutputFile("tofu_risk_include"); |
| 412 | |
| 413 | { |
| 414 | std::ofstream ofs(inputFile, std::ios::binary); |
| 415 | ASSERT_TRUE(ofs.is_open()); |
| 416 | ofs << "㑮"; |
| 417 | } |
| 418 | |
| 419 | ASSERT_EQ(0, system(TestCommandWithFlags( |
| 420 | "t2s", inputFile, outputFile, |
| 421 | "--include-tofu-risk-dictionaries") |
| 422 | .c_str())); |
| 423 | EXPECT_EQ("𫝈", GetFileContents(outputFile)); |
| 424 | } |
| 425 | |
| 426 | #if defined(BAZEL) && defined(OPENCC_ENABLE_RESOURCE_ZIP_TEST) |
| 427 | TEST_F(CommandLineConvertTest, ResourceZipConvertsWithoutResourcePaths) { |
| 428 | const std::string inputFile = InputFile("resource_zip"); |
| 429 | const std::string outputFile = OutputFile("resource_zip"); |
| 430 | |
| 431 | { |
| 432 | std::ofstream ofs(inputFile, std::ios::binary); |
| 433 | ASSERT_TRUE(ofs.is_open()); |
| 434 | ofs << "打印机和鼠标"; |
| 435 | } |
| 436 | |
| 437 | ASSERT_EQ(0, |
| 438 | RunCommand(TestResourceZipCommand("s2twp", inputFile, outputFile))); |
| 439 | EXPECT_EQ("印表機和滑鼠", GetFileContents(outputFile)); |
| 440 | } |
| 441 | |
| 442 | TEST_F(CommandLineConvertTest, ResourceOcd2ZipConvertsWithoutResourcePaths) { |
| 443 | const std::string inputFile = InputFile("resource_ocd2_zip"); |
| 444 | const std::string outputFile = OutputFile("resource_ocd2_zip"); |
| 445 | |
| 446 | { |
| 447 | std::ofstream ofs(inputFile, std::ios::binary); |
| 448 | ASSERT_TRUE(ofs.is_open()); |
| 449 | ofs << "打印机和鼠标"; |
| 450 | } |
| 451 | |
| 452 | std::string cmd = QuotePath(OpenccCommand()) + " -i " + |
| 453 | QuotePath(inputFile) + " -o " + QuotePath(outputFile) + |
| 454 | " -c s2twp.json" + |
| 455 | " --resource-zip " + QuotePath(ResourceOcd2ZipFile()); |
| 456 | #ifdef _WIN32 |
| 457 | cmd = "\"" + cmd + "\""; |
| 458 | #endif |
| 459 | |
| 460 | ASSERT_EQ(0, RunCommand(cmd)); |
| 461 | EXPECT_EQ("印表機和滑鼠", GetFileContents(outputFile)); |
| 462 | } |
| 463 | #endif |
| 464 | |
| 465 | TEST_F(CommandLineConvertTest, StdinPreservesLineEndingsAndUnknownCharacters) { |
| 466 | const std::string config = "s2t"; |
| 467 | const std::string inputFile = InputFile("stdin_line_endings"); |
| 468 | const std::string outputFile = OutputFile("stdin_line_endings"); |
| 469 | |
| 470 | { |
| 471 | std::ofstream ofs(inputFile, std::ios::binary); |
| 472 | ASSERT_TRUE(ofs.is_open()); |
| 473 | ofs << "鼠标=mouse\r\n123\n未登录"; |
| 474 | } |
| 475 | |
| 476 | ASSERT_EQ(0, system(TestStdinCommand(config, inputFile, outputFile).c_str())); |
| 477 | EXPECT_EQ("鼠標=mouse\r\n123\n未登錄", GetFileContents(outputFile)); |
| 478 | } |
| 479 | |
| 480 | #ifndef _WIN32 |
| 481 | TEST_F(CommandLineConvertTest, WarnsWhenInputContainsVariationSelector) { |
| 482 | const std::string inputFile = InputFile("ivs_warning"); |
| 483 | const std::string outputFile = OutputFile("ivs_warning"); |
| 484 | const std::string stderrFile = OutputFile("ivs_warning.stderr"); |
| 485 | const std::string variationSelector = "\xF3\xA0\x84\x80"; |
| 486 | |
| 487 | { |
| 488 | std::ofstream ofs(inputFile, std::ios::binary); |
| 489 | ASSERT_TRUE(ofs.is_open()); |
| 490 | ofs << "汉禰" << variationSelector; |
| 491 | } |
| 492 | |
| 493 | const std::string command = |
| 494 | TestCommand("s2t", inputFile, outputFile) + " 2> " + |
| 495 | QuotePath(stderrFile); |
| 496 | ASSERT_EQ(0, system(command.c_str())); |
| 497 | EXPECT_EQ("漢禰" + variationSelector, GetFileContents(outputFile)); |
| 498 | EXPECT_NE(std::string::npos, |
| 499 | GetFileContents(stderrFile).find( |
| 500 | "warning: input contains Unicode variation selectors")); |
| 501 | } |
| 502 | |
| 503 | TEST_F(CommandLineConvertTest, |
| 504 | WarnsWhenSupplementaryVariationSelectorCrossesChunkBoundary) { |
| 505 | const std::string inputFile = InputFile("ivs_warning_chunk_boundary"); |
| 506 | const std::string outputFile = OutputFile("ivs_warning_chunk_boundary"); |
| 507 | const std::string stderrFile = |
| 508 | OutputFile("ivs_warning_chunk_boundary.stderr"); |
| 509 | |
| 510 | std::string input(1048576 - 1, 'a'); |
| 511 | input.push_back(static_cast<char>(0xF3)); |
| 512 | input.push_back(static_cast<char>(0xA0)); |
| 513 | input.push_back(static_cast<char>(0x84)); |
| 514 | input.push_back(static_cast<char>(0x80)); |
| 515 | |
| 516 | { |
| 517 | std::ofstream ofs(inputFile, std::ios::binary); |
| 518 | ASSERT_TRUE(ofs.is_open()); |
| 519 | ofs << input; |
| 520 | } |
| 521 | |
| 522 | const std::string command = |
| 523 | TestCommand("s2t", inputFile, outputFile) + " 2> " + |
| 524 | QuotePath(stderrFile); |
| 525 | ASSERT_EQ(0, system(command.c_str())); |
| 526 | EXPECT_EQ(input, GetFileContents(outputFile)); |
| 527 | EXPECT_NE(std::string::npos, |
| 528 | GetFileContents(stderrFile).find( |
| 529 | "warning: input contains Unicode variation selectors")); |
| 530 | } |
| 531 | #endif |
| 532 | |
| 533 | #ifndef _WIN32 |
| 534 | TEST_F(CommandLineConvertTest, PipeShortReadContinuesUntilEof) { |
| 535 | const std::string outputFile = OutputFile("pipe_short_read"); |
| 536 | |
| 537 | ASSERT_EQ(0, system(TestPipeCommand("s2t", outputFile).c_str())); |
| 538 | |
| 539 | ASSERT_EQ("後臺老闆", GetFileContents(outputFile)); |
| 540 | } |
| 541 | #endif |
| 542 | |
| 543 | TEST_F(CommandLineConvertTest, ConvertsFilesWithUnicodePaths) { |
| 544 | const fs::path unicodeDir = |
| 545 | fs::u8path(OutputDirectory()) / fs::u8path("opencc-中文路径-cli-😀-𠮷"); |
| 546 | fs::create_directories(unicodeDir); |
| 547 | |
| 548 | const fs::path inputFile = unicodeDir / fs::u8path("输入 文件.txt"); |
| 549 | const fs::path outputFile = unicodeDir / fs::u8path("輸出 文件.txt"); |
| 550 | const fs::path measuredResultFile = |
| 551 | unicodeDir / fs::u8path("測量 結果.json"); |
| 552 | |
| 553 | { |
| 554 | std::ofstream ofs(inputFile, std::ios::binary); |
| 555 | ASSERT_TRUE(ofs.is_open()) << inputFile.u8string(); |
| 556 | ofs << "开放中文转换"; |
| 557 | } |
| 558 | |
| 559 | ASSERT_EQ(0, RunCommand(TestCommand("s2t", inputFile.u8string(), |
| 560 | outputFile.u8string(), |
| 561 | measuredResultFile.u8string()))); |
| 562 | EXPECT_EQ("開放中文轉換", GetFileContents(outputFile)); |
| 563 | |
| 564 | const std::string measured = GetFileContents(measuredResultFile); |
| 565 | rapidjson::Document doc; |
| 566 | doc.Parse(measured.c_str()); |
| 567 | ASSERT_FALSE(doc.HasParseError()) << measured; |
| 568 | ASSERT_TRUE(doc.IsObject()); |
| 569 | ASSERT_TRUE(doc.HasMember("input")); |
| 570 | EXPECT_EQ(inputFile.u8string(), std::string(doc["input"].GetString())); |
| 571 | } |
| 572 | |
| 573 | TEST_F(CommandLineConvertTest, ConvertsInPlaceWithUnicodePath) { |
| 574 | const fs::path unicodeDir = |
| 575 | fs::u8path(OutputDirectory()) / fs::u8path("opencc-就地转换-cli-😀"); |
| 576 | fs::create_directories(unicodeDir); |
| 577 | |
| 578 | const fs::path file = unicodeDir / fs::u8path("输入输出同一文件.txt"); |
| 579 | |
| 580 | { |
| 581 | std::ofstream ofs(file, std::ios::binary); |
| 582 | ASSERT_TRUE(ofs.is_open()) << file.u8string(); |
| 583 | ofs << "开放中文转换"; |
| 584 | } |
| 585 | |
| 586 | ASSERT_EQ(0, RunCommand(TestCommand("s2t", file.u8string(), file.u8string(), |
| 587 | "", "--in-place"))); |
| 588 | EXPECT_EQ("開放中文轉換", GetFileContents(file)); |
| 589 | } |
| 590 | |
| 591 | TEST_F(CommandLineConvertTest, RejectsInPlaceConversionWithoutFlag) { |
| 592 | const fs::path unicodeDir = |
| 593 | fs::u8path(OutputDirectory()) / fs::u8path("opencc-拒绝就地转换-cli"); |
| 594 | fs::create_directories(unicodeDir); |
| 595 | |
| 596 | const fs::path file = unicodeDir / fs::u8path("输入输出同一文件.txt"); |
| 597 | |
| 598 | { |
| 599 | std::ofstream ofs(file, std::ios::binary); |
| 600 | ASSERT_TRUE(ofs.is_open()) << file.u8string(); |
| 601 | ofs << "开放中文转换"; |
| 602 | } |
| 603 | |
| 604 | EXPECT_NE(0, RunCommand(TestCommand("s2t", file.u8string(), file.u8string()))); |
| 605 | EXPECT_EQ("开放中文转换", GetFileContents(file)); |
| 606 | } |
| 607 | |
| 608 | TEST_F(CommandLineConvertTest, MissingInputDoesNotTruncateOutput) { |
| 609 | const fs::path unicodeDir = |
| 610 | fs::u8path(OutputDirectory()) / fs::u8path("opencc-缺失输入-cli"); |
| 611 | fs::create_directories(unicodeDir); |
| 612 | |
| 613 | const fs::path inputFile = unicodeDir / fs::u8path("不存在.txt"); |
| 614 | const fs::path outputFile = unicodeDir / fs::u8path("已有输出.txt"); |
| 615 | |
| 616 | { |
| 617 | std::ofstream ofs(outputFile, std::ios::binary); |
| 618 | ASSERT_TRUE(ofs.is_open()) << outputFile.u8string(); |
| 619 | ofs << "existing output"; |
| 620 | } |
| 621 | |
| 622 | EXPECT_NE(0, RunCommand(TestCommand("s2t", inputFile.u8string(), |
| 623 | outputFile.u8string()))); |
| 624 | EXPECT_EQ("existing output", GetFileContents(outputFile)); |
| 625 | } |
| 626 | |
| 627 | TEST_F(CommandLineConvertTest, ConvertsInPlaceWithDifferentPathSpellings) { |
| 628 | const fs::path unicodeDir = |
| 629 | fs::u8path(OutputDirectory()) / fs::u8path("opencc-同文件不同路径-cli"); |
| 630 | fs::create_directories(unicodeDir); |
| 631 | |
| 632 | const fs::path file = unicodeDir / fs::u8path("输入输出同一文件.txt"); |
| 633 | |
| 634 | { |
| 635 | std::ofstream ofs(file, std::ios::binary); |
| 636 | ASSERT_TRUE(ofs.is_open()) << file.u8string(); |
| 637 | ofs << "开放中文转换"; |
| 638 | } |
| 639 | |
| 640 | const fs::path spelledDifferently = unicodeDir / fs::u8path(".") / |
| 641 | fs::u8path("输入输出同一文件.txt"); |
| 642 | ASSERT_EQ(0, RunCommand(TestCommand("s2t", file.u8string(), |
| 643 | spelledDifferently.u8string(), "", |
| 644 | "--in-place"))); |
| 645 | EXPECT_EQ("開放中文轉換", GetFileContents(file)); |
| 646 | } |
| 647 | |
| 648 | #ifndef _WIN32 |
| 649 | TEST_F(CommandLineConvertTest, InPlaceConversionPreservesFileMode) { |
| 650 | const fs::path unicodeDir = |
| 651 | fs::u8path(OutputDirectory()) / fs::u8path("opencc-保留权限-cli"); |
| 652 | fs::create_directories(unicodeDir); |
| 653 | |
| 654 | const fs::path file = unicodeDir / fs::u8path("输入输出同一文件.txt"); |
| 655 | |
| 656 | { |
| 657 | std::ofstream ofs(file, std::ios::binary); |
| 658 | ASSERT_TRUE(ofs.is_open()) << file.u8string(); |
| 659 | ofs << "开放中文转换"; |
| 660 | } |
| 661 | ASSERT_EQ(0, chmod(file.c_str(), 0644)); |
| 662 | |
| 663 | ASSERT_EQ(0, RunCommand(TestCommand("s2t", file.u8string(), file.u8string(), |
| 664 | "", "--in-place"))); |
| 665 | EXPECT_EQ("開放中文轉換", GetFileContents(file)); |
| 666 | |
| 667 | struct stat info; |
| 668 | ASSERT_EQ(0, stat(file.c_str(), &info)); |
| 669 | EXPECT_EQ(0644, info.st_mode & 07777); |
| 670 | } |
| 671 | |
| 672 | TEST_F(CommandLineConvertTest, InPlaceConversionRejectsHardLinks) { |
| 673 | const fs::path unicodeDir = |
| 674 | fs::u8path(OutputDirectory()) / fs::u8path("opencc-拒绝硬链接-cli"); |
| 675 | fs::create_directories(unicodeDir); |
| 676 | |
| 677 | const fs::path file = unicodeDir / fs::u8path("真实输入输出.txt"); |
| 678 | const fs::path hardLink = unicodeDir / fs::u8path("硬链接输出.txt"); |
| 679 | |
| 680 | { |
| 681 | std::ofstream ofs(file, std::ios::binary); |
| 682 | ASSERT_TRUE(ofs.is_open()) << file.u8string(); |
| 683 | ofs << "开放中文转换"; |
| 684 | } |
| 685 | |
| 686 | std::error_code error; |
| 687 | fs::remove(hardLink, error); |
| 688 | fs::create_hard_link(file, hardLink, error); |
| 689 | if (error) { |
| 690 | GTEST_SKIP() << "Hard-link creation failed: " << error.message(); |
| 691 | } |
| 692 | |
| 693 | EXPECT_NE(0, RunCommand(TestCommand("s2t", file.u8string(), |
| 694 | hardLink.u8string(), "", |
| 695 | "--in-place"))); |
| 696 | EXPECT_EQ("开放中文转换", GetFileContents(file)); |
| 697 | EXPECT_EQ("开放中文转换", GetFileContents(hardLink)); |
| 698 | } |
| 699 | #endif |
| 700 | |
| 701 | TEST_F(CommandLineConvertTest, ConvertsInPlaceThroughSymlink) { |
| 702 | const fs::path unicodeDir = |
| 703 | fs::u8path(OutputDirectory()) / fs::u8path("opencc-符号链接-cli"); |
| 704 | fs::create_directories(unicodeDir); |
| 705 | |
| 706 | const fs::path file = unicodeDir / fs::u8path("真实输入输出.txt"); |
| 707 | const fs::path symlink = unicodeDir / fs::u8path("符号链接输出.txt"); |
| 708 | |
| 709 | { |
| 710 | std::ofstream ofs(file, std::ios::binary); |
| 711 | ASSERT_TRUE(ofs.is_open()) << file.u8string(); |
| 712 | ofs << "开放中文转换"; |
| 713 | } |
| 714 | |
| 715 | std::error_code error; |
| 716 | fs::remove(symlink, error); |
| 717 | fs::create_symlink(file.filename(), symlink, error); |
| 718 | if (error) { |
| 719 | GTEST_SKIP() << "Symlink creation failed: " << error.message(); |
| 720 | } |
| 721 | |
| 722 | ASSERT_EQ(0, RunCommand(TestCommand("s2t", file.u8string(), |
| 723 | symlink.u8string(), "", "--in-place"))); |
| 724 | EXPECT_EQ("開放中文轉換", GetFileContents(file)); |
| 725 | } |
| 726 | |
| 727 | TEST_F(CommandLineConvertTest, WritesMeasuredResultJson) { |
| 728 | const std::string config = "s2t"; |
| 729 | const std::string inputFile = InputFile(config.c_str()) + ".measured"; |
| 730 | const std::string outputFile = OutputFile(config.c_str()) + ".measured"; |
| 731 | const std::string measuredResultFile = |
| 732 | OutputDirectory() + config + ".measured_result.json"; |
| 733 | |
| 734 | { |
| 735 | std::ofstream ofs(inputFile, std::ios::binary); |
| 736 | ASSERT_TRUE(ofs.is_open()) << "Failed to open input file for writing: " |
| 737 | << inputFile; |
| 738 | ofs << "开放中文转换" << std::endl; |
| 739 | } |
| 740 | |
| 741 | ASSERT_EQ(0, system(TestCommand(config, inputFile, outputFile, |
| 742 | measuredResultFile).c_str())); |
| 743 | |
| 744 | const std::string content = GetFileContents(measuredResultFile); |
| 745 | rapidjson::Document doc; |
| 746 | doc.Parse(content.c_str()); |
| 747 | ASSERT_FALSE(doc.HasParseError()); |
| 748 | ASSERT_TRUE(doc.IsObject()); |
| 749 | ASSERT_TRUE(doc.HasMember("config")); |
| 750 | ASSERT_TRUE(doc["config"].IsString()); |
| 751 | EXPECT_EQ(ConfigurationDirectory() + config + ".json", |
| 752 | std::string(doc["config"].GetString())); |
| 753 | ASSERT_TRUE(doc.HasMember("mode")); |
| 754 | EXPECT_STREQ("file", doc["mode"].GetString()); |
| 755 | ASSERT_TRUE(doc.HasMember("load_ms")); |
| 756 | EXPECT_TRUE(doc["load_ms"].IsNumber()); |
| 757 | ASSERT_TRUE(doc.HasMember("convert_ms")); |
| 758 | EXPECT_TRUE(doc["convert_ms"].IsNumber()); |
| 759 | ASSERT_TRUE(doc.HasMember("write_ms")); |
| 760 | EXPECT_TRUE(doc["write_ms"].IsNumber()); |
| 761 | ASSERT_TRUE(doc.HasMember("total_ms")); |
| 762 | EXPECT_TRUE(doc["total_ms"].IsNumber()); |
| 763 | ASSERT_TRUE(doc.HasMember("input_bytes")); |
| 764 | EXPECT_TRUE(doc["input_bytes"].IsUint64()); |
| 765 | ASSERT_TRUE(doc.HasMember("output_bytes")); |
| 766 | EXPECT_TRUE(doc["output_bytes"].IsUint64()); |
| 767 | } |
| 768 | |
| 769 | TEST_F(CommandLineConvertTest, SegmentationOutputIsJson) { |
| 770 | const std::string config = "s2twp"; |
| 771 | const std::string inputFile = InputFile("segmentation_test"); |
| 772 | const std::string outputFile = OutputFile("segmentation_test"); |
| 773 | |
| 774 | { |
| 775 | std::ofstream ofs(inputFile, std::ios::binary); |
| 776 | ASSERT_TRUE(ofs.is_open()); |
| 777 | ofs << "\xe5\xbc\x80\xe6\x94\xbe\xe4\xb8\xad\xe6\x96\x87\xe8\xbd\xac\xe6" |
| 778 | "\x8d\xa2" // 开放中文转换 |
| 779 | << "\n"; |
| 780 | } |
| 781 | |
| 782 | ASSERT_EQ(0, system(TestCommandWithFlags(config, inputFile, outputFile, |
| 783 | "--segmentation").c_str())); |
| 784 | |
| 785 | const std::string content = GetFileContents(outputFile); |
| 786 | rapidjson::Document doc; |
| 787 | doc.Parse(content.c_str()); |
| 788 | ASSERT_FALSE(doc.HasParseError()) << "Output is not valid JSON: " << content; |
| 789 | ASSERT_TRUE(doc.IsObject()); |
| 790 | ASSERT_TRUE(doc.HasMember("input")); |
| 791 | ASSERT_TRUE(doc["input"].IsString()); |
| 792 | ASSERT_TRUE(doc.HasMember("segments")); |
| 793 | ASSERT_TRUE(doc["segments"].IsArray()); |
| 794 | EXPECT_FALSE(doc["segments"].GetArray().Empty()); |
| 795 | // Should NOT have 'stages' or 'output' keys |
| 796 | EXPECT_FALSE(doc.HasMember("stages")); |
| 797 | EXPECT_FALSE(doc.HasMember("output")); |
| 798 | } |
| 799 | |
| 800 | TEST_F(CommandLineConvertTest, InspectOutputIsJson) { |
| 801 | const std::string config = "s2t"; |
| 802 | const std::string inputFile = InputFile("inspect_test"); |
| 803 | const std::string outputFile = OutputFile("inspect_test"); |
| 804 | |
| 805 | { |
| 806 | std::ofstream ofs(inputFile, std::ios::binary); |
| 807 | ASSERT_TRUE(ofs.is_open()); |
| 808 | ofs << "\xe5\xbc\x80\xe6\x94\xbe\xe4\xb8\xad\xe6\x96\x87\xe8\xbd\xac\xe6" |
| 809 | "\x8d\xa2" // 开放中文转换 |
| 810 | << "\n"; |
| 811 | } |
| 812 | |
| 813 | ASSERT_EQ(0, system(TestCommandWithFlags(config, inputFile, outputFile, |
| 814 | "--inspect").c_str())); |
| 815 | |
| 816 | const std::string content = GetFileContents(outputFile); |
| 817 | rapidjson::Document doc; |
| 818 | doc.Parse(content.c_str()); |
| 819 | ASSERT_FALSE(doc.HasParseError()) << "Output is not valid JSON: " << content; |
| 820 | ASSERT_TRUE(doc.IsObject()); |
| 821 | ASSERT_TRUE(doc.HasMember("input")); |
| 822 | ASSERT_TRUE(doc["input"].IsString()); |
| 823 | ASSERT_TRUE(doc.HasMember("segments")); |
| 824 | ASSERT_TRUE(doc["segments"].IsArray()); |
| 825 | ASSERT_TRUE(doc.HasMember("stages")); |
| 826 | ASSERT_TRUE(doc["stages"].IsArray()); |
| 827 | ASSERT_TRUE(doc.HasMember("output")); |
| 828 | ASSERT_TRUE(doc["output"].IsString()); |
| 829 | // Validate stage schema |
| 830 | for (auto& stage : doc["stages"].GetArray()) { |
| 831 | ASSERT_TRUE(stage.IsObject()); |
| 832 | ASSERT_TRUE(stage.HasMember("index")); |
| 833 | ASSERT_TRUE(stage["index"].IsUint64()); |
| 834 | ASSERT_TRUE(stage.HasMember("segments")); |
| 835 | ASSERT_TRUE(stage["segments"].IsArray()); |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | TEST_F(CommandLineConvertTest, SegmentationAndInspectAreMutuallyExclusive) { |
| 840 | const std::string config = "s2t"; |
| 841 | const std::string inputFile = InputFile("mutex_test"); |
| 842 | const std::string outputFile = OutputFile("mutex_test"); |
| 843 | |
| 844 | { |
| 845 | std::ofstream ofs(inputFile, std::ios::binary); |
| 846 | ASSERT_TRUE(ofs.is_open()); |
| 847 | ofs << "test\n"; |
| 848 | } |
| 849 | |
| 850 | // Should fail with non-zero exit code |
| 851 | const int exitCode = |
| 852 | system(TestCommandWithFlags(config, inputFile, outputFile, |
| 853 | "--segmentation --inspect") |
| 854 | .c_str()); |
| 855 | EXPECT_NE(0, exitCode); |
| 856 | } |
| 857 | |
| 858 | TEST_F(CommandLineConvertTest, SegmentationFailsWhenConfigHasNoSegmentation) { |
| 859 | // s2t has no segmentation step; --segmentation should exit non-zero. |
| 860 | const std::string config = "s2t"; |
| 861 | const std::string inputFile = InputFile("seg_no_seg_test"); |
| 862 | const std::string outputFile = OutputFile("seg_no_seg_test"); |
| 863 | { |
| 864 | std::ofstream ofs(inputFile, std::ios::binary); |
| 865 | ASSERT_TRUE(ofs.is_open()); |
| 866 | ofs << "开放中文转换\n"; |
| 867 | } |
| 868 | EXPECT_NE(0, system(TestCommandWithFlags(config, inputFile, outputFile, |
| 869 | "--segmentation").c_str())); |
| 870 | } |
| 871 | |
| 872 | TEST_F(CommandLineConvertTest, MeasuredResultIncludesOutputMode) { |
| 873 | const std::string config = "s2t"; |
| 874 | const std::string inputFile = InputFile("inspect_measured_test"); |
| 875 | const std::string outputFile = OutputFile("inspect_measured_test"); |
| 876 | const std::string measuredResultFile = |
| 877 | OutputDirectory() + "inspect_measured_result.json"; |
| 878 | |
| 879 | { |
| 880 | std::ofstream ofs(inputFile, std::ios::binary); |
| 881 | ASSERT_TRUE(ofs.is_open()); |
| 882 | ofs << "\xe5\xbc\x80\xe6\x94\xbe\xe4\xb8\xad\xe6\x96\x87\xe8\xbd\xac\xe6" |
| 883 | "\x8d\xa2" // 开放中文转换 |
| 884 | << "\n"; |
| 885 | } |
| 886 | |
| 887 | ASSERT_EQ(0, |
| 888 | system(TestCommandWithFlags(config, inputFile, outputFile, |
| 889 | "--inspect", measuredResultFile) |
| 890 | .c_str())); |
| 891 | |
| 892 | const std::string content = GetFileContents(measuredResultFile); |
| 893 | rapidjson::Document doc; |
| 894 | doc.Parse(content.c_str()); |
| 895 | ASSERT_FALSE(doc.HasParseError()); |
| 896 | ASSERT_TRUE(doc.IsObject()); |
| 897 | ASSERT_TRUE(doc.HasMember("output_mode")); |
| 898 | ASSERT_TRUE(doc["output_mode"].IsString()); |
| 899 | EXPECT_STREQ("inspect", doc["output_mode"].GetString()); |
| 900 | } |
| 901 | |
| 902 | // Verify --segmentation does NOT run the conversion chain: the segments in the |
| 903 | // output must be the raw segmenter tokens, not post-conversion text. |
| 904 | // With s2t.json on "开放中文转换", segmentation splits into simplified-Chinese |
| 905 | // tokens; none of those tokens should already be Traditional Chinese unless |
| 906 | // the conversion chain ran. |
| 907 | TEST_F(CommandLineConvertTest, SegmentationDoesNotRunConversionChain) { |
| 908 | const std::string config = "s2twp"; |
| 909 | const std::string inputFile = InputFile("seg_no_convert_test"); |
| 910 | const std::string outputFile = OutputFile("seg_no_convert_test"); |
| 911 | |
| 912 | { |
| 913 | std::ofstream ofs(inputFile, std::ios::binary); |
| 914 | ASSERT_TRUE(ofs.is_open()); |
| 915 | // 开放中文转换 — all simplified; after s2t conversion it would become |
| 916 | // 開放中文轉換. --segmentation must return the simplified tokens. |
| 917 | ofs << "\xe5\xbc\x80\xe6\x94\xbe\xe4\xb8\xad\xe6\x96\x87\xe8\xbd\xac\xe6" |
| 918 | "\x8d\xa2" // 开放中文转换 |
| 919 | << "\n"; |
| 920 | } |
| 921 | |
| 922 | ASSERT_EQ(0, system(TestCommandWithFlags(config, inputFile, outputFile, |
| 923 | "--segmentation").c_str())); |
| 924 | |
| 925 | const std::string content = GetFileContents(outputFile); |
| 926 | rapidjson::Document doc; |
| 927 | doc.Parse(content.c_str()); |
| 928 | ASSERT_FALSE(doc.HasParseError()); |
| 929 | ASSERT_TRUE(doc.IsObject()); |
| 930 | ASSERT_TRUE(doc.HasMember("segments")); |
| 931 | ASSERT_TRUE(doc["segments"].IsArray()); |
| 932 | |
| 933 | // Reconstruct the concatenation of all segments. |
| 934 | std::string joined; |
| 935 | for (auto& seg : doc["segments"].GetArray()) { |
| 936 | ASSERT_TRUE(seg.IsString()); |
| 937 | joined += seg.GetString(); |
| 938 | } |
| 939 | // The joined segments must equal the *original* simplified input, |
| 940 | // not the converted traditional output. |
| 941 | const std::string simplified = |
| 942 | "\xe5\xbc\x80\xe6\x94\xbe\xe4\xb8\xad\xe6\x96\x87\xe8\xbd\xac\xe6" |
| 943 | "\x8d\xa2"; // 开放中文转换 |
| 944 | EXPECT_EQ(simplified, joined) |
| 945 | << "Segments were converted — conversion chain must not run in " |
| 946 | "--segmentation mode"; |
| 947 | } |
| 948 | |
| 949 | // Verify that a multi-line input in --segmentation mode produces exactly one |
| 950 | // JSON object per input line with no spurious extra record at EOF. |
| 951 | TEST_F(CommandLineConvertTest, SegmentationNoSpuriousEofRecord) { |
| 952 | const std::string config = "s2twp"; |
| 953 | const std::string inputFile = InputFile("seg_eof_test"); |
| 954 | const std::string outputFile = OutputFile("seg_eof_test"); |
| 955 | |
| 956 | { |
| 957 | std::ofstream ofs(inputFile, std::ios::binary); |
| 958 | ASSERT_TRUE(ofs.is_open()); |
| 959 | // Two lines, each terminated by \n (file ends with a newline). |
| 960 | ofs << "\xe5\xbc\x80\xe6\x94\xbe\xe4\xb8\xad\xe6\x96\x87\xe8\xbd\xac\xe6" |
| 961 | "\x8d\xa2\n" // 开放中文转换 |
| 962 | << "\xe6\xb1\x89\xe5\xad\x97\n"; // 汉字 |
| 963 | } |
| 964 | |
| 965 | ASSERT_EQ(0, system(TestCommandWithFlags(config, inputFile, outputFile, |
| 966 | "--segmentation").c_str())); |
| 967 | |
| 968 | // Output should be exactly two JSON objects separated by a newline. |
| 969 | const std::string content = GetFileContents(outputFile); |
| 970 | // Count newlines — the format is "obj\nobj" so there should be exactly 1 |
| 971 | // newline separator for 2 records. |
| 972 | size_t newlines = 0; |
| 973 | for (char c : content) { |
| 974 | if (c == '\n') { |
| 975 | ++newlines; |
| 976 | } |
| 977 | } |
| 978 | // Allow at most one trailing newline; the important thing is that we have |
| 979 | // exactly two JSON objects. |
| 980 | const size_t separators = (newlines > 0 && content.back() == '\n') |
| 981 | ? newlines - 1 |
| 982 | : newlines; |
| 983 | EXPECT_EQ(1u, separators) << "Expected exactly 2 JSON records (1 separator)," |
| 984 | " got extra records. Content: " |
| 985 | << content; |
| 986 | |
| 987 | // Also parse both records to confirm they're valid JSON. |
| 988 | // Records are separated by exactly one '\n' with no trailing newline in the |
| 989 | // payload itself. |
| 990 | size_t sep = content.find('\n'); |
| 991 | ASSERT_NE(std::string::npos, sep) << "No separator found"; |
| 992 | std::string first = content.substr(0, sep); |
| 993 | // skip trailing newline if present |
| 994 | std::string rest = content.substr(sep + 1); |
| 995 | if (!rest.empty() && rest.back() == '\n') { |
| 996 | rest.pop_back(); |
| 997 | } |
| 998 | |
| 999 | rapidjson::Document d1, d2; |
| 1000 | d1.Parse(first.c_str()); |
| 1001 | EXPECT_FALSE(d1.HasParseError()) << "First record invalid JSON: " << first; |
| 1002 | EXPECT_TRUE(d1.IsObject()); |
| 1003 | d2.Parse(rest.c_str()); |
| 1004 | EXPECT_FALSE(d2.HasParseError()) << "Second record invalid JSON: " << rest; |
| 1005 | EXPECT_TRUE(d2.IsObject()); |
| 1006 | } |
| 1007 | TEST_F(CommandLineConvertTest, PreservesLineEnding_LF) { |
| 1008 | const std::string config = "s2t"; |
| 1009 | const std::string inputFile = InputFile("lf_input"); |
| 1010 | const std::string outputFile = OutputFile("lf_output"); |
| 1011 | |
| 1012 | { |
| 1013 | std::ofstream ofs(inputFile, std::ios::binary); |
| 1014 | ASSERT_TRUE(ofs.is_open()); |
| 1015 | ofs << "第一行\n第二行\n第三行\n"; |
| 1016 | } |
| 1017 | |
| 1018 | ASSERT_EQ(0, system(TestCommand(config, inputFile, outputFile).c_str())); |
| 1019 | |
| 1020 | // Read output in binary mode to check line endings |
| 1021 | std::ifstream ifs(outputFile, std::ios::binary); |
| 1022 | ASSERT_TRUE(ifs.is_open()); |
| 1023 | std::string content((std::istreambuf_iterator<char>(ifs)), |
| 1024 | (std::istreambuf_iterator<char>())); |
| 1025 | ifs.close(); |
| 1026 | |
| 1027 | // Should contain LF (0a) but not CR (0d) |
| 1028 | ASSERT_NE(std::string::npos, content.find('\n')); |
| 1029 | ASSERT_EQ(std::string::npos, content.find('\r')); |
| 1030 | } |
| 1031 | |
| 1032 | TEST_F(CommandLineConvertTest, PreservesLineEnding_CRLF) { |
| 1033 | const std::string config = "s2t"; |
| 1034 | const std::string inputFile = InputFile("crlf_input"); |
| 1035 | const std::string outputFile = OutputFile("crlf_output"); |
| 1036 | |
| 1037 | { |
| 1038 | std::ofstream ofs(inputFile, std::ios::binary); |
| 1039 | ASSERT_TRUE(ofs.is_open()); |
| 1040 | ofs << "第一行\r\n第二行\r\n第三行\r\n"; |
| 1041 | } |
| 1042 | |
| 1043 | ASSERT_EQ(0, system(TestCommand(config, inputFile, outputFile).c_str())); |
| 1044 | |
| 1045 | // Read output in binary mode to check line endings |
| 1046 | std::ifstream ifs(outputFile, std::ios::binary); |
| 1047 | ASSERT_TRUE(ifs.is_open()); |
| 1048 | std::string content((std::istreambuf_iterator<char>(ifs)), |
| 1049 | (std::istreambuf_iterator<char>())); |
| 1050 | ifs.close(); |
| 1051 | |
| 1052 | // Should contain both CR (0d) and LF (0a) |
| 1053 | ASSERT_NE(std::string::npos, content.find('\r')); |
| 1054 | ASSERT_NE(std::string::npos, content.find('\n')); |
| 1055 | } |
| 1056 | |
| 1057 | TEST_F(CommandLineConvertTest, PreservesLineEnding_CRLF_ASCII) { |
| 1058 | const std::string config = "s2t"; |
| 1059 | const std::string inputFile = InputFile("crlf_ascii_input"); |
| 1060 | const std::string outputFile = OutputFile("crlf_ascii_output"); |
| 1061 | |
| 1062 | { |
| 1063 | std::ofstream ofs(inputFile, std::ios::binary); |
| 1064 | ASSERT_TRUE(ofs.is_open()); |
| 1065 | ofs << "hello\r\nworld\r\n"; |
| 1066 | } |
| 1067 | |
| 1068 | ASSERT_EQ(0, system(TestCommand(config, inputFile, outputFile).c_str())); |
| 1069 | |
| 1070 | // Read output in binary mode |
| 1071 | std::ifstream ifs(outputFile, std::ios::binary); |
| 1072 | ASSERT_TRUE(ifs.is_open()); |
| 1073 | std::string content((std::istreambuf_iterator<char>(ifs)), |
| 1074 | (std::istreambuf_iterator<char>())); |
| 1075 | ifs.close(); |
| 1076 | |
| 1077 | // Should preserve CRLF |
| 1078 | ASSERT_NE(std::string::npos, content.find('\r')); |
| 1079 | ASSERT_NE(std::string::npos, content.find('\n')); |
| 1080 | } |
| 1081 | |
| 1082 | TEST_F(CommandLineConvertTest, PreservesLineEnding_NoTrailingNewline_LF) { |
| 1083 | const std::string config = "s2t"; |
| 1084 | const std::string inputFile = InputFile("no_trailing_lf_input"); |
| 1085 | const std::string outputFile = OutputFile("no_trailing_lf_output"); |
| 1086 | |
| 1087 | { |
| 1088 | std::ofstream ofs(inputFile, std::ios::binary); |
| 1089 | ASSERT_TRUE(ofs.is_open()); |
| 1090 | ofs << "第一行\n第二行"; // No trailing newline |
| 1091 | } |
| 1092 | |
| 1093 | ASSERT_EQ(0, system(TestCommand(config, inputFile, outputFile).c_str())); |
| 1094 | |
| 1095 | // Read output in binary mode |
| 1096 | std::ifstream ifs(outputFile, std::ios::binary); |
| 1097 | ASSERT_TRUE(ifs.is_open()); |
| 1098 | std::string content((std::istreambuf_iterator<char>(ifs)), |
| 1099 | (std::istreambuf_iterator<char>())); |
| 1100 | ifs.close(); |
| 1101 | |
| 1102 | // Should have LF but no CR, and no trailing newline |
| 1103 | ASSERT_NE(std::string::npos, content.find('\n')); |
| 1104 | ASSERT_EQ(std::string::npos, content.find('\r')); |
| 1105 | ASSERT_NE('\n', content.back()); |
| 1106 | } |
| 1107 | |
| 1108 | TEST_F(CommandLineConvertTest, PreservesLineEnding_NoTrailingNewline_CRLF) { |
| 1109 | const std::string config = "s2t"; |
| 1110 | const std::string inputFile = InputFile("no_trailing_crlf_input"); |
| 1111 | const std::string outputFile = OutputFile("no_trailing_crlf_output"); |
| 1112 | |
| 1113 | { |
| 1114 | std::ofstream ofs(inputFile, std::ios::binary); |
| 1115 | ASSERT_TRUE(ofs.is_open()); |
| 1116 | ofs << "第一行\r\n第二行"; // No trailing newline |
| 1117 | } |
| 1118 | |
| 1119 | ASSERT_EQ(0, system(TestCommand(config, inputFile, outputFile).c_str())); |
| 1120 | |
| 1121 | // Read output in binary mode |
| 1122 | std::ifstream ifs(outputFile, std::ios::binary); |
| 1123 | ASSERT_TRUE(ifs.is_open()); |
| 1124 | std::string content((std::istreambuf_iterator<char>(ifs)), |
| 1125 | (std::istreambuf_iterator<char>())); |
| 1126 | ifs.close(); |
| 1127 | |
| 1128 | // Should preserve CRLF but no trailing newline |
| 1129 | ASSERT_NE(std::string::npos, content.find('\r')); |
| 1130 | ASSERT_NE(std::string::npos, content.find('\n')); |
| 1131 | ASSERT_NE('\r', content.back()); |
| 1132 | ASSERT_NE('\n', content.back()); |
| 1133 | } |
| 1134 | |
| 1135 | TEST_F(CommandLineConvertTest, ChunkingBoundaryTruncationFix) { |
| 1136 | const std::string config = "s2t"; |
| 1137 | const std::string inputFile = InputFile("chunk_boundary_test"); |
| 1138 | const std::string outputFile = OutputFile("chunk_boundary_test"); |
| 1139 | |
| 1140 | { |
| 1141 | std::ofstream ofs(inputFile, std::ios::binary); |
| 1142 | ASSERT_TRUE(ofs.is_open()); |
| 1143 | // Create exactly 1MB - 3 bytes of padding. |
| 1144 | // This forces the "头" character (3 bytes) to end exactly at the 1MB |
| 1145 | // chunk boundary, while "发尾巴" falls into the next read chunk. |
| 1146 | std::string padding(1048576 - 3, 'a'); |
| 1147 | ofs << padding << "头发尾巴"; |
| 1148 | } |
| 1149 | |
| 1150 | ASSERT_EQ(0, system(TestCommand(config, inputFile, outputFile).c_str())); |
| 1151 | |
| 1152 | // Read output in binary mode |
| 1153 | std::ifstream ifs(outputFile, std::ios::binary); |
| 1154 | ASSERT_TRUE(ifs.is_open()); |
| 1155 | std::string content((std::istreambuf_iterator<char>(ifs)), |
| 1156 | (std::istreambuf_iterator<char>())); |
| 1157 | ifs.close(); |
| 1158 | |
| 1159 | // 1. Verify EOF truncation bug is fixed (the output shouldn't be truncated) |
| 1160 | // 2. Verify Semantic-safe chunking (the word shouldn't be split into 頭發) |
| 1161 | const std::string expectedEnd = "頭髮尾巴"; |
| 1162 | ASSERT_GE(content.size(), expectedEnd.size()); |
| 1163 | EXPECT_EQ(expectedEnd, content.substr(content.size() - expectedEnd.size())); |
| 1164 | } |
| 1165 | |
| 1166 | TEST_F(CommandLineConvertTest, ExactChunkSizeDoesNotTruncate) { |
| 1167 | const std::string config = "s2t"; |
| 1168 | const std::string inputFile = InputFile("exact_chunk_test"); |
| 1169 | const std::string outputFile = OutputFile("exact_chunk_test"); |
| 1170 | |
| 1171 | { |
| 1172 | std::ofstream ofs(inputFile, std::ios::binary); |
| 1173 | ASSERT_TRUE(ofs.is_open()); |
| 1174 | // Create EXACTLY 1MB of data (1048576 bytes). |
| 1175 | // This triggers the bug where fread reads exactly bufferSizeAvailable, |
| 1176 | // defers MAX_KEEP_CHARS to the next iteration, and then the next fread |
| 1177 | // returns 0. If the loop breaks immediately on fread returning 0, the |
| 1178 | // deferred tail is lost. |
| 1179 | std::string padding(1048576, 'a'); |
| 1180 | ofs << padding; |
| 1181 | } |
| 1182 | |
| 1183 | ASSERT_EQ(0, system(TestCommand(config, inputFile, outputFile).c_str())); |
| 1184 | |
| 1185 | // Read output in binary mode |
| 1186 | std::ifstream ifs(outputFile, std::ios::binary); |
| 1187 | ASSERT_TRUE(ifs.is_open()); |
| 1188 | std::string content((std::istreambuf_iterator<char>(ifs)), |
| 1189 | (std::istreambuf_iterator<char>())); |
| 1190 | ifs.close(); |
| 1191 | |
| 1192 | // Verify output length is exactly 1MB. |
| 1193 | EXPECT_EQ(1048576, content.size()); |
| 1194 | } |
| 1195 | } // namespace opencc |