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


Golang strings.NewReader函数代码示例

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


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

示例1: TestValidateResponse

func TestValidateResponse(t *testing.T) {
	valid := &http.Response{
		Request:    &http.Request{},
		StatusCode: http.StatusOK,
		Body:       ioutil.NopCloser(strings.NewReader("OK")),
	}

	if err := validateResponse(valid); err != nil {
		t.Errorf("ValidateResponse with valid response returned error %+v", err)
	}

	invalid := &http.Response{
		Request:    &http.Request{},
		StatusCode: http.StatusBadRequest,
		Body: ioutil.NopCloser(strings.NewReader(`{
			"error" : {
				"statuscode": 400,
				"statusdesc": "Bad Request",
				"errormessage": "This is an error"
			}
		}`)),
	}

	want := &PingdomError{400, "Bad Request", "This is an error"}
	if err := validateResponse(invalid); !reflect.DeepEqual(err, want) {
		t.Errorf("ValidateResponse with invalid response returned %+v, want %+v", err, want)
	}

}
开发者ID:russellcardullo,项目名称:go-pingdom,代码行数:29,代码来源:pingdom_test.go

示例2: TestLambda

func TestLambda(t *testing.T) {
	env := environment.New(nil)

	environment.Define(env, &types.Symbol{"+"}, &types.Builtin{add})
	environment.Define(env, &types.Symbol{"begin"}, &types.Builtin{begin})

	f, _ := parser.Parse(strings.NewReader("(lambda (n) n)"))
	if a, err := Eval(env, f); err != nil {
		t.Error("Evaluating lambda failed:", err, f)
	} else if !types.IsSFunction(a) {
		t.Error("Evaluating lambda didn't return an SFunction:", a)
	}

	f, _ = parser.Parse(strings.NewReader("(define add1 (lambda (n) (+ 1 n)))"))
	if _, err := Eval(env, f); err != nil {
		t.Error("Evaluating define lambda failed:", err)
	}

	if a, err := environment.Get(env, &types.Symbol{"add1"}); err != nil {
		t.Error("'Get'ting add1 caused an error: ", err)
	} else if !types.IsSFunction(a) {
		t.Error("add1 is not an SFunction:", a)
	}

	f, _ = parser.Parse(strings.NewReader("(add1 1)"))
	if a, err := Eval(env, f); err != nil {
		t.Error("Evaluating (add1 1) failed:", err)
	} else if !types.Eqv(a, &types.Number{2}) {
		t.Error("(add1 1) != 2", a)
	}
}
开发者ID:alanthird,项目名称:gscheme,代码行数:31,代码来源:evaluator_test.go

示例3: newAuthenticatedRequest

