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"
36 func runCgiTest(t *testing.T, h *Handler, httpreq string, expectedMap map[string]string) *httptest.ResponseRecorder {
37 rw := httptest.NewRecorder()
38 req := newRequest(httpreq)
41 // Make a map to hold the test map that the CGI returns.
42 m := make(map[string]string)
43 m["_body"] = rw.Body.String()
47 line, err := rw.Body.ReadString('\n')
52 t.Fatalf("unexpected error reading from CGI: %v", err)
55 trimmedLine := strings.TrimRight(line, "\r\n")
56 split := strings.SplitN(trimmedLine, "=", 2)
58 t.Fatalf("Unexpected %d parts from invalid line number %v: %q; existing map=%v",
59 len(split), linesRead, line, m)
61 m[split[0]] = split[1]
64 for key, expected := range expectedMap {
67 // For Windows. golang.org/issue/4645.
68 fi1, _ := os.Stat(got)
69 fi2, _ := os.Stat(expected)
70 if os.SameFile(fi1, fi2) {
75 t.Errorf("for key %q got %q; expected %q", key, got, expected)
81 var cgiTested, cgiWorks bool
83 func check(t *testing.T) {
86 cgiWorks = exec.Command("./testdata/test.cgi").Run() == nil
89 // No Perl on Windows, needed by test.cgi
90 // TODO: make the child process be Go, not Perl.
91 t.Skip("Skipping test: test.cgi failed.")
95 func TestCGIBasicGet(t *testing.T) {
98 Path: "testdata/test.cgi",
101 expectedMap := map[string]string{
105 "env-GATEWAY_INTERFACE": "CGI/1.1",
106 "env-HTTP_HOST": "example.com",
108 "env-QUERY_STRING": "foo=bar&a=b",
109 "env-REMOTE_ADDR": "1.2.3.4",
110 "env-REMOTE_HOST": "1.2.3.4",
111 "env-REQUEST_METHOD": "GET",
112 "env-REQUEST_URI": "/test.cgi?foo=bar&a=b",
113 "env-SCRIPT_FILENAME": "testdata/test.cgi",
114 "env-SCRIPT_NAME": "/test.cgi",
115 "env-SERVER_NAME": "example.com",
116 "env-SERVER_PORT": "80",
117 "env-SERVER_SOFTWARE": "go",
119 replay := runCgiTest(t, h, "GET /test.cgi?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
121 if expected, got := "text/html", replay.Header().Get("Content-Type"); got != expected {
122 t.Errorf("got a Content-Type of %q; expected %q", got, expected)
124 if expected, got := "X-Test-Value", replay.Header().Get("X-Test-Header"); got != expected {
125 t.Errorf("got a X-Test-Header of %q; expected %q", got, expected)
129 func TestCGIBasicGetAbsPath(t *testing.T) {
131 pwd, err := os.Getwd()
133 t.Fatalf("getwd error: %v", err)
136 Path: pwd + "/testdata/test.cgi",
139 expectedMap := map[string]string{
140 "env-REQUEST_URI": "/test.cgi?foo=bar&a=b",
141 "env-SCRIPT_FILENAME": pwd + "/testdata/test.cgi",
142 "env-SCRIPT_NAME": "/test.cgi",
144 runCgiTest(t, h, "GET /test.cgi?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
147 func TestPathInfo(t *testing.T) {
150 Path: "testdata/test.cgi",
153 expectedMap := map[string]string{
155 "env-PATH_INFO": "/extrapath",
156 "env-QUERY_STRING": "a=b",
157 "env-REQUEST_URI": "/test.cgi/extrapath?a=b",
158 "env-SCRIPT_FILENAME": "testdata/test.cgi",
159 "env-SCRIPT_NAME": "/test.cgi",
161 runCgiTest(t, h, "GET /test.cgi/extrapath?a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
164 func TestPathInfoDirRoot(t *testing.T) {
167 Path: "testdata/test.cgi",
170 expectedMap := map[string]string{
171 "env-PATH_INFO": "bar",
172 "env-QUERY_STRING": "a=b",
173 "env-REQUEST_URI": "/myscript/bar?a=b",
174 "env-SCRIPT_FILENAME": "testdata/test.cgi",
175 "env-SCRIPT_NAME": "/myscript/",
177 runCgiTest(t, h, "GET /myscript/bar?a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
180 func TestDupHeaders(t *testing.T) {
183 Path: "testdata/test.cgi",
185 expectedMap := map[string]string{
186 "env-REQUEST_URI": "/myscript/bar?a=b",
187 "env-SCRIPT_FILENAME": "testdata/test.cgi",
188 "env-HTTP_COOKIE": "nom=NOM; yum=YUM",
189 "env-HTTP_X_FOO": "val1, val2",
191 runCgiTest(t, h, "GET /myscript/bar?a=b HTTP/1.0\n"+
196 "Host: example.com\n\n",
200 func TestPathInfoNoRoot(t *testing.T) {
203 Path: "testdata/test.cgi",
206 expectedMap := map[string]string{
207 "env-PATH_INFO": "/bar",
208 "env-QUERY_STRING": "a=b",
209 "env-REQUEST_URI": "/bar?a=b",
210 "env-SCRIPT_FILENAME": "testdata/test.cgi",
211 "env-SCRIPT_NAME": "/",
213 runCgiTest(t, h, "GET /bar?a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
216 func TestCGIBasicPost(t *testing.T) {
218 postReq := `POST /test.cgi?a=b HTTP/1.0
220 Content-Type: application/x-www-form-urlencoded
225 Path: "testdata/test.cgi",
228 expectedMap := map[string]string{
230 "param-postfoo": "postbar",
231 "env-REQUEST_METHOD": "POST",
232 "env-CONTENT_LENGTH": "15",
233 "env-REQUEST_URI": "/test.cgi?a=b",
235 runCgiTest(t, h, postReq, expectedMap)
238 func chunk(s string) string {
239 return fmt.Sprintf("%x\r\n%s\r\n", len(s), s)
242 // The CGI spec doesn't allow chunked requests.
243 func TestCGIPostChunked(t *testing.T) {
245 postReq := `POST /test.cgi?a=b HTTP/1.1
247 Content-Type: application/x-www-form-urlencoded
248 Transfer-Encoding: chunked
250 ` + chunk("postfoo") + chunk("=") + chunk("postbar") + chunk("")
253 Path: "testdata/test.cgi",
256 expectedMap := map[string]string{}
257 resp := runCgiTest(t, h, postReq, expectedMap)
258 if got, expected := resp.Code, http.StatusBadRequest; got != expected {
259 t.Fatalf("Expected %v response code from chunked request body; got %d",
264 func TestRedirect(t *testing.T) {
267 Path: "testdata/test.cgi",
270 rec := runCgiTest(t, h, "GET /test.cgi?loc=http://foo.com/ HTTP/1.0\nHost: example.com\n\n", nil)
271 if e, g := 302, rec.Code; e != g {
272 t.Errorf("expected status code %d; got %d", e, g)
274 if e, g := "http://foo.com/", rec.Header().Get("Location"); e != g {
275 t.Errorf("expected Location header of %q; got %q", e, g)
279 func TestInternalRedirect(t *testing.T) {
281 baseHandler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
282 fmt.Fprintf(rw, "basepath=%s\n", req.URL.Path)
283 fmt.Fprintf(rw, "remoteaddr=%s\n", req.RemoteAddr)
286 Path: "testdata/test.cgi",
288 PathLocationHandler: baseHandler,
290 expectedMap := map[string]string{
292 "remoteaddr": "1.2.3.4",
294 runCgiTest(t, h, "GET /test.cgi?loc=/foo HTTP/1.0\nHost: example.com\n\n", expectedMap)
297 // TestCopyError tests that we kill the process if there's an error copying
298 // its output. (for example, from the client having gone away)
299 func TestCopyError(t *testing.T) {
301 if runtime.GOOS == "windows" {
302 t.Skipf("skipping test on %q", runtime.GOOS)
305 Path: "testdata/test.cgi",
308 ts := httptest.NewServer(h)
311 conn, err := net.Dial("tcp", ts.Listener.Addr().String())
315 req, _ := http.NewRequest("GET", "http://example.com/test.cgi?bigresponse=1", nil)
316 err = req.Write(conn)
318 t.Fatalf("Write: %v", err)
321 res, err := http.ReadResponse(bufio.NewReader(conn), req)
323 t.Fatalf("ReadResponse: %v", err)
326 pidstr := res.Header.Get("X-CGI-Pid")
328 t.Fatalf("expected an X-CGI-Pid header in response")
330 pid, err := strconv.Atoi(pidstr)
332 t.Fatalf("invalid X-CGI-Pid value")
336 n, err := io.ReadFull(res.Body, buf[:])
338 t.Fatalf("ReadFull: %d bytes, %v", n, err)
341 childRunning := func() bool {
342 return isProcessRunning(t, pid)
346 t.Fatalf("pre-conn.Close, expected child to be running")
351 for tries < 25 && childRunning() {
352 time.Sleep(50 * time.Millisecond * time.Duration(tries))
356 t.Fatalf("post-conn.Close, expected child to be gone")
360 func TestDirUnix(t *testing.T) {
362 if runtime.GOOS == "windows" {
363 t.Skipf("skipping test on %q", runtime.GOOS)
367 Path: "testdata/test.cgi",
371 expectedMap := map[string]string{
374 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
377 cwd = filepath.Join(cwd, "testdata")
379 Path: "testdata/test.cgi",
382 expectedMap = map[string]string{
385 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
388 func TestDirWindows(t *testing.T) {
389 if runtime.GOOS != "windows" {
390 t.Skip("Skipping windows specific test.")
393 cgifile, _ := filepath.Abs("testdata/test.cgi")
397 perl, err = exec.LookPath("perl")
399 t.Skip("Skipping test: perl not found.")
401 perl, _ = filepath.Abs(perl)
408 Args: []string{cgifile},
409 Env: []string{"SCRIPT_FILENAME=" + cgifile},
411 expectedMap := map[string]string{
414 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
416 // If not specify Dir on windows, working directory should be
417 // base directory of perl.
418 cwd, _ = filepath.Split(perl)
419 if cwd != "" && cwd[len(cwd)-1] == filepath.Separator {
420 cwd = cwd[:len(cwd)-1]
425 Args: []string{cgifile},
426 Env: []string{"SCRIPT_FILENAME=" + cgifile},
428 expectedMap = map[string]string{
431 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
434 func TestEnvOverride(t *testing.T) {
435 cgifile, _ := filepath.Abs("testdata/test.cgi")
439 perl, err = exec.LookPath("perl")
441 t.Skipf("Skipping test: perl not found.")
443 perl, _ = filepath.Abs(perl)
450 Args: []string{cgifile},
452 "SCRIPT_FILENAME=" + cgifile,
453 "REQUEST_URI=/foo/bar"},
455 expectedMap := map[string]string{
457 "env-SCRIPT_FILENAME": cgifile,
458 "env-REQUEST_URI": "/foo/bar",
460 runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)