@@ -18,8 +18,11 @@ package prometheus
18
18
import (
19
19
"bytes"
20
20
"errors"
21
+ "fmt"
21
22
"os"
23
+ "path/filepath"
22
24
"regexp"
25
+ "strings"
23
26
"testing"
24
27
25
28
"github.com/prometheus/common/expfmt"
@@ -101,3 +104,64 @@ func TestProcessCollector(t *testing.T) {
101
104
t .Errorf ("%d metrics collected, want 1" , n )
102
105
}
103
106
}
107
+
108
+ func TestNewPidFileFn (t * testing.T ) {
109
+ folderPath , err := os .Getwd ()
110
+ if err != nil {
111
+ t .Error ("failed to get current path" )
112
+ }
113
+ mockPidFilePath := filepath .Join (folderPath , "mockPidFile" )
114
+ defer os .Remove (mockPidFilePath )
115
+
116
+ testCases := []struct {
117
+ mockPidFile func ()
118
+ expectedErrPrefix string
119
+ expectedPid int
120
+ desc string
121
+ }{
122
+ {
123
+ mockPidFile : func () {
124
+ os .Remove (mockPidFilePath )
125
+ },
126
+ expectedErrPrefix : "can't read pid file" ,
127
+ expectedPid : 0 ,
128
+ desc : "no existed pid file" ,
129
+ },
130
+ {
131
+ mockPidFile : func () {
132
+ os .Remove (mockPidFilePath )
133
+ f , _ := os .Create (mockPidFilePath )
134
+ f .Write ([]byte ("abc" ))
135
+ f .Close ()
136
+ },
137
+ expectedErrPrefix : "can't parse pid file" ,
138
+ expectedPid : 0 ,
139
+ desc : "existed pid file, error pid number" ,
140
+ },
141
+ {
142
+ mockPidFile : func () {
143
+ os .Remove (mockPidFilePath )
144
+ f , _ := os .Create (mockPidFilePath )
145
+ f .Write ([]byte ("123" ))
146
+ f .Close ()
147
+ },
148
+ expectedErrPrefix : "" ,
149
+ expectedPid : 123 ,
150
+ desc : "existed pid file, correct pid number" ,
151
+ },
152
+ }
153
+
154
+ for _ , tc := range testCases {
155
+ fn := NewPidFileFn (mockPidFilePath )
156
+ if fn == nil {
157
+ t .Error ("Should not get nil PidFileFn" )
158
+ }
159
+
160
+ tc .mockPidFile ()
161
+
162
+ if pid , err := fn (); pid != tc .expectedPid || (err != nil && ! strings .HasPrefix (err .Error (), tc .expectedErrPrefix )) {
163
+ fmt .Println (err .Error ())
164
+ t .Error (tc .desc )
165
+ }
166
+ }
167
+ }
0 commit comments