|
| 1 | +package fileline |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/macadmins/osquery-extension/pkg/utils" |
| 9 | + "github.com/stretchr/testify/assert" |
| 10 | +) |
| 11 | + |
| 12 | +func TestProcessFile(t *testing.T) { |
| 13 | + t.Run("processFile with wildcard", func(t *testing.T) { |
| 14 | + // Create temporary files for testing |
| 15 | + tmpFile1, err := os.CreateTemp("", "testfile1-*.txt") |
| 16 | + assert.NoError(t, err) |
| 17 | + defer os.Remove(tmpFile1.Name()) |
| 18 | + |
| 19 | + tmpFile2, err := os.CreateTemp("", "testfile2-*.txt") |
| 20 | + assert.NoError(t, err) |
| 21 | + defer os.Remove(tmpFile2.Name()) |
| 22 | + |
| 23 | + _, err = tmpFile1.WriteString("line1\nline2\n") |
| 24 | + assert.NoError(t, err) |
| 25 | + _, err = tmpFile2.WriteString("line3\nline4\n") |
| 26 | + assert.NoError(t, err) |
| 27 | + |
| 28 | + tmpFile1.Close() |
| 29 | + tmpFile2.Close() |
| 30 | + |
| 31 | + path := filepath.Join(filepath.Dir(tmpFile1.Name()), "testfile%-*.txt") |
| 32 | + fs := utils.MockFileSystem{FileExists: true, Err: nil} |
| 33 | + lines, err := processFile(path, true, fs) |
| 34 | + assert.NoError(t, err) |
| 35 | + assert.Len(t, lines, 4) |
| 36 | + }) |
| 37 | + |
| 38 | + t.Run("processFile without wildcard", func(t *testing.T) { |
| 39 | + // Create a temporary file for testing |
| 40 | + tmpFile, err := os.CreateTemp("", "testfile-*.txt") |
| 41 | + assert.NoError(t, err) |
| 42 | + defer os.Remove(tmpFile.Name()) |
| 43 | + |
| 44 | + _, err = tmpFile.WriteString("line1\nline2\n") |
| 45 | + assert.NoError(t, err) |
| 46 | + tmpFile.Close() |
| 47 | + |
| 48 | + fs := utils.MockFileSystem{FileExists: true, Err: nil} |
| 49 | + |
| 50 | + lines, err := processFile(tmpFile.Name(), false, fs) |
| 51 | + assert.NoError(t, err) |
| 52 | + assert.Len(t, lines, 2) |
| 53 | + }) |
| 54 | +} |
| 55 | + |
| 56 | +func TestReadLines(t *testing.T) { |
| 57 | + t.Run("readLines file exists", func(t *testing.T) { |
| 58 | + // Create a temporary file for testing |
| 59 | + tmpFile, err := os.CreateTemp("", "testfile-*.txt") |
| 60 | + assert.NoError(t, err) |
| 61 | + defer os.Remove(tmpFile.Name()) |
| 62 | + |
| 63 | + _, err = tmpFile.WriteString("line1\nline2\n") |
| 64 | + assert.NoError(t, err) |
| 65 | + tmpFile.Close() |
| 66 | + fs := utils.MockFileSystem{FileExists: true, Err: nil} |
| 67 | + lines, err := readLines(tmpFile.Name(), fs) |
| 68 | + assert.NoError(t, err) |
| 69 | + assert.Len(t, lines, 2) |
| 70 | + }) |
| 71 | + |
| 72 | + t.Run("readLines file does not exist", func(t *testing.T) { |
| 73 | + fs := utils.MockFileSystem{FileExists: false, Err: nil} |
| 74 | + lines, err := readLines("nonexistentfile.txt", fs) |
| 75 | + assert.Error(t, err) |
| 76 | + assert.Nil(t, lines) |
| 77 | + assert.Equal(t, "file does not exist", err.Error()) |
| 78 | + }) |
| 79 | +} |
0 commit comments