github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmhttp/cgi/integration_test.go (about)

     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.
     4  
     5  // Tests a Go CGI program running under a Go CGI host process.
     6  // Further, the two programs are the same binary, just checking
     7  // their environment to figure out what mode to run in.
     8  
     9  package cgi
    10  
    11  import (
    12  	"bytes"
    13  	"errors"
    14  	"fmt"
    15  	"io"
    16  	"net/url"
    17  	"os"
    18  	"strings"
    19  	"testing"
    20  	"time"
    21  
    22  	http "github.com/hxx258456/ccgo/gmhttp"
    23  	"github.com/hxx258456/ccgo/gmhttp/httptest"
    24  	"github.com/hxx258456/ccgo/internal/testenv"
    25  )
    26  
    27  // This test is a CGI host (testing host.go) that runs its own binary
    28  // as a child process testing the other half of CGI (child.go).
    29  func TestHostingOurselves(t *testing.T) {
    30  	testenv.MustHaveExec(t)
    31  
    32  	h := &Handler{
    33  		Path: os.Args[0],
    34  		Root: "/test.go",
    35  		Args: []string{"-test.run=TestBeChildCGIProcess"},
    36  	}
    37  	expectedMap := map[string]string{
    38  		"test":                  "Hello CGI-in-CGI",
    39  		"param-a":               "b",
    40  		"param-foo":             "bar",
    41  		"env-GATEWAY_INTERFACE": "CGI/1.1",
    42  		"env-HTTP_HOST":         "example.com",
    43  		"env-PATH_INFO":         "",
    44  		"env-QUERY_STRING":      "foo=bar&a=b",
    45  		"env-REMOTE_ADDR":       "1.2.3.4",
    46  		"env-REMOTE_HOST":       "1.2.3.4",
    47  		"env-REMOTE_PORT":       "1234",
    48  		"env-REQUEST_METHOD":    "GET",
    49  		"env-REQUEST_URI":       "/test.go?foo=bar&a=b",
    50  		"env-SCRIPT_FILENAME":   os.Args[0],
    51  		"env-SCRIPT_NAME":       "/test.go",
    52  		"env-SERVER_NAME":       "example.com",
    53  		"env-SERVER_PORT":       "80",
    54  		"env-SERVER_SOFTWARE":   "go",
    55  	}
    56  	replay := runCgiTest(t, h, "GET /test.go?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
    57  
    58  	if expected, got := "text/plain; charset=utf-8", replay.Header().Get("Content-Type"); got != expected {
    59  		t.Errorf("got a Content-Type of %q; expected %q", got, expected)
    60  	}
    61  	if expected, got := "X-Test-Value", replay.Header().Get("X-Test-Header"); got != expected {
    62  		t.Errorf("got a X-Test-Header of %q; expected %q", got, expected)
    63  	}
    64  }
    65  
    66  type customWriterRecorder struct {
    67  	w io.Writer
    68  	*httptest.ResponseRecorder
    69  }
    70  
    71  func (r *customWriterRecorder) Write(p []byte) (n int, err error) {
    72  	return r.w.Write(p)
    73  }
    74  
    75  type limitWriter struct {
    76  	w io.Writer
    77  	n int
    78  }
    79  
    80  func (w *limitWriter) Write(p []byte) (n int, err error) {
    81  	if len(p) > w.n {
    82  		p = p[:w.n]
    83  	}
    84  	if len(p) > 0 {
    85  		n, err = w.w.Write(p)
    86  		w.n -= n
    87  	}
    88  	if w.n == 0 {
    89  		err = errors.New("past write limit")
    90  	}
    91  	return
    92  }
    93  
    94  // If there's an error copying the child's output to the parent, test
    95  // that we kill the child.
    96  func TestKillChildAfterCopyError(t *testing.T) {
    97  	testenv.MustHaveExec(t)
    98  
    99  	h := &Handler{
   100  		Path: os.Args[0],
   101  		Root: "/test.go",
   102  		Args: []string{"-test.run=TestBeChildCGIProcess"},
   103  	}
   104  	req, _ := http.NewRequest("GET", "http://example.com/test.cgi?write-forever=1", nil)
   105  	rec := httptest.NewRecorder()
   106  	var out bytes.Buffer
   107  	const writeLen = 50 << 10
   108  	rw := &customWriterRecorder{&limitWriter{&out, writeLen}, rec}
   109  
   110  	h.ServeHTTP(rw, req)
   111  	if out.Len() != writeLen || out.Bytes()[0] != 'a' {
   112  		t.Errorf("unexpected output: %q", out.Bytes())
   113  	}
   114  }
   115  
   116  // Test that a child handler writing only headers works.
   117  // golang.org/issue/7196
   118  func TestChildOnlyHeaders(t *testing.T) {
   119  	testenv.MustHaveExec(t)
   120  
   121  	h := &Handler{
   122  		Path: os.Args[0],
   123  		Root: "/test.go",
   124  		Args: []string{"-test.run=TestBeChildCGIProcess"},
   125  	}
   126  	expectedMap := map[string]string{
   127  		"_body": "",
   128  	}
   129  	replay := runCgiTest(t, h, "GET /test.go?no-body=1 HTTP/1.0\nHost: example.com\n\n", expectedMap)
   130  	if expected, got := "X-Test-Value", replay.Header().Get("X-Test-Header"); got != expected {
   131  		t.Errorf("got a X-Test-Header of %q; expected %q", got, expected)
   132  	}
   133  }
   134  
   135  // Test that a child handler does not receive a nil Request Body.
   136  // golang.org/issue/39190
   137  func TestNilRequestBody(t *testing.T) {
   138  	testenv.MustHaveExec(t)
   139  
   140  	h := &Handler{
   141  		Path: os.Args[0],
   142  		Root: "/test.go",
   143  		Args: []string{"-test.run=TestBeChildCGIProcess"},
   144  	}
   145  	expectedMap := map[string]string{
   146  		"nil-request-body": "false",
   147  	}
   148  	_ = runCgiTest(t, h, "POST /test.go?nil-request-body=1 HTTP/1.0\nHost: example.com\n\n", expectedMap)
   149  	_ = runCgiTest(t, h, "POST /test.go?nil-request-body=1 HTTP/1.0\nHost: example.com\nContent-Length: 0\n\n", expectedMap)
   150  }
   151  
   152  func TestChildContentType(t *testing.T) {
   153  	testenv.MustHaveExec(t)
   154  
   155  	h := &Handler{
   156  		Path: os.Args[0],
   157  		Root: "/test.go",
   158  		Args: []string{"-test.run=TestBeChildCGIProcess"},
   159  	}
   160  	var tests = []struct {
   161  		name   string
   162  		body   string
   163  		wantCT string
   164  	}{
   165  		{
   166  			name:   "no body",
   167  			wantCT: "text/plain; charset=utf-8",
   168  		},
   169  		{
   170  			name:   "html",
   171  			body:   "<html><head><title>test page</title></head><body>This is a body</body></html>",
   172  			wantCT: "text/html; charset=utf-8",
   173  		},
   174  		{
   175  			name:   "text",
   176  			body:   strings.Repeat("gopher", 86),
   177  			wantCT: "text/plain; charset=utf-8",
   178  		},
   179  		{
   180  			name:   "jpg",
   181  			body:   "\xFF\xD8\xFF" + strings.Repeat("B", 1024),
   182  			wantCT: "image/jpeg",
   183  		},
   184  	}
   185  	for _, tt := range tests {
   186  		t.Run(tt.name, func(t *testing.T) {
   187  			expectedMap := map[string]string{"_body": tt.body}
   188  			req := fmt.Sprintf("GET /test.go?exact-body=%s HTTP/1.0\nHost: example.com\n\n", url.QueryEscape(tt.body))
   189  			replay := runCgiTest(t, h, req, expectedMap)
   190  			if got := replay.Header().Get("Content-Type"); got != tt.wantCT {
   191  				t.Errorf("got a Content-Type of %q; expected it to start with %q", got, tt.wantCT)
   192  			}
   193  		})
   194  	}
   195  }
   196  
   197  // golang.org/issue/7198
   198  func Test500WithNoHeaders(t *testing.T)     { want500Test(t, "/immediate-disconnect") }
   199  func Test500WithNoContentType(t *testing.T) { want500Test(t, "/no-content-type") }
   200  func Test500WithEmptyHeaders(t *testing.T)  { want500Test(t, "/empty-headers") }
   201  
   202  func want500Test(t *testing.T, path string) {
   203  	h := &Handler{
   204  		Path: os.Args[0],
   205  		Root: "/test.go",
   206  		Args: []string{"-test.run=TestBeChildCGIProcess"},
   207  	}
   208  	expectedMap := map[string]string{
   209  		"_body": "",
   210  	}
   211  	replay := runCgiTest(t, h, "GET "+path+" HTTP/1.0\nHost: example.com\n\n", expectedMap)
   212  	if replay.Code != 500 {
   213  		t.Errorf("Got code %d; want 500", replay.Code)
   214  	}
   215  }
   216  
   217  type neverEnding byte
   218  
   219  func (b neverEnding) Read(p []byte) (n int, err error) {
   220  	for i := range p {
   221  		p[i] = byte(b)
   222  	}
   223  	return len(p), nil
   224  }
   225  
   226  // Note: not actually a test.
   227  func TestBeChildCGIProcess(t *testing.T) {
   228  	if os.Getenv("REQUEST_METHOD") == "" {
   229  		// Not in a CGI environment; skipping test.
   230  		return
   231  	}
   232  	switch os.Getenv("REQUEST_URI") {
   233  	case "/immediate-disconnect":
   234  		os.Exit(0)
   235  	case "/no-content-type":
   236  		fmt.Printf("Content-Length: 6\n\nHello\n")
   237  		os.Exit(0)
   238  	case "/empty-headers":
   239  		fmt.Printf("\nHello")
   240  		os.Exit(0)
   241  	}
   242  	Serve(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
   243  		if req.FormValue("nil-request-body") == "1" {
   244  			fmt.Fprintf(rw, "nil-request-body=%v\n", req.Body == nil)
   245  			return
   246  		}
   247  		rw.Header().Set("X-Test-Header", "X-Test-Value")
   248  		req.ParseForm()
   249  		if req.FormValue("no-body") == "1" {
   250  			return
   251  		}
   252  		if eb, ok := req.Form["exact-body"]; ok {
   253  			io.WriteString(rw, eb[0])
   254  			return
   255  		}
   256  		if req.FormValue("write-forever") == "1" {
   257  			io.Copy(rw, neverEnding('a'))
   258  			for {
   259  				time.Sleep(5 * time.Second) // hang forever, until killed
   260  			}
   261  		}
   262  		fmt.Fprintf(rw, "test=Hello CGI-in-CGI\n")
   263  		for k, vv := range req.Form {
   264  			for _, v := range vv {
   265  				fmt.Fprintf(rw, "param-%s=%s\n", k, v)
   266  			}
   267  		}
   268  		for _, kv := range os.Environ() {
   269  			fmt.Fprintf(rw, "env-%s\n", kv)
   270  		}
   271  	}))
   272  	os.Exit(0)
   273  }