當前位置: 首頁>>代碼示例>>Golang>>正文


Golang httptest.NewTLSServer函數代碼示例

本文整理匯總了Golang中net/http/httptest.NewTLSServer函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewTLSServer函數的具體用法?Golang NewTLSServer怎麽用?Golang NewTLSServer使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewTLSServer函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestRefreshingTheToken

func TestRefreshingTheToken(t *testing.T) {
	ccServer := httptest.NewTLSServer(http.HandlerFunc(refreshTokenApiEndpoint))
	defer ccServer.Close()

	authServer := httptest.NewTLSServer(http.HandlerFunc(refreshTokenAuthEndpoint))
	defer authServer.Close()

	configRepo := testhelpers.FakeConfigRepository{}
	configRepo.Delete()
	config, err := configRepo.Get()
	assert.NoError(t, err)

	config.AuthorizationEndpoint = authServer.URL
	config.Target = ccServer.URL
	config.AccessToken = "bearer initial-access-token"
	config.RefreshToken = "initial-refresh-token"

	auth := NewUAAAuthenticator(configRepo)
	client := NewApiClient(auth)

	request, err := NewRequest("GET", config.Target+"/v2/foo", config.AccessToken, nil)
	assert.NoError(t, err)
	_, err = client.PerformRequest(request)
	assert.NoError(t, err)

	savedConfig := testhelpers.SavedConfiguration
	assert.Equal(t, savedConfig.AccessToken, "bearer new-access-token")
	assert.Equal(t, savedConfig.RefreshToken, "new-refresh-token")
}
開發者ID:KaiYoung,項目名稱:cli,代碼行數:29,代碼來源:client_test.go

示例2: TestTailsLogsFor

func TestTailsLogsFor(t *testing.T) {
	expectedMessage := messagetesthelpers.MarshalledLogMessage(t, "My message", "my-app-id")

	websocketEndpoint := func(conn *websocket.Conn) {
		conn.Write(expectedMessage)
		conn.Close()
	}

	websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint))
	defer websocketServer.Close()

	var redirectEndpoint = func(writer http.ResponseWriter, request *http.Request) {
		assert.Equal(t, request.URL.Path, "/tail/")
		assert.Equal(t, request.URL.RawQuery, "app=my-app-guid")
		assert.Equal(t, request.Method, "GET")
		assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token")

		writer.Header().Set("Location", strings.Replace(websocketServer.URL, "https", "wss", 1))
		writer.WriteHeader(http.StatusFound)
	}

	http.HandleFunc("/", redirectEndpoint)

	go http.ListenAndServe(":"+LOGGREGATOR_REDIRECTOR_PORT, nil)

	redirectServer := httptest.NewTLSServer(http.HandlerFunc(redirectEndpoint))
	defer redirectServer.Close()

	gateway := net.NewCloudControllerGateway(&testhelpers.FakeAuthenticator{})
	app := cf.Application{Name: "my-app", Guid: "my-app-guid"}
	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "http://localhost"}

	loggregatorHostResolver := func(hostname string) string { return hostname }
	logsRepo := NewLoggregatorLogsRepository(config, gateway, loggregatorHostResolver)

	connected := false

	onConnect := func() {
		connected = true
	}

	tailedMessages := []*logmessage.LogMessage{}

	onMessage := func(message *logmessage.LogMessage) {
		tailedMessages = append(tailedMessages, message)
	}

	logsRepo.TailLogsFor(app, onConnect, onMessage)

	assert.Equal(t, len(tailedMessages), 1)
	actualMessage, err := proto.Marshal(tailedMessages[0])
	assert.NoError(t, err)
	assert.Equal(t, actualMessage, expectedMessage)

	assert.True(t, connected)
}
開發者ID:jbayer,項目名稱:cli,代碼行數:56,代碼來源:logs_test.go

示例3: TestRefreshingTheTokenWithCloudControllerRequest

