Golang NewUnstartedServer示例

说明

golang newunstartedserver示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http/httptest

示例#1
文件: pinger_internals_test.go 项目: turnkey-commerce/go-ping-sites

func TestIsInternetAccessibleBothBad(t *testing.T) {
	// Set up both as non-running servers
	statusOK := statusHandler(http.StatusOK)
	s1 := httptest.NewUnstartedServer(&statusOK)
	s2 := httptest.NewUnstartedServer(&statusOK)
	defer s1.Close()
	defer s2.Close()

	result := isInternetAccessible(s1.URL, s2.URL)
	if result {
		t.Error("Should fail on both servers.")
	}
}

示例#2
文件: cloud_controller.go 项目: dieucao/notifications

func NewCloudController() *CloudController {
	fake := &CloudController{
		Organizations:    NewOrganizations(),
		Spaces:           NewSpaces(),
		Users:            NewUsers(),
		ServiceInstances: NewServiceInstances(),
	}

	router := mux.NewRouter()
	router.HandleFunc("/v2/organizations", fake.CreateOrganization).Methods("POST")
	router.HandleFunc("/v2/organizations/{guid}", fake.GetOrganization).Methods("GET")
	router.HandleFunc("/v2/organizations/{guid}/users", fake.GetOrganizationUsers).Methods("GET")
	router.HandleFunc("/v2/organizations/{guid}/users/{user_guid}", fake.AssociateUserToOrganization).Methods("PUT")
	router.HandleFunc("/v2/organizations/{guid}/billing_managers", fake.GetOrganizationBillingManagers).Methods("GET")
	router.HandleFunc("/v2/organizations/{guid}/billing_managers/{billing_manager_guid}", fake.AssociateBillingManagerToOrganization).Methods("PUT")
	router.HandleFunc("/v2/organizations/{guid}/auditors", fake.GetOrganizationAuditors).Methods("GET")
	router.HandleFunc("/v2/organizations/{guid}/auditors/{auditor_guid}", fake.AssociateAuditorToOrganization).Methods("PUT")
	router.HandleFunc("/v2/organizations/{guid}/managers", fake.GetOrganizationManagers).Methods("GET")
	router.HandleFunc("/v2/organizations/{guid}/managers/{manager_guid}", fake.AssociateManagerToOrganization).Methods("PUT")
	router.HandleFunc("/v2/spaces", fake.CreateSpace).Methods("POST")
	router.HandleFunc("/v2/spaces/{guid}", fake.GetSpace).Methods("GET")
	router.HandleFunc("/v2/spaces/{guid}/developers/{developer_guid}", fake.AssociateDeveloperToSpace).Methods("PUT")
	router.HandleFunc("/v2/spaces/{guid}/developers", fake.GetSpaceDevelopers).Methods("GET")
	router.HandleFunc("/v2/users", fake.GetUsers).Methods("GET")
	router.HandleFunc("/v2/users", fake.CreateUser).Methods("POST")
	router.HandleFunc("/v2/users/{guid}", fake.GetUser).Methods("GET")
	router.HandleFunc("/v2/service_instances", fake.CreateServiceInstance).Methods("POST")
	router.HandleFunc("/v2/service_instances/{guid}", fake.GetServiceInstance).Methods("GET")

	handler := fake.RequireToken(router)
	fake.server = httptest.NewUnstartedServer(handler)
	return fake
}

示例#3
文件: clientserver_test.go 项目: Mahdi89/riscv-go

func newClientServerTest(t *testing.T, h2 bool, h Handler) *clientServerTest {
	cst := &clientServerTest{
		t:  t,
		h2: h2,
		h:  h,
		tr: &Transport{},
	}
	cst.c = &Client{Transport: cst.tr}
	if !h2 {
		cst.ts = httptest.NewServer(h)
		return cst
	}
	cst.ts = httptest.NewUnstartedServer(h)
	ExportHttp2ConfigureServer(cst.ts.Config, nil)
	cst.ts.TLS = cst.ts.Config.TLSConfig
	cst.ts.StartTLS()

	cst.tr.TLSClientConfig = &tls.Config{
		InsecureSkipVerify: true,
	}
	if err := ExportHttp2ConfigureTransport(cst.tr); err != nil {
		t.Fatal(err)
	}
	return cst
}

示例#4
文件: cf_console_suite_test.go 项目: 18F/cg-dashboard

