本文整理汇总了Golang中gopkg/in/macaroon-bakery/v1/httpbakery.NewClient函数的典型用法代码示例。如果您正苦于以下问题:Golang NewClient函数的具体用法?Golang NewClient怎么用?Golang NewClient使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewClient函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestDoWithBodyAndCustomError
func (s *ClientSuite) TestDoWithBodyAndCustomError(c *gc.C) {
d := bakerytest.NewDischarger(nil, noCaveatChecker)
defer d.Close()
// Create a target service.
svc := newService("loc", d)
type customError struct {
CustomError *httpbakery.Error
}
callCount := 0
handler := func(w http.ResponseWriter, req *http.Request) {
callCount++
if _, checkErr := httpbakery.CheckRequest(svc, req, nil, checkers.New()); checkErr != nil {
httprequest.WriteJSON(w, http.StatusTeapot, customError{
CustomError: newDischargeRequiredError(svc, d.Location(), nil, checkErr, req).(*httpbakery.Error),
})
return
}
fmt.Fprintf(w, "hello there")
}
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
req, err := http.NewRequest("GET", srv.URL, nil)
c.Assert(err, gc.IsNil)
// First check that a normal request fails.
resp, err := httpbakery.NewClient().Do(req)
c.Assert(err, gc.IsNil)
defer resp.Body.Close()
c.Assert(resp.StatusCode, gc.Equals, http.StatusTeapot)
c.Assert(callCount, gc.Equals, 1)
callCount = 0
// Then check that a request with a custom error getter succeeds.
errorGetter := func(resp *http.Response) error {
if resp.StatusCode != http.StatusTeapot {
return nil
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var respErr customError
if err := json.Unmarshal(data, &respErr); err != nil {
panic(err)
}
return respErr.CustomError
}
resp, err = httpbakery.NewClient().DoWithBodyAndCustomError(req, nil, errorGetter)
c.Assert(err, gc.IsNil)
data, err := ioutil.ReadAll(resp.Body)
c.Assert(err, gc.IsNil)
c.Assert(string(data), gc.Equals, "hello there")
c.Assert(callCount, gc.Equals, 2)
}
示例2: TestMeteredCharmDeployError
func (s *registrationSuite) TestMeteredCharmDeployError(c *gc.C) {
client := httpbakery.NewClient().Client
d := DeploymentInfo{
CharmURL: charm.MustParseURL("cs:quantal/metered-1"),
ServiceName: "service name",
ModelUUID: "environment uuid",
}
err := s.register.RunPre(&mockAPIConnection{Stub: s.stub}, client, s.ctx, d)
c.Assert(err, jc.ErrorIsNil)
deployError := errors.New("deployment failed")
err = s.register.RunPost(&mockAPIConnection{Stub: s.stub}, client, s.ctx, d, deployError)
c.Assert(err, jc.ErrorIsNil)
authorization, err := json.Marshal([]byte("hello registration"))
authorization = append(authorization, byte(0xa))
c.Assert(err, jc.ErrorIsNil)
s.stub.CheckCalls(c, []testing.StubCall{{
"APICall", []interface{}{"Charms", "IsMetered", params.CharmInfo{CharmURL: "cs:quantal/metered-1"}},
}, {
"Authorize", []interface{}{metricRegistrationPost{
ModelUUID: "environment uuid",
CharmURL: "cs:quantal/metered-1",
ServiceName: "service name",
PlanURL: "someplan",
}},
}})
}
示例3: TestInteractiveDischargerURL
func (s *suite) TestInteractiveDischargerURL(c *gc.C) {
var d *bakerytest.InteractiveDischarger
d = bakerytest.NewInteractiveDischarger(nil, http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, d.URL("/redirect", r), http.StatusFound)
},
))
defer d.Close()
d.Mux.Handle("/redirect", http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
d.FinishInteraction(w, r, nil, nil)
},
))
svc, err := bakery.NewService(bakery.NewServiceParams{
Location: "here",
Locator: d,
})
c.Assert(err, gc.IsNil)
m, err := svc.NewMacaroon("", nil, []checkers.Caveat{{
Location: d.Location(),
Condition: "something",
}})
c.Assert(err, gc.IsNil)
client := httpbakery.NewClient()
client.VisitWebPage = func(u *url.URL) error {
var c httprequest.Client
return c.Get(u.String(), nil)
}
ms, err := client.DischargeAll(m)
c.Assert(err, gc.IsNil)
c.Assert(ms, gc.HasLen, 2)
err = svc.Check(ms, failChecker)
c.Assert(err, gc.IsNil)
}
示例4: TestLoginDischargerError
func (s *suite) TestLoginDischargerError(c *gc.C) {
var d *bakerytest.InteractiveDischarger
d = bakerytest.NewInteractiveDischarger(nil, http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
d.FinishInteraction(w, r, nil, errors.New("test error"))
},
))
defer d.Close()
svc, err := bakery.NewService(bakery.NewServiceParams{
Location: "here",
Locator: d,
})
c.Assert(err, gc.IsNil)
m, err := svc.NewMacaroon("", nil, []checkers.Caveat{{
Location: d.Location(),
Condition: "something",
}})
c.Assert(err, gc.IsNil)
client := httpbakery.NewClient()
client.VisitWebPage = func(u *url.URL) error {
c.Logf("visiting %s", u)
var c httprequest.Client
return c.Get(u.String(), nil)
}
_, err = client.DischargeAll(m)
c.Assert(err, gc.ErrorMatches, `cannot get discharge from ".*": failed to acquire macaroon after waiting: third party refused discharge: test error`)
}
示例5: TestMeteredCharmNoDefaultPlan
func (s *registrationSuite) TestMeteredCharmNoDefaultPlan(c *gc.C) {
s.stub.SetErrors(nil, errors.NotFoundf("default plan"))
s.register = &RegisterMeteredCharm{
AllocationSpec: "personal:100",
RegisterURL: s.server.URL,
QueryURL: s.server.URL}
client := httpbakery.NewClient()
d := DeploymentInfo{
CharmID: charmstore.CharmID{
URL: charm.MustParseURL("cs:quantal/metered-1"),
},
ApplicationName: "application name",
ModelUUID: "model uuid",
CharmInfo: &apicharms.CharmInfo{
Metrics: &charm.Metrics{
Plan: &charm.Plan{Required: true},
},
},
}
err := s.register.RunPre(&mockMeteredDeployAPI{Stub: s.stub}, client, s.ctx, d)
c.Assert(err, gc.ErrorMatches, `cs:quantal/metered-1 has no default plan. Try "juju deploy --plan <plan-name> with one of thisplan, thisotherplan"`)
s.stub.CheckCalls(c, []testing.StubCall{{
"IsMetered", []interface{}{"cs:quantal/metered-1"},
}, {
"DefaultPlan", []interface{}{"cs:quantal/metered-1"},
}, {
"ListPlans", []interface{}{"cs:quantal/metered-1"},
}})
}
示例6: TestAgentLogin
func (s *agentSuite) TestAgentLogin(c *gc.C) {
u, err := url.Parse(s.discharger.URL)
c.Assert(err, gc.IsNil)
for i, test := range agentLoginTests {
c.Logf("%d. %s", i, test.about)
s.discharger.LoginHandler = test.loginHandler
client := httpbakery.NewClient()
client.Key, err = bakery.GenerateKey()
c.Assert(err, gc.IsNil)
err = agent.SetUpAuth(client, u, "test-user")
c.Assert(err, gc.IsNil)
m, err := s.bakery.NewMacaroon("", nil, []checkers.Caveat{{
Location: s.discharger.URL,
Condition: "test condition",
}})
c.Assert(err, gc.IsNil)
ms, err := client.DischargeAll(m)
if test.expectError != "" {
c.Assert(err, gc.ErrorMatches, test.expectError)
continue
}
c.Assert(err, gc.IsNil)
err = s.bakery.Check(ms, bakery.FirstPartyCheckerFunc(
func(caveat string) error {
return nil
},
))
c.Assert(err, gc.IsNil)
}
}
示例7: TestMeteredCharmNoPlanSet
func (s *registrationSuite) TestMeteredCharmNoPlanSet(c *gc.C) {
s.register = &RegisterMeteredCharm{RegisterURL: s.server.URL, QueryURL: s.server.URL}
client := httpbakery.NewClient().Client
d := DeploymentInfo{
CharmURL: charm.MustParseURL("local:quantal/metered-1"),
ServiceName: "service name",
EnvUUID: "environment uuid",
}
err := s.register.RunPre(&mockAPIConnection{Stub: s.stub}, client, d)
c.Assert(err, jc.ErrorIsNil)
err = s.register.RunPost(&mockAPIConnection{Stub: s.stub}, client, d)
c.Assert(err, jc.ErrorIsNil)
authorization, err := json.Marshal([]byte("hello registration"))
authorization = append(authorization, byte(0xa))
c.Assert(err, jc.ErrorIsNil)
s.stub.CheckCalls(c, []testing.StubCall{{
"APICall", []interface{}{"Charms", "IsMetered", params.CharmInfo{CharmURL: "local:quantal/metered-1"}},
}, {
"DefaultPlan", []interface{}{"local:quantal/metered-1"},
}, {
"Authorize", []interface{}{metricRegistrationPost{
EnvironmentUUID: "environment uuid",
CharmURL: "local:quantal/metered-1",
ServiceName: "service name",
PlanURL: "thisplan",
}},
}, {
"APICall", []interface{}{"Service", "SetMetricCredentials", params.ServiceMetricCredentials{
Creds: []params.ServiceMetricCredential{params.ServiceMetricCredential{
ServiceName: "service name",
MetricCredentials: authorization,
}},
}},
}})
}
示例8: TestMeteredCharmAPIError
func (s *registrationSuite) TestMeteredCharmAPIError(c *gc.C) {
s.stub.SetErrors(nil, errors.New("something failed"))
client := httpbakery.NewClient()
d := DeploymentInfo{
CharmID: charmstore.CharmID{
URL: charm.MustParseURL("cs:quantal/metered-1"),
},
ServiceName: "service name",
ModelUUID: "model uuid",
}
err := s.register.RunPre(&mockAPIConnection{Stub: s.stub}, client, s.ctx, d)
c.Assert(err, gc.ErrorMatches, `authorization failed: something failed`)
s.stub.CheckCalls(c, []testing.StubCall{{
"APICall", []interface{}{"Charms", "IsMetered", params.CharmInfo{CharmURL: "cs:quantal/metered-1"}},
}, {
"Authorize", []interface{}{metricRegistrationPost{
ModelUUID: "model uuid",
CharmURL: "cs:quantal/metered-1",
ServiceName: "service name",
PlanURL: "someplan",
Budget: "personal",
Limit: "100",
}},
}})
}
示例9: TestMultiVisitorSequence
func (*VisitorSuite) TestMultiVisitorSequence(c *gc.C) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"method": "http://somewhere/something"}`)
}))
defer srv.Close()
firstCalled, secondCalled := 0, 0
v := httpbakery.NewMultiVisitor(
visitorFunc(func(_ *httpbakery.Client, m map[string]*url.URL) error {
c.Check(m["method"], gc.NotNil)
firstCalled++
return httpbakery.ErrMethodNotSupported
}),
visitorFunc(func(_ *httpbakery.Client, m map[string]*url.URL) error {
c.Check(m["method"], gc.NotNil)
secondCalled++
return nil
}),
)
err := v.VisitWebPage(httpbakery.NewClient(), map[string]*url.URL{
httpbakery.UserInteractionMethod: mustParseURL(srv.URL),
})
c.Assert(err, gc.IsNil)
c.Assert(firstCalled, gc.Equals, 1)
c.Assert(secondCalled, gc.Equals, 1)
}
示例10: TestFormLogin
func (s *formSuite) TestFormLogin(c *gc.C) {
d := &formDischarger{}
d.discharger = bakerytest.NewInteractiveDischarger(nil, http.HandlerFunc(d.login))
defer d.discharger.Close()
d.discharger.Mux.Handle("/form", http.HandlerFunc(d.form))
svc, err := bakery.NewService(bakery.NewServiceParams{
Locator: d.discharger,
})
c.Assert(err, gc.IsNil)
for i, test := range formLoginTests {
c.Logf("%d. %s", i, test.about)
d.dischargeOptions = test.opts
m, err := svc.NewMacaroon("", nil, []checkers.Caveat{{
Location: d.discharger.Location(),
Condition: "test condition",
}})
c.Assert(err, gc.Equals, nil)
client := httpbakery.NewClient()
h := defaultFiller
if test.filler != nil {
h = test.filler
}
client.VisitWebPage = test.fallback
form.SetUpAuth(client, h)
ms, err := client.DischargeAll(m)
if test.expectError != "" {
c.Assert(err, gc.ErrorMatches, test.expectError)
continue
}
c.Assert(err, gc.IsNil)
c.Assert(len(ms), gc.Equals, 2)
}
}
示例11: TestUserInteractionFallback
func (*VisitorSuite) TestUserInteractionFallback(c *gc.C) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"method": "http://somewhere/something"}`)
}))
defer srv.Close()
called := 0
// Check that even though the methods didn't explicitly
// include the "interactive" method, it is still supplied.
v := httpbakery.NewMultiVisitor(
visitorFunc(func(_ *httpbakery.Client, m map[string]*url.URL) error {
c.Check(m, jc.DeepEquals, map[string]*url.URL{
"method": mustParseURL("http://somewhere/something"),
httpbakery.UserInteractionMethod: mustParseURL(srv.URL),
})
called++
return nil
}),
)
err := v.VisitWebPage(httpbakery.NewClient(), map[string]*url.URL{
httpbakery.UserInteractionMethod: mustParseURL(srv.URL),
})
c.Assert(err, gc.IsNil)
c.Assert(called, gc.Equals, 1)
}
示例12: TestServerBakery
func (s *macaroonServerSuite) TestServerBakery(c *gc.C) {
srv := newServer(c, s.State)
defer srv.Stop()
m, err := apiserver.ServerMacaroon(srv)
c.Assert(err, gc.IsNil)
bsvc, err := apiserver.ServerBakeryService(srv)
c.Assert(err, gc.IsNil)
// Check that we can add a third party caveat addressed to the
// discharger, which indirectly ensures that the discharger's public
// key has been added to the bakery service's locator.
m = m.Clone()
err = bsvc.AddCaveat(m, checkers.Caveat{
Location: s.discharger.Location(),
Condition: "true",
})
c.Assert(err, jc.ErrorIsNil)
// Check that we can discharge the macaroon and check it with
// the service.
client := httpbakery.NewClient()
ms, err := client.DischargeAll(m)
c.Assert(err, jc.ErrorIsNil)
err = bsvc.Check(ms, checkers.New())
c.Assert(err, gc.IsNil)
}
示例13: TestThirdPartyDischargeRefused
func (s *ClientSuite) TestThirdPartyDischargeRefused(c *gc.C) {
d := bakerytest.NewDischarger(nil, func(_ *http.Request, cond, arg string) ([]checkers.Caveat, error) {
return nil, errgo.New("boo! cond " + cond)
})
defer d.Close()
// Create a target service.
svc := newService("loc", d)
ts := httptest.NewServer(serverHandler(serverHandlerParams{
service: svc,
authLocation: d.Location(),
}))
defer ts.Close()
// Create a client request.
req, err := http.NewRequest("GET", ts.URL, nil)
c.Assert(err, gc.IsNil)
client := httpbakery.NewClient()
// Make the request to the server.
resp, err := client.Do(req)
c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httpbakery.DischargeError)(nil))
c.Assert(err, gc.ErrorMatches, `cannot get discharge from ".*": third party refused discharge: cannot discharge: boo! cond is-ok`)
c.Assert(resp, gc.IsNil)
}
示例14: TestWithLargeBody
func (s ClientSuite) TestWithLargeBody(c *gc.C) {
// This test is designed to fail when run with the race
// checker enabled and when go issue #12796
// is not fixed.
d := bakerytest.NewDischarger(nil, noCaveatChecker)
defer d.Close()
// Create a target service.
svc := newService("loc", d)
ts := httptest.NewServer(serverHandler(serverHandlerParams{
service: svc,
authLocation: d.Location(),
}))
defer ts.Close()
// Create a client request.
req, err := http.NewRequest("POST", ts.URL+"/no-body", nil)
c.Assert(err, gc.IsNil)
body := &largeReader{total: 3 * 1024 * 1024}
resp, err := httpbakery.NewClient().DoWithBody(req, body)
c.Assert(err, gc.IsNil)
resp.Body.Close()
body.Close()
c.Assert(resp.StatusCode, gc.Equals, http.StatusOK)
}
示例15: TestFormTitle
func (s *formSuite) TestFormTitle(c *gc.C) {
d := &formDischarger{}
d.discharger = bakerytest.NewInteractiveDischarger(nil, http.HandlerFunc(d.login))
defer d.discharger.Close()
d.discharger.Mux.Handle("/form", http.HandlerFunc(d.form))
svc, err := bakery.NewService(bakery.NewServiceParams{
Locator: testLocator{
loc: d.discharger.Location(),
locator: d.discharger,
},
})
c.Assert(err, gc.IsNil)
for i, test := range formTitleTests {
c.Logf("%d. %s", i, test.host)
m, err := svc.NewMacaroon("", nil, []checkers.Caveat{{
Location: "https://" + test.host,
Condition: "test condition",
}})
c.Assert(err, gc.Equals, nil)
client := httpbakery.NewClient()
client.Client.Transport = httptesting.URLRewritingTransport{
MatchPrefix: "https://" + test.host,
Replace: d.discharger.Location(),
RoundTripper: http.DefaultTransport,
}
f := new(titleTestFiller)
form.SetUpAuth(client, f)
ms, err := client.DischargeAll(m)
c.Assert(err, gc.IsNil)
c.Assert(len(ms), gc.Equals, 2)
c.Assert(f.title, gc.Equals, test.expect)
}
}