func TestRefreshingTheTokenWithCloudControllerRequest(t *testing.T) {
	ccServer := httptest.NewTLSServer(http.HandlerFunc(refreshTokenCloudControllerApiEndpoint))
	defer ccServer.Close()

	authServer := httptest.NewTLSServer(http.HandlerFunc(refreshTokenAuthEndpoint))
	defer authServer.Close()

	configRepo, auth := createAuthenticator(t, ccServer, authServer)

	gateway := NewCloudControllerGateway(auth)

	testRefreshToken(t, configRepo, gateway)
}
開發者ID:jbayer,項目名稱:cli,代碼行數:13,代碼來源:gateway_test.go

示例4: TestRefreshingTheTokenWithUAARequest

func TestRefreshingTheTokenWithUAARequest(t *testing.T) {
	uaaServer := httptest.NewTLSServer(http.HandlerFunc(refreshTokenUAAApiEndpoint))
	defer uaaServer.Close()

	authServer := httptest.NewTLSServer(http.HandlerFunc(refreshTokenAuthEndpoint))
	defer authServer.Close()

	configRepo, auth := createAuthenticator(t, uaaServer, authServer)

	gateway := NewUAAGateway(auth)

	testRefreshToken(t, configRepo, gateway)
}
開發者ID:jbayer,項目名稱:cli,代碼行數:13,代碼來源:gateway_test.go

示例5: TestListFiles

func TestListFiles(t *testing.T) {
	expectedResponse := "file 1\n file 2\n file 3"

	listFilesEndpoint := func(writer http.ResponseWriter, request *http.Request) {
		methodMatches := request.Method == "GET"
		pathMatches := request.URL.Path == "/some/path"

		if !methodMatches || !pathMatches {
			fmt.Printf("One of the matchers did not match. Method [%t] Path [%t]",
				methodMatches, pathMatches)

			writer.WriteHeader(http.StatusInternalServerError)
			return
		}

		writer.WriteHeader(http.StatusOK)
		fmt.Fprint(writer, expectedResponse)
	}

	listFilesServer := httptest.NewTLSServer(http.HandlerFunc(listFilesEndpoint))
	defer listFilesServer.Close()

	listFilesRedirectEndpoint := func(writer http.ResponseWriter, req *http.Request) {
		baseEndpoint := testhelpers.CreateEndpoint(
			"GET",
			"/v2/apps/my-app-guid/instances/0/files/some/path",
			nil,
			testhelpers.TestResponse{Status: http.StatusTemporaryRedirect},
		)

		writer.Header().Add("Location", fmt.Sprintf("%s/some/path", listFilesServer.URL))
		baseEndpoint(writer, req)
	}

	listFilesRedirectServer := httptest.NewTLSServer(http.HandlerFunc(listFilesRedirectEndpoint))
	defer listFilesRedirectServer.Close()

	config := &configuration.Configuration{
		Target:      listFilesRedirectServer.URL,
		AccessToken: "BEARER my_access_token",
	}

	gateway := net.NewCloudControllerGateway(&testhelpers.FakeAuthenticator{})
	repo := NewCloudControllerAppFilesRepository(config, gateway)

	list, err := repo.ListFiles(cf.Application{Guid: "my-app-guid"}, "some/path")

	assert.NoError(t, err)
	assert.Equal(t, list, expectedResponse)
}
開發者ID:jbayer,項目名稱:cli,代碼行數:50,代碼來源:app_files_test.go

示例6: BenchmarkHTTPOutput

func BenchmarkHTTPOutput(b *testing.B) {
	wg := new(sync.WaitGroup)
	quit := make(chan int)

	server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(50 * time.Millisecond)
		wg.Done()
	}))
	defer server.Close()

	input := NewTestInput()
	output := NewHTTPOutput(server.URL, &HTTPOutputConfig{})

	Plugins.Inputs = []io.Reader{input}
	Plugins.Outputs = []io.Writer{output}

	go Start(quit)

	for i := 0; i < b.N; i++ {
		wg.Add(1)
		input.EmitPOST()
	}

	wg.Wait()

	close(quit)
}
開發者ID:npk,項目名稱:gor,代碼行數:27,代碼來源:output_http_test.go

示例7: Server