// Helper function to handle all the weird work of creating a test server.
func startServer() (*httptest.Server, AcceptanceTestEnvVars) {
	// Load the environment variables to conduct the tests.
	testEnvVars := AcceptanceTestEnvVars{}
	testEnvVars.LoadTestEnvVars()
	var TimeoutConstant = time.Second * 10
	SetDefaultEventuallyTimeout(TimeoutConstant)

	var err error
	// Attempt to initial routers
	app, settings, err := controllers.InitApp(testEnvVars.EnvVars)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	// Since we are running in a separate folder from the main package, we need to change the location of the static folder.
	app.Middleware(web.StaticMiddleware("../static", web.StaticOption{IndexFile: "index.html"}))

	// Create the httptest server
	server := httptest.NewUnstartedServer(app)
	server.Start()

	// Change config values to fit the URL of the httptest server that is created on a random port.
	testEnvVars.Hostname = server.URL
	settings.OAuthConfig.RedirectURL = server.URL + "/oauth2callback"

	return server, testEnvVars
}

示例#5
文件: target_test.go 项目: prometheus/prometheus

func TestNewHTTPClientCert(t *testing.T) {
	server := httptest.NewUnstartedServer(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				w.Header().Set("Content-Type", `text/plain; version=0.0.4`)
				w.Write([]byte{})
			},
		),
	)
	tlsConfig := newTLSConfig("server", t)
	tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
	tlsConfig.ClientCAs = tlsConfig.RootCAs
	tlsConfig.BuildNameToCertificate()
	server.TLS = tlsConfig
	server.StartTLS()
	defer server.Close()

	cfg := config.HTTPClientConfig{
		TLSConfig: config.TLSConfig{
			CAFile:   caCertPath,
			CertFile: "testdata/client.cer",
			KeyFile:  "testdata/client.key",
		},
	}
	c, err := NewHTTPClient(cfg)
	if err != nil {
		t.Fatal(err)
	}
	_, err = c.Get(server.URL)
	if err != nil {
		t.Fatal(err)
	}
}

示例#6
文件: helpers.go 项目: mikepea/cdn-acceptance-tests

// Start resets the handler back to the default and starts the server on
// Port. It will exit immediately if it's unable to bind the port, due to
// permissions or a conflicting application.
func (s *CDNBackendServer) Start() {
	s.ResetHandler()

	addr := fmt.Sprintf(":%d", s.Port)
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}

	// Store the port randomly assigned by the kernel if we started with 0.
	if s.Port == 0 {
		_, portStr, _ := net.SplitHostPort(ln.Addr().String())
		s.Port, _ = strconv.Atoi(portStr)
	}

	s.server = httptest.NewUnstartedServer(s)
	s.server.Listener = ln

	if len(s.TLSCerts) > 0 {
		s.server.TLS = &tls.Config{
			Certificates: s.TLSCerts,
		}
		s.server.StartTLS()
	} else {
		s.server.Start()
	}

	log.Printf("Started server on port %d", s.Port)
}

示例#7
文件: proxy_test.go 项目: WIZARD-CXY/golang-devops-stuff

func (s *ProxySuite) TestReadTimeout(c *C) {
	c.Skip("This test is not stable")

	server := NewTestServer(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hi, I'm endpoint"))
	})
	defer server.Close()

	proxy, err := NewProxy(&ConstRouter{&ConstHttpLocation{server.URL}})
	c.Assert(err, IsNil)

	// Set a very short read timeout
	proxyServer := httptest.NewUnstartedServer(proxy)
	proxyServer.Config.ReadTimeout = time.Millisecond
	proxyServer.Start()
	defer proxyServer.Close()

	value := make([]byte, 65636)
	for i := 0; i < len(value); i += 1 {
		value[i] = byte(i % 255)
	}

	response, _ := Get(c, proxyServer.URL, nil, string(value))
	c.Assert(response.StatusCode, Equals, http.StatusRequestTimeout)
}

示例#8
文件: httpserver.go 项目: vmware/photon-controller-go-sdk

