Skip to content

Commit

Permalink
Add tests for getFileOwner_unix (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
kavir1698 authored May 16, 2024
1 parent 3908c0b commit 6e31986
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
4 changes: 4 additions & 0 deletions datasetIngestor/getFileOwner_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
45 changes: 45 additions & 0 deletions datasetIngestor/getFileOwner_unix_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}

0 comments on commit 6e31986

Please sign in to comment.