test: Add unit tests for chown() with User and Group parameters
authorThomas Jarosch <thomas.jarosch@intra2net.com>
Tue, 30 Dec 2025 13:44:21 +0000 (14:44 +0100)
committerThomas Jarosch <thomas.jarosch@intra2net.com>
Wed, 31 Dec 2025 11:11:25 +0000 (12:11 +0100)
Test the sentinel value handling for uid_t and gid_t types that
was fixed in the previous commit.

Added tests:
- TestChownWithInvalidUid: Verify chown fails when User has invalid uid
- TestChownWithValidUidAndInvalidGid: Verify chown succeeds when gid falls back to valid user.Gid
- TestChownWithUserAndGroupObjects: Verify chown works with valid User and Group objects

test/test_filefunc.cpp

index 583de35..6ad516d 100644 (file)
@@ -35,6 +35,7 @@ on this file might be covered by the GNU General Public License.
 #include <fstream>
 #include <sstream>
 #include <algorithm>
+#include <unistd.h>
 
 #define BOOST_TEST_DYN_LINK
 #include <boost/test/unit_test.hpp>
@@ -302,6 +303,66 @@ BOOST_AUTO_TEST_CASE(TestFileModes1)
     BOOST_CHECK_EQUAL( true, res );
 } // eo TestFileModes1()
 
+BOOST_AUTO_TEST_CASE(TestChownWithInvalidUid)
+{
+    std::string path= get_check_file_path("ChownInvalidUid");
+
+    write_file(path,"42");
+
+    // Create User with invalid uid (equals sentinel value)
+    User invalid_user;
+    BOOST_CHECK_EQUAL( false, invalid_user.is_valid() );
+
+    // Create valid Group
+    Group group((gid_t)0);
+
+    // Should fail because uid is invalid
+    bool res = chown(path, invalid_user, group);
+    BOOST_CHECK_EQUAL( false, res );
+} // eo TestChownWithInvalidUid()
+
+BOOST_AUTO_TEST_CASE(TestChownWithValidUidAndInvalidGid)
+{
+    std::string path= get_check_file_path("ChownValidUidInvalidGid");
+
+    write_file(path,"42");
+
+    // Get valid user from current process (use getuid() to avoid requiring root)
+    User valid_user(static_cast<uid_t>(getuid()));
+
+    // Create Group with invalid gid (equals sentinel value)
+    Group invalid_group;
+    BOOST_CHECK_EQUAL( false, invalid_group.is_valid() );
+
+    // Should succeed because gid is invalid but falls back to user.Gid which is valid
+    bool res = chown(path, valid_user, invalid_group);
+    BOOST_CHECK_EQUAL( true, res );
+} // eo TestChownWithValidUidAndInvalidGid()
+
+BOOST_AUTO_TEST_CASE(TestChownWithUserAndGroupObjects)
+{
+    // This test requires root privileges to change ownership
+    // Skip if not running as root
+    if (getuid() != 0)
+    {
+        BOOST_TEST_MESSAGE("Skipping TestChownWithUserAndGroupObjects - not running as root");
+        return;
+    }
+
+    std::string path= get_check_file_path("ChownUserGroup");
+
+    write_file(path,"42");
+
+    User user_root((uid_t)0);
+    Group group_root((gid_t)0);
+
+    // Both uid and gid are valid
+    bool res = chown(path, user_root, group_root);
+
+    // Should succeed
+    BOOST_CHECK_EQUAL( true, res );
+} // eo TestChownWithUserAndGroupObjects()
+
 
 
 BOOST_AUTO_TEST_CASE(TestPidOf1)