func Server(t *testing.T, stubs ...Http) *httptest.Server {
	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		found := false

		for _, stub := range stubs {
			if stub.Method == r.Method && stub.Path == r.URL.Path {
				data, err := json.Marshal(stub.Response)

				if err != nil {
					w.WriteHeader(503)
					w.Write(serverError(err.Error()))
				}

				w.WriteHeader(stub.Code)
				w.Write(data)

				found = true
				break
			}
		}

		if !found {
			fmt.Fprintf(os.Stderr, "Missing HTTP stub:\n")
			fmt.Fprintf(os.Stderr, "  %s %s\n", r.Method, r.URL.Path)
			t.Fail()

			w.WriteHeader(404)
			w.Write(serverError("stub not found"))
		}
	}))

	return ts
}
開發者ID:jbuck,項目名稱:rack,代碼行數:33,代碼來源:server.go

示例8: TestSyncEndpointsItems

func TestSyncEndpointsItems(t *testing.T) {
	body, _ := json.Marshal(newPodList(1))
	fakeHandler := util.FakeHandler{
		StatusCode:   200,
		ResponseBody: string(body),
	}
	testServer := httptest.NewTLSServer(&fakeHandler)
	client := client.NewOrDie(testServer.URL, nil)
	serviceRegistry := registrytest.ServiceRegistry{
		List: api.ServiceList{
			Items: []api.Service{
				{
					Selector: map[string]string{
						"foo": "bar",
					},
				},
			},
		},
	}
	endpoints := NewEndpointController(&serviceRegistry, client)
	if err := endpoints.SyncServiceEndpoints(); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if len(serviceRegistry.Endpoints.Endpoints) != 1 {
		t.Errorf("Unexpected endpoints update: %#v", serviceRegistry.Endpoints)
	}
}
開發者ID:jhuamonte,項目名稱:kubernetes,代碼行數:27,代碼來源:endpoints_controller_test.go

示例9: TestAppsCreate

func TestAppsCreate(t *testing.T) {
	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/apps":
			_ = App{Name: r.FormValue("name")}
			http.Error(w, "ok", 302)

		case "/apps/foobar":
			app := App{Name: "foobar"}
			data, _ := json.Marshal(app)
			_, _ = w.Write(data)

		case "/apps/foobar/status":
			w.Write([]byte("running"))
		}
	}))
	defer ts.Close()

	setLoginEnv(ts)

	stdout, stderr := appRun([]string{"convox", "apps", "create", "foobar"})

	expect(t, stdout, "Creating app foobar... OK\n")
	expect(t, stderr, "")
}
開發者ID:2opremio,項目名稱:cli,代碼行數:25,代碼來源:apps_test.go

示例10: TestClientWithIncorrectTLSServerName

func TestClientWithIncorrectTLSServerName(t *testing.T) {
	defer afterTest(t)
	ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
	defer ts.Close()
	errc := make(chanWriter, 10) // but only expecting 1
	ts.Config.ErrorLog = log.New(errc, "", 0)

	trans := newTLSTransport(t, ts)
	trans.TLSClientConfig.ServerName = "badserver"
	c := &Client{Transport: trans}
	_, err := c.Get(ts.URL)
	if err == nil {
		t.Fatalf("expected an error")
	}
	if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
		t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
	}
	select {
	case v := <-errc:
		if !strings.Contains(v, "TLS handshake error") {
			t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
		}
	case <-time.After(5 * time.Second):
		t.Errorf("timeout waiting for logged error")
	}
}
開發者ID:arnold8,項目名稱:go,代碼行數:26,代碼來源:client_test.go

示例11: TestV2Check

func TestV2Check(t *testing.T) {
	called := make(chan struct{}, 2)
	var uri *url.URL
	server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		called <- struct{}{}
		if strings.HasSuffix(r.URL.Path, "/v2/") {
			w.WriteHeader(http.StatusOK)
			return
		}
		if strings.HasSuffix(r.URL.Path, "/tags/list") {
			w.WriteHeader(http.StatusOK)
			fmt.Fprintln(w, `{"tags":["tag1","image1"]}`)
			return
		}
		t.Fatalf("unexpected request: %s %s", r.Method, r.URL.RequestURI())
	}))
	uri, _ = url.Parse(server.URL)
	conn, err := NewClient().Connect(uri.Host, true)
	if err != nil {
		t.Fatal(err)
	}
	tags, err := conn.ImageTags("foo", "bar")
	if err != nil {
		t.Fatal(err)
	}
	if tags["tag1"] != "tag1" {
		t.Errorf("unexpected tags: %#v", tags)
	}
	if tags["image1"] != "image1" {
		t.Errorf("unexpected tags: %#v", tags)
	}

	<-called
	<-called
}
開發者ID:nitintutlani,項目名稱:origin,代碼行數:35,代碼來源:client_test.go