func newUnstartedTestServer() (server *Server) {
	status := 200
	body := ""

	server = &Server{
		nil,
		&ServerResponseData{&status, &body},
		make(map[string]*ServerResponseData),
	}

	server.HttpServer = httptest.NewUnstartedServer(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json")

			var response *ServerResponseData
			for k, v := range server.Responses {
				if strings.HasPrefix(r.URL.Path, k) {
					response = v
					break
				}
			}

			if response == nil {
				response = server.DefaultResponse
			}

			w.WriteHeader(*response.StatuCode)
			fmt.Fprintln(w, *response.Body)
		}))
	return
}

示例#9
文件: handler_test.go 项目: lmineiro/hydra

func TestAuthCode(t *testing.T) {
	var callbackURL *url.URL
	router := mux.NewRouter()
	ts := httptest.NewUnstartedServer(router)
	callbackCalled := false

	handler.SetRoutes(router, mockAuthorization("", new(jwt.Token)))
	router.HandleFunc("/remote/oauth2/auth", authHandlerMock(t, ts))
	router.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
		callbackURL = r.URL
		callbackCalled = true
	})

	ts.Start()
	defer ts.Close()

	for _, c := range []struct{ config *oauth2.Config }{{configs["working"]}} {
		config := *c.config
		config.Endpoint = oauth2.Endpoint{AuthURL: ts.URL + "/oauth2/auth?provider=mockprovider", TokenURL: ts.URL + "/oauth2/token"}
		authURL := config.AuthCodeURL(uuid.New())
		t.Logf("Auth code URL: %s", authURL)

		resp, err := http.Get(authURL)
		require.Nil(t, err)
		defer resp.Body.Close()
		require.True(t, callbackCalled)
		callbackCalled = false

		token, err := config.Exchange(oauth2.NoContext, callbackURL.Query().Get("code"))
		require.Nil(t, err)
		require.NotEmpty(t, token.AccessToken)
		require.NotEmpty(t, token.RefreshToken)
		testTokenRefresh(t, ts.URL, config.ClientID, config.ClientSecret, token.RefreshToken, true)
	}
}

示例#10
文件: client_test.go 项目: ringtail/etcd

// TestV2NoRetryNoLeader tests destructive api calls won't retry if given an error code.
func TestV2NoRetryNoLeader(t *testing.T) {
	defer testutil.AfterTest(t)

	lHttp := integration.NewListenerWithAddr(t, fmt.Sprintf("errHttp:123.%d.sock", os.Getpid()))
	eh := &errHandler{errCode: http.StatusServiceUnavailable}
	srv := httptest.NewUnstartedServer(eh)
	defer lHttp.Close()
	defer srv.Close()
	srv.Listener = lHttp
	go srv.Start()
	lHttpURL := integration.UrlScheme + "://" + lHttp.Addr().String()

	cli := integration.MustNewHTTPClient(t, []string{lHttpURL, lHttpURL}, nil)
	kapi := client.NewKeysAPI(cli)
	// test error code
	for i, f := range noRetryList(kapi) {
		reqs := eh.reqs
		if err := f(); err == nil || !strings.Contains(err.Error(), "no leader") {
			t.Errorf("#%d: expected \"no leader\", got %v", i, err)
		}
		if eh.reqs != reqs+1 {
			t.Errorf("#%d: expected 1 request, got %d", i, eh.reqs-reqs)
		}
	}
}

示例#11
文件: fwd_test.go 项目: martensson/oxy

func (s *FwdSuite) TestForwardedProto(c *C) {
	var proto string
	srv := testutils.NewHandler(func(w http.ResponseWriter, req *http.Request) {
		proto = req.Header.Get(XForwardedProto)
		w.Write([]byte("hello"))
	})
	defer srv.Close()

	buf := &bytes.Buffer{}
	l := utils.NewFileLogger(buf, utils.INFO)

	f, err := New(Logger(l))
	c.Assert(err, IsNil)

	proxy := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		req.URL = testutils.ParseURI(srv.URL)
		f.ServeHTTP(w, req)
	})
	tproxy := httptest.NewUnstartedServer(proxy)
	tproxy.StartTLS()
	defer tproxy.Close()

	re, _, err := testutils.Get(tproxy.URL)
	c.Assert(err, IsNil)
	c.Assert(re.StatusCode, Equals, http.StatusOK)
	c.Assert(proto, Equals, "https")

	c.Assert(strings.Contains(buf.String(), "tls"), Equals, true)
}

示例#12
文件: test_utils.go 项目: 4578395263256/godropbox

