本文整理汇总了Golang中github.com/onsi/gomega/ghttp.Server.RouteToHandler方法的典型用法代码示例。如果您正苦于以下问题:Golang Server.RouteToHandler方法的具体用法?Golang Server.RouteToHandler怎么用?Golang Server.RouteToHandler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/onsi/gomega/ghttp.Server
的用法示例。
在下文中一共展示了Server.RouteToHandler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewTestServer
func NewTestServer(server *ghttp.Server) *ghttp.Server {
sampleSuccessTokenStringFormat := `{"access_token":"%s","token_type":"bearer","refresh_token":"%s","expires_in":599,"scope":"password.write cloud_controller.write openid cloud_controller.read","jti":"%s"}`
loginTokenResponse := fmt.Sprintf(sampleSuccessTokenStringFormat, "access-token", "refresh-token", "jti")
aiBasicResponse, _ := ioutil.ReadFile("fixtures/ai_basic_response.json")
aiInfoHandler := ghttp.RespondWith(http.StatusOK, aiBasicResponse)
aiDeleteHandler := ghttp.RespondWith(http.StatusNoContent, "")
aiInfoPath, _ := regexp.Compile("/v2/apps/.*/instances")
aiDeletePath, _ := regexp.Compile("/v2/apps/.*/instances/.*")
server.RouteToHandler("GET", aiInfoPath, aiInfoHandler)
server.RouteToHandler("DELETE", aiDeletePath, aiDeleteHandler)
server.RouteToHandler("POST", "/oauth/token", ghttp.RespondWith(http.StatusOK, "{}"))
server.AppendHandlers(
ghttp.RespondWith(http.StatusOK, loginTokenResponse),
)
return server
}
示例2:
<D:collection/>
</D:resourcetype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
`
responseBodyRoot = strings.Replace(responseBodyRoot, "http://192.168.11.11:8444", fakeServer.URL(), -1)
})
It("lists objects", func() {
fakeServer.RouteToHandler("PROPFIND", "/blobs", ghttp.CombineHandlers(
ghttp.VerifyHeaderKV("Depth", "1"),
ghttp.VerifyBasicAuth("user", "pass"),
ghttp.RespondWith(207, responseBodyRoot, http.Header{"Content-Type": []string{"application/xml"}}),
))
expectedTime, err := time.Parse(time.RFC1123, "Wed, 29 Jul 2015 18:43:36 GMT")
Expect(err).NotTo(HaveOccurred())
Expect(blobStore.List()).To(ConsistOf(
blob.Blob{Path: "b-droplet.tgz", Size: 4096, Created: expectedTime},
blob.Blob{Path: "a-droplet.tgz", Size: 4096, Created: expectedTime},
blob.Blob{Path: "c-droplet.tgz", Size: 4096, Created: expectedTime},
))
Expect(fakeServer.ReceivedRequests()).To(HaveLen(1))
})
示例3:
flushEvents chan struct{}
)
var getActualLRPGroups = func() []*models.ActualLRPGroup {
actualLRPGroups, err := bbsClient.ActualLRPGroups(models.ActualLRPFilter{})
Expect(err).NotTo(HaveOccurred())
return actualLRPGroups
}
BeforeEach(func() {
Eventually(getActualLRPGroups, 5*pollingInterval).Should(BeEmpty())
flushEvents = make(chan struct{})
fakeGarden = ghttp.NewUnstartedServer()
// these tests only look for the start of a sequence of requests
fakeGarden.AllowUnhandledRequests = false
fakeGarden.RouteToHandler("GET", "/ping", ghttp.RespondWithJSONEncoded(http.StatusOK, struct{}{}))
fakeGarden.RouteToHandler("GET", "/containers", ghttp.RespondWithJSONEncoded(http.StatusOK, struct{}{}))
fakeGarden.RouteToHandler("GET", "/capacity", ghttp.RespondWithJSONEncoded(http.StatusOK,
garden.Capacity{MemoryInBytes: 1024 * 1024 * 1024, DiskInBytes: 2048 * 1024 * 1024, MaxContainers: 4}))
fakeGarden.RouteToHandler("GET", "/containers/bulk_info", ghttp.RespondWithJSONEncoded(http.StatusOK, struct{}{}))
logger = lagertest.NewTestLogger("test")
serviceClient = bbs.NewServiceClient(consulSession, clock.NewClock())
pollingInterval = 50 * time.Millisecond
evacuationTimeout = 200 * time.Millisecond
rootFSName = "the-rootfs"
rootFSPath = "/path/to/rootfs"
rootFSArg := fmt.Sprintf("%s:%s", rootFSName, rootFSPath)
示例4:
callbackURL string
taskDB *dbfakes.FakeTaskDB
statusCodes chan int
reqCount chan struct{}
task *models.Task
httpClient *http.Client
)
BeforeEach(func() {
httpClient = cf_http.NewClient()
statusCodes = make(chan int)
reqCount = make(chan struct{})
fakeServer.RouteToHandler("POST", "/the-callback/url", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(<-statusCodes)
})
callbackURL = fakeServer.URL() + "/the-callback/url"
taskDB = new(dbfakes.FakeTaskDB)
taskDB.ResolvingTaskReturns(nil)
taskDB.DeleteTaskReturns(nil)
})
simulateTaskCompleting := func(signals <-chan os.Signal, ready chan<- struct{}) error {
close(ready)
task = model_helpers.NewValidTask("the-task-guid")
task.CompletionCallbackUrl = callbackURL
taskworkpool.HandleCompletedTask(logger, httpClient, taskDB, task)
return nil
}
示例5:
Mask: net.CIDRMask(24, 32),
},
Gateway: net.ParseIP("192.168.1.1"),
Routes: []types.Route{{
Dst: net.IPNet{
IP: net.ParseIP("192.168.0.0"),
Mask: net.CIDRMask(16, 32),
},
GW: net.ParseIP("192.168.1.1"),
}},
},
}
statusCode := http.StatusCreated
server.RouteToHandler("POST", "/cni/add", ghttp.CombineHandlers(
ghttp.VerifyHeaderKV("Content-Type", "application/json"),
ghttp.RespondWithJSONEncodedPtr(&statusCode, &ipamResult),
))
})
AfterEach(func() {
server.Close()
})
Describe("ADD", func() {
It("returns IPAM data", func() {
var err error
var cmd *exec.Cmd
cmd, err = buildCNICmdLight("ADD", netConfig, containerNSPath, containerID)
Expect(err).NotTo(HaveOccurred())
session, err = gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
Expect(err).NotTo(HaveOccurred())
示例6:
desiredLRPResponse = &models.DesiredLRPResponse{
Error: nil,
DesiredLrp: &models.DesiredLRP{
ProcessGuid: processGuid,
Instances: 100,
Routes: &models.Routes{routes.DIEGO_SSH: &sshRouteMessage},
},
}
clientConfig = &ssh.ClientConfig{}
})
JustBeforeEach(func() {
fakeBBS.RouteToHandler("POST", "/v1/actual_lrp_groups/get_by_process_guid_and_index", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/v1/actual_lrp_groups/get_by_process_guid_and_index"),
VerifyProto(expectedGetActualLRPRequest),
RespondWithProto(actualLRPGroupResponse),
))
fakeBBS.RouteToHandler("POST", "/v1/desired_lrps/get_by_process_guid.r1", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/v1/desired_lrps/get_by_process_guid.r1"),
VerifyProto(getDesiredLRPRequest),
RespondWithProto(desiredLRPResponse),
))
args := testrunner.Args{
Address: address,
BBSAddress: bbsAddress,
CCAPIURL: ccAPIURL,
DiegoCredentials: diegoCredentials,
EnableCFAuth: enableCFAuth,
EnableDiegoAuth: enableDiegoAuth,
示例7:
),
ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/api/v1/pipes"),
ghttp.RespondWithJSONEncoded(http.StatusCreated, atc.Pipe{
ID: "some-other-pipe-id",
}),
),
)
atcServer.RouteToHandler("POST", "/api/v1/builds",
ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/api/v1/builds"),
ghttp.VerifyJSONRepresenting(expectedPlan),
func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "Some-Cookie",
Value: "some-cookie-data",
Path: "/",
Expires: time.Now().Add(1 * time.Minute),
})
},
ghttp.RespondWith(201, `{"id":128}`),
),
)
atcServer.RouteToHandler("GET", "/api/v1/builds/128/events",
ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/api/v1/builds/128/events"),
func(w http.ResponseWriter, r *http.Request) {
flusher := w.(http.Flusher)
w.Header().Add("Content-Type", "text/event-stream; charset=utf-8")
w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
示例8:
BeforeEach(func() {
sshAccessResponseCode = http.StatusInternalServerError
sshAccessResponse = &authenticators.AppSSHResponse{}
})
It("fails to authenticate", func() {
Expect(authenErr).To(Equal(authenticators.FetchAppFailedErr))
Expect(fakeCC.ReceivedRequests()).To(HaveLen(1))
})
})
Context("when the cc ssh_access response cannot be parsed", func() {
BeforeEach(func() {
fakeCC.RouteToHandler("GET", "/internal/apps/app-guid/ssh_access/1", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/internal/apps/app-guid/ssh_access/1"),
ghttp.VerifyHeader(http.Header{"Authorization": []string{"bearer exchanged-token"}}),
ghttp.RespondWith(http.StatusOK, "{{"),
))
})
It("fails to authenticate", func() {
Expect(authenErr).To(Equal(authenticators.InvalidCCResponse))
Expect(fakeCC.ReceivedRequests()).To(HaveLen(1))
})
})
Context("the the cc ssh_access check times out", func() {
BeforeEach(func() {
ccTempClientTimeout := httpClientTimeout
fakeCC.RouteToHandler("GET", "/internal/apps/app-guid/ssh_access/1",
func(w http.ResponseWriter, req *http.Request) {
示例9:
listener, err := net.Listen("tcp", ip+":0")
Expect(err).NotTo(HaveOccurred())
timeout = 100 * time.Millisecond
serverDelay = 0
server.HTTPTestServer.Listener = listener
serverAddr = listener.Addr().String()
_, port, err = net.SplitHostPort(serverAddr)
Expect(err).NotTo(HaveOccurred())
})
JustBeforeEach(func() {
server.RouteToHandler("GET", "/api/_ping",
func(http.ResponseWriter, *http.Request) {
time.Sleep(serverDelay)
})
server.Start()
hc = healthcheck.NewHealthCheck("tcp", uri, port, timeout)
})
AfterEach(func() {
if server != nil {
server.CloseClientConnections()
server.Close()
}
})
Describe("check interfaces", func() {
It("succeeds when there are healthy interfaces", func() {
示例10:
)
})
Context("when configuring with templated keys succeeds", func() {
BeforeEach(func() {
path, err := atc.Routes.CreatePathForRoute(atc.SaveConfig, rata.Params{"pipeline_name": "awesome-pipeline"})
Expect(err).NotTo(HaveOccurred())
atcServer.RouteToHandler("PUT", path,
ghttp.CombineHandlers(
ghttp.VerifyHeaderKV(atc.ConfigVersionHeader, "42"),
func(w http.ResponseWriter, r *http.Request) {
bodyConfig := getConfig(r)
receivedConfig := atc.Config{}
err = yaml.Unmarshal(bodyConfig, &receivedConfig)
Expect(err).NotTo(HaveOccurred())
Expect(receivedConfig).To(Equal(config))
w.WriteHeader(http.StatusNoContent)
},
),
)
})
It("parses the config file and sends it to the ATC", func() {
flyCmd := exec.Command(
flyPath, "-t", atcServer.URL()+"/",
"set-pipeline",
"--pipeline", "awesome-pipeline",
"-c", "fixtures/testConfig.yml",
示例11:
os.Environ(),
fmt.Sprintf(`CF_INSTANCE_PORTS=[{"external":%s,"internal":%s}]`, port, "8080"),
)
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).NotTo(HaveOccurred())
return session
}
BeforeEach(func() {
_, port, err = net.SplitHostPort(serverAddr)
Expect(err).NotTo(HaveOccurred())
})
Context("when the healthcheck is properly invoked", func() {
BeforeEach(func() {
server.RouteToHandler("GET", "/api/_ping", ghttp.VerifyRequest("GET", "/api/_ping"))
})
Context("when the address is listening", func() {
itExitsWithCode(httpHealthCheck, 0, "healthcheck passed")
})
Context("when the address returns error http code", func() {
BeforeEach(func() {
server.RouteToHandler("GET", "/api/_ping", ghttp.RespondWith(500, ""))
})
itExitsWithCode(httpHealthCheck, 6, "failure to get valid HTTP status code: 500")
})
})
})
示例12:
"execution_metadata": "execution-metadata-3",
"health_check_timeout_in_seconds": 123456,
"etag": "3.1"
}`,
}
fakeCC.RouteToHandler("GET", "/internal/bulk/apps",
ghttp.RespondWith(200, `{
"token": {},
"fingerprints": [
{
"process_guid": "process-guid-1",
"etag": "1.1"
},
{
"process_guid": "process-guid-2",
"etag": "2.1"
},
{
"process_guid": "process-guid-3",
"etag": "3.1"
}
]
}`),
)
fakeCC.RouteToHandler("POST", "/internal/bulk/apps",
http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var processGuids []string
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&processGuids)
示例13:
BeforeEach(func() {
sessionFactory = docker_metadata_fetcher.NewDockerSessionFactory()
dockerRegistryServer = ghttp.NewServer()
})
AfterEach(func() {
dockerRegistryServer.Close()
})
Describe("creating registry sessions", func() {
BeforeEach(func() {
parts, err := url.Parse(dockerRegistryServer.URL())
Expect(err).NotTo(HaveOccurred())
registryHost = parts.Host
dockerRegistryServer.RouteToHandler("GET", "/v1/_ping", ghttp.VerifyRequest("GET", "/v1/_ping"))
dockerRegistryServer.RouteToHandler("GET", "/v2/", ghttp.VerifyRequest("GET", "/v2/"))
})
Context("when connecting to a secure registry", func() {
It("creates a registry session for the given repo", func() {
session, err := sessionFactory.MakeSession(registryHost+"/lattice-mappppppppppppappapapa", false)
Expect(err).NotTo(HaveOccurred())
registrySession, ok := session.(*registry.Session)
Expect(ok).To(BeTrue())
Expect(*registrySession.GetAuthConfig(true)).To(Equal(registry.AuthConfig{}))
Expect(dockerRegistryServer.ReceivedRequests()).To(HaveLen(2))
})
})
示例14:
request *http.Request
)
BeforeEach(func() {
serviceReady = make(chan struct{})
fakeServer = ghttp.NewServer()
handler = handlers.NewUnavailableHandler(fakeServer, serviceReady)
var err error
request, err = http.NewRequest("GET", "/test", nil)
Expect(err).NotTo(HaveOccurred())
fakeServer.RouteToHandler("GET", "/test", ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/test"),
ghttp.RespondWith(200, nil, nil),
))
})
verifyResponse := func(expectedStatus int, handler *handlers.UnavailableHandler) {
responseRecorder := httptest.NewRecorder()
handler.ServeHTTP(responseRecorder, request)
Expect(responseRecorder.Code).To(Equal(expectedStatus))
}
It("responds with 503 until the service is ready", func() {
verifyResponse(http.StatusServiceUnavailable, handler)
verifyResponse(http.StatusServiceUnavailable, handler)
close(serviceReady)
示例15:
Tags: []string{"some", "tags"},
}
fakeATC = ghttp.NewServer()
registerRoute, found := atc.Routes.FindRouteByName(atc.RegisterWorker)
Ω(found).Should(BeTrue())
registered := make(chan registration, 100)
registrations = registered
fakeATC.RouteToHandler(registerRoute.Method, registerRoute.Path, func(w http.ResponseWriter, r *http.Request) {
var worker atc.Worker
err := json.NewDecoder(r.Body).Decode(&worker)
Ω(err).ShouldNot(HaveOccurred())
ttl, err := time.ParseDuration(r.URL.Query().Get("ttl"))
Ω(err).ShouldNot(HaveOccurred())
registered <- registration{worker, ttl}
})
fakeGardenClient = new(gfakes.FakeClient)
})
JustBeforeEach(func() {
atcEndpoint := rata.NewRequestGenerator(fakeATC.URL(), atc.Routes)
heartbeater = ifrit.Invoke(
NewHeartbeater(
logger,
interval,
fakeGardenClient,