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


Golang httptest.NewServer函数代码示例

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


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

示例1: TestProxyUpgrade

func TestProxyUpgrade(t *testing.T) {
	backendServer := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
		defer ws.Close()
		body := make([]byte, 5)
		ws.Read(body)
		ws.Write([]byte("hello " + string(body)))
	}))
	defer backendServer.Close()

	serverURL, _ := url.Parse(backendServer.URL)
	proxyHandler := &UpgradeAwareProxyHandler{
		Location: serverURL,
	}
	proxy := httptest.NewServer(proxyHandler)
	defer proxy.Close()

	ws, err := websocket.Dial("ws://"+proxy.Listener.Addr().String()+"/some/path", "", "http://127.0.0.1/")
	if err != nil {
		t.Fatalf("websocket dial err: %s", err)
	}
	defer ws.Close()

	if _, err := ws.Write([]byte("world")); err != nil {
		t.Fatalf("write err: %s", err)
	}

	response := make([]byte, 20)
	n, err := ws.Read(response)
	if err != nil {
		t.Fatalf("read err: %s", err)
	}
	if e, a := "hello world", string(response[0:n]); e != a {
		t.Fatalf("expected '%#v', got '%#v'", e, a)
	}
}
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:35,代码来源:proxy_test.go

示例2: TestServerHappyPathSingleServer

func TestServerHappyPathSingleServer(t *testing.T) {
	originServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("hey"))
	}))
	defer originServer.Close()
	originURL, _ := url.Parse(originServer.URL)

	handler := httptransport.NewServer(
		context.Background(),
		originURL,
	)
	proxyServer := httptest.NewServer(handler)
	defer proxyServer.Close()

	resp, _ := http.Get(proxyServer.URL)
	if want, have := http.StatusOK, resp.StatusCode; want != have {
		t.Errorf("want %d, have %d", want, have)
	}

	responseBody, _ := ioutil.ReadAll(resp.Body)
	if want, have := "hey", string(responseBody); want != have {
		t.Errorf("want %q, have %q", want, have)
	}
}
开发者ID:basvanbeek,项目名称:kit,代码行数:25,代码来源:server_test.go

示例3: TestCotacao

func TestCotacao(t *testing.T) {

	Convey("Ao executar o comando cotação", t, func() {
		cmd := &bot.Cmd{}

		Convey("Deve responder com a cotação do dólar e euro", func() {
			ts := httptest.NewServer(
				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					fmt.Fprintln(w, expectedJSON)
				}))
			defer ts.Close()

			url = ts.URL

			c, err := cotacao(cmd)

			So(err, ShouldBeNil)
			So(c, ShouldEqual, "Dólar: 2.2430 (+0.36), Euro: 2.9018 (-1.21)")
		})

		Convey("Quando o webservice retornar algo inválido deve retornar erro", func() {
			ts := httptest.NewServer(
				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					fmt.Fprintln(w, "invalid")
				}))
			defer ts.Close()

			url = ts.URL

			_, err := cotacao(cmd)

			So(err, ShouldNotBeNil)
		})
	})
}
开发者ID:imtranQ,项目名称:BjornBot,代码行数:35,代码来源:cotacao_test.go

示例4: NewSignatureTest