// Create a dummy server for unittesting.  DO NOT USE IN PRODUCTION.
func SetupTestServer(ssl bool) (*TestServer, string) {
	closeChan := make(chan bool, 1)

	serveMux := http.NewServeMux()
	serveMux.HandleFunc(
		"/slow_request",
		func(writer http.ResponseWriter, req *http.Request) {

			select {
			case <-closeChan:
				return
			case <-time.After(500 * time.Millisecond):
				return
			}
		})
	serveMux.HandleFunc(
		"/",
		func(writer http.ResponseWriter, req *http.Request) {

			writer.Write([]byte("ok"))
		})

	server := httptest.NewUnstartedServer(serveMux)
	server.Config.ReadTimeout = 5 * time.Second
	server.Config.WriteTimeout = 5 * time.Second
	if ssl {
		server.StartTLS()
	} else {
		server.Start()
	}

	addr := server.Listener.Addr().String()
	return &TestServer{server, closeChan}, addr
}

示例#13
文件: clientserver_test.go 项目: kuangchanglang/go

func newClientServerTest(t *testing.T, h2 bool, h Handler, opts ...interface{}) *clientServerTest {
	cst := &clientServerTest{
		t:  t,
		h2: h2,
		h:  h,
		tr: &Transport{},
	}
	cst.c = &Client{Transport: cst.tr}

	for _, opt := range opts {
		switch opt := opt.(type) {
		case func(*Transport):
			opt(cst.tr)
		default:
			t.Fatalf("unhandled option type %T", opt)
		}
	}

	if !h2 {
		cst.ts = httptest.NewServer(h)
		return cst
	}
	cst.ts = httptest.NewUnstartedServer(h)
	ExportHttp2ConfigureServer(cst.ts.Config, nil)
	cst.ts.TLS = cst.ts.Config.TLSConfig
	cst.ts.StartTLS()

	cst.tr.TLSClientConfig = &tls.Config{
		InsecureSkipVerify: true,
	}
	if err := ExportHttp2ConfigureTransport(cst.tr); err != nil {
		t.Fatal(err)
	}
	return cst
}

示例#14
文件: smock.go 项目: MohamedBassem/Smock

// NewMockServer returns a MockServer instance that you can use on your own or use the CaptureRequests function. At least one of: the GlobalTimeout, the RequestTimeout or MaximumRequestCount must be set.
// If to be used on your own mockServer.Start() should be called first before starting to use the server and mockServer.Close() should be called to stop the server.
func NewMockServer(config MockServerConfig) *MockServer {

	mergeDefaultConfigs(&config)
	if config.GlobalTimeout == 0 && config.RequestTimeout == 0 && config.MaximumRequestCount == 0 {
		panic("At least one of: the GlobalTimeout, the RequestTimeout or MaximumRequestCount must be set")
	}

	server := MockServer{
		config: config,
	}

	server.testServer = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(config.ResponseStatusCode)
		body, _ := ioutil.ReadAll(r.Body)
		r.Body.Close()

		server.Reqs.In() <- MockRequest{
			Body:    string(body),
			Headers: r.Header,
			Method:  r.Method,
		}
	}))

	return &server
}

示例#15
文件: server_test.go 项目: csarven/gold

func TestRedirectSignUpWithVhosts(t *testing.T) {
	// test vhosts
	testServer1 := httptest.NewUnstartedServer(handler1)
	testServer1.TLS = new(tls.Config)
	testServer1.TLS.ClientAuth = tls.RequestClientCert
	testServer1.TLS.NextProtos = []string{"http/1.1"}
	testServer1.StartTLS()

	request, err := http.NewRequest("GET", testServer1.URL, nil)
	assert.NoError(t, err)
	request.Header.Add("Accept", "text/html")
	response, err := user1h.Do(request)
	assert.NoError(t, err)
	body, _ := ioutil.ReadAll(response.Body)
	response.Body.Close()
	assert.Equal(t, 200, response.StatusCode)
	assert.NotEmpty(t, string(body))

	request, err = http.NewRequest("GET", testServer1.URL+"/dir/", nil)
	assert.NoError(t, err)
	request.Header.Add("Accept", "text/html")
	response, err = user1h.Do(request)
	assert.NoError(t, err)
	response.Body.Close()
	assert.Equal(t, 404, response.StatusCode)

	request, err = http.NewRequest("GET", testServer1.URL+"/file", nil)
	assert.NoError(t, err)
	request.Header.Add("Accept", "text/html")
	response, err = user1h.Do(request)
	assert.NoError(t, err)
	assert.Equal(t, 404, response.StatusCode)
}

