|
1 | 1 | package deviceutils
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "fmt" |
| 5 | + "regexp" |
4 | 6 | "testing"
|
| 7 | + |
| 8 | + "github.com/google/go-cmp/cmp" |
| 9 | + "github.com/google/go-cmp/cmp/cmpopts" |
5 | 10 | )
|
6 | 11 |
|
7 | 12 | func TestParseNvmeSerial(t *testing.T) {
|
@@ -45,3 +50,61 @@ func TestParseNvmeSerial(t *testing.T) {
|
45 | 50 | }
|
46 | 51 | }
|
47 | 52 | }
|
| 53 | + |
| 54 | +func less(a, b fmt.Stringer) bool { |
| 55 | + return a.String() < b.String() |
| 56 | +} |
| 57 | + |
| 58 | +// Test that the NVMe Regex matches expected paths |
| 59 | +// Note that this only tests the regex, not the actual path finding codepath. |
| 60 | +// The real codepath uses filepath.Glob(), which doesn't have an easy way to mock out local |
| 61 | +// directory paths (eg: using a subdirectory prefix). |
| 62 | +// We could use a recursive child process, setting a root UID, and use Chroot (which requires superuser). |
| 63 | +// This is done in upstream golang tests, but this adds additional complexity |
| 64 | +// and may prevent our tests from running on all platforms. See the following test for an example: |
| 65 | +// https://github.com/golang/go/blob/d33548d178016122726342911f8e15016a691472/src/syscall/exec_linux_test.go#L250 |
| 66 | +func TestDiskNvmePattern(t *testing.T) { |
| 67 | + nvmeDiskRegex := regexp.MustCompile(diskNvmePattern) |
| 68 | + |
| 69 | + testCases := []struct { |
| 70 | + paths []string |
| 71 | + wantPaths []string |
| 72 | + }{ |
| 73 | + { |
| 74 | + paths: []string{ |
| 75 | + "/dev/nvme0n1p15", |
| 76 | + "/dev/nvme0n1p14", |
| 77 | + "/dev/nvme0n1p1", |
| 78 | + "/dev/nvme0n1", |
| 79 | + "/dev/nvme0n2", |
| 80 | + "/dev/nvme0", |
| 81 | + }, |
| 82 | + wantPaths: []string{ |
| 83 | + "/dev/nvme0n1", |
| 84 | + "/dev/nvme0n2", |
| 85 | + }, |
| 86 | + }, |
| 87 | + { |
| 88 | + paths: []string{ |
| 89 | + "/dev/nvme1", |
| 90 | + "/dev/nvme0n1p15", |
| 91 | + "/dev/nvme0n1p14", |
| 92 | + "/dev/nvme0n1p1", |
| 93 | + "/dev/nvme2", |
| 94 | + }, |
| 95 | + wantPaths: []string{}, |
| 96 | + }, |
| 97 | + } |
| 98 | + |
| 99 | + for _, tc := range testCases { |
| 100 | + gotPaths := []string{} |
| 101 | + for _, path := range tc.paths { |
| 102 | + if nvmeDiskRegex.MatchString(path) { |
| 103 | + gotPaths = append(gotPaths, path) |
| 104 | + } |
| 105 | + } |
| 106 | + if diff := cmp.Diff(gotPaths, tc.wantPaths, cmpopts.SortSlices(less)); diff != "" { |
| 107 | + t.Errorf("Unexpected NVMe device paths (-got, +want):\n%s", diff) |
| 108 | + } |
| 109 | + } |
| 110 | +} |
0 commit comments