From 4fc6dbcb7afbeee7727a1188ac802d7f25110ea2 Mon Sep 17 00:00:00 2001 From: Kouame Behouba Manasse Date: Wed, 6 Mar 2024 07:48:41 -0500 Subject: [PATCH] test(crit): add unit test for SearchPattern method of MemoryReader Signed-off-by: Kouame Behouba Manasse --- crit/mempages_test.go | 74 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/crit/mempages_test.go b/crit/mempages_test.go index 2c087b8a6..571e5d20d 100644 --- a/crit/mempages_test.go +++ b/crit/mempages_test.go @@ -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{})