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 4fc6dbc
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions crit/mempages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,80 @@ 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
shouldMatch bool // Whether the pattern should match
expectedError error
}{
{
name: "PATH environment variable",
pattern: "PATH=",
shouldMatch: true,
},
{
name: "PATH environment variable regex",
pattern: `\bPATH=([^\s]+)\b`,
shouldMatch: true,
},
{
name: "PATH environment variable regex with 10 bytes context",
pattern: `\bPATH=([^\s]+)\b`,
context: 10,
shouldMatch: true,
},
{
name: "PATH environment variable regex with a negative context",
pattern: `\bPATH=([^\s]+)\b`,
context: -1,
expectedError: errors.New("context size cannot be negative"),
},
{
name: "PATH environment variable regex with a large context",
pattern: `\bPATH=([^\s]+)\b`,
context: 100_000,
shouldMatch: true,
},
{
name: "non existent pattern",
pattern: "NON_EXISTENT_PATTERN",
},
}

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 tc.shouldMatch {
if len(results) == 0 {
t.Errorf("Expected to find matches for pattern %s, but found none", tc.pattern)
}
} else {
if len(results) > 0 {
t.Errorf("Expected no matches for pattern %s", tc.pattern)
}
}
})
}
}

// 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 4fc6dbc

Please sign in to comment.