示例#16
文件: target_test.go 项目: prasincs/prometheus

func TestNewHTTPClientCert(t *testing.T) {
	server := httptest.NewUnstartedServer(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				w.Header().Set("Content-Type", `text/plain; version=0.0.4`)
				w.Write([]byte{})
			},
		),
	)
	tlsConfig := newTLSConfig(t)
	tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
	tlsConfig.ClientCAs = tlsConfig.RootCAs
	tlsConfig.BuildNameToCertificate()
	server.TLS = tlsConfig
	server.StartTLS()
	defer server.Close()

	cfg := &config.ScrapeConfig{
		ScrapeTimeout: config.Duration(1 * time.Second),
		CACert:        "testdata/ca.cer",
		ClientCert: &config.ClientCert{
			Cert: "testdata/client.cer",
			Key:  "testdata/client.key",
		},
	}
	c, err := newHTTPClient(cfg)
	if err != nil {
		t.Fatal(err)
	}
	_, err = c.Get(server.URL)
	if err != nil {
		t.Fatal(err)
	}
}

示例#17
文件: event_test.go 项目: goodeggs/platform

func TestTLSEventListeners(t *testing.T) {
	testEventListeners("TestTLSEventListeners", t, func(handler http.Handler) *httptest.Server {
		server := httptest.NewUnstartedServer(handler)

		cert, err := tls.LoadX509KeyPair("testing/data/server.pem", "testing/data/serverkey.pem")
		if err != nil {
			t.Fatalf("Error loading server key pair: %s", err)
		}

		caCert, err := ioutil.ReadFile("testing/data/ca.pem")
		if err != nil {
			t.Fatalf("Error loading ca certificate: %s", err)
		}
		caPool := x509.NewCertPool()
		if !caPool.AppendCertsFromPEM(caCert) {
			t.Fatalf("Could not add ca certificate")
		}

		server.TLS = &tls.Config{
			Certificates: []tls.Certificate{cert},
			RootCAs:      caPool,
		}
		server.StartTLS()
		return server
	}, func(url string) (*Client, error) {
		return NewTLSClient(url, "testing/data/cert.pem", "testing/data/key.pem", "testing/data/ca.pem")
	})
}

示例#18
文件: system_test.go 项目: WebCivics/gold

func TestAccountStatusWithoutVhosts(t *testing.T) {
	// test vhosts
	testServer1 := httptest.NewUnstartedServer(handler2)
	testServer1.TLS = new(tls.Config)
	testServer1.TLS.ClientAuth = tls.RequestClientCert
	testServer1.TLS.NextProtos = []string{"http/1.1"}
	testServer1.StartTLS()

	ar := accountRequest{
		Method:      "accountStatus",
		AccountName: "user",
	}
	jsonData, err := json.Marshal(ar)
	assert.NoError(t, err)

	request, err := http.NewRequest("POST", testServer1.URL+"/"+SystemPrefix+"/accountStatus", bytes.NewReader(jsonData))
	assert.NoError(t, err)
	response, err := user1h.Do(request)
	assert.NoError(t, err)
	body, _ := ioutil.ReadAll(response.Body)
	response.Body.Close()
	assert.Equal(t, `{"method":"accountStatus","status":"success","formURL":"`+testServer1.URL+`/`+SystemPrefix+`/newAccount","loginURL":"`+testServer1.URL+`/user/","response":{"accountURL":"`+testServer1.URL+`/user/","available":true}}`, string(body))
	assert.Equal(t, 200, response.StatusCode)

	// delete user
	err = os.RemoveAll("_test/")
	assert.NoError(t, err)
}

示例#19
文件: RequestRecordingServer.go 项目: REAANDREW/jarvis

