1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Tests for package cgi
26 func newRequest(httpreq string) *http.Request {
27 buf := bufio.NewReader(strings.NewReader(httpreq))
28 req, err := http.ReadRequest(buf)
30 panic("cgi: bogus http request in test: " + httpreq)
32 req.RemoteAddr = "1.2.3.4:1234"
36 func runCgiTest(t *testing.T, h *Handler, httpreq string, expectedMap map[string]string) *httptest.ResponseRecorder {
37 rw := httptest.NewRecorder()
38 req := newRequest(httpreq)
40 runResponseChecks(t, rw, expectedMap)
44 func runResponseChecks(t *testing.T, rw *httptest.ResponseRecorder, expectedMap map[string]string) {
45 // Make a map to hold the test map that the CGI returns.
46 m := make(map[string]string)
47 m["_body"] = rw.Body.String()
51 line, err := rw.Body.ReadString('\n')
56 t.Fatalf("unexpected error reading from CGI: %v", err)
59 trimmedLine := strings.TrimRight(line, "\r\n")
60 split := strings.SplitN(trimmedLine, "=", 2)
62 t.Fatalf("Unexpected %d parts from invalid line number %v: %q; existing map=%v",
63 len(split), linesRead, line, m)
65 m[split[0]] = split[1]
68 for key, expected := range expectedMap {
71 // For Windows. golang.org/issue/4645.
72 fi1, _ := os.Stat(got)
73 fi2, _ := os.Stat(expected)
74 if os.SameFile(fi1, fi2) {
79 t.Errorf("for key %q got %q; expected %q", key, got, expected)
84 var cgiTested, cgiWorks bool
86 func check(t *testing.T) {
89 cgiWorks = exec.Command("./testdata/test.cgi").Run() == nil
92 // No Perl on Windows, needed by test.cgi
93 // TODO: make the child process be Go, not Perl.
94 t.Skip("Skipping test: test.cgi failed.")
98 func TestCGIBasicGet(t *testing.T) {
101 Path: "testdata/test.cgi",
104 expectedMap := map[string]string{
108 "env-GATEWAY_INTERFACE": "CGI/1.1",
109 "env-HTTP_HOST": "example.com",
111 "env-QUERY_STRING": "foo=bar&a=b",
112 "env-REMOTE_ADDR": "1.2.3.4",
113 "env-REMOTE_HOST": "1.2.3.4",
114 "env-REMOTE_PORT": "1234",
115 "env-REQUEST_METHOD": "GET",
116 "env-REQUEST_URI": "/test.cgi?foo=bar&a=b",
117 "env-SCRIPT_FILENAME": "testdata/test.cgi",
118 "env-SCRIPT_NAME": "/test.cgi",
119 "env-SERVER_NAME": "example.com",
120 "env-SERVER_PORT": "80",
121 "env-SERVER_SOFTWARE": "go",
123 replay := runCgiTest(t, h, "GET /test.cgi?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
125 if expected, got := "text/html", replay.Header().Get("Content-Type"); got != expected {
126 t.Errorf("got a Content-Type of %q; expected %q", got, expected)
128 if expected, got := "X-Test-Value", replay.Header().Get("X-Test-Header"); got != expected {
129 t.Errorf("got a X-Test-Header of %q; expected %q", got, expected)
133 func TestCGIEnvIPv6(t *testing.T) {
136 Path: "testdata/test.cgi",
139 expectedMap := map[string]string{
143 "env-GATEWAY_INTERFACE": "CGI/1.1",
144 "env-HTTP_HOST": "example.com",
146 "env-QUERY_STRING": "foo=bar&a=b",
147 "env-REMOTE_ADDR": "2000::3000",
148 "env-REMOTE_HOST": "2000::3000",
149 "env-REMOTE_PORT": "12345",
150 "env-REQUEST_METHOD": "GET",
151 "env-REQUEST_URI": "/test.cgi?foo=bar&a=b",
152 "env-SCRIPT_FILENAME": "testdata/test.cgi",
153 "env-SCRIPT_NAME": "/test.cgi",
154 "env-SERVER_NAME": "example.com",
155 "env-SERVER_PORT": "80",
156 "env-SERVER_SOFTWARE": "go",
159 rw := httptest.NewRecorder()
160 req := newRequest("GET /test.cgi?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n")
161 req.RemoteAddr = "[2000::3000]:12345"
163 runResponseChecks(t, rw, expectedMap)
166 func TestCGIBasicGetAbsPath(t *testing.T) {
168 pwd, err := os.Getwd()
170 t.Fatalf("getwd error: %v", err)
173 Path: pwd + "/testdata/test.cgi",
176 expectedMap := map[string]string{
177 "env-REQUEST_URI": "/test.cgi?foo=bar&a=b",
178 "env-SCRIPT_FILENAME": pwd + "/testdata/test.cgi",
179 "env-SCRIPT_NAME": "/test.cgi",
181 runCgiTest(t, h, "GET /test.cgi?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
184 func TestPathInfo(t *testing.T) {
187 Path: "testdata/test.cgi",
190 expectedMap := map[string]string{
192 "env-PATH_INFO": "/extrapath",
193 "env-QUERY_STRING": "a=b",
194 "env-REQUEST_URI": "/test.cgi/extrapath?a=b",
195 "env-SCRIPT_FILENAME": "testdata/test.cgi",
196 "env-SCRIPT_NAME": "/test.cgi",
198 runCgiTest(t, h, "GET /test.cgi/extrapath?a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
201 func TestPathInfoDirRoot(t *testing.T) {
204 Path: "testdata/test.cgi",
207 expectedMap := map[string]string{
208 "env-PATH_INFO": "bar",
209 "env-QUERY_STRING": "a=b",
210 "env-REQUEST_URI": "/myscript/bar?a=b",
211 "env-SCRIPT_FILENAME": "testdata/test.cgi",
212 "env-SCRIPT_NAME": "/myscript/",
214 runCgiTest(t, h, "GET /myscript/bar?a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
217 func TestDupHeaders(t *testing.T) {
220 Path: "testdata/test.cgi",
222 expectedMap := map[string]string{
223 "env-REQUEST_URI": "/myscript/bar?a=b",
224 "env-SCRIPT_FILENAME": "testdata/test.cgi",
225 "env-HTTP_COOKIE": "nom=NOM; yum=YUM",
226 "env-HTTP_X_FOO": "val1, val2",
228 runCgiTest(t, h, "GET /myscript/bar?a=b HTTP/1.0\n"+
233 "Host: example.com\n\n",
237 func TestPathInfoNoRoot(t *testing.T) {
240 Path: "testdata/test.cgi",
243 expectedMap := map[string]string{
244 "env-PATH_INFO": "/bar",
245 "env-QUERY_STRING": "a=b",
246 "env-REQUEST_URI": "/bar?a=b",
247 "env-SCRIPT_FILENAME": "testdata/test.cgi",
248 "env-SCRIPT_NAME": "/",
250 runCgiTest(t, h, "GET /bar?a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
253 func TestCGIBasicPost(t *testing.T) {
255 postReq := `POST /test.cgi?a=b HTTP/1.0
257 Content-Type: application/x-www-form-urlencoded
262 Path: "testdata/test.cgi",
265 expectedMap := map[string]string{
267 "param-postfoo": "postbar",
268 "env-REQUEST_METHOD": "POST",
269 "env-CONTENT_LENGTH": "15",
270 "env-REQUEST_URI": "/test.cgi?a=b",
272 runCgiTest(t, h, postReq, expectedMap)
275 func chunk(s string) string {
276 return fmt.Sprintf("%x\r\n%s\r\n", len(s), s)
279 // The CGI spec doesn't allow chunked requests.
280 func TestCGIPostChunked(t *testing.T) {
282 postReq := `POST /test.cgi?a=b HTTP/1.1
284 Content-Type: application/x-www-form-urlencoded
285 Transfer-Encoding: chunked
287 ` + chunk("postfoo") + chunk("=") + chunk("postbar") + chunk("")
290 Path: "testdata/test.cgi",
293 expectedMap := map[string]string{}
294 resp := runCgiTest(t, h, postReq, expectedMap)
295 if got, expected := resp.Code, http.StatusBadRequest; got != expected {
296 t.Fatalf("Expected %v response code from chunked request body; got %d",
301 func TestRedirect(t *testing.T) {
304 Path: "testdata/test.cgi",
307 rec := runCgiTest(t, h, "GET /test.cgi?loc=http://foo.com/ HTTP/1.0\nHost: example.com\n\n", nil)
308 if e, g := 302, rec.Code; e != g {
309 t.Errorf("expected status code %d; got %d", e, g)
311 if e, g := "http://foo.com/", rec.Header().Get("Location"); e != g {
312 t.Errorf("expected Location header of %q; got %q", e, g)
316 func TestInternalRedirect(t *testing.T) {
318 baseHandler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
319 fmt.Fprintf(rw, "basepath=%s\n", req.URL.Path)
320 fmt.Fprintf(rw, "remoteaddr=%s\n", req.RemoteAddr)
323 Path: "testdata/test.cgi",
325 PathLocationHandler: baseHandler,
327 expectedMap := map[string]string{
329 "remoteaddr": "1.2.3.4:1234",
331 runCgiTest(t, h, "GET /test.cgi?loc=/foo HTTP/1.0\nHost: example.com\n\n", expectedMap)
334 // TestCopyError tests that we kill the process if there's an error copying
335 // its output. (for example, from the client having gone away)
336 func TestCopyError(t *testing.T) {
338 if runtime.GOOS == "windows" {
339 t.Skipf("skipping test on %q", runtime.GOOS)
342 Path: "testdata/test.cgi",
345 ts := httptest.NewServer(h)
348 conn, err := net.Dial("tcp", ts.Listener.Addr().String())
352 req, _ := http.NewRequest("GET", "http://example.com/test.cgi?bigresponse=1", nil)
353 err = req.Write(conn)
355 t.Fatalf("Write: %v", err)
358 res, err := http.ReadResponse(bufio.NewReader(conn), req)
360 t.Fatalf("ReadResponse: %v", err)
363 pidstr := res.Header.Get("X-CGI-Pid")
365 t.Fatalf("expected an X-CGI-Pid header in response")
367 pid, err := strconv.Atoi(pidstr)
369 t.Fatalf("invalid X-CGI-Pid value")
373 n, err := io.ReadFull(res.Body, buf[:])
375 t.Fatalf("ReadFull: %d bytes, %v", n, err)
378 childRunning := func() bool {
379 return isProcessRunning(t, pid)
383 t.Fatalf("pre-conn.Close, expected child to be running")
388 for tries < 25 && childRunning() {
389 time.Sleep(50 * time.Millisecond * time.Duration(tries))
393 t.Fatalf("post-conn.Close, expected child to be gone")
397 func TestDirUnix(t *testing.T) {
399 if runtime.GOOS == "windows" {
400 t.Skipf("skipping test on %q", runtime.GOOS)
404 Path: "testdata/test.cgi",
408 expectedMap := map[string]string{
411 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
414 cwd = filepath.Join(cwd, "testdata")
416 Path: "testdata/test.cgi",
419 expectedMap = map[string]string{
422 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
425 func TestDirWindows(t *testing.T) {
426 if runtime.GOOS != "windows" {
427 t.Skip("Skipping windows specific test.")
430 cgifile, _ := filepath.Abs("testdata/test.cgi")
434 perl, err = exec.LookPath("perl")
436 t.Skip("Skipping test: perl not found.")
438 perl, _ = filepath.Abs(perl)
445 Args: []string{cgifile},
446 Env: []string{"SCRIPT_FILENAME=" + cgifile},
448 expectedMap := map[string]string{
451 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
453 // If not specify Dir on windows, working directory should be
454 // base directory of perl.
455 cwd, _ = filepath.Split(perl)
456 if cwd != "" && cwd[len(cwd)-1] == filepath.Separator {
457 cwd = cwd[:len(cwd)-1]
462 Args: []string{cgifile},
463 Env: []string{"SCRIPT_FILENAME=" + cgifile},
465 expectedMap = map[string]string{
468 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
471 func TestEnvOverride(t *testing.T) {
472 cgifile, _ := filepath.Abs("testdata/test.cgi")
476 perl, err = exec.LookPath("perl")
478 t.Skipf("Skipping test: perl not found.")
480 perl, _ = filepath.Abs(perl)
487 Args: []string{cgifile},
489 "SCRIPT_FILENAME=" + cgifile,
490 "REQUEST_URI=/foo/bar"},
492 expectedMap := map[string]string{
494 "env-SCRIPT_FILENAME": cgifile,
495 "env-REQUEST_URI": "/foo/bar",
497 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)