support custom /proc path

This commit is contained in:
Neo Zhuo
2021-07-20 11:19:47 +08:00
parent 78c11c4ceb
commit 11ddb5e6bf
12 changed files with 42 additions and 37 deletions

View File

@@ -19,8 +19,6 @@ import (
"strings"
)
var cmdlineFilePath = "/proc/cmdline"
type CmdlineArg struct {
Key string `json:"key"`
Value string `json:"value"`
@@ -52,7 +50,7 @@ func splitAfterSpace(inputChar rune) bool {
}
// CmdlineArgs returns all the kernel cmdline. It is read from cat /proc/cmdline.
func CmdlineArgs() ([]CmdlineArg, error) {
func CmdlineArgs(cmdlineFilePath string) ([]CmdlineArg, error) {
lines, err := ReadFileIntoLines(cmdlineFilePath)
if err != nil {
return nil, fmt.Errorf("error reading the file %s, %v", cmdlineFilePath, err)

View File

@@ -69,15 +69,9 @@ func TestCmdlineStats(t *testing.T) {
}
for _, test := range testcases {
t.Run(test.name, func(t *testing.T) {
originalCmdlineFilePath := cmdlineFilePath
defer func() {
cmdlineFilePath = originalCmdlineFilePath
}()
cmdlineFilePath = test.fakeCmdlineFilePath
cmdlineArgs, err := CmdlineArgs()
cmdlineArgs, err := CmdlineArgs(test.fakeCmdlineFilePath)
if err != nil {
t.Errorf("Unexpected error retrieving cmdlineArgs: %v\nCmdlineArgsFilePath: %s\n", err, cmdlineFilePath)
t.Errorf("Unexpected error retrieving cmdlineArgs: %v\nCmdlineArgsFilePath: %s\n", err, test.fakeCmdlineFilePath)
}
for _, expectedCmdlineArg := range test.expectedCmdlineArgs {
assert.Contains(t, cmdlineArgs, expectedCmdlineArg, "Failed to find cmdlineArgs: %v\n", expectedCmdlineArg)

View File

@@ -20,8 +20,6 @@ import (
"strings"
)
var modulesFilePath = "/proc/modules"
type Module struct {
ModuleName string `json:"moduleName"`
Instances uint64 `json:"instances"`
@@ -37,7 +35,7 @@ func (d Module) String() string {
// Module returns all the kernel modules and their
// usage. It is read from cat /proc/modules.
func Modules() ([]Module, error) {
func Modules(modulesFilePath string) ([]Module, error) {
lines, err := ReadFileIntoLines(modulesFilePath)
if err != nil {
return nil, fmt.Errorf("error reading the contents of %s: %s", modulesFilePath, err)

View File

@@ -97,15 +97,9 @@ func TestModules(t *testing.T) {
}
for _, test := range testcases {
t.Run(test.name, func(t *testing.T) {
originalModuleFilePath := modulesFilePath
defer func() {
modulesFilePath = originalModuleFilePath
}()
modulesFilePath = test.fakeModuleFilePath
modules, err := Modules()
modules, err := Modules(test.fakeModuleFilePath)
if err != nil {
t.Errorf("Unexpected error retrieving modules: %v\nModulesFilePath: %s\n", err, modulesFilePath)
t.Errorf("Unexpected error retrieving modules: %v\nModulesFilePath: %s\n", err, test.fakeModuleFilePath)
}
assert.Equal(t, modules, test.expectedModules, "unpected modules retrieved: %v, expected: %v", modules, test.expectedModules)
})