Skip to content

Commit

Permalink
test(crit): add unit test for SearchPattern method of MemoryReader
Browse files Browse the repository at this point in the history
Signed-off-by: Kouame Behouba Manasse <behouba@gmail.com>
  • Loading branch information
behouba committed Mar 17, 2024
1 parent d23b600 commit 3fac1c7
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions crit/mempages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,81 @@ func TestGetShmemSize(t *testing.T) {
}
}

func TestSearchPattern(t *testing.T) {
pid, err := getTestImgPID()
if err != nil {
t.Fatal(err)
}

mr, err := NewMemoryReader(testImgsDir, pid, sysPageSize)
if err != nil {
t.Fatal(err)
}

testCases := []struct {
name string
pattern string
context int
expectedError error
expectedCount int
}{
{
name: "PATH environment variable",
pattern: "PATH=",
expectedError: nil,
expectedCount: 1,
},
{
name: "PATH environment variable regex",
pattern: `\bPATH=([^\s]+)\b`,
expectedError: nil,
expectedCount: 1,
},
{
name: "PATH environment variable regex with 10 bytes context",
pattern: `\bPATH=([^\s]+)\b`,
context: 10,
expectedError: nil,
expectedCount: 1,
},
{
name: "PATH environment variable regex with a negative context",
pattern: `\bPATH=([^\s]+)\b`,
context: -1,
expectedError: errors.New("context size cannot be negative"),
expectedCount: 0,
},
{
name: "PATH environment variable regex with a large context",
pattern: `\bPATH=([^\s]+)\b`,
context: 10_000,
expectedError: nil,
expectedCount: 1,
},
{
name: "non existing pattern",
pattern: "NON_EXISTENT_PATTERN",
expectedError: nil,
expectedCount: 0,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
results, err := mr.SearchPattern(tc.pattern, tc.context)
if err != nil && tc.expectedError == nil {
t.Errorf("Unexpected error for pattern %s: %v", tc.pattern, err)
} else if err == nil && tc.expectedError != nil {
t.Errorf("Expected error for pattern %s: %v", tc.pattern, tc.expectedError)
}

if len(results) != tc.expectedCount {
t.Errorf("Expected %d occurrences of pattern %s, but found %d", tc.expectedCount, tc.pattern, len(results))
}
})
}
}

// helper function to get the PID from the test-imgs directory
func getTestImgPID() (uint32, error) {
psTreeImg, err := getImg(filepath.Join(testImgsDir, "pstree.img"), &pstree.PstreeEntry{})
Expand Down

0 comments on commit 3fac1c7

Please sign in to comment.