//Start ...
func (instance *RequestRecordingServer) Start() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		body, err := ioutil.ReadAll(r.Body)
		check(err)
		recordedRequest := RecordedRequest{
			request: r,
			body:    string(body),
		}
		instance.requests = append(instance.requests, recordedRequest)
		if instance.use != nil {
			for _, item := range instance.use {
				if item.RequestPredicates != nil {
					result := instance.Evaluate(recordedRequest, item.RequestPredicates...)
					if result {
						item.ResponseFactory(w)
						return
					}
				} else {
					item.ResponseFactory(w)
					return
				}
			}
			w.WriteHeader(http.StatusOK)
		} else {
			w.WriteHeader(http.StatusOK)
		}
	})
	instance.server = httptest.NewUnstartedServer(handler)
	instance.server.Listener, _ = net.Listen("tcp", ":"+strconv.Itoa(instance.port))
	instance.server.Start()
}

示例#20
文件: system_test.go 项目: WebCivics/gold

func TestAccountInfo(t *testing.T) {
	err := os.MkdirAll("_test/user", 0755)
	assert.NoError(t, err)

	sizeLocal, err := DiskUsage("_test/")
	assert.NoError(t, err)

	testServer1 := httptest.NewUnstartedServer(handler2)
	testServer1.TLS = new(tls.Config)
	testServer1.TLS.ClientAuth = tls.RequestClientCert
	testServer1.TLS.NextProtos = []string{"http/1.1"}
	testServer1.StartTLS()

	request, err := http.NewRequest("GET", testServer1.URL+"/"+SystemPrefix+"/accountInfo", nil)
	assert.NoError(t, err)
	response, err := httpClient.Do(request)
	assert.NoError(t, err)
	body, _ := ioutil.ReadAll(response.Body)
	response.Body.Close()

	err = os.RemoveAll("_test/")
	assert.NoError(t, err)

	assert.Equal(t, 200, response.StatusCode)
	assert.NotEmpty(t, body)

	dataLocal := accountInformation{
		DiskUsed:  fmt.Sprintf("%d", sizeLocal),
		DiskLimit: fmt.Sprintf("%d", config2.DiskLimit),
	}
	jsonData, err := json.Marshal(dataLocal)
	assert.Equal(t, body, jsonData)
}

示例#21
文件: target_test.go 项目: nicr9/prometheus

func TestNewHTTPCACert(t *testing.T) {
	server := httptest.NewUnstartedServer(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				w.Header().Set("Content-Type", `text/plain; version=0.0.4`)
				w.Write([]byte{})
			},
		),
	)
	server.TLS = newTLSConfig(t)
	server.StartTLS()
	defer server.Close()

	cfg := &config.ScrapeConfig{
		ScrapeTimeout: config.Duration(1 * time.Second),
		TLSConfig: config.TLSConfig{
			CAFile: "testdata/ca.cer",
		},
	}
	c, err := newHTTPClient(cfg)
	if err != nil {
		t.Fatal(err)
	}
	_, err = c.Get(server.URL)
	if err != nil {
		t.Fatal(err)
	}
}

示例#22
文件: system_test.go 项目: WebCivics/gold

func TestNewAccountWithVhosts(t *testing.T) {
	testServer1 := httptest.NewUnstartedServer(handler1)
	testServer1.TLS = new(tls.Config)
	testServer1.TLS.ClientAuth = tls.RequestClientCert
	testServer1.TLS.NextProtos = []string{"http/1.1"}
	testServer1.StartTLS()

	form := url.Values{
		"username": {"user"},
		"email":    {"[email protected]"},
	}
	request, err := http.NewRequest("POST", testServer1.URL+"/"+SystemPrefix+"/newAccount", bytes.NewBufferString(form.Encode()))
	assert.NoError(t, err)
	request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Add("Content-Length", strconv.Itoa(len(form.Encode())))
	response, err := httpClient.Do(request)
	assert.NoError(t, err)
	body, _ := ioutil.ReadAll(response.Body)
	response.Body.Close()
	assert.Equal(t, 200, response.StatusCode)
	assert.Empty(t, body)

	// delete user
	err = os.RemoveAll("_test/")
	assert.NoError(t, err)
}

示例#23
文件: stream_test.go 项目: Christeefym/lantern