func (c *Client) newAuthenticatedRequest(urlToken string, values url.Values) (*http.Request, error) {
	var req *http.Request
	var err error
	switch c.authMethod {
	case AuthMethodClientSecretPost:
		values.Set("client_secret", c.creds.Secret)
		req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
		if err != nil {
			return nil, err
		}
	case AuthMethodClientSecretBasic:
		req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
		if err != nil {
			return nil, err
		}
		encodedID := url.QueryEscape(c.creds.ID)
		encodedSecret := url.QueryEscape(c.creds.Secret)
		req.SetBasicAuth(encodedID, encodedSecret)
	default:
		panic("misconfigured client: auth method not supported")
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	return req, nil

}
开发者ID:40a,项目名称:bootkube,代码行数:26,代码来源:oauth2.go

示例4: TestNewRequestContentLength

func TestNewRequestContentLength(t *testing.T) {
	readByte := func(r io.Reader) io.Reader {
		var b [1]byte
		r.Read(b[:])
		return r
	}
	tests := []struct {
		r    io.Reader
		want int64
	}{
		{bytes.NewReader([]byte("123")), 3},
		{bytes.NewBuffer([]byte("1234")), 4},
		{strings.NewReader("12345"), 5},
		// Not detected:
		{struct{ io.Reader }{strings.NewReader("xyz")}, 0},
		{io.NewSectionReader(strings.NewReader("x"), 0, 6), 0},
		{readByte(io.NewSectionReader(strings.NewReader("xy"), 0, 6)), 0},
	}
	for _, tt := range tests {
		req, err := NewRequest("POST", "http://localhost/", tt.r)
		if err != nil {
			t.Fatal(err)
		}
		if req.ContentLength != tt.want {
			t.Errorf("ContentLength(%T) = %d; want %d", tt.r, req.ContentLength, tt.want)
		}
	}
}
开发者ID:xslonepiece,项目名称:goios,代码行数:28,代码来源:request_test.go

示例5: TestReadTriggerParams

func TestReadTriggerParams(t *testing.T) {
	t.Parallel()

	h := newHarness(t)
	defer h.Stop()

	h.env.In = ioutil.NopCloser(strings.NewReader("\n"))
	_, err := readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Class name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\n"))
	_, err = readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Trigger name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave"))
	hook, err := readTriggerName(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{ClassName: "foo", TriggerName: "beforeSave"})

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/foo/beforeSave\n"))
	hook, err = readTriggerParams(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{
		ClassName:   "foo",
		TriggerName: "beforeSave",
		URL:         "https://api.example.com/foo/beforeSave",
	})
}
开发者ID:huamichaelchen,项目名称:parse-cli,代码行数:28,代码来源:triggers_cmd_test.go

示例6: main

func main() {
	br := bufio.NewReader(os.Stdin)

	line, _ := br.ReadString('\n')
	taxa := strings.Fields(line)
	taxaInv := map[string]int{}
	for i, taxon := range taxa {
		taxaInv[taxon] = i
	}

	line, _ = br.ReadString('\n')
	t1, _ := tree.ReadNewick(strings.NewReader(line))
	line, _ = br.ReadString('\n')
	t2, _ := tree.ReadNewick(strings.NewReader(line))

	splits1 := phylo.Splits(t1, taxaInv)
	splits2 := phylo.Splits(t2, taxaInv)
	normalize(splits1)
	normalize(splits2)

	m1 := map[string]bool{}
	for _, a := range splits1 {
		m1[string(a)] = true
	}

	shared := 0
	for _, a := range splits2 {
		if m1[string(a)] {
			shared++
		}
	}

	d := 2 * (len(taxa) - 3 - shared)
	fmt.Println(d)
}
开发者ID:nkitchen,项目名称:rosalind,代码行数:35,代码来源:sptd.go

示例7: NewTokenHarness

func NewTokenHarness(t testing.TB) *Harness {
	h := NewHarness(t)
	ht := TransportFunc(func(r *http.Request) (*http.Response, error) {
		ensure.DeepEqual(t, r.URL.Path, "/1/accountkey")
		ensure.DeepEqual(t, r.Method, "POST")

		key := &struct {
			AccountKey string `json:"accountKey"`
		}{}
		ensure.Nil(t, json.NewDecoder(ioutil.NopCloser(r.Body)).Decode(key))

		if key.AccountKey != "token" {
			return &http.Response{
				StatusCode: http.StatusUnauthorized,
				Body:       ioutil.NopCloser(strings.NewReader(`{"error": "incorrect token"}`)),
			}, nil
		}

		return &http.Response{
			StatusCode: http.StatusOK,
			Body:       ioutil.NopCloser(strings.NewReader(`{"email": "email"}`)),
		}, nil
	})
	h.Env.ParseAPIClient = &ParseAPIClient{APIClient: &parse.Client{Transport: ht}}
	return h
}
开发者ID:swhitley,项目名称:parse-cli,代码行数:26,代码来源:main.go

示例8: TestOVirtCloudConfiguration

func TestOVirtCloudConfiguration(t *testing.T) {
	config1 := (io.Reader)(nil)

	_, err1 := cloudprovider.GetCloudProvider("ovirt", config1)
	if err1 == nil {
		t.Fatalf("An error is expected when the configuration is missing")
	}

	config2 := strings.NewReader("")

	_, err2 := cloudprovider.GetCloudProvider("ovirt", config2)
	if err2 == nil {
		t.Fatalf("An error is expected when the configuration is empty")
	}

	config3 := strings.NewReader(`
[connection]
	`)

	_, err3 := cloudprovider.GetCloudProvider("ovirt", config3)
	if err3 == nil {
		t.Fatalf("An error is expected when the uri is missing")
	}

	config4 := strings.NewReader(`
[connection]
uri = https://localhost:8443/ovirt-engine/api
`)

	_, err4 := cloudprovider.GetCloudProvider("ovirt", config4)
	if err4 != nil {
		t.Fatalf("Unexpected error creating the provider: %s", err4)
	}
}
开发者ID:CodeJuan,项目名称:kubernetes,代码行数:34,代码来源:ovirt_test.go

示例9: TestCopyNEOF

func TestCopyNEOF(t *testing.T) {
	// Test that EOF behavior is the same regardless of whether
	// argument to CopyN has ReadFrom.

	b := new(bytes.Buffer)

	n, err := CopyN(&noReadFrom{b}, strings.NewReader("foo"), 3)
	if n != 3 || err != nil {
		t.Errorf("CopyN(noReadFrom, foo, 3) = %d, %v; want 3, nil", n, err)
	}

	n, err = CopyN(&noReadFrom{b}, strings.NewReader("foo"), 4)
	if n != 3 || err != EOF {
		t.Errorf("CopyN(noReadFrom, foo, 4) = %d, %v; want 3, EOF", n, err)
	}

	n, err = CopyN(b, strings.NewReader("foo"), 3) // b has read from
	if n != 3 || err != nil {
		t.Errorf("CopyN(bytes.Buffer, foo, 3) = %d, %v; want 3, nil", n, err)
	}

	n, err = CopyN(b, strings.NewReader("foo"), 4) // b has read from
	if n != 3 || err != EOF {
		t.Errorf("CopyN(bytes.Buffer, foo, 4) = %d, %v; want 3, EOF", n, err)
	}
}
开发者ID:anuvazhayil,项目名称:HelloWorld_32bitOS,代码行数:26,代码来源:io_test.go

示例10: GetPosts

func (ps BoltPostStore) GetPosts(channelID string) StoreChannel {
	storeChannel := make(StoreChannel)

	go func() {
		var result StoreResult
		posts := make(map[string]*model.Post)
		channelPostsJson, err := ps.postsByChannel.Get([]byte(channelID))
		if err != nil {
			result.Err = model.NewAppError("BoltPostStore.", "Post is not valid", "")
		} else {
			channelPosts := model.BoolMapFromJson(strings.NewReader(string(channelPostsJson)))
			postItems, err := ps.postStore.Items()
			if err != nil {
				result.Err = model.NewAppError("BoltPostStore.", "Post is not valid", "")
				storeChannel <- result
				close(storeChannel)
				return
			}

			for _, postItem := range postItems {
				if channelPosts[string(postItem.Key)] {
					postString := string(postItem.Value)
					posts[string(postItem.Key)] = model.PostFromJson(strings.NewReader(postString))
				}
			}
			result.Data = posts
		}

		storeChannel <- result
		close(storeChannel)
		return
	}()

	return storeChannel
}
开发者ID:sichacvah,项目名称:portable_chat,代码行数:35,代码来源:bolt_post_store.go

示例11: TestNewReadCloserWrapperWithAReadCloser

func TestNewReadCloserWrapperWithAReadCloser(t *testing.T) {
	br := bufio.NewReader(strings.NewReader(""))
	sr := &simpleReaderCloser{
		Reader: strings.NewReader("foobar"),
		closed: false,
	}
	reader := BufioReader32KPool.NewReadCloserWrapper(br, sr)
	if reader == nil {
		t.Fatalf("NewReadCloserWrapper should not return a nil reader.")
	}
	// Verify the content of reader
	buf := make([]byte, 3)
	_, err := reader.Read(buf)
	if err != nil {
		t.Fatal(err)
	}
	if actual := string(buf); actual != "foo" {
		t.Fatalf("The first 3 letter should have been 'foo' but were %v", actual)
	}
	reader.Close()
	// Read 3 more bytes "bar"
	_, err = reader.Read(buf)
	if err != nil {
		t.Fatal(err)
	}
	if actual := string(buf); actual != "bar" {
		t.Fatalf("The first 3 letter should have been 'bar' but were %v", actual)
	}
	if !sr.closed {
		t.Fatalf("The ReaderCloser should have been closed, it is not.")
	}
}
开发者ID:DaveDaCoda,项目名称:docker,代码行数:32,代码来源:pools_test.go

示例12: TestUpload

func TestUpload(t *testing.T) {
	fs := NewFileStore("./")
	id := "yyy"

	info := &FileInfo{}
	info.ID = id
	info.Offset = 0
	info.Size = 10
	info.Type = ".jpg"

	if offset, isCompleted, _ := fs.NewUpload(info); offset != 0 || isCompleted {
		t.Fatal()
	}

	if n, isCompleted, _ := fs.WriteChunk(id, 0, strings.NewReader("hello")); n != 5 || isCompleted {
		t.Fatal()
	}

	if offset, isCompleted, _ := fs.NewUpload(info); offset != 5 || isCompleted {
		t.Fatal()
	}

	if n, isCompleted, _ := fs.WriteChunk(id, 5, strings.NewReader("world")); n != 5 || !isCompleted {
		t.Fatal()
	}

	if n, isCompleted, _ := fs.WriteChunk(id, 5, strings.NewReader("abc")); n != 0 || !isCompleted {
		t.Fatal()
	}

	os.Remove(id + ".bin")
	os.Remove(id + ".info")
}
开发者ID:gansidui,项目名称:cofile,代码行数:33,代码来源:filestore_test.go

示例13: TestShortcut

func (test *ServerTest) TestShortcut(c *C) {
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("PUT", "https://idp.example.com/shortcuts/bob",
		strings.NewReader("{\"url_suffix_as_relay_state\": true, \"service_provider\": \"https://sp.example.com/saml2/metadata\"}"))
	test.Server.ServeHTTP(w, r)
	c.Assert(w.Code, Equals, http.StatusNoContent)

	w = httptest.NewRecorder()
	r, _ = http.NewRequest("PUT", "https://idp.example.com/users/alice",
		strings.NewReader(`{"name": "alice", "password": "hunter2"}`+"\n"))
	test.Server.ServeHTTP(w, r)
	c.Assert(w.Code, Equals, http.StatusNoContent)

	w = httptest.NewRecorder()
	r, _ = http.NewRequest("POST", "https://idp.example.com/login",
		strings.NewReader("user=alice&password=hunter2"))
	r.Header.Set("Content-type", "application/x-www-form-urlencoded")
	test.Server.ServeHTTP(w, r)
	c.Assert(w.Code, Equals, http.StatusOK)

	w = httptest.NewRecorder()
	r, _ = http.NewRequest("GET", "https://idp.example.com/login/bob/whoami", nil)
	r.Header.Set("Cookie", "session=AAIEBggKDA4QEhQWGBocHiAiJCYoKiwuMDI0Njg6PD4=")
	test.Server.ServeHTTP(w, r)
	c.Assert(w.Code, Equals, http.StatusOK)
	body := string(w.Body.Bytes())
	c.Assert(strings.Contains(body, "<input type=\"hidden\" name=\"RelayState\" value=\"/whoami\" />"), Equals, true)
	c.Assert(strings.Contains(body, "<script>document.getElementById('SAMLResponseForm').submit();</script>"), Equals, true)
}
开发者ID:crewjam,项目名称:saml,代码行数:29,代码来源:shortcut_test.go

示例14: TestConfigureAcessToken

func TestConfigureAcessToken(t *testing.T) {
	t.Parallel()

	h, _ := newAppHarness(t)
	defer h.Stop()

	c := configureCmd{login: login{tokenReader: strings.NewReader("")}}
	h.env.In = ioutil.NopCloser(strings.NewReader("n\ntoken\n"))
	ensure.Nil(t, c.accessToken(h.env))
	ensure.DeepEqual(t,
		h.Out.String(),
		`Please enter an access token if you already generated it.
If you do not have an access token or would like to generate a new one,
please type: "y" to open the browser or "n" to continue: Access Token: Successfully stored credentials.
`,
	)
	h.env.In = ioutil.NopCloser(strings.NewReader("n\nemail\ninvalid\n"))
	ensure.Err(t, c.accessToken(h.env), regexp.MustCompile("Please try again"))
	ensure.DeepEqual(t,
		h.Err.String(),
		`Sorry, the access token you provided is not valid.
Please follow instructions at https://www.parse.com/account_keys to generate a new access token.
`,
	)
}
开发者ID:google2013,项目名称:parse-cli,代码行数:25,代码来源:configure_cmd_test.go

示例15: TestPostBadData

func TestPostBadData(t *testing.T) {
	handler := NewHandler("")

	req, _ := http.NewRequest("POST", "/", strings.NewReader("[]"))
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)

	if http.StatusInternalServerError != w.Code {
		t.Errorf(
			"Expected internal server error on non-\"dict\" post, got response\n%s",
			w.Body.String(),
		)
	}

	req, _ = http.NewRequest("POST", "/", strings.NewReader("500"))
	w = httptest.NewRecorder()
	handler.ServeHTTP(w, req)

	if http.StatusInternalServerError != w.Code {
		t.Errorf(
			"Expected internal server error on non-\"dict\" post, got response\n%s",
			w.Body.String(),
		)
	}

	req, _ = http.NewRequest("POST", "/", strings.NewReader(`{"from":"reader"}`))
	w = httptest.NewRecorder()
	handler.ServeHTTP(w, req)

	if http.StatusCreated != w.Code {
		t.Errorf("Expected %d on valid \"dict\" data, got %d", http.StatusCreated, w.Code)
	}
}
开发者ID:homburg,项目名称:adhocrest,代码行数:33,代码来源:rest_test.go


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