go.mway.dev/x@v0.0.0-20240520034138-950aede9a3fb/os/with_cwd_internals_test.go (about) 1 // Copyright (c) 2022 Matt Way 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to 5 // deal in the Software without restriction, including without limitation the 6 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7 // sell copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 19 // IN THE THE SOFTWARE. 20 21 package os 22 23 import ( 24 "errors" 25 "testing" 26 27 "github.com/stretchr/testify/require" 28 ) 29 30 func TestWithCwdFixedCwd(t *testing.T) { 31 prevwd := _getwd 32 defer func() { 33 _getwd = prevwd 34 }() 35 _getwd = func() (string, error) { return "sometestdir", nil } 36 37 var called bool 38 err := WithCwd("sometestdir", func() { 39 called = true 40 }) 41 require.NoError(t, err) 42 require.True(t, called) 43 } 44 45 func TestWithCwdGetwdError(t *testing.T) { 46 var ( 47 expectErr = errors.New("os.Getwd error") 48 prevwd = _getwd 49 ) 50 defer func() { 51 _getwd = prevwd 52 }() 53 _getwd = func() (string, error) { return "", expectErr } 54 55 err := WithCwd(".", func() { 56 require.FailNow(t, "WithCwd func argument should not be called") 57 }) 58 require.ErrorIs(t, err, expectErr) 59 } 60 61 func TestWithCwdChdirError(t *testing.T) { 62 var ( 63 expectErr = errors.New("os.Chdir error") 64 prevChdir = _chdir 65 ) 66 defer func() { 67 _chdir = prevChdir 68 }() 69 _chdir = func(string) error { return expectErr } 70 71 require.NotPanics(t, func() { 72 err := WithCwd(".", func() { 73 require.FailNow(t, "WithCwd func argument should not be called") 74 }) 75 require.ErrorIs(t, err, expectErr) 76 }) 77 }