// Make sure that stream handler preserves TLS settings
func (s *STSuite) TestPreservesTLS(c *C) {
	srv := testutils.NewHandler(func(w http.ResponseWriter, req *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("ok"))
	})
	defer srv.Close()

	// forwarder will proxy the request to whatever destination
	fwd, err := forward.New()
	c.Assert(err, IsNil)

	var t *tls.ConnectionState
	// this is our redirect to server
	rdr := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		t = req.TLS
		req.URL = testutils.ParseURI(srv.URL)
		fwd.ServeHTTP(w, req)
	})

	// stream handler will forward requests to redirect
	st, err := New(rdr, Logger(utils.NewFileLogger(os.Stdout, utils.INFO)))
	c.Assert(err, IsNil)

	proxy := httptest.NewUnstartedServer(st)
	proxy.StartTLS()
	defer proxy.Close()

	re, _, err := testutils.Get(proxy.URL)
	c.Assert(err, IsNil)
	c.Assert(re.StatusCode, Equals, http.StatusOK)

	c.Assert(t, NotNil)
}

示例#24
文件: server.go 项目: matomesc/rkt

func NewServer(serverType ServerType, auth AuthType, msgCapacity int) *Server {
	msg := make(chan string, msgCapacity)
	server := &Server{
		Msg: msg,
		handler: &serverHandler{
			auth:         auth,
			msg:          msg,
			serverType:   serverType,
			fileSet:      make(map[string]string),
			servedImages: make(map[string]struct{}),
		},
	}
	server.http = httptest.NewUnstartedServer(server.handler)
	server.http.TLS = &tls.Config{InsecureSkipVerify: true}
	server.http.StartTLS()
	server.URL = server.http.URL
	host := server.http.Listener.Addr().String()
	switch auth {
	case AuthNone:
		// nothing to do
	case AuthBasic:
		creds := `"user": "bar",
		"password": "baz"`
		server.Conf = sprintCreds(host, "basic", creds)
	case AuthOauth:
		creds := `"token": "sometoken"`
		server.Conf = sprintCreds(host, "oauth", creds)
	default:
		panic("Woe is me!")
	}
	return server
}

示例#25
文件: target_test.go 项目: prometheus/prometheus

func TestNewHTTPWithBadServerName(t *testing.T) {
	server := httptest.NewUnstartedServer(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				w.Header().Set("Content-Type", `text/plain; version=0.0.4`)
				w.Write([]byte{})
			},
		),
	)
	server.TLS = newTLSConfig("servername", t)
	server.StartTLS()
	defer server.Close()

	cfg := config.HTTPClientConfig{
		TLSConfig: config.TLSConfig{
			CAFile:     caCertPath,
			ServerName: "badname",
		},
	}
	c, err := NewHTTPClient(cfg)
	if err != nil {
		t.Fatal(err)
	}
	_, err = c.Get(server.URL)
	if err == nil {
		t.Fatal("Expected error, got nil.")
	}
}

示例#26
文件: oidc_test.go 项目: RomainVabre/origin

func TestOIDCDiscoveryNoKeyEndpoint(t *testing.T) {
	var err error
	expectErr := fmt.Errorf("failed to fetch provider config after 0 retries")

	cert := path.Join(os.TempDir(), "oidc-cert")
	key := path.Join(os.TempDir(), "oidc-key")

	defer os.Remove(cert)
	defer os.Remove(key)

	generateSelfSignedCert(t, "127.0.0.1", cert, key)

	op := newOIDCProvider(t)
	srv := httptest.NewUnstartedServer(op.mux)
	srv.TLS = &tls.Config{Certificates: make([]tls.Certificate, 1)}
	srv.TLS.Certificates[0], err = tls.LoadX509KeyPair(cert, key)
	if err != nil {
		t.Fatalf("Cannot load cert/key pair: %v", err)
	}
	srv.StartTLS()
	// TODO: Uncomment when fix #19254
	// defer srv.Close()

	op.pcfg = oidc.ProviderConfig{
		Issuer: mustParseURL(t, srv.URL), // An invalid ProviderConfig. Keys endpoint is required.
	}

	_, err = New(OIDCOptions{srv.URL, "client-foo", cert, "sub", "", 0, 0})
	if !reflect.DeepEqual(err, expectErr) {
		t.Errorf("Expecting %v, but got %v", expectErr, err)
	}
}

示例#27
文件: httploc_test.go 项目: GitHub9527/vulcan

