本文整理汇总了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")
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
示例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
}
示例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)
}
}
示例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, "")
}
示例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")
}
}
示例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
}
示例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()
}
}
示例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()
}
}
}
示例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))
}
}
示例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)
}
}