|
1 | 1 | package runtime |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "context" |
4 | 5 | "errors" |
5 | 6 | "io/fs" |
6 | 7 | "testing" |
@@ -32,53 +33,70 @@ func TestFindMainProcess(t *testing.T) { |
32 | 33 | return nil, errors.New("error") |
33 | 34 | } |
34 | 35 | var testFileInfo fs.FileInfo |
| 36 | + ctx := context.Background() |
| 37 | + cancellingCtx, cancel := context.WithCancel(ctx) |
| 38 | + time.AfterFunc(1*time.Millisecond, cancel) |
35 | 39 |
|
36 | 40 | tests := []struct { |
| 41 | + ctx context.Context |
37 | 42 | readFile readFileFunc |
38 | 43 | checkFile checkFileFunc |
39 | 44 | msg string |
40 | 45 | expected int |
41 | 46 | expectError bool |
42 | 47 | }{ |
43 | 48 | { |
| 49 | + ctx: ctx, |
44 | 50 | readFile: readFileFuncGen([]byte("1\n")), |
45 | 51 | checkFile: checkFileFuncGen(testFileInfo), |
46 | 52 | expected: 1, |
47 | 53 | expectError: false, |
48 | 54 | msg: "normal case", |
49 | 55 | }, |
50 | 56 | { |
| 57 | + ctx: ctx, |
51 | 58 | readFile: readFileFuncGen([]byte("")), |
52 | 59 | checkFile: checkFileFuncGen(testFileInfo), |
53 | 60 | expected: 0, |
54 | 61 | expectError: true, |
55 | 62 | msg: "empty file content", |
56 | 63 | }, |
57 | 64 | { |
| 65 | + ctx: ctx, |
58 | 66 | readFile: readFileFuncGen([]byte("not a number")), |
59 | 67 | checkFile: checkFileFuncGen(testFileInfo), |
60 | 68 | expected: 0, |
61 | 69 | expectError: true, |
62 | 70 | msg: "bad file content", |
63 | 71 | }, |
64 | 72 | { |
| 73 | + ctx: ctx, |
65 | 74 | readFile: readFileError, |
66 | 75 | checkFile: checkFileFuncGen(testFileInfo), |
67 | 76 | expected: 0, |
68 | 77 | expectError: true, |
69 | 78 | msg: "cannot read file", |
70 | 79 | }, |
71 | 80 | { |
| 81 | + ctx: ctx, |
72 | 82 | readFile: readFileFuncGen([]byte("1\n")), |
73 | 83 | checkFile: checkFileError, |
74 | 84 | expected: 0, |
75 | 85 | expectError: true, |
76 | | - msg: "cannot file pid file", |
| 86 | + msg: "cannot find pid file", |
| 87 | + }, |
| 88 | + { |
| 89 | + ctx: cancellingCtx, |
| 90 | + readFile: readFileFuncGen([]byte("1\n")), |
| 91 | + checkFile: checkFileError, |
| 92 | + expected: 0, |
| 93 | + expectError: true, |
| 94 | + msg: "context canceled", |
77 | 95 | }, |
78 | 96 | } |
79 | 97 |
|
80 | 98 | for _, test := range tests { |
81 | | - result, err := findMainProcess(test.checkFile, test.readFile, 1*time.Microsecond) |
| 99 | + result, err := findMainProcess(test.ctx, test.checkFile, test.readFile, 2*time.Millisecond) |
82 | 100 |
|
83 | 101 | if result != test.expected { |
84 | 102 | t.Errorf("findMainProcess() returned %d but expected %d for case %q", result, test.expected, test.msg) |
|
0 commit comments