From 6e3198691abe42c606573cf31688961a3429eb9e Mon Sep 17 00:00:00 2001 From: Ali Vahdati <3798865+kavir1698@users.noreply.github.com> Date: Thu, 16 May 2024 15:04:26 +0200 Subject: [PATCH] Add tests for `getFileOwner_unix` (#48) --- datasetIngestor/getFileOwner_unix.go | 4 ++ datasetIngestor/getFileOwner_unix_test.go | 45 +++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 datasetIngestor/getFileOwner_unix_test.go diff --git a/datasetIngestor/getFileOwner_unix.go b/datasetIngestor/getFileOwner_unix.go index 6d57bc1..fcaa620 100644 --- a/datasetIngestor/getFileOwner_unix.go +++ b/datasetIngestor/getFileOwner_unix.go @@ -10,6 +10,10 @@ import ( "syscall" ) +/* GetFileOwner retrieves the owner of a given file. It takes an os.FileInfo object as input +and returns two strings: the username of the file's owner and the name of the group that owns the file. +If the user or group cannot be determined, it returns the user ID or group ID as a string. +If there is an error during the lookup of the user or group, it prefixes the user ID with "e" and uses the group ID as is.*/ func GetFileOwner(f os.FileInfo) (uidName string, gidName string) { uid := strconv.Itoa(int(f.Sys().(*syscall.Stat_t).Uid)) u, err2 := user.LookupId(uid) diff --git a/datasetIngestor/getFileOwner_unix_test.go b/datasetIngestor/getFileOwner_unix_test.go new file mode 100644 index 0000000..3112da0 --- /dev/null +++ b/datasetIngestor/getFileOwner_unix_test.go @@ -0,0 +1,45 @@ +// +build aix darwin dragonfly freebsd js,wasm linux nacl netbsd openbsd solaris + +package datasetIngestor + +import ( + "os" + "os/user" + "testing" + "io/ioutil" +) + +func TestGetFileOwner(t *testing.T) { + // Create a temporary file + tmpfile, err := ioutil.TempFile("", "example") + if err != nil { + t.Fatal(err) + } + defer os.Remove(tmpfile.Name()) // clean up + + // Get the current user + currentUser, err := user.Current() + if err != nil { + t.Fatal(err) + } + + // Get the file info + fileInfo, err := tmpfile.Stat() + if err != nil { + t.Fatal(err) + } + + // Get the file owner + uidName, _ := GetFileOwner(fileInfo) + + // Check if the file owner matches the current user + if uidName != currentUser.Username { + t.Errorf("Expected %s, got %s", currentUser.Username, uidName) + } + + // Check owner of a non-existent file + _, err = os.Stat("non_existent_file") + if err == nil { + t.Fatal("Expected error, got none") + } +}