本文整理汇总了Golang中net/http/httptest.Server.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang Server.Close方法的具体用法?Golang Server.Close怎么用?Golang Server.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http/httptest.Server
的用法示例。
在下文中一共展示了Server.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestListProjectsThroughChannel
func TestListProjectsThroughChannel(t *testing.T) {
page := 0
var ts *httptest.Server
ts = httptest.NewServer(authenticated(t, "GET", "/projects", func(w http.ResponseWriter, r *http.Request) {
page += 1
if page < 10 {
w.Header().Set("Link", fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", ts.URL, r.URL.Path, page+1))
}
response(array_of_projects)(w, r)
}))
defer ts.Close()
f := letsTestFreckle(ts)
pp, err := f.ProjectsAPI().ListProjects()
assert.Nil(t, err, "Error should be nil")
projects := 0
// reading through the channel should do 10 HTTP request, yielding 1 project each
for _ = range pp.AllProjects() {
projects += 1
}
assert.Equal(t, 10, projects, "Should have read 10 projects")
assert.Equal(t, 10, page, "We should have read up to page 10")
}
示例2: TestGetData
func TestGetData(t *testing.T) {
var err error
var ts *httptest.Server
ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("1 2 3 4 5"))
}))
defer ts.Close()
i := 0
writer := JsonWriteFunc(func(d json.RawMessage) error {
i++
return nil
})
n, err := getData(ts.URL, writer, nil)
if err != nil {
t.Error(err)
}
if n != 5 {
t.Error("n != 5")
}
if i != 5 {
t.Error("i != 5")
}
}
示例3: TestHTTPAuth
func TestHTTPAuth(t *testing.T) {
var ts *httptest.Server
ts = httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
from, err := HostPortToIP(r.RemoteAddr)
if err != nil {
t.Fatal(err)
}
to := ts.Listener.Addr()
uid, err := AddrPairUserid(from, to)
if err != nil {
fmt.Fprintf(rw, "ERR: %v", err)
return
}
fmt.Fprintf(rw, "uid=%d", uid)
}))
defer ts.Close()
res, err := http.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
if g, e := string(body), fmt.Sprintf("uid=%d", os.Getuid()); g != e {
t.Errorf("got body %q; want %q", g, e)
}
}
示例4: TestSubmitTasks
func TestSubmitTasks(t *testing.T) {
var err error
var ts *httptest.Server
ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(201)
}))
defer ts.Close()
TASKS_ADDRESS = ts.URL + "/%s/tasks"
i := 0
reader := JsonReaderFunc(func(d *json.RawMessage) error {
if i == 5 {
return io.EOF
}
i++
data := json.RawMessage("1")
d = &data
return nil
})
n, err := SubmitTasks("", reader)
if err != nil {
t.Error(err)
}
if n != 5 {
t.Error("n != 5")
}
}
示例5: TestSuperviceReadLimit
func TestSuperviceReadLimit(t *testing.T) {
buf.Reset()
var server *httptest.Server
var h http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "0123456789")
}
server = httptest.NewServer(h)
defer server.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: server.URL,
ReadLimit: 5,
Expect: Expect{
Status: 200,
},
}
ez := &Epazote{
Services: s,
}
ez.debug = true
ez.Supervice(s["s 1"])()
rc := s["s 1"].retryCount
if rc != 0 {
t.Errorf("Expecting retryCount = 0 got: %d", rc)
}
data := buf.String()
re := regexp.MustCompile("(?m)[\r\n]+^01234$")
match := re.FindString(data)
if match == "" {
t.Error("Expecting: 01234")
}
}
示例6: init
func init() {
suite := &routertest.RouterSuite{
SetUpSuiteFunc: func(c *check.C) {
config.Set("routers:galeb:username", "myusername")
config.Set("routers:galeb:password", "mypassword")
config.Set("routers:galeb:domain", "galeb.com")
config.Set("routers:galeb:type", "galeb")
config.Set("database:url", "127.0.0.1:27017")
config.Set("database:name", "router_galebv2_tests")
},
}
var server *httptest.Server
suite.SetUpTestFunc = func(c *check.C) {
handler, err := NewFakeGalebServer()
c.Assert(err, check.IsNil)
server = httptest.NewServer(handler)
config.Set("routers:galeb:api-url", server.URL+"/api")
gRouter, err := createRouter("routers:galeb")
c.Assert(err, check.IsNil)
suite.Router = gRouter
conn, err := db.Conn()
c.Assert(err, check.IsNil)
defer conn.Close()
dbtest.ClearAllCollections(conn.Collection("router_galebv2_tests").Database)
}
suite.TearDownTestFunc = func(c *check.C) {
server.Close()
}
check.Suite(suite)
}
示例7: teardown
func teardown(server *httptest.Server) {
server.Close()
// Cleanup cache files.
er := os.RemoveAll("./raincollector")
if er != nil {
panic(er.Error())
}
}
示例8: testRedirectsByMethod
func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
defer afterTest(t)
var log struct {
sync.Mutex
bytes.Buffer
}
var ts *httptest.Server
ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
log.Lock()
slurp, _ := ioutil.ReadAll(r.Body)
fmt.Fprintf(&log.Buffer, "%s %s %q\n", r.Method, r.RequestURI, slurp)
log.Unlock()
urlQuery := r.URL.Query()
if v := urlQuery.Get("code"); v != "" {
location := ts.URL
if final := urlQuery.Get("next"); final != "" {
splits := strings.Split(final, ",")
first, rest := splits[0], splits[1:]
location = fmt.Sprintf("%s?code=%s", location, first)
if len(rest) > 0 {
location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
}
}
code, _ := strconv.Atoi(v)
if code/100 == 3 {
w.Header().Set("Location", location)
}
w.WriteHeader(code)
}
}))
defer ts.Close()
for _, tt := range table {
content := tt.redirectBody
req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
res, err := DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if res.StatusCode != tt.want {
t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
}
}
log.Lock()
got := log.String()
log.Unlock()
got = strings.TrimSpace(got)
want = strings.TrimSpace(want)
if got != want {
t.Errorf("Log differs.\n Got:\n%s\nWant:\n%s\n", got, want)
}
}
示例9: TestRedirectCookiesJar
func TestRedirectCookiesJar(t *testing.T) {
var ts *httptest.Server
ts = httptest.NewServer(echoCookiesRedirectHandler)
defer ts.Close()
c := &Client{}
c.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
u, _ := url.Parse(ts.URL)
c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
resp, _ := c.Get(ts.URL)
matchReturnedCookies(t, expectedCookies, resp.Cookies())
}
示例10: TestFeedManagerDetection
func TestFeedManagerDetection(t *testing.T) {
var ts *httptest.Server
ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI == "/link" {
w.WriteHeader(http.StatusOK)
w.Write([]byte(strings.Replace(atomXml, "{{ .FeedLink }}", ts.URL+"/link", -1)))
} else if r.RequestURI == "/html" {
w.Write([]byte(`
<html>
<head>
<link type="text/css" href="/foo.css">
<link rel="alternative" type="application/rss+xml" href="/link"/>
</head>
<body><main></main></body>
</html>
`))
} else {
w.WriteHeader(http.StatusNotFound)
}
}))
defer ts.Close()
_, err := discoverParserFeeds(ts.URL)
if err == nil {
t.Fatalf("Expected an ErrNoFeed error, got nothing\n")
} else if err != ErrNoFeed {
t.Fatalf("Expected an ErrNoFeed error, got %v\n", err)
}
pf, err := discoverParserFeeds(ts.URL + "/link")
if err != nil {
t.Fatal(err)
}
expectedStr := ts.URL + "/link"
if pf[0].Link != expectedStr {
t.Fatalf("Expected '%s' for a url, got '%s'\n", expectedStr, pf[0].Link)
}
pf, err = discoverParserFeeds(ts.URL + "/html")
if err != nil {
t.Fatal(err)
}
expectedStr = ts.URL + "/link"
if pf[0].Link != expectedStr {
t.Fatalf("Expected '%s' for a url, got '%s'\n", expectedStr, pf[0].Link)
}
}
示例11: TestWithHttptestWithSpecifiedPort
func TestWithHttptestWithSpecifiedPort(t *testing.T) {
router := New()
router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })
l, _ := net.Listen("tcp", ":8033")
ts := httptest.Server{
Listener: l,
Config: &http.Server{Handler: router},
}
ts.Start()
defer ts.Close()
testRequest(t, "http://localhost:8033/example")
}
示例12: TestFetchCertBreadth
func TestFetchCertBreadth(t *testing.T) {
var ts *httptest.Server
ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for i := 0; i < maxChainLen+1; i++ {
w.Header().Add("link", fmt.Sprintf("<%s>;rel=up", ts.URL))
}
w.Write([]byte{1})
}))
defer ts.Close()
_, err := (&Client{}).FetchCert(context.Background(), ts.URL, true)
if err == nil {
t.Errorf("err is nil")
}
}
示例13: TestProvider
func TestProvider(t *testing.T) {
var (
h *httptest.Server
g *httptest.Server
)
header := `-----> Fetching archive link for ejholmes/[email protected] done.
-----> Deploying to acme-inc...
`
logs := "Hello"
h = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Logf("%s %s", r.Method, r.URL.Path)
switch r.URL.Path {
case "/apps/acme-inc/builds":
fmt.Fprintf(w, `{"id": "1234", "output_stream_url": "%s/stream"}`, h.URL)
case "/stream":
fmt.Fprintf(w, logs)
case "/apps/acme-inc/builds/1234/result":
fmt.Fprintf(w, `{"build":{"status":"succeeded"}}`)
}
}))
g = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", "http://github.com/archive")
w.WriteHeader(302)
}))
defer h.Close()
defer g.Close()
p := NewProvider("", "")
p.heroku.URL = h.URL
p.github.BaseURL = mustURLParse(g.URL)
d := &tugboat.Deployment{
Repo: "ejholmes/acme-inc",
Environment: "production",
Sha: "abcd",
}
w := new(bytes.Buffer)
if err := p.Deploy(context.Background(), d, w); err != nil {
t.Fatal(err)
}
if got, want := w.String(), header+logs; got != want {
t.Fatalf("Logs => %s; want %s", got, want)
}
}
示例14: TestRedirectCookiesJar
func TestRedirectCookiesJar(t *testing.T) {
var ts *httptest.Server
ts = httptest.NewServer(echoCookiesRedirectHandler)
defer ts.Close()
c := &http.Client{
Jar: new(TestJar),
}
u, _ := url.Parse(ts.URL)
c.Jar.SetCookies(u, []*http.Cookie{expectedCookies[0]})
resp, err := c.Get(ts.URL)
if err != nil {
t.Fatalf("Get: %v", err)
}
matchReturnedCookies(t, expectedCookies, resp.Cookies())
}
示例15: TestRedirectCookiesOnRequest
func TestRedirectCookiesOnRequest(t *testing.T) {
var ts *httptest.Server
ts = httptest.NewServer(echoCookiesRedirectHandler)
defer ts.Close()
c := &Client{}
req, _ := NewRequest("GET", ts.URL, nil)
req.AddCookie(expectedCookies[0])
// TODO: Uncomment when an implementation of a RFC6265 cookie jar lands.
_ = c
// resp, _ := c.Do(req)
// matchReturnedCookies(t, expectedCookies, resp.Cookies())
req, _ = NewRequest("GET", ts.URL, nil)
// resp, _ = c.Do(req)
// matchReturnedCookies(t, expectedCookies[1:], resp.Cookies())
}