// Test that X-Forwarded-For and X-Forwarded-Proto are passed through
func (s *LocSuite) TestForwardedProtoHTTPS(c *C) {
	called := false
	server := NewTestServer(func(w http.ResponseWriter, r *http.Request) {
		called = true
		c.Assert(r.Header.Get(headers.XForwardedProto), Equals, "https")
	})
	defer server.Close()

	lb := s.newRoundRobin(server.URL)

	location, err := NewLocation("dummy", lb)
	c.Assert(err, IsNil)

	proxy, err := vulcan.NewProxy(&ConstRouter{
		Location: location,
	})
	c.Assert(err, IsNil)

	srv := httptest.NewUnstartedServer(proxy)
	srv.StartTLS()
	defer srv.Close()

	_, _, err = MakeRequest(srv.URL, Opts{})
	c.Assert(err, IsNil)
	c.Assert(called, Equals, true)
}

示例#28
文件: jsonrpc.go 项目: donh/query

// Initialize mock JSONRPC server for NQM log
// You may use "test.mockrpc.port" to customize port of HTTP for it
func StartMockJsonRpcServer(c *C, jsonrpcServiceSetupFunc func(*rpc.Server)) {
	if testHttpServer != nil {
		return
	}

	flag.Parse()

	jsonrpcService := rpc.NewServer()
	jsonrpcService.RegisterCodec(json2.NewCodec(), "application/json")
	jsonrpcServiceSetupFunc(jsonrpcService)

	/**
	 * Set-up HTTP server for testing
	 */
	testHttpServer = httptest.NewUnstartedServer(jsonrpcService)
	listener, err := net.Listen("tcp", "127.0.0.1:"+*mockRpcPort)
	if err != nil {
		panic(err)
	}
	testHttpServer.Listener = listener
	testHttpServer.Start()
	// :~)

	rpcServiceCaller = jsonrpc.NewService(testHttpServer.URL)

	c.Logf("Test HTTP Server: \"%v\"", testHttpServer.URL)
}

示例#29
文件: mux_test.go 项目: vnadgir-ef/vulcand

func (s *ServerSuite) TestBackendHTTPS(c *C) {
	e := httptest.NewUnstartedServer(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("hi https"))
		}))
	e.StartTLS()
	defer e.Close()

	b := MakeBatch(Batch{
		Addr:  "localhost:41000",
		Route: `Path("/")`,
		URL:   e.URL,
	})

	c.Assert(s.mux.UpsertHost(b.H), IsNil)
	c.Assert(s.mux.UpsertServer(b.BK, b.S), IsNil)
	c.Assert(s.mux.UpsertFrontend(b.F), IsNil)
	c.Assert(s.mux.UpsertListener(b.L), IsNil)

	c.Assert(s.mux.Start(), IsNil)

	re, _, err := testutils.Get(b.FrontendURL("/"))
	c.Assert(err, IsNil)
	c.Assert(re.StatusCode, Equals, 500) // failed because of bad cert

	b.B.Settings = engine.HTTPBackendSettings{TLS: &engine.TLSSettings{InsecureSkipVerify: true}}
	c.Assert(s.mux.UpsertBackend(b.B), IsNil)

	re, body, err := testutils.Get(b.FrontendURL("/"))
	c.Assert(err, IsNil)
	c.Assert(re.StatusCode, Equals, 200)
	c.Assert(string(body), Equals, "hi https")
}

示例#30
文件: oidc_test.go 项目: jwforres/origin

func TestOIDCDiscoveryNoKeyEndpoint(t *testing.T) {
	var err error
	expectErr := fmt.Errorf("OIDC provider must provide 'jwks_uri' for public key discovery")

	cert := path.Join(os.TempDir(), "oidc-cert")
	key := path.Join(os.TempDir(), "oidc-key")

	defer os.Remove(cert)
	defer os.Remove(key)

	generateSelfSignedCert(t, "127.0.0.1", cert, key)

	op := newOIDCProvider(t)
	srv := httptest.NewUnstartedServer(op.mux)
	srv.TLS = &tls.Config{Certificates: make([]tls.Certificate, 1)}
	srv.TLS.Certificates[0], err = tls.LoadX509KeyPair(cert, key)
	if err != nil {
		t.Fatalf("Cannot load cert/key pair: %v", err)
	}
	srv.StartTLS()
	// TODO: Uncomment when fix #19254
	// defer srv.Close()

	op.pcfg = oidc.ProviderConfig{
		Issuer: srv.URL,
	}

	_, err = New(srv.URL, "client-foo", cert, "sub", "")
	if !reflect.DeepEqual(err, expectErr) {
		t.Errorf("Expecting %v, but got %v", expectErr, err)
	}
}

展开阅读全文