Skip to content

Commit

Permalink
Add unixsock test (#1109)
Browse files Browse the repository at this point in the history
  • Loading branch information
thom-at-redhat authored Aug 5, 2024
1 parent 9f2d0a8 commit 06da333
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 3 deletions.
6 changes: 3 additions & 3 deletions pkg/utils/flock.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ var ErrLocked = fmt.Errorf("fslock is already locked")

// FLock represents a file lock.
type FLock struct {
fd int
Fd int
}

// TryFLock non-blockingly attempts to acquire a lock on the file.
Expand All @@ -32,10 +32,10 @@ func TryFLock(filename string) (*FLock, error) {
return nil, err
}

return &FLock{fd: fd}, nil
return &FLock{Fd: fd}, nil
}

// Unlock unlocks the file lock.
func (lock *FLock) Unlock() error {
return syscall.Close(lock.fd)
return syscall.Close(lock.Fd)
}
87 changes: 87 additions & 0 deletions pkg/utils/unixsock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//go:build !windows
// +build !windows

package utils_test

import (
"io/fs"
"net"
"os"
"path/filepath"
"testing"

"github.com/ansible/receptor/pkg/utils"
"golang.org/x/sys/unix"
)

func TestUnixSocketListen(t *testing.T) {
type args struct {
filename string
permissions os.FileMode
}

badFilename := ""

tests := []struct {
name string
args args
want net.Listener
want1 *utils.FLock
wantErr bool
}{
{
name: "Positive",
args: args{
filename: filepath.Join(os.TempDir(), "good_listener"),
permissions: 0x0400,
},
wantErr: false,
},
{
name: "Negative",
args: args{
filename: badFilename,
permissions: 0x0000,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
lockFilename := tt.args.filename + ".lock"
defer os.Remove(lockFilename)

_, got1, err := utils.UnixSocketListen(tt.args.filename, tt.args.permissions)
if (err != nil) != tt.wantErr {
t.Errorf("%s: UnixSocketListen(): error = %+v, wantErr = %+v", tt.name, err, tt.wantErr)

return
}

if err == nil {
if got1.Fd < 0 {
t.Errorf("%s: UnixSocketListen(): Invalid got1 fd = %+v", tt.name, got1)
}

defer got1.Unlock()

err = unix.Flock(got1.Fd, unix.LOCK_EX)
if err != nil {
t.Errorf("%s: UnixSocketListen(): Test lock error = %+v", tt.name, err)
}

gotFileInfo, err := os.Stat(tt.args.filename)
if err != nil {
t.Errorf("%s: UnixSocketListen(): Stat error = %+v", tt.name, err)
}

gotPermissions := gotFileInfo.Mode() & fs.ModePerm

wantPermissions := tt.args.permissions & fs.ModePerm
if gotPermissions != wantPermissions {
t.Errorf("%s: UnixSocketListen(): Got permission = %d, want permissions = %d", tt.name, gotPermissions, wantPermissions)
}
}
})
}
}

0 comments on commit 06da333

Please sign in to comment.