From fcb69e6e3056e86ecb18f0c8af66bed8cbce51d4 Mon Sep 17 00:00:00 2001 From: DanielZhao0432 Date: Sun, 22 Nov 2026 00:23:56 +0800 Subject: [PATCH 1/3] Fix(cell): validate core STRU fields against malformed input Confirmed with a local driver on current develop: an ATOMIC_SPECIES line without a mass is accepted with mass = 0; a LATTICE_VECTORS block with fewer than 9 components keeps the unread tail at the Matrix3 identity default (det stays 1, surviving even a determinant check); a truncated coordinate line is caught only deep in parse_atom_properties() with the misleading 'mismatch in atom number' message and exit(1); a non-numeric atom count leaves na = 0 and triggers the 'atom number is 0' banner for the wrong reason. - read_atom_species(): quit if the species label/mass extraction fails; - read_lattice_constant(): read the 9 LATTICE_VECTORS components with a single extraction chain and quit on failure; - read_atom_positions(): reject a failed coordinate-triplet extraction at the extraction point with a clear message; - read_atom_type_header(): reject a failed atom-count extraction (extraction checked before the line remainder is consumed, so a valid final zero at EOF is still accepted). New unit tests in unittests/test_read_atom_species.cpp and unittests/test_read_atoms.cpp; both binaries built and run locally, 6/6 pass. Refs #8356. --- source/source_cell/read_atom_species.cpp | 19 ++- source/source_cell/read_atoms.cpp | 6 + source/source_cell/read_atoms_helper.cpp | 9 +- source/source_cell/unittests/CMakeLists.txt | 16 +++ .../unittests/test_read_atom_species.cpp | 112 +++++++++++++++++ .../source_cell/unittests/test_read_atoms.cpp | 118 ++++++++++++++++++ 6 files changed, 273 insertions(+), 7 deletions(-) create mode 100644 source/source_cell/unittests/test_read_atom_species.cpp create mode 100644 source/source_cell/unittests/test_read_atoms.cpp diff --git a/source/source_cell/read_atom_species.cpp b/source/source_cell/read_atom_species.cpp index 1dc1afb75d3..c9d7bbc040a 100644 --- a/source/source_cell/read_atom_species.cpp +++ b/source/source_cell/read_atom_species.cpp @@ -35,6 +35,11 @@ bool read_atom_species(std::ifstream& ifa, std::stringstream ss; ss << one_line; ss >> ucell.atoms[i].label >> ucell.atoms[i].mass; + if (ss.fail()) + { + ModuleBase::WARNING_QUIT("read_atom_species", + "invalid ATOMIC_SPECIES line: failed to read element label and mass"); + } ucell.pseudo_fn[i] = "auto"; ucell.pseudo_type[i] = "auto"; @@ -180,12 +185,14 @@ bool read_lattice_constant(std::ifstream& ifa, // Reading lattice vectors. notice // here that only one cpu read these // parameters. - ifa >> latvec.e11 >> latvec.e12; - ModuleBase::GlobalFunc::READ_VALUE(ifa, latvec.e13); - ifa >> latvec.e21 >> latvec.e22; - ModuleBase::GlobalFunc::READ_VALUE(ifa, latvec.e23); - ifa >> latvec.e31 >> latvec.e32; - ModuleBase::GlobalFunc::READ_VALUE(ifa, latvec.e33); + ifa >> latvec.e11 >> latvec.e12 >> latvec.e13 + >> latvec.e21 >> latvec.e22 >> latvec.e23 + >> latvec.e31 >> latvec.e32 >> latvec.e33; + if (ifa.fail()) + { + ModuleBase::WARNING_QUIT("unitcell::read_lattice_constant", + "invalid LATTICE_VECTORS: failed to read 9 lattice vector components"); + } } }//supply lattice vectors else diff --git a/source/source_cell/read_atoms.cpp b/source/source_cell/read_atoms.cpp index 831a761b791..9967e63963b 100644 --- a/source/source_cell/read_atoms.cpp +++ b/source/source_cell/read_atoms.cpp @@ -84,6 +84,12 @@ bool unitcell::read_atom_positions(UnitCell& ucell, ModuleBase::Vector3 v; ModuleBase::Vector3 mv; ifpos >> v.x >> v.y >> v.z; + if (ifpos.fail()) + { + ofs_warning << " Error: failed to read the coordinate triplet of atom " + << ia + 1 << " for atom type " << ucell.atoms[it].label << std::endl; + return false; + } mv.x = true ; mv.y = true ; mv.z = true ; diff --git a/source/source_cell/read_atoms_helper.cpp b/source/source_cell/read_atoms_helper.cpp index 58ce696db68..4bdf75e191d 100644 --- a/source/source_cell/read_atoms_helper.cpp +++ b/source/source_cell/read_atoms_helper.cpp @@ -646,7 +646,14 @@ bool read_atom_type_header(int it, UnitCell& ucell, // (3) read in atom number //========================= int na = 0; - ModuleBase::GlobalFunc::READ_VALUE(ifpos, na); + ifpos >> na; + if (ifpos.fail()) + { + ofs_warning << " Error: failed to read the number of atoms for this atom type." << std::endl; + return false; + } + std::string na_rest_of_line; + std::getline(ifpos, na_rest_of_line); ucell.atoms[it].na = na; ModuleBase::GlobalFunc::OUT(ofs_running,"Number of atoms for this type",na); diff --git a/source/source_cell/unittests/CMakeLists.txt b/source/source_cell/unittests/CMakeLists.txt index 0a8d0f15c9e..50dd08cbcd7 100644 --- a/source/source_cell/unittests/CMakeLists.txt +++ b/source/source_cell/unittests/CMakeLists.txt @@ -33,3 +33,19 @@ addtest( TARGET MODULE_CELL_index_test LIBS base device SOURCES test_cell_index.cpp ../cell_index.cpp) + +addtest( + TARGET MODULE_CELL_read_species_malformed_test + LIBS parameter base device cell domain_decomposition neighbor symmetry + SOURCES test_read_atom_species.cpp + ../module_neighlist/neighbor_search.cpp + ../module_neighlist/bin_manager.cpp + ../module_neighlist/page_allocator.cpp) + +addtest( + TARGET MODULE_CELL_read_atoms_malformed_test + LIBS parameter base device cell domain_decomposition neighbor symmetry + SOURCES test_read_atoms.cpp + ../module_neighlist/neighbor_search.cpp + ../module_neighlist/bin_manager.cpp + ../module_neighlist/page_allocator.cpp) diff --git a/source/source_cell/unittests/test_read_atom_species.cpp b/source/source_cell/unittests/test_read_atom_species.cpp new file mode 100644 index 00000000000..85ec1229050 --- /dev/null +++ b/source/source_cell/unittests/test_read_atom_species.cpp @@ -0,0 +1,112 @@ +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include +#include +#include + +#include "source_cell/read_stru.h" +#include "source_cell/unitcell.h" + +/************************************************ + * unit test of read_atom_species.cpp malformed-input handling + ***********************************************/ + +/** + * - Tested Functions: + * - SpeciesMissingMassRejected + * - read_atom_species(): an ATOMIC_SPECIES line without a mass left + * mass = 0 silently (issue #8356); it must now quit with a message + * - PartialLatticeVectorsRejected + * - read_lattice_constant(): fewer than 9 LATTICE_VECTORS components left + * the unread tail at the Matrix3 default (identity), surviving even the + * determinant check; it must now quit with a message + * - ValidSpeciesAndVectors + * - a well-formed species line and a full 3x3 LATTICE_VECTORS block still + * read normally + */ + +class ReadSpeciesMalformedTest : public ::testing::Test +{ + protected: + UnitCell ucell; + std::ofstream ofs_running; + std::string log_path; + std::string stru_path; + + void SetUp() override + { + log_path = testing::TempDir() + "read_species_malformed.log"; + ofs_running.open(log_path); + ucell.ntype = 1; + ucell.atoms = new Atom[1]; + ucell.pseudo_fn.resize(1); + ucell.pseudo_type.resize(1); + ucell.orbital_fn.resize(1); + } + + void TearDown() override + { + ofs_running.close(); + std::remove(log_path.c_str()); + if (!stru_path.empty()) + { + std::remove(stru_path.c_str()); + } + } + + std::string write_stru_file(const std::string& name, const std::string& content) + { + stru_path = testing::TempDir() + name; + std::ofstream ofs(stru_path); + ofs << content; + ofs.close(); + ofs_running << "created test STRU file: " << stru_path << std::endl; + return stru_path; + } +}; + +TEST_F(ReadSpeciesMalformedTest, SpeciesMissingMassRejected) +{ + const std::string stru = write_stru_file("species_no_mass.stru", "ATOMIC_SPECIES\nH\n"); + std::ifstream ifa(stru); + testing::internal::CaptureStdout(); + EXPECT_EXIT(unitcell::read_atom_species(ifa, ofs_running, ucell, "pw", "", "atomic", 0.0, false, false), + ::testing::ExitedWithCode(1), + ""); + const std::string output = testing::internal::GetCapturedStdout(); + EXPECT_THAT(output, testing::HasSubstr("invalid ATOMIC_SPECIES line")); + ifa.close(); +} + +TEST_F(ReadSpeciesMalformedTest, PartialLatticeVectorsRejected) +{ + const std::string stru = write_stru_file("latvec_partial.stru", + "LATTICE_CONSTANT\n4.0\nLATTICE_VECTORS\n1 0 0\n0 1 0\n"); + ucell.latName = "user_defined_lattice"; + std::ifstream ifa(stru); + testing::internal::CaptureStdout(); + EXPECT_EXIT(unitcell::read_lattice_constant(ifa, ofs_running, ucell.lat), + ::testing::ExitedWithCode(1), + ""); + const std::string output = testing::internal::GetCapturedStdout(); + EXPECT_THAT(output, testing::HasSubstr("invalid LATTICE_VECTORS")); + ifa.close(); +} + +TEST_F(ReadSpeciesMalformedTest, ValidSpeciesAndVectors) +{ + const std::string stru = write_stru_file("species_ok.stru", "ATOMIC_SPECIES\nH 1.008 H.upf\n"); + std::ifstream ifa(stru); + EXPECT_TRUE(unitcell::read_atom_species(ifa, ofs_running, ucell, "pw", "", "atomic", 0.0, false, false)); + EXPECT_DOUBLE_EQ(ucell.atoms[0].mass, 1.008); + ifa.close(); + + const std::string stru2 = write_stru_file("latvec_ok.stru", + "LATTICE_CONSTANT\n4.0\nLATTICE_VECTORS\n1 0 0\n0 1 0\n0 0 1\n"); + ucell.latName = "user_defined_lattice"; + std::ifstream ifa2(stru2); + EXPECT_TRUE(unitcell::read_lattice_constant(ifa2, ofs_running, ucell.lat)); + EXPECT_DOUBLE_EQ(ucell.lat.latvec.e33, 1.0); + ifa2.close(); +} diff --git a/source/source_cell/unittests/test_read_atoms.cpp b/source/source_cell/unittests/test_read_atoms.cpp new file mode 100644 index 00000000000..7501a0af06f --- /dev/null +++ b/source/source_cell/unittests/test_read_atoms.cpp @@ -0,0 +1,118 @@ +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include +#include +#include + +#include "source_cell/read_stru.h" +#include "source_cell/unitcell.h" + +/************************************************ + * unit test of read_atoms.cpp malformed-input handling + ***********************************************/ + +/** + * - Tested Functions: + * - TruncatedCoordinateRejected + * - read_atom_positions(): a coordinate line with fewer than three numbers + * was previously caught deep in parse_atom_properties() with the + * misleading "mismatch in atom number" message plus exit(1); it is now + * rejected at the extraction point (issue #8356) + * - NonNumericAtomCountRejected + * - read_atom_type_header(): a non-numeric atom count left na = 0 and + * triggered the "atom number is 0" banner for the wrong reason; it is + * now rejected at the extraction point + * - ValidPositionsAccepted + * - a well-formed ATOMIC_POSITIONS section still reads normally + */ + +class ReadAtomsMalformedTest : public ::testing::Test +{ + protected: + UnitCell ucell; + std::ofstream ofs_running; + std::ofstream ofs_warning; + std::string log_path; + std::string warn_path; + std::string stru_path; + + void SetUp() override + { + log_path = testing::TempDir() + "read_atoms_malformed.log"; + warn_path = testing::TempDir() + "read_atoms_malformed.warn"; + ofs_running.open(log_path); + ofs_warning.open(warn_path); + ucell.ntype = 1; + ucell.atoms = new Atom[1]; + ucell.atoms[0].label = "H"; + ucell.pseudo_fn.resize(1); + ucell.pseudo_type.resize(1); + ucell.orbital_fn.resize(1); + // a sane lattice scale: finalize_atom_positions() checks the + // transformed coordinates, which are divided by lat0 + ucell.lat0 = 4.0; + } + + void TearDown() override + { + ofs_running.close(); + ofs_warning.close(); + std::remove(log_path.c_str()); + std::remove(warn_path.c_str()); + if (!stru_path.empty()) + { + std::remove(stru_path.c_str()); + } + } + + bool read_positions(const std::string& content) + { + stru_path = testing::TempDir() + "positions.stru"; + std::ofstream ofs(stru_path); + ofs << content; + ofs.close(); + ofs_running << "created test STRU file: " << stru_path << std::endl; + std::ifstream ifpos(stru_path); + const bool result = unitcell::read_atom_positions(ucell, + ifpos, + ofs_running, + ofs_warning, + 1, + "pw", + "", + "atomic", + 0.0, + false, + false, + "scf", + "ksdft", + 0); + ifpos.close(); + return result; + } +}; + +TEST_F(ReadAtomsMalformedTest, TruncatedCoordinateRejected) +{ + const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n2\n0.0 0.0 0.0\n1.0 1.0\n"); + EXPECT_FALSE(result); +} + +TEST_F(ReadAtomsMalformedTest, NonNumericAtomCountRejected) +{ + const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\nx\n0.0 0.0 0.0\n"); + EXPECT_FALSE(result); +} + +TEST_F(ReadAtomsMalformedTest, ValidPositionsAccepted) +{ + // the second atom sits at half a cell on each axis: anything on an exact + // lattice period (e.g. 1.0 1.0 1.0) wraps onto the first atom by PBC and + // check_tau would legitimately report overlapping atoms + const bool result = + read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n2\n0.0 0.0 0.0\n0.5 0.5 0.5\n"); + EXPECT_TRUE(result); + EXPECT_EQ(ucell.atoms[0].na, 2); + EXPECT_DOUBLE_EQ(ucell.atoms[0].tau[1].z, 0.5); +} From ab15c9551dbacd9e5fb2299ce5604f5ef53cdde4 Mon Sep 17 00:00:00 2001 From: DanielZhao0432 Date: Sun, 22 Nov 2026 13:31:06 +0800 Subject: [PATCH 2/3] Fix(cell): preserve READ_VALUE line semantics in LATTICE_VECTORS and EOF handling READ_VALUE swallows the rest of the line after each extraction, and real STRU files annotate lattice vector rows with trailing comments (0.5 0.5 0.0 # a3); the single 9-component chain rejected those valid files. Read per row and getline the remainder instead, keeping the extraction check. A coordinate triplet that fails at EOF means fewer lines than the declared atom count; leave that to the existing mismatch-in-atom-number exit in parse_atom_properties, and reject only malformed numeric content (fail without eof). --- source/source_cell/read_atom_species.cpp | 10 +++++++--- source/source_cell/read_atoms.cpp | 5 ++++- .../unittests/test_read_atom_species.cpp | 20 +++++++++++++++++++ .../source_cell/unittests/test_read_atoms.cpp | 14 ++++++------- 4 files changed, 38 insertions(+), 11 deletions(-) diff --git a/source/source_cell/read_atom_species.cpp b/source/source_cell/read_atom_species.cpp index c9d7bbc040a..538d57ec2ac 100644 --- a/source/source_cell/read_atom_species.cpp +++ b/source/source_cell/read_atom_species.cpp @@ -185,14 +185,18 @@ bool read_lattice_constant(std::ifstream& ifa, // Reading lattice vectors. notice // here that only one cpu read these // parameters. - ifa >> latvec.e11 >> latvec.e12 >> latvec.e13 - >> latvec.e21 >> latvec.e22 >> latvec.e23 - >> latvec.e31 >> latvec.e32 >> latvec.e33; + std::string latvec_line_rest; + ifa >> latvec.e11 >> latvec.e12 >> latvec.e13; + std::getline(ifa, latvec_line_rest); // swallow inline comments after each row + ifa >> latvec.e21 >> latvec.e22 >> latvec.e23; + std::getline(ifa, latvec_line_rest); + ifa >> latvec.e31 >> latvec.e32 >> latvec.e33; if (ifa.fail()) { ModuleBase::WARNING_QUIT("unitcell::read_lattice_constant", "invalid LATTICE_VECTORS: failed to read 9 lattice vector components"); } + std::getline(ifa, latvec_line_rest); } }//supply lattice vectors else diff --git a/source/source_cell/read_atoms.cpp b/source/source_cell/read_atoms.cpp index 9967e63963b..eeba6267915 100644 --- a/source/source_cell/read_atoms.cpp +++ b/source/source_cell/read_atoms.cpp @@ -84,7 +84,10 @@ bool unitcell::read_atom_positions(UnitCell& ucell, ModuleBase::Vector3 v; ModuleBase::Vector3 mv; ifpos >> v.x >> v.y >> v.z; - if (ifpos.fail()) + // An EOF failure means fewer coordinate lines than the + // declared atom count; leave that to the existing + // mismatch-in-atom-number exit in parse_atom_properties. + if (ifpos.fail() && !ifpos.eof()) { ofs_warning << " Error: failed to read the coordinate triplet of atom " << ia + 1 << " for atom type " << ucell.atoms[it].label << std::endl; diff --git a/source/source_cell/unittests/test_read_atom_species.cpp b/source/source_cell/unittests/test_read_atom_species.cpp index 85ec1229050..52df09e22ce 100644 --- a/source/source_cell/unittests/test_read_atom_species.cpp +++ b/source/source_cell/unittests/test_read_atom_species.cpp @@ -24,6 +24,9 @@ * - ValidSpeciesAndVectors * - a well-formed species line and a full 3x3 LATTICE_VECTORS block still * read normally + * - LatticeVectorsWithInlineCommentsAccepted + * - vector rows annotated with trailing comments ("0.5 0.5 0.0 # a3"), + * common in real STRU files, must still be accepted */ class ReadSpeciesMalformedTest : public ::testing::Test @@ -110,3 +113,20 @@ TEST_F(ReadSpeciesMalformedTest, ValidSpeciesAndVectors) EXPECT_DOUBLE_EQ(ucell.lat.latvec.e33, 1.0); ifa2.close(); } + +TEST_F(ReadSpeciesMalformedTest, LatticeVectorsWithInlineCommentsAccepted) +{ + // real STRU files annotate vector rows with trailing comments + // (e.g. "0.5 0.5 0.0 # a3"); the reader must swallow the rest of + // each row like the old READ_VALUE-based code did + const std::string stru = write_stru_file("latvec_comments.stru", + "LATTICE_CONSTANT\n4.0\nLATTICE_VECTORS\n" + "1 0 0 # Lattice vector 1\n" + "0 1 0 # Lattice vector 2\n" + "0 0 1 # Lattice vector 3\n"); + ucell.latName = "user_defined_lattice"; + std::ifstream ifa(stru); + EXPECT_TRUE(unitcell::read_lattice_constant(ifa, ofs_running, ucell.lat)); + EXPECT_DOUBLE_EQ(ucell.lat.latvec.e33, 1.0); + ifa.close(); +} diff --git a/source/source_cell/unittests/test_read_atoms.cpp b/source/source_cell/unittests/test_read_atoms.cpp index 7501a0af06f..1c9451cde11 100644 --- a/source/source_cell/unittests/test_read_atoms.cpp +++ b/source/source_cell/unittests/test_read_atoms.cpp @@ -14,11 +14,11 @@ /** * - Tested Functions: - * - TruncatedCoordinateRejected - * - read_atom_positions(): a coordinate line with fewer than three numbers - * was previously caught deep in parse_atom_properties() with the - * misleading "mismatch in atom number" message plus exit(1); it is now - * rejected at the extraction point (issue #8356) + * - NonNumericCoordinateRejected + * - read_atom_positions(): a coordinate line with non-numeric content + * (e.g. "1.0 1.0 x") is now rejected at the extraction point; a line + * truncated at EOF still goes to the existing mismatch-in-atom-number + * exit in parse_atom_properties() (issue #8356) * - NonNumericAtomCountRejected * - read_atom_type_header(): a non-numeric atom count left na = 0 and * triggered the "atom number is 0" banner for the wrong reason; it is @@ -93,9 +93,9 @@ class ReadAtomsMalformedTest : public ::testing::Test } }; -TEST_F(ReadAtomsMalformedTest, TruncatedCoordinateRejected) +TEST_F(ReadAtomsMalformedTest, NonNumericCoordinateRejected) { - const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n2\n0.0 0.0 0.0\n1.0 1.0\n"); + const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n2\n0.0 0.0 0.0\n1.0 1.0 x\n"); EXPECT_FALSE(result); } From 759990eecfebcd6f4dce71c9fa0bf6861f85cde2 Mon Sep 17 00:00:00 2001 From: DanielZhao0432 Date: Sun, 22 Nov 2026 16:12:04 +0800 Subject: [PATCH 3/3] Fix(cell): consume STRU reader returns in setup_cell and fix EOF handling setup_cell ignored the return values of read_atom_species and read_lattice_constant, silently continuing after a failed read; fold them into the ok flag that is already broadcast and checked. The legacy signed-char EOF check in parse_atom_properties was non-portable and misreported a complete final coordinate triplet ending exactly at EOF as a count mismatch; distinguish the cases by stream state instead. Tests: two-species discriminating count case with warning-text assertion, literal-zero-count control, valid exact-EOF control, and fixture repairs (Atom ownership, full temp-file tracking, rule-16 read confirmations). --- source/source_cell/read_atoms_helper.cpp | 18 +++- source/source_cell/unitcell_setup.cpp | 7 +- .../unittests/test_read_atom_species.cpp | 42 ++++++--- .../source_cell/unittests/test_read_atoms.cpp | 93 ++++++++++++++++--- 4 files changed, 128 insertions(+), 32 deletions(-) diff --git a/source/source_cell/read_atoms_helper.cpp b/source/source_cell/read_atoms_helper.cpp index 4bdf75e191d..1828764d249 100644 --- a/source/source_cell/read_atoms_helper.cpp +++ b/source/source_cell/read_atoms_helper.cpp @@ -422,14 +422,26 @@ bool parse_atom_properties(std::ifstream& ifpos, bool& set_element_mag_zero) { std::string tmpid; - tmpid = ifpos.get(); - - if( (int)tmpid[0] < 0 ) + if (ifpos.fail()) { + // the coordinate triplet itself failed to extract: fewer coordinate + // lines than the declared atom count std::cout << "read_atom_positions, mismatch in atom number for atom type: " << atom.label << std::endl; exit(1); } + const int next_char = ifpos.get(); + if (next_char == std::char_traits::eof()) + { + // a complete final triplet ending exactly at EOF has no optional + // properties; treat the clean EOF as end-of-line instead of a + // mismatch (the legacy signed-char check was also non-portable) + tmpid = "\n"; + } + else + { + tmpid = std::string(1, static_cast(next_char)); + } // read if catch goodbit before "\n" and "#" while ( (tmpid != "\n") && (ifpos.good()) && (tmpid !="#") ) diff --git a/source/source_cell/unitcell_setup.cpp b/source/source_cell/unitcell_setup.cpp index e996015c167..1a82c0902bf 100644 --- a/source/source_cell/unitcell_setup.cpp +++ b/source/source_cell/unitcell_setup.cpp @@ -89,12 +89,15 @@ void UnitCell::setup_cell(const std::string& fn, std::ofstream& log, const doubl //======================== // call read_atom_species //======================== - const bool read_atom_species = unitcell::read_atom_species(ifa, log, *this, + ok = unitcell::read_atom_species(ifa, log, *this, basis_type, orbital_dir, init_wfc, onsite_radius, deepks_setorb, rpa); //======================== // call read_lattice_constant //======================== - const bool read_lattice_constant = unitcell::read_lattice_constant(ifa, log ,this->lat); + if (ok) + { + ok = unitcell::read_lattice_constant(ifa, log, this->lat); + } //========================== // readl sep potential, currently using the pseudopotential folder (pseudo_dir in INPUT) //========================== diff --git a/source/source_cell/unittests/test_read_atom_species.cpp b/source/source_cell/unittests/test_read_atom_species.cpp index 52df09e22ce..b204ff3a3b7 100644 --- a/source/source_cell/unittests/test_read_atom_species.cpp +++ b/source/source_cell/unittests/test_read_atom_species.cpp @@ -3,7 +3,10 @@ #include #include +#include +#include #include +#include #include "source_cell/read_stru.h" #include "source_cell/unitcell.h" @@ -35,14 +38,18 @@ class ReadSpeciesMalformedTest : public ::testing::Test UnitCell ucell; std::ofstream ofs_running; std::string log_path; - std::string stru_path; + std::vector stru_paths; + std::unique_ptr owned_atoms; void SetUp() override { log_path = testing::TempDir() + "read_species_malformed.log"; ofs_running.open(log_path); ucell.ntype = 1; - ucell.atoms = new Atom[1]; + // UnitCell::~UnitCell() deletes atoms only when set_atom_flag is + // true; keep ownership here instead of relying on that flag + owned_atoms.reset(new Atom[1]); + ucell.atoms = owned_atoms.get(); ucell.pseudo_fn.resize(1); ucell.pseudo_type.resize(1); ucell.orbital_fn.resize(1); @@ -52,27 +59,36 @@ class ReadSpeciesMalformedTest : public ::testing::Test { ofs_running.close(); std::remove(log_path.c_str()); - if (!stru_path.empty()) + for (const std::string& path : stru_paths) { - std::remove(stru_path.c_str()); + std::remove(path.c_str()); } } std::string write_stru_file(const std::string& name, const std::string& content) { - stru_path = testing::TempDir() + name; - std::ofstream ofs(stru_path); + const std::string path = testing::TempDir() + name; + std::ofstream ofs(path); ofs << content; ofs.close(); - ofs_running << "created test STRU file: " << stru_path << std::endl; - return stru_path; + stru_paths.push_back(path); + ofs_running << "created test STRU file: " << path << std::endl; + return path; + } + + std::ifstream open_stru_file(const std::string& path) + { + const std::string msg = "reading test STRU file: " + path; + std::cout << msg << std::endl; + ofs_running << msg << std::endl; + return std::ifstream(path); } }; TEST_F(ReadSpeciesMalformedTest, SpeciesMissingMassRejected) { const std::string stru = write_stru_file("species_no_mass.stru", "ATOMIC_SPECIES\nH\n"); - std::ifstream ifa(stru); + std::ifstream ifa = open_stru_file(stru); testing::internal::CaptureStdout(); EXPECT_EXIT(unitcell::read_atom_species(ifa, ofs_running, ucell, "pw", "", "atomic", 0.0, false, false), ::testing::ExitedWithCode(1), @@ -87,7 +103,7 @@ TEST_F(ReadSpeciesMalformedTest, PartialLatticeVectorsRejected) const std::string stru = write_stru_file("latvec_partial.stru", "LATTICE_CONSTANT\n4.0\nLATTICE_VECTORS\n1 0 0\n0 1 0\n"); ucell.latName = "user_defined_lattice"; - std::ifstream ifa(stru); + std::ifstream ifa = open_stru_file(stru); testing::internal::CaptureStdout(); EXPECT_EXIT(unitcell::read_lattice_constant(ifa, ofs_running, ucell.lat), ::testing::ExitedWithCode(1), @@ -100,7 +116,7 @@ TEST_F(ReadSpeciesMalformedTest, PartialLatticeVectorsRejected) TEST_F(ReadSpeciesMalformedTest, ValidSpeciesAndVectors) { const std::string stru = write_stru_file("species_ok.stru", "ATOMIC_SPECIES\nH 1.008 H.upf\n"); - std::ifstream ifa(stru); + std::ifstream ifa = open_stru_file(stru); EXPECT_TRUE(unitcell::read_atom_species(ifa, ofs_running, ucell, "pw", "", "atomic", 0.0, false, false)); EXPECT_DOUBLE_EQ(ucell.atoms[0].mass, 1.008); ifa.close(); @@ -108,7 +124,7 @@ TEST_F(ReadSpeciesMalformedTest, ValidSpeciesAndVectors) const std::string stru2 = write_stru_file("latvec_ok.stru", "LATTICE_CONSTANT\n4.0\nLATTICE_VECTORS\n1 0 0\n0 1 0\n0 0 1\n"); ucell.latName = "user_defined_lattice"; - std::ifstream ifa2(stru2); + std::ifstream ifa2 = open_stru_file(stru2); EXPECT_TRUE(unitcell::read_lattice_constant(ifa2, ofs_running, ucell.lat)); EXPECT_DOUBLE_EQ(ucell.lat.latvec.e33, 1.0); ifa2.close(); @@ -125,7 +141,7 @@ TEST_F(ReadSpeciesMalformedTest, LatticeVectorsWithInlineCommentsAccepted) "0 1 0 # Lattice vector 2\n" "0 0 1 # Lattice vector 3\n"); ucell.latName = "user_defined_lattice"; - std::ifstream ifa(stru); + std::ifstream ifa = open_stru_file(stru); EXPECT_TRUE(unitcell::read_lattice_constant(ifa, ofs_running, ucell.lat)); EXPECT_DOUBLE_EQ(ucell.lat.latvec.e33, 1.0); ifa.close(); diff --git a/source/source_cell/unittests/test_read_atoms.cpp b/source/source_cell/unittests/test_read_atoms.cpp index 1c9451cde11..055e9ef330c 100644 --- a/source/source_cell/unittests/test_read_atoms.cpp +++ b/source/source_cell/unittests/test_read_atoms.cpp @@ -3,7 +3,11 @@ #include #include +#include +#include +#include #include +#include #include "source_cell/read_stru.h" #include "source_cell/unitcell.h" @@ -20,9 +24,15 @@ * truncated at EOF still goes to the existing mismatch-in-atom-number * exit in parse_atom_properties() (issue #8356) * - NonNumericAtomCountRejected - * - read_atom_type_header(): a non-numeric atom count left na = 0 and - * triggered the "atom number is 0" banner for the wrong reason; it is - * now rejected at the extraction point + * - read_atom_type_header(): a non-numeric atom count after a valid first + * species left na = 0 while the total atom count stayed positive, so + * the old reader accepted it; it is now rejected at the extraction + * point and the warning text is asserted + * - LiteralZeroCountAccepted + * - a species with a literal zero atom count is intentionally supported + * - ValidFinalTripletAtExactEofAccepted + * - a complete final coordinate triplet ending exactly at EOF must not be + * misreported as a count mismatch * - ValidPositionsAccepted * - a well-formed ATOMIC_POSITIONS section still reads normally */ @@ -35,7 +45,8 @@ class ReadAtomsMalformedTest : public ::testing::Test std::ofstream ofs_warning; std::string log_path; std::string warn_path; - std::string stru_path; + std::vector stru_paths; + std::unique_ptr owned_atoms; void SetUp() override { @@ -43,36 +54,53 @@ class ReadAtomsMalformedTest : public ::testing::Test warn_path = testing::TempDir() + "read_atoms_malformed.warn"; ofs_running.open(log_path); ofs_warning.open(warn_path); - ucell.ntype = 1; - ucell.atoms = new Atom[1]; - ucell.atoms[0].label = "H"; - ucell.pseudo_fn.resize(1); - ucell.pseudo_type.resize(1); - ucell.orbital_fn.resize(1); // a sane lattice scale: finalize_atom_positions() checks the // transformed coordinates, which are divided by lat0 ucell.lat0 = 4.0; } + // UnitCell::~UnitCell() deletes atoms only when set_atom_flag is true; + // keep ownership here instead of relying on that flag + void init_types(const int ntype) + { + ucell.ntype = ntype; + owned_atoms.reset(new Atom[ntype]); + ucell.atoms = owned_atoms.get(); + ucell.pseudo_fn.resize(ntype); + ucell.pseudo_type.resize(ntype); + ucell.orbital_fn.resize(ntype); + } + void TearDown() override { ofs_running.close(); ofs_warning.close(); std::remove(log_path.c_str()); std::remove(warn_path.c_str()); - if (!stru_path.empty()) + for (const std::string& path : stru_paths) { - std::remove(stru_path.c_str()); + std::remove(path.c_str()); } } + std::string read_warn_file() + { + ofs_warning.flush(); + std::ifstream ifs(warn_path); + return std::string(std::istreambuf_iterator(ifs), std::istreambuf_iterator()); + } + bool read_positions(const std::string& content) { - stru_path = testing::TempDir() + "positions.stru"; + const std::string stru_path = testing::TempDir() + "positions.stru"; std::ofstream ofs(stru_path); ofs << content; ofs.close(); + stru_paths.push_back(stru_path); ofs_running << "created test STRU file: " << stru_path << std::endl; + const std::string msg = "reading test STRU file: " + stru_path; + std::cout << msg << std::endl; + ofs_running << msg << std::endl; std::ifstream ifpos(stru_path); const bool result = unitcell::read_atom_positions(ucell, ifpos, @@ -95,14 +123,49 @@ class ReadAtomsMalformedTest : public ::testing::Test TEST_F(ReadAtomsMalformedTest, NonNumericCoordinateRejected) { + init_types(1); + ucell.atoms[0].label = "H"; const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n2\n0.0 0.0 0.0\n1.0 1.0 x\n"); EXPECT_FALSE(result); } TEST_F(ReadAtomsMalformedTest, NonNumericAtomCountRejected) { - const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\nx\n0.0 0.0 0.0\n"); + // discriminating case: with a valid first species, the old reader left + // the failed count at zero while the total atom count stayed positive, + // so parsing succeeded; the new check must reject at the extraction point + init_types(2); + ucell.atoms[0].label = "H"; + ucell.atoms[1].label = "O"; + const bool result = + read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n1\n0.0 0.0 0.0\nO\n0.0\nx\n"); EXPECT_FALSE(result); + EXPECT_THAT(read_warn_file(), testing::HasSubstr("failed to read the number of atoms")); +} + +TEST_F(ReadAtomsMalformedTest, LiteralZeroCountAccepted) +{ + // a species with a literal zero atom count is intentionally supported; + // only a failed conversion must be rejected + init_types(2); + ucell.atoms[0].label = "H"; + ucell.atoms[1].label = "O"; + const bool result = + read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n1\n0.0 0.0 0.0\nO\n0.0\n0\n"); + EXPECT_TRUE(result); + EXPECT_EQ(ucell.atoms[1].na, 0); +} + +TEST_F(ReadAtomsMalformedTest, ValidFinalTripletAtExactEofAccepted) +{ + // a complete final coordinate triplet ending exactly at EOF (no trailing + // newline) is valid input; the legacy signed-char EOF check used to + // misreport it as "mismatch in atom number" + init_types(1); + ucell.atoms[0].label = "H"; + const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n1\n0.0 0.0 0.0"); + EXPECT_TRUE(result); + EXPECT_EQ(ucell.atoms[0].na, 1); } TEST_F(ReadAtomsMalformedTest, ValidPositionsAccepted) @@ -110,6 +173,8 @@ TEST_F(ReadAtomsMalformedTest, ValidPositionsAccepted) // the second atom sits at half a cell on each axis: anything on an exact // lattice period (e.g. 1.0 1.0 1.0) wraps onto the first atom by PBC and // check_tau would legitimately report overlapping atoms + init_types(1); + ucell.atoms[0].label = "H"; const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n2\n0.0 0.0 0.0\n0.5 0.5 0.5\n"); EXPECT_TRUE(result);