示例12: TestDeleteScanHistory

func TestDeleteScanHistory(t *testing.T) {
	testServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		response := `{"token":"Example"}` // Example for CreateSession, this method does not return a result
		fmt.Fprintln(w, response)
	}))
	defer testServer.Close()

	transport := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	httpClient := &http.Client{Transport: transport}

	port := strings.Split(testServer.URL, ":")[2]

	client := &Client{
		username: "testU",
		password: "testP",
		ip:       "127.0.0.1",
		port:     port,
	}

	client, err := client.CreateSession(httpClient)
	if err != nil {
		t.FailNow()
	}

	successfullyDeletedHistory, err := client.DeleteScanHistory(httpClient, 36, 1)
	if err != nil || successfullyDeletedHistory != true {
		t.FailNow()
	}
}
開發者ID:kkirsche,項目名稱:nessusControl,代碼行數:33,代碼來源:apiScans_test.go

示例13: TestClientInsecureTransport

func TestClientInsecureTransport(t *testing.T) {
	defer afterTest(t)
	ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
		w.Write([]byte("Hello"))
	}))
	defer ts.Close()

	// TODO(bradfitz): add tests for skipping hostname checks too?
	// would require a new cert for testing, and probably
	// redundant with these tests.
	for _, insecure := range []bool{true, false} {
		tr := &Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: insecure,
			},
		}
		defer tr.CloseIdleConnections()
		c := &Client{Transport: tr}
		res, err := c.Get(ts.URL)
		if (err == nil) != insecure {
			t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
		}
		if res != nil {
			res.Body.Close()
		}
	}
}
開發者ID:kostyll,項目名稱:gccpy,代碼行數:27,代碼來源:client_test.go

示例14: TestBasicConnectAuthWithCurl

func TestBasicConnectAuthWithCurl(t *testing.T) {
	expected := ":c>"
	background := httptest.NewTLSServer(ConstantHanlder(expected))
	defer background.Close()
	proxy := gopensslproxy.NewProxyHttpServer()
	proxy.OnRequest().HandleConnect(auth.BasicConnect("my_realm", func(user, passwd string) bool {
		return user == "user" && passwd == "open sesame"
	}))
	_, proxyserver := oneShotProxy(proxy)
	defer proxyserver.Close()

	cmd := exec.Command("curl",
		"--silent", "--show-error", "--insecure",
		"-x", proxyserver.URL,
		"-U", "user:open sesame",
		"-p",
		"--url", background.URL+"/[1-3]",
	)
	out, err := cmd.CombinedOutput() // if curl got error, it'll show up in stderr
	if err != nil {
		t.Fatal(err, string(out))
	}
	finalexpected := times(3, expected)
	if string(out) != finalexpected {
		t.Error("Expected", finalexpected, "got", string(out))
	}
}
開發者ID:g3rk6,項目名稱:gopensslproxy,代碼行數:27,代碼來源:basic_test.go

示例15: TestCheck

// Test a successful Check request / response.
func TestCheck(t *testing.T) {
	ts := httptest.NewTLSServer(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprintln(w, `
            {
              "stat": "OK",
              "response": {
                "time": 1357020061
              }
            }`)
			}))
	defer ts.Close()

	duo := buildAuthApi(ts.URL)

	result, err := duo.Check()
	if err != nil {
		t.Error("Failed TestCheck: " + err.Error())
	}
	if result.Stat != "OK" {
		t.Error("Expected OK, but got " + result.Stat)
	}
	if result.Response.Time != 1357020061 {
		t.Errorf("Expected 1357020061, but got %d", result.Response.Time)
	}
}
開發者ID:kgutwin,項目名稱:vault,代碼行數:28,代碼來源:authapi_test.go


注:本文中的net/http/httptest.NewTLSServer函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。