func NewSignatureTest() *SignatureTest {
	opts := NewOptions()
	opts.CookieSecret = "cookie secret"
	opts.ClientID = "client ID"
	opts.ClientSecret = "client secret"
	opts.EmailDomains = []string{"acm.org"}

	authenticator := &SignatureAuthenticator{}
	upstream := httptest.NewServer(
		http.HandlerFunc(authenticator.Authenticate))
	upstream_url, _ := url.Parse(upstream.URL)
	opts.Upstreams = append(opts.Upstreams, upstream.URL)

	providerHandler := func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"access_token": "my_auth_token"}`))
	}
	provider := httptest.NewServer(http.HandlerFunc(providerHandler))
	provider_url, _ := url.Parse(provider.URL)
	opts.provider = NewTestProvider(provider_url, "[email protected]")

	return &SignatureTest{
		opts,
		upstream,
		upstream_url.Host,
		provider,
		make(http.Header),
		httptest.NewRecorder(),
		authenticator,
	}
}
开发者ID:coreos,项目名称:oauth2_proxy,代码行数:30,代码来源:oauthproxy_test.go

示例5: TestTransportCircuitOpenWith5PercentError

func TestTransportCircuitOpenWith5PercentError(t *testing.T) {
	pass := httptest.NewServer(code(200))
	defer pass.Close()

	fail := httptest.NewServer(code(500))
	defer fail.Close()

	c := http.Client{
		Transport: Transport(NewBreaker(0.05), DefaultResponseValidator, http.DefaultTransport),
	}

	var lastError error
	for i := 1; i <= 100; i++ {
		url := pass.URL

		if i >= 95 {
			url = fail.URL
		}

		_, lastError = c.Get(url)
	}

	if lastError == nil {
		t.Fatalf("expected %q after 5%% error rate, got no error", ErrCircuitOpen)
	}

	urlError, ok := lastError.(*url.Error)
	if !ok {
		t.Fatalf("expected url.Error after 5%% error rate, got %s", reflect.TypeOf(lastError))
	}

	if err := urlError.Err; err != ErrCircuitOpen {
		t.Fatalf("expected %q after 5%% error rate, got %q", ErrCircuitOpen, err)
	}
}
开发者ID:nickstenning,项目名称:roshi,代码行数:35,代码来源:transport_test.go

示例6: TestCustomPrefix

func TestCustomPrefix(t *testing.T) {
	Convey("Given the App running with PREFIX", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		f := Flag
		f.Prefix = "BETA"
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", f)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting a message", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte(""))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldContainSubstring, "\"__prefix\":\"BETA\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

	})

	Convey("Given the App running WITHOUT prefix", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		f := Flag
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", f)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting a message", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte(""))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldNotContainSubstring, "\"__prefix\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

	})
}
开发者ID:KSCTECHNOLOGIES,项目名称:uberlog-proxy,代码行数:60,代码来源:http_api_test.go

示例7: TestRedirectPolicyFunc

// TODO: more tests on redirect
func TestRedirectPolicyFunc(t *testing.T) {
	redirectSuccess := false
	redirectFuncGetCalled := false
	tsRedirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		redirectSuccess = true
	}))
	defer tsRedirect.Close()
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, tsRedirect.URL, http.StatusMovedPermanently)
	}))
	defer ts.Close()

	New().
		Get(ts.URL).
		RedirectPolicy(func(req Request, via []Request) error {
			redirectFuncGetCalled = true
			return nil
		}).End()
	if !redirectSuccess {
		t.Errorf("Expected reaching another redirect url not original one")
	}
	if !redirectFuncGetCalled {
		t.Errorf("Expected redirect policy func to get called")
	}
}
开发者ID:smallnest,项目名称:goreq,代码行数:26,代码来源:goreq_test.go

示例8: TestPrintKubernetesVersions

func TestPrintKubernetesVersions(t *testing.T) {
	// test that no kubernetes version text is printed if there are no versions being served
	// TODO(aprindle) or should this be an error?!?!
	handlerNone := &URLHandlerNone{}
	server := httptest.NewServer(handlerNone)

	var outputBuffer bytes.Buffer
	PrintKubernetesVersions(&outputBuffer, server.URL)
	if len(outputBuffer.String()) != 0 {
		t.Fatalf("Expected PrintKubernetesVersions to not output text as there are no versioned served at the current URL but output was [%s]", outputBuffer.String())
	}

	// test that update text is printed if the latest version is greater than the current version
	// k8sVersionsFromURL = "100.0.0-dev"
	version0 := "0.0.0"
	version1 := "1.0.0"
	handlerCorrect := &URLHandlerCorrect{
		K8sReleases: []k8sRelease{{Version: version0}, {Version: version1}},
	}
	server = httptest.NewServer(handlerCorrect)

	PrintKubernetesVersions(&outputBuffer, server.URL)
	if len(outputBuffer.String()) == 0 {
		t.Fatalf("Expected PrintKubernetesVersion to output text as %d versions were served from URL but output was [%s]",
			2, outputBuffer.String()) //TODO(aprindle) change the 2
	}
}
开发者ID:gashcrumb,项目名称:gofabric8,代码行数:27,代码来源:kubernetes_versions_test.go

示例9: TestUpdateClusterStatusOK

func TestUpdateClusterStatusOK(t *testing.T) {
	clusterName := "foobarCluster"
	// create dummy httpserver
	testClusterServer := httptest.NewServer(createHttptestFakeHandlerForCluster(true))
	defer testClusterServer.Close()
	federationCluster := newCluster(clusterName, testClusterServer.URL)
	federationClusterList := newClusterList(federationCluster)

	testFederationServer := httptest.NewServer(createHttptestFakeHandlerForFederation(federationClusterList, true))
	defer testFederationServer.Close()

	restClientCfg, err := clientcmd.BuildConfigFromFlags(testFederationServer.URL, "")
	if err != nil {
		t.Errorf("Failed to build client config")
	}
	federationClientSet := federationclientset.NewForConfigOrDie(restclient.AddUserAgent(restClientCfg, "cluster-controller"))

	manager := NewclusterController(federationClientSet, 5)
	err = manager.UpdateClusterStatus()
	if err != nil {
		t.Errorf("Failed to Update Cluster Status: %v", err)
	}
	clusterStatus, found := manager.clusterClusterStatusMap[clusterName]
	if !found {
		t.Errorf("Failed to Update Cluster Status")
	} else {
		if (clusterStatus.Conditions[1].Status != v1.ConditionFalse) || (clusterStatus.Conditions[1].Type != federation_v1alpha1.ClusterOffline) {
			t.Errorf("Failed to Update Cluster Status")
		}
	}
}
开发者ID:odacremolbap,项目名称:kubernetes,代码行数:31,代码来源:clustercontroller_test.go

示例10: TestServerOriginServerUnreachable

func TestServerOriginServerUnreachable(t *testing.T) {
	// create a server, then promptly shut it down
	originServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	originURL, _ := url.Parse(originServer.URL)
	originServer.Close()

	handler := httptransport.NewServer(
		context.Background(),
		originURL,
	)
	proxyServer := httptest.NewServer(handler)
	defer proxyServer.Close()

	resp, _ := http.Get(proxyServer.URL)
	switch resp.StatusCode {
	case http.StatusBadGateway: // go1.7 and beyond
		break
	case http.StatusInternalServerError: // to go1.7
		break
	default:
		t.Errorf("want %d or %d, have %d", http.StatusBadGateway, http.StatusInternalServerError, resp.StatusCode)
	}
}
开发者ID:basvanbeek,项目名称:kit,代码行数:25,代码来源:server_test.go

示例11: TestInspectContainerNoSuchContainer

func TestInspectContainerNoSuchContainer(t *testing.T) {
	server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "No such container", http.StatusNotFound)
	}))
	defer server1.Close()
	server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "No such container", http.StatusNotFound)
	}))
	defer server2.Close()
	cluster, err := New(nil,
		Node{ID: "handler0", Address: server1.URL},
		Node{ID: "handler1", Address: server2.URL},
	)
	if err != nil {
		t.Fatal(err)
	}
	id := "e90302"
	container, err := cluster.InspectContainer(id)
	if container != nil {
		t.Errorf("InspectContainer(%q): Expected <nil> container, got %#v.", id, container)
	}
	expected := &dclient.NoSuchContainer{ID: id}
	if !reflect.DeepEqual(err, expected) {
		t.Errorf("InspectContainer(%q): Wrong error. Want %#v. Got %#v.", id, expected, err)
	}
}
开发者ID:rainsongsky,项目名称:docker-cluster,代码行数:26,代码来源:container_test.go

示例12: TestEncodedSlashes

func TestEncodedSlashes(t *testing.T) {
	var seen string
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		seen = r.RequestURI
	}))
	defer backend.Close()

	b, _ := url.Parse(backend.URL)
	proxyHandler := NewReverseProxy(b)
	setProxyDirector(proxyHandler)
	frontend := httptest.NewServer(proxyHandler)
	defer frontend.Close()

	f, _ := url.Parse(frontend.URL)
	encodedPath := "/a%2Fb/?c=1"
	getReq := &http.Request{URL: &url.URL{Scheme: "http", Host: f.Host, Opaque: encodedPath}}
	_, err := http.DefaultClient.Do(getReq)
	if err != nil {
		t.Fatalf("err %s", err)
	}
	if seen != encodedPath {
		t.Errorf("got bad request %q expected %q", seen, encodedPath)
	}
}
开发者ID:nginx-modules,项目名称:oauth2_proxy,代码行数:25,代码来源:oauthproxy_test.go

示例13: TestRedirectOnMissingTrailingSlash

func TestRedirectOnMissingTrailingSlash(t *testing.T) {
	table := []struct {
		// The requested path
		path string
		// The path requested on the proxy server.
		proxyServerPath string
		// query string
		query string
	}{
		{"/trailing/slash/", "/trailing/slash/", ""},
		{"/", "/", "test1=value1&test2=value2"},
		// "/" should be added at the end.
		{"", "/", "test1=value1&test2=value2"},
		// "/" should not be added at a non-root path.
		{"/some/path", "/some/path", ""},
	}

	for _, item := range table {
		proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			if req.URL.Path != item.proxyServerPath {
				t.Errorf("Unexpected request on path: %s, expected path: %s, item: %v", req.URL.Path, item.proxyServerPath, item)
			}
			if req.URL.RawQuery != item.query {
				t.Errorf("Unexpected query on url: %s, expected: %s", req.URL.RawQuery, item.query)
			}
		}))
		defer proxyServer.Close()

		serverURL, _ := url.Parse(proxyServer.URL)
		simpleStorage := &SimpleRESTStorage{
			errors:                    map[string]error{},
			resourceLocation:          serverURL,
			expectedResourceNamespace: "ns",
		}

		handler := handleNamespaced(map[string]rest.Storage{"foo": simpleStorage})
		server := httptest.NewServer(handler)
		defer server.Close()

		proxyTestPattern := "/api/version2/proxy/namespaces/ns/foo/id" + item.path
		req, err := http.NewRequest(
			"GET",
			server.URL+proxyTestPattern+"?"+item.query,
			strings.NewReader(""),
		)
		if err != nil {
			t.Errorf("unexpected error %v", err)
			continue
		}
		// Note: We are using a default client here, that follows redirects.
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			t.Errorf("unexpected error %v", err)
			continue
		}
		if resp.StatusCode != http.StatusOK {
			t.Errorf("Unexpected errorCode: %v, expected: 200. Response: %v, item: %v", resp.StatusCode, resp, item)
		}
	}
}
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:60,代码来源:proxy_test.go

示例14: TestReverseProxyQuery

func TestReverseProxyQuery(t *testing.T) {
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Got-Query", r.URL.RawQuery)
		w.Write([]byte("hi"))
	}))
	defer backend.Close()

	for i, tt := range proxyQueryTests {
		backendURL, err := url.Parse(backend.URL + tt.baseSuffix)
		if err != nil {
			t.Fatal(err)
		}
		frontend := httptest.NewServer(NewSingleHostReverseProxy(backendURL))
		req, _ := http.NewRequest("GET", frontend.URL+tt.reqSuffix, nil)
		req.Close = true
		res, err := http.DefaultClient.Do(req)
		if err != nil {
			t.Fatalf("%d. Get: %v", i, err)
		}
		if g, e := res.Header.Get("X-Got-Query"), tt.want; g != e {
			t.Errorf("%d. got query %q; expected %q", i, g, e)
		}
		res.Body.Close()
		frontend.Close()
	}
}
开发者ID:gmwu,项目名称:go,代码行数:26,代码来源:reverseproxy_test.go

示例15: TestNilBody

// Issue 12344
func TestNilBody(t *testing.T) {
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hi"))
	}))
	defer backend.Close()

	frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		backURL, _ := url.Parse(backend.URL)
		rp := NewSingleHostReverseProxy(backURL)
		r := req(t, "GET / HTTP/1.0\r\n\r\n")
		r.Body = nil // this accidentally worked in Go 1.4 and below, so keep it working
		rp.ServeHTTP(w, r)
	}))
	defer frontend.Close()

	res, err := http.Get(frontend.URL)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	slurp, err := ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatal(err)
	}
	if string(slurp) != "hi" {
		t.Errorf("Got %q; want %q", slurp, "hi")
	}
}
开发者ID:gmwu,项目名称:go,代码行数:29,代码来源:reverseproxy_test.go


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