| package module |
| |
| import ( |
| "fmt" |
| "reflect" |
| "strings" |
| "testing" |
| ) |
| |
| type fakeOSUtils struct { |
| lsmod string |
| } |
| |
| func (f *fakeOSUtils) run(command string, args []string, _ bool) (string, error) { |
| switch command { |
| case "lsmod": |
| return f.lsmod, nil |
| case "modinfo": |
| if strings.HasSuffix(args[0], "skip.ko") { |
| return "", fmt.Errorf("Run: couldn't retrieve module name for %s", args[0]) |
| } |
| modName, _ := strings.CutSuffix(args[0], ".ko") |
| modName, _ = strings.CutPrefix(modName, "var/lib/modules/") |
| return modName, nil |
| case "insmod": |
| return "Installed", nil |
| default: |
| return "", fmt.Errorf("Unexpected command entered.") |
| } |
| } |
| |
| func TestRetrieveAllInstalledModules(t *testing.T) { |
| lsmod := `Module Size Used by |
| module1 12288 0 |
| module2 28672 1 module1 |
| module3 12288 1` |
| wantModNames := set{"module1": true, "module2": true, "module3": true} |
| f := fakeOSUtils{lsmod: lsmod} |
| run = f.run |
| got, err := retrieveAllInstalledModules() |
| if err != nil { |
| t.Errorf("TestRetrieveAllInstalledModules: failed to retrieve installed modules: %v", err) |
| } |
| if !reflect.DeepEqual(wantModNames, got) { |
| t.Errorf("TestRetrieveAllInstalledModules: expected modules:%v\t got modules:%v", wantModNames, got) |
| } |
| } |
| |
| func TestRetrieveInstalledModules(t *testing.T) { |
| f := fakeOSUtils{lsmod: `Module Size Used by |
| module1 12288 0 |
| module2 28672 1 module1 |
| module3 12288 1`} |
| tests := []struct { |
| desc string |
| modFiles []string |
| want map[string]string |
| }{ |
| { |
| desc: "No module is installed", |
| modFiles: []string{"var/lib/modules/a.ko", "var/lib/modules/b.ko", "var/lib/modules/c.ko"}, |
| want: map[string]string{}, |
| }, { |
| desc: "Skips file skip.ko as cannot retrieve name", |
| modFiles: []string{"var/lib/modules/module1.ko", "var/lib/modules/skip.ko"}, |
| want: map[string]string{ |
| "var/lib/modules/module1.ko": "module1", |
| }, |
| }, { |
| desc: "All modules installed", |
| modFiles: []string{"var/lib/modules/module1.ko", "var/lib/modules/module2.ko"}, |
| want: map[string]string{ |
| "var/lib/modules/module1.ko": "module1", |
| "var/lib/modules/module2.ko": "module2", |
| }, |
| }, |
| } |
| for _, test := range tests { |
| t.Run(test.desc, func(t *testing.T) { |
| run = f.run |
| got, err := RetrieveInstalledModules(test.modFiles) |
| if err != nil { |
| t.Errorf("TestRetrieveInstalledModules(%s): failed to validate installed modules: %v", test.desc, err) |
| } |
| if !reflect.DeepEqual(test.want, got) { |
| t.Errorf("TestRetrieveInstalledModules(%s): expected mapping: %v\t got mapping: %v", test.desc, test.want, got) |
| } |
| }) |
| } |
| } |