当前位置: 首页>>代码示例>>Golang>>正文


Golang httptest.Server类代码示例

本文整理汇总了Golang中net/http/httptest.Server的典型用法代码示例。如果您正苦于以下问题:Golang Server类的具体用法?Golang Server怎么用?Golang Server使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Server类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: 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")
	}
}
开发者ID:nbari,项目名称:epazote,代码行数:34,代码来源:supervice_test.go

示例2: doTestProxy

func doTestProxy(t *testing.T, origin *httptest.Server, server *httptest.Server, disableKeepAlives bool) {
	u, _ := url.Parse(server.URL)
	client := &http.Client{Transport: &http.Transport{
		Dial: func(network, addr string) (net.Conn, error) {
			conn, err := net.Dial("tcp", u.Host)
			if err == nil {
				initReq, reqErr := http.NewRequest("GET", fmt.Sprintf("http://%v", addr), nil)
				if reqErr != nil {
					return nil, fmt.Errorf("Unable to construct initial request: %v", reqErr)
				}
				initReq.Header.Set(XLanternPersistent, "true")
				writeErr := initReq.Write(conn)
				if writeErr != nil {
					return nil, fmt.Errorf("Unable to write initial request: %v", writeErr)
				}
			}
			return conn, err
		},
		DisableKeepAlives: disableKeepAlives,
	}}

	// Do a simple GET
	if !testGet(t, client, origin) {
		return
	}

	// Do another GET to test keepalive functionality
	if !testGet(t, client, origin) {
		return
	}

	// Forcibly close client connections and make sure we can still proxy
	origin.CloseClientConnections()
	testGet(t, client, origin)
}
开发者ID:getlantern,项目名称:http-proxy,代码行数:35,代码来源:pforward_test.go

示例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)
	}
}
开发者ID:t3rm1n4l,项目名称:camlistore,代码行数:28,代码来源:ident_test.go

示例4: 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")
	}
}
开发者ID:Acidburn0zzz,项目名称:crp-cli,代码行数:29,代码来源:tasks_test.go

示例5: 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")
	}
}
开发者ID:Acidburn0zzz,项目名称:crp-cli,代码行数:31,代码来源:tasks_test.go

示例6: 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")

}
开发者ID:yml,项目名称:freckle-project-indicators,代码行数:25,代码来源:projects_test.go

示例7: 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)
}
开发者ID:hermancaldara,项目名称:tsuru,代码行数:30,代码来源:router_test.go

示例8: teardown

func teardown(server *httptest.Server) {
	server.Close()
	// Cleanup cache files.
	er := os.RemoveAll("./raincollector")
	if er != nil {
		panic(er.Error())
	}
}
开发者ID:heindl,项目名称:raincollector,代码行数:8,代码来源:collection_test.go

示例9: 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)
	}
}
开发者ID:riscv,项目名称:riscv-go,代码行数:56,代码来源:client_test.go

示例10: 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())
}
开发者ID:stevenxiao215,项目名称:go,代码行数:11,代码来源:client_test.go

示例11: 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)
	}
}
开发者ID:yourchanges,项目名称:readeef,代码行数:51,代码来源:feed_manager_test.go

示例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")
	}
}
开发者ID:duzhanyuan,项目名称:platform,代码行数:14,代码来源:acme_test.go

示例13: 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")
}
开发者ID:4Second2None,项目名称:gin,代码行数:14,代码来源:gin_integration_test.go

示例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())
}
开发者ID:fdr,项目名称:roundtripper,代码行数:15,代码来源:client_test.go

示例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())
}
开发者ID:stevenxiao215,项目名称:go,代码行数:16,代码来源:client_test.go


注:本文中的net/http/httptest.Server类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。