当前位置: 首页>>代码示例>>Golang>>正文


Golang httptest.NewUnstartedServer函数代码示例

本文整理汇总了Golang中net/http/httptest.NewUnstartedServer函数的典型用法代码示例。如果您正苦于以下问题:Golang NewUnstartedServer函数的具体用法?Golang NewUnstartedServer怎么用?Golang NewUnstartedServer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewUnstartedServer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestIsInternetAccessibleBothBad

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.")
	}
}
开发者ID:turnkey-commerce,项目名称:go-ping-sites,代码行数:13,代码来源:pinger_internals_test.go

示例2: NewCloudController

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
}
开发者ID:dieucao,项目名称:notifications,代码行数:33,代码来源:cloud_controller.go

示例3: newClientServerTest

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
}
开发者ID:Mahdi89,项目名称:riscv-go,代码行数:25,代码来源:clientserver_test.go

示例4: startServer

// 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
}
开发者ID:18F,项目名称:cg-dashboard,代码行数:29,代码来源:cf_console_suite_test.go

示例5: TestNewHTTPClientCert

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)
	}
}
开发者ID:prometheus,项目名称:prometheus,代码行数:33,代码来源:target_test.go

示例6: Start

// 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)
}
开发者ID:mikepea,项目名称:cdn-acceptance-tests,代码行数:32,代码来源:helpers.go

示例7: TestReadTimeout

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)
}
开发者ID:WIZARD-CXY,项目名称:golang-devops-stuff,代码行数:25,代码来源:proxy_test.go

示例8: newUnstartedTestServer

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
}
开发者ID:vmware,项目名称:photon-controller-go-sdk,代码行数:31,代码来源:httpserver.go

示例9: TestAuthCode

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)
	}
}
开发者ID:lmineiro,项目名称:hydra,代码行数:35,代码来源:handler_test.go

示例10: TestV2NoRetryNoLeader

// 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)
		}
	}
}
开发者ID:ringtail,项目名称:etcd,代码行数:26,代码来源:client_test.go

示例11: TestForwardedProto

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)
}
开发者ID:martensson,项目名称:oxy,代码行数:29,代码来源:fwd_test.go

示例12: SetupTestServer

// 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
}
开发者ID:4578395263256,项目名称:godropbox,代码行数:35,代码来源:test_utils.go

示例13: newClientServerTest

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
}
开发者ID:kuangchanglang,项目名称:go,代码行数:35,代码来源:clientserver_test.go

示例14: NewMockServer

// 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
}
开发者ID:MohamedBassem,项目名称:Smock,代码行数:27,代码来源:smock.go

示例15: TestRedirectSignUpWithVhosts

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)
}
开发者ID:csarven,项目名称:gold,代码行数:33,代码来源:server_test.go


注:本文中的net/http/httptest.NewUnstartedServer函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。