File: writefile_test.go

package info (click to toggle)
glab 1.53.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 20,936 kB
  • sloc: sh: 295; makefile: 153; perl: 99; ruby: 68; javascript: 67
file content (80 lines) | stat: -rw-r--r-- 1,847 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package config

import (
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func Test_WriteFile(t *testing.T) {
	dir, err := os.MkdirTemp("", "")
	if err != nil {
		t.Skipf("unexpected error while creating temporary directory = %s", err)
	}
	t.Cleanup(func() {
		os.RemoveAll(dir)
	})

	testCases := []struct {
		name        string
		filePath    string
		content     string
		permissions os.FileMode
		isSymlink   bool
	}{
		{
			name:        "regular",
			filePath:    "test-file",
			content:     "profclems/glab",
			permissions: 0o644,
			isSymlink:   false,
		},
		{
			name:        "config",
			filePath:    "config-file",
			content:     "profclems/glab/config",
			permissions: 0o600,
			isSymlink:   false,
		},
		{
			name:        "symlink",
			filePath:    "test-file",
			content:     "profclems/glab/symlink",
			permissions: 0o644,
			isSymlink:   true,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			fullPath := filepath.Join(dir, tc.filePath)

			if tc.isSymlink {
				symPath := filepath.Join(dir, "test-symlink")
				require.Nil(t, os.Symlink(tc.filePath, symPath), "failed to create a symlink")
				fullPath = symPath
			}

			require.Nilf(t,
				WriteFile(fullPath, []byte(tc.content), tc.permissions),
				"unexpected error for testCase %q", tc.name,
			)

			result, err := os.ReadFile(fullPath)
			require.Nilf(t, err, "failed to read file %q due to %q", fullPath, err)
			assert.Equal(t, tc.content, string(result))

			fileInfo, err := os.Lstat(fullPath)
			require.Nil(t, err, "failed to get info about the file", err)

			if tc.isSymlink {
				assert.Equal(t, os.ModeSymlink, fileInfo.Mode()&os.ModeSymlink, "this file should be a symlink")
			} else {
				assert.Equal(t, tc.permissions, fileInfo.Mode())
			}
		})
	}
}