11package runtime
22
33import (
4+ "context"
45 "errors"
6+ "io/fs"
57 "testing"
8+ "time"
69)
710
811func TestFindMainProcess (t * testing.T ) {
@@ -18,40 +21,82 @@ func TestFindMainProcess(t *testing.T) {
1821 return nil , errors .New ("error" )
1922 }
2023
24+ checkFileFuncGen := func (content fs.FileInfo ) checkFileFunc {
25+ return func (name string ) (fs.FileInfo , error ) {
26+ if name != pidFile {
27+ return nil , errors .New ("error" )
28+ }
29+ return content , nil
30+ }
31+ }
32+ checkFileError := func (string ) (fs.FileInfo , error ) {
33+ return nil , errors .New ("error" )
34+ }
35+ var testFileInfo fs.FileInfo
36+ ctx := context .Background ()
37+ cancellingCtx , cancel := context .WithCancel (ctx )
38+ time .AfterFunc (1 * time .Millisecond , cancel )
39+
2140 tests := []struct {
41+ ctx context.Context
2242 readFile readFileFunc
43+ checkFile checkFileFunc
2344 msg string
2445 expected int
2546 expectError bool
2647 }{
2748 {
49+ ctx : ctx ,
2850 readFile : readFileFuncGen ([]byte ("1\n " )),
51+ checkFile : checkFileFuncGen (testFileInfo ),
2952 expected : 1 ,
3053 expectError : false ,
3154 msg : "normal case" ,
3255 },
3356 {
57+ ctx : ctx ,
3458 readFile : readFileFuncGen ([]byte ("" )),
59+ checkFile : checkFileFuncGen (testFileInfo ),
3560 expected : 0 ,
3661 expectError : true ,
3762 msg : "empty file content" ,
3863 },
3964 {
65+ ctx : ctx ,
4066 readFile : readFileFuncGen ([]byte ("not a number" )),
67+ checkFile : checkFileFuncGen (testFileInfo ),
4168 expected : 0 ,
4269 expectError : true ,
4370 msg : "bad file content" ,
4471 },
4572 {
73+ ctx : ctx ,
4674 readFile : readFileError ,
75+ checkFile : checkFileFuncGen (testFileInfo ),
4776 expected : 0 ,
4877 expectError : true ,
4978 msg : "cannot read file" ,
5079 },
80+ {
81+ ctx : ctx ,
82+ readFile : readFileFuncGen ([]byte ("1\n " )),
83+ checkFile : checkFileError ,
84+ expected : 0 ,
85+ expectError : true ,
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" ,
95+ },
5196 }
5297
5398 for _ , test := range tests {
54- result , err := findMainProcess (test .readFile )
99+ result , err := findMainProcess (test .ctx , test . checkFile , test . readFile , 2 * time . Millisecond )
55100
56101 if result != test .expected {
57102 t .Errorf ("findMainProcess() returned %d but expected %d for case %q" , result , test .expected , test .msg )
0 commit comments