From 41cd564d8a39807ca496eeb52d30fc07e30bd14a Mon Sep 17 00:00:00 2001 From: Ludovic Fernandez Date: Sun, 30 Jun 2024 19:33:12 +0200 Subject: [PATCH] tests: remove files generated during tests (#77) --- flock.go | 8 +++++--- flock_internal_test.go | 35 ++++++++++++++++++++--------------- flock_test.go | 2 +- flock_windows.go | 1 - 4 files changed, 26 insertions(+), 20 deletions(-) diff --git a/flock.go b/flock.go index b71f98f..1ab65d8 100644 --- a/flock.go +++ b/flock.go @@ -171,8 +171,10 @@ func (f *Flock) setFh() error { // ensure the file handle is closed if no lock is held. func (f *Flock) ensureFhState() { - if !f.l && !f.r && f.fh != nil { - f.fh.Close() - f.fh = nil + if f.l || f.r || f.fh == nil { + return } + + f.fh.Close() + f.fh = nil } diff --git a/flock_internal_test.go b/flock_internal_test.go index 262785f..7a9d511 100644 --- a/flock_internal_test.go +++ b/flock_internal_test.go @@ -8,27 +8,32 @@ package flock import ( "os" "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test(t *testing.T) { - tmpFileFh, _ := os.CreateTemp(os.TempDir(), "go-flock-") - tmpFileFh.Close() - tmpFile := tmpFileFh.Name() - os.Remove(tmpFile) + tmpFile, err := os.CreateTemp(t.TempDir(), "go-flock-") + require.NoError(t, err) + + tmpFile.Close() + os.Remove(tmpFile.Name()) + + lock := New(tmpFile.Name()) - lock := New(tmpFile) locked, err := lock.TryLock() - if locked == false || err != nil { - t.Fatalf("failed to lock: locked: %t, err: %v", locked, err) - } + require.NoError(t, err) + require.True(t, locked) + + newLock := New(tmpFile.Name()) - newLock := New(tmpFile) locked, err = newLock.TryLock() - if locked != false || err != nil { - t.Fatalf("should have failed locking: locked: %t, err: %v", locked, err) - } + require.NoError(t, err) + require.False(t, locked) + + assert.Nil(t, newLock.fh, "file handle should have been released and be nil") - if newLock.fh != nil { - t.Fatal("file handle should have been released and be nil") - } + err = lock.Unlock() + require.NoError(t, err) } diff --git a/flock_test.go b/flock_test.go index a85f1ce..26104a9 100644 --- a/flock_test.go +++ b/flock_test.go @@ -26,7 +26,7 @@ type TestSuite struct { func Test(t *testing.T) { suite.Run(t, &TestSuite{}) } func (s *TestSuite) SetupTest() { - tmpFile, err := os.CreateTemp(os.TempDir(), "go-flock-") + tmpFile, err := os.CreateTemp(s.T().TempDir(), "go-flock-") s.Require().NoError(err) s.Require().NotNil(tmpFile) diff --git a/flock_windows.go b/flock_windows.go index 1f0c968..ab8294d 100644 --- a/flock_windows.go +++ b/flock_windows.go @@ -130,7 +130,6 @@ func (f *Flock) try(locked *bool, flag uint32) (bool, error) { } _, errNo := lockFileEx(syscall.Handle(f.fh.Fd()), flag|winLockfileFailImmediately, 0, 1, 0, &syscall.Overlapped{}) - if errNo > 0 { if errNo == ErrorLockViolation || errNo == syscall.ERROR_IO_PENDING { return false, nil