@@ -120,3 +120,85 @@ func TestParsePortRange(t *testing.T) {
120120 })
121121 }
122122}
123+
124+ func TestParsePortNumber (t * testing.T ) {
125+ tests := []struct {
126+ doc string
127+ input string
128+ exp int
129+ expErr string
130+ }{
131+ {
132+ doc : "empty string" ,
133+ input : "" ,
134+ expErr : "value is empty" ,
135+ },
136+ {
137+ doc : "whitespace only" ,
138+ input : " " ,
139+ expErr : "invalid syntax" ,
140+ },
141+ {
142+ doc : "single valid port" ,
143+ input : "1234" ,
144+ exp : 1234 ,
145+ },
146+ {
147+ doc : "zero port" ,
148+ input : "0" ,
149+ exp : 0 ,
150+ },
151+ {
152+ doc : "max valid port" ,
153+ input : "65535" ,
154+ exp : 65535 ,
155+ },
156+ {
157+ doc : "leading/trailing spaces" ,
158+ input : " 42 " ,
159+ expErr : "invalid syntax" ,
160+ },
161+ {
162+ doc : "negative port" ,
163+ input : "-1" ,
164+ expErr : "value out of range (0–65535)" ,
165+ },
166+ {
167+ doc : "too large port" ,
168+ input : "70000" ,
169+ expErr : "value out of range (0–65535)" ,
170+ },
171+ {
172+ doc : "non-numeric" ,
173+ input : "foo" ,
174+ expErr : "invalid syntax" ,
175+ },
176+ {
177+ doc : "trailing garbage" ,
178+ input : "1234abc" ,
179+ expErr : "invalid syntax" ,
180+ },
181+ }
182+
183+ for _ , tc := range tests {
184+ t .Run (tc .doc , func (t * testing.T ) {
185+ got , err := parsePortNumber (tc .input )
186+
187+ if tc .expErr == "" {
188+ if err != nil {
189+ t .Fatalf ("unexpected error: %v" , err )
190+ }
191+ if got != tc .exp {
192+ t .Errorf ("expected %d, got %d" , tc .exp , got )
193+ }
194+ } else {
195+ if err == nil {
196+ t .Fatalf ("expected error %q, got nil" , tc .expErr )
197+ }
198+ if err .Error () != tc .expErr {
199+ t .Errorf ("expected error %q, got %q" , tc .expErr , err .Error ())
200+ }
201+ }
202+ })
203+ }
204+ }
0 commit comments