Esempio n. 1
0
// this init function is deprecated, but I'm keeping it
// around just in case it proves useful in the future.
func deprecated_init() {
	// if piping from stdin we can just exit
	// and use the default Stdin value
	stat, _ := os.Stdin.Stat()
	if (stat.Mode() & os.ModeCharDevice) == 0 {
		return
	}

	// check for params after the double dash
	// in the command string
	for i, argv := range os.Args {
		if argv == "--" {
			arg := os.Args[i+1]
			buf := bytes.NewBufferString(arg)
			Stdin = NewParamSet(buf)
			return
		}
	}

	// else use the first variable in the list
	if len(os.Args) > 1 {
		buf := bytes.NewBufferString(os.Args[1])
		Stdin = NewParamSet(buf)
	}
}
Esempio n. 2
0
func TestDifferentStrings(t *testing.T) {
	s1 := "one\ntwo\nthree\nfour\n"
	s2 := "one\nTwo\nthree\nfore\n"
	a, b := bytes.NewBufferString(s1), bytes.NewBufferString(s2)

	diffs, err := text.Compare(a, b)

	if err != nil {
		t.Error(err)
	}
	if len(diffs) != 2 {
		t.Errorf("Expected 2 diffs, got %d", len(diffs))
	}

	if len(diffs) > 0 {
		ed := core.Diff{Expected: "two", Actual: "Two", Pos: []string{"2"}}
		ad := diffs[0]

		if !ad.Equals(ed) {
			t.Errorf("Expected %s but got %s", ed, ad)
		}
	}

	if len(diffs) > 1 {
		ed := core.Diff{Expected: "four", Actual: "fore", Pos: []string{"4"}}
		ad := diffs[1]

		if !ad.Equals(ed) {
			t.Errorf("Expected %s but got %s", ed, ad)
		}
	}
}
Esempio n. 3
0
func TestDelete(t *testing.T) {
	buf := bytes.NewBufferString("[general]\nfoo=bar\nfoo2=bar2\nfoo3=baz\n")
	cfg := ini.Parse(buf)
	cfg.Delete("general", "foo")
	out := new(bytes.Buffer)
	cfg.Write(out)
	correct := "[general]\nfoo2=bar2\nfoo3=baz\n\n"

	if s := out.String(); s != correct {
		t.Errorf("Incorrect INI after delete:\n%s", s)
	}

	buf = bytes.NewBufferString("[general]\nfoo=bar\nfoo2=bar2\nfoo3=baz\n")
	cfg = ini.Parse(buf)
	cfg.Delete("general", "foo2")
	out = new(bytes.Buffer)
	cfg.Write(out)
	correct = "[general]\nfoo=bar\nfoo3=baz\n\n"

	if s := out.String(); s != correct {
		t.Errorf("Incorrect INI after delete:\n%s", s)
	}

	buf = bytes.NewBufferString("[general]\nfoo=bar\nfoo2=bar2\nfoo3=baz\n")
	cfg = ini.Parse(buf)
	cfg.Delete("general", "foo3")
	out = new(bytes.Buffer)
	cfg.Write(out)
	correct = "[general]\nfoo=bar\nfoo2=bar2\n\n"

	if s := out.String(); s != correct {
		t.Errorf("Incorrect INI after delete:\n%s", s)
	}
}
Esempio n. 4
0
func (s *S) TestAddPool(c *check.C) {
	b := bytes.NewBufferString("name=pool1")
	req, err := http.NewRequest("POST", "/pools", b)
	c.Assert(err, check.IsNil)
	req.Header.Set("Authorization", "bearer "+s.token.GetValue())
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec := httptest.NewRecorder()
	defer provision.RemovePool("pool1")
	m := RunServer(true)
	m.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusCreated)
	c.Assert(err, check.IsNil)
	pools, err := provision.ListPools(bson.M{"_id": "pool1"})
	c.Assert(err, check.IsNil)
	c.Assert(pools, check.HasLen, 1)
	b = bytes.NewBufferString("name=pool2&public=true")
	req, err = http.NewRequest("POST", "/pools", b)
	c.Assert(err, check.IsNil)
	req.Header.Set("Authorization", "bearer "+s.token.GetValue())
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec = httptest.NewRecorder()
	defer provision.RemovePool("pool2")
	m.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusCreated)
	pools, err = provision.ListPools(bson.M{"_id": "pool2"})
	c.Assert(err, check.IsNil)
	c.Assert(pools[0].Public, check.Equals, true)
}
Esempio n. 5
0
func TestSimpleString(t *testing.T) {
	var data string
	msg := bytes.NewBufferString("+This is a simple string\r\n+This simple string\rfails\r\n")
	err := Scan(msg, &data)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("%q", data)

	err = Scan(msg, &data)
	if err != ErrMalformedSimpleString {
		t.Fatal("simple string containing \\r did not fail")
	} else {
		t.Logf("err=%v", err)
	}
	t.Logf("%q", data)

	msg = bytes.NewBufferString("+This simple string fails because of a \n\r\n")
	err = Scan(msg, &data)
	if err != ErrMalformedSimpleString {
		t.Fatal("simple string containing \\n did not fail")
	} else {
		t.Logf("err=%v", err)
	}
	t.Logf("%q", data)
}
Esempio n. 6
0
func singReqDep(url, ryaml, dyaml string) (*dtos.SingularityRequestParent, error) {
	h := &http.Client{}
	ru := url + `/api/requests`
	du := url + `/api/deploys`

	rrz, err := h.Post(ru, `application/json`, bytes.NewBufferString(ryaml))
	if err != nil {
		return nil, err
	}
	logBody("POST /api/requests", rrz)

	dqz, err := h.Post(du, `application/json`, bytes.NewBufferString(dyaml))
	if err != nil {
		return nil, err
	}
	logBody("POST /api/deploys", dqz)

	rqz, err := h.Get(ru)

	time.Sleep(3 * time.Second)

	resBody := logBody("GET /api/requests", rqz)

	var sr dtos.SingularityRequestParentList
	sr.Populate(resBody)

	return sr[0], nil
}
Esempio n. 7
0
func TestJSON(t *testing.T) {
	wantMap := map[string]interface{}{
		"a": "aye",
		"b": "bee",
		"c": "see",
	}
	wantArray := []interface{}{"1", "2", "3"}

	tests := [][2]interface{}{
		{`{"a":"aye","b":"bee","c":"see"}`, wantMap},
		{[]byte(`{"a":"aye","b":"bee","c":"see"}`), wantMap},
		{bytes.NewBufferString(`{"a":"aye","b":"bee","c":"see"}`), wantMap},
		{`["1", "2", "3"]`, wantArray},
		{[]byte(`["1", "2", "3"]`), wantArray},
		{bytes.NewBufferString(`["1", "2", "3"]`), wantArray},
	}

	for _, test := range tests {
		if have, err := JSON(test[0]); err == nil {
			want := test[1]
			if !reflect.DeepEqual(have, want) {
				t.Error("output invalid:")
				t.Errorf("  have: %+v\n", have)
				t.Errorf("  want: %+v\n", want)
			}
		} else {
			t.Error(err)
		}
	}
}
Esempio n. 8
0
func compare(
	original string,
	modified string,
	block_size uint,
) (results <-chan BlockMatchResult, err error) {

	originalFileContent := bytes.NewBufferString(original)
	generator := filechecksum.NewFileChecksumGenerator(block_size)

	_, reference, _, err := indexbuilder.BuildChecksumIndex(
		generator,
		originalFileContent,
	)

	if err != nil {
		return
	}

	modifiedContent := bytes.NewBufferString(modified)

	results = (&Comparer{}).StartFindMatchingBlocks(
		modifiedContent,
		0,
		generator,
		reference,
	)

	return
}
Esempio n. 9
0
func (res digDnsResolver) runCommand(cmdName string, args ...string) (stdout, stderr string, err error) {
	res.logger.Debug("Dig Dns Resolver", "Running command: %s %s", cmdName, strings.Join(args, " "))
	cmd := exec.Command(cmdName, args...)

	stdoutWriter := bytes.NewBufferString("")
	stderrWriter := bytes.NewBufferString("")
	cmd.Stdout = stdoutWriter
	cmd.Stderr = stderrWriter

	err = cmd.Start()
	if err != nil {
		err = bosherr.WrapError(err, "Starting dig command")
		return
	}

	err = cmd.Wait()
	stdout = string(stdoutWriter.Bytes())
	stderr = string(stderrWriter.Bytes())

	res.logger.Debug("Cmd Runner", "Stdout: %s", stdout)
	res.logger.Debug("Cmd Runner", "Stderr: %s", stderr)
	res.logger.Debug("Cmd Runner", "Successful: %t", err == nil)

	if err != nil {
		err = bosherr.WrapError(err, "Waiting for dig command")
	}
	return
}
Esempio n. 10
0
func runCmd(cmdName string, args []string, cmdHook func(*exec.Cmd)) (stdout, stderr string, err error) {
	cmd := exec.Command(cmdName, args...)
	cmdString := strings.Join(append([]string{cmdName}, args...), " ")

	stdoutWriter := bytes.NewBufferString("")
	stderrWriter := bytes.NewBufferString("")
	cmd.Stdout = stdoutWriter
	cmd.Stderr = stderrWriter

	if cmdHook != nil {
		cmdHook(cmd)
	}

	err = cmd.Start()
	if err != nil {
		err = bosherr.WrapError(err, fmt.Sprintf("Error starting command %s", cmdString))
		return
	}

	err = cmd.Wait()
	stdout = string(stdoutWriter.Bytes())
	stderr = string(stderrWriter.Bytes())
	if err != nil {
		err = bosherr.WrapError(err, fmt.Sprintf("Error running command: '%s', stdout: '%s', stderr: '%s'",
			cmdString, stdout, stderr))
	}
	return
}
Esempio n. 11
0
File: ot_test.go Progetto: kpmy/ot
func TestGenerate(t *testing.T) {
	const testTemplate = `
	html:
		body: br awef wef "fwef'wef" 22323 0.1112 49U true false nil inf -inf
		;
	;`

	p := otp.ConnectTo(ots.ConnectTo(bufio.NewReader(bytes.NewBufferString(testTemplate))))
	if tpl, err := p.Template(); err == nil {
		m := conv.Map(tpl)
		conv.Resolve(m)

		buf := bytes.NewBuffer(nil)
		otg.ConnectTo(buf).Write(m)
		s := buf.String()
		t.Log(s)
		p0 := otp.ConnectTo(ots.ConnectTo(bufio.NewReader(bytes.NewBufferString(s))))
		if tpl0, err0 := p0.Template(); err0 == nil {
			m0 := conv.Map(tpl0)
			conv.Resolve(m0)
			prettyPrintObject(m0, t)
		}
	} else {
		t.Fatal(err)
	}
	{
		buf := bytes.NewBuffer(nil)
		otg.ConnectTo(buf).Write(conv.Begin(otm.Qualident{Class: "test"}).Value("asdf asdf asdf `asdfasdf").Value([]uint8{0, 1, 2, 3, 4}).End())
		s := buf.String()
		t.Log(s)
	}
}
Esempio n. 12
0
func TestRenderPlainAndHtmlText(t *testing.T) {
	plainBody := "你好 from message1, should show in plain text"
	htmlBody := "<h2>你好 from message1, should show in html text</h2>"
	testDate, _ := time.Parse("2006-Jan-02", "2014-Feb-23")
	message := &Message{
		From:      "*****@*****.**",
		To:        []string{"*****@*****.**", "*****@*****.**"},
		Subject:   "这个是第11封from message1, single connection",
		PlainBody: bytes.NewBufferString(plainBody),
		HtmlBody:  bytes.NewBufferString(htmlBody),
		Date:      testDate,
		MessageId: "*****@*****.**",
	}

	b, _ := message.RenderData()
	recipient := string(b)

	if !strings.Contains(recipient, plainBody) {
		t.Errorf("should have plain body: %s \n", plainBody)
	}

	if !strings.Contains(recipient, htmlBody) {
		t.Errorf("should have html body: %s \n", htmlBody)
	}

	if !strings.Contains(recipient, "Date: Sun, 23 Feb 2014 00:00:00 GMT") {
		t.Error("Message should have the Date header set")
	}

	if !strings.Contains(recipient, "Message-Id: <*****@*****.**>") {
		t.Error("Message should have the Message-Id header set")
	}
}
Esempio n. 13
0
func MakeSummary(post Mapper, lines int, topCtx mustache.Context) string {
	content := post["_content"].(*DocContent).Source
	r := bufio.NewReader(bytes.NewBufferString(content))
	dst := ""
	for lines > 0 {
		line, _ := r.ReadString('\n')
		dst += line
		lines--
		if lines == 0 {
			for "" != strings.Trim(line, "\r\n\t ") {
				line, _ = r.ReadString('\n')
				dst += line
			}
		}
	}
	str, err := mustache.RenderString(dst, topCtx)
	if err != nil {
		log.Println("BAD Mustache after Summary cut!")
		str, err = mustache.RenderString(dst, topCtx)
		if err != nil {
			log.Println("BAD Mustache Summary?", err)
			str = post["_content"].(*DocContent).Main
		}
	}
	mdParser := markdown.NewParser(&markdown.Extensions{Smart: true})
	buf := bytes.NewBuffer(nil)
	mdParser.Markdown(bytes.NewBufferString(str), markdown.ToHTML(buf))
	return buf.String()
}
Esempio n. 14
0
func searchColors(text string, clean bool) string {
	if text == "" {
		return ""
	}

	closed := true
	input := bytes.NewBufferString(text)
	output := bytes.NewBufferString("")

	for {
		i, _, err := input.ReadRune()

		if err != nil {
			break
		}

		switch i {
		case '{':
			closed = replaceColorTags(input, output, clean)
		case rune(65533):
			continue
		default:
			output.WriteRune(i)
		}
	}

	if !closed {
		output.WriteString(_CODE_RESET)
	}

	return output.String()
}
Esempio n. 15
0
func TestClient_syncStreams(t *testing.T) {
	client, server := TestPluginRPCConn(t, map[string]Plugin{})

	// Create streams for the server that we can talk to
	stdout_r, stdout_w := io.Pipe()
	stderr_r, stderr_w := io.Pipe()
	server.Stdout = stdout_r
	server.Stderr = stderr_r

	// Start the data copying
	var stdout_out, stderr_out bytes.Buffer
	stdout := bytes.NewBufferString("stdouttest")
	stderr := bytes.NewBufferString("stderrtest")
	go client.SyncStreams(&stdout_out, &stderr_out)
	go io.Copy(stdout_w, stdout)
	go io.Copy(stderr_w, stderr)

	// Unfortunately I can't think of a better way to make sure all the
	// copies above go through so let's just exit.
	time.Sleep(100 * time.Millisecond)

	// Close everything, and lets test the result
	client.Close()
	stdout_w.Close()
	stderr_w.Close()

	if v := stdout_out.String(); v != "stdouttest" {
		t.Fatalf("bad: %s", v)
	}
	if v := stderr_out.String(); v != "stderrtest" {
		t.Fatalf("bad: %s", v)
	}
}
Esempio n. 16
0
func (run execCmdRunner) runCmd(cmd *exec.Cmd) (stdout, stderr string, err error) {
	cmdString := strings.Join(cmd.Args, " ")

	run.logger.Debug("Cmd Runner", "Running command: %s", cmdString)

	stdoutWriter := bytes.NewBufferString("")
	stderrWriter := bytes.NewBufferString("")
	cmd.Stdout = stdoutWriter
	cmd.Stderr = stderrWriter

	err = cmd.Start()
	if err != nil {
		err = bosherr.WrapError(err, "Starting command %s", cmdString)
		return
	}

	err = cmd.Wait()
	stdout = string(stdoutWriter.Bytes())
	stderr = string(stderrWriter.Bytes())

	run.logger.Debug("Cmd Runner", "Stdout: %s", stdout)
	run.logger.Debug("Cmd Runner", "Stderr: %s", stderr)
	run.logger.Debug("Cmd Runner", "Successful: %t", err == nil)

	if err != nil {
		err = bosherr.WrapError(err, "Running command: '%s', stdout: '%s', stderr: '%s'", cmdString, stdout, stderr)
	}
	return
}
Esempio n. 17
0
// issue #342, #371
func (self *SingleServerSuite) TestDataResurrectionAfterRestart(c *C) {
	s := CreatePoints("data_resurrection", 1, 10)
	self.server.WriteData(s, c)
	self.server.WaitForServerToSync()
	fmt.Printf("wrote some data\n")
	series := self.server.RunQuery("select count(column0) from data_resurrection", "s", c)
	c.Assert(series, HasLen, 1)
	c.Assert(series[0].Points[0][1], Equals, 10.0)
	req, err := http.NewRequest("DELETE", "http://localhost:8086/db/db1?u=root&p=root", nil)
	c.Assert(err, IsNil)
	resp, err := http.DefaultClient.Do(req)
	c.Assert(err, IsNil)
	c.Assert(resp.StatusCode, Equals, http.StatusNoContent)
	resp, err = http.Post("http://localhost:8086/db?u=root&p=root", "", bytes.NewBufferString("{\"name\":\"db1\", \"replicationFactor\":3}"))
	c.Assert(err, IsNil)
	defer resp.Body.Close()
	c.Assert(resp.StatusCode, Equals, http.StatusCreated)
	resp, err = http.Post("http://localhost:8086/db/db1/users?u=root&p=root", "", bytes.NewBufferString("{\"name\":\"user\", \"password\":\"pass\"}"))
	c.Assert(err, IsNil)
	defer resp.Body.Close()
	c.Assert(resp.StatusCode, Equals, http.StatusOK)
	self.server.Stop()
	c.Assert(self.server.Start(), IsNil)
	self.server.WaitForServerToStart()
	series = self.server.RunQuery("select count(column0) from data_resurrection", "s", c)
	c.Assert(series, HasLen, 0)
	series = self.server.RunQuery("list series", "s", c)
	c.Assert(series, HasLen, 0)
}
Esempio n. 18
0
func TestJsonTwoMetrics(t *testing.T) {
	c := Client{}
	c.Config()

	// Client store metrics in a map which are not ordered

	resp := `{"metrics":[{"name":"test","measurements":[{"ts":11111,"values":[1234]},{"ts":11111,"values":[456]}],"mtype":"timer"},{"name":"test2","measurements":[{"ts":11111,"values":[1234]},{"ts":11111,"values":[456]}],"mtype":"timer"}]}`
	resp2 := `{"metrics":[{"name":"test2","measurements":[{"ts":11111,"values":[1234]},{"ts":11111,"values":[456]}],"mtype":"timer"},{"name":"test","measurements":[{"ts":11111,"values":[1234]},{"ts":11111,"values":[456]}],"mtype":"timer"}]}`

	c.Timer("test").RecordWithTs(11111, 1234)
	c.Timer("test").RecordWithTs(11111, 456)
	c.Timer("test2").RecordWithTs(11111, 1234)
	c.Timer("test2").RecordWithTs(11111, 456)

	js, err := c.toJson()

	if err != nil {
		t.Fail()
	}

	if js != resp+"\n" && js != resp2+"\n" {
		t.Logf("\n%q\n%q", bytes.NewBufferString(js), bytes.NewBufferString(resp))
		t.Fail()
	}
}
Esempio n. 19
0
func (s *HandlersSuite) TestAddNodeHandlerWithInvalidURLAddress(c *check.C) {
	config.Set("docker:cluster:redis-server", "127.0.0.1:6379")
	defer config.Unset("docker:cluster:redis-server")
	b := bytes.NewBufferString(`{"address": "/invalid", "pool": "pool1"}`)
	req, err := http.NewRequest("POST", "/docker/node?register=true", b)
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	err = addNodeHandler(rec, req, nil)
	c.Assert(err, check.IsNil)
	var result map[string]string
	err = json.NewDecoder(rec.Body).Decode(&result)
	c.Assert(err, check.IsNil)
	c.Assert(rec.Code, check.Equals, http.StatusBadRequest)
	c.Assert(result["error"], check.Matches, "Invalid address url: host cannot be empty")
	b = bytes.NewBufferString(`{"address": "xxx://abc/invalid", "pool": "pool1"}`)
	req, err = http.NewRequest("POST", "/docker/node?register=true", b)
	c.Assert(err, check.IsNil)
	rec = httptest.NewRecorder()
	err = addNodeHandler(rec, req, nil)
	c.Assert(err, check.IsNil)
	err = json.NewDecoder(rec.Body).Decode(&result)
	c.Assert(err, check.IsNil)
	c.Assert(rec.Code, check.Equals, http.StatusBadRequest)
	c.Assert(result["error"], check.Matches, `Invalid address url: scheme must be http\[s\]`)
}
Esempio n. 20
0
func tableFormat(ctx FormattingContext, containers []docker.APIContainers) {

	var (
		buffer = bytes.NewBufferString("")
		tmpl   = ctx.Template
	)

	for index, container := range containers {
		containerCtx := &ContainerFormatter{
			trunc: ctx.Trunc,
			c:     container,
		}
		//Ugly!!
		//The lengh of both tags must be the same or the column will be displaced
		//because template execution happens before markup interpretation.
		if index == ctx.Selected {
			buffer.WriteString("<white>")
		} else {
			if IsContainerRunning(container) {
				buffer.WriteString("<cyan0>")
			} else {
				buffer.WriteString("<grey2>")
			}
		}
		if err := tmpl.Execute(buffer, containerCtx); err != nil {
			buffer = bytes.NewBufferString(fmt.Sprintf("Template parsing error: %v\n", err))
			buffer.WriteTo(ctx.Output)
			return
		}

		buffer.WriteString("</>")
		buffer.WriteString("\n")
	}
	buffer.WriteTo(ctx.Output)
}
Esempio n. 21
0
func (l *LibSuite) TestReadRowsFromSheetWithMergeCells(c *C) {
	var sharedstringsXML = bytes.NewBufferString(`
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="3" uniqueCount="3">
  <si>
    <t>Value A</t>
  </si>
  <si>
    <t>Value B</t>
  </si>
  <si>
    <t>Value C</t>
  </si>
</sst>
`)
	var sheetxml = bytes.NewBufferString(`
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mv="urn:schemas-microsoft-com:mac:vml" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">
  <sheetViews>
    <sheetView workbookViewId="0"/>
  </sheetViews>
  <sheetFormatPr customHeight="1" defaultColWidth="17.29" defaultRowHeight="15.0"/>
  <cols>
    <col customWidth="1" min="1" max="6" width="14.43"/>
  </cols>
  <sheetData>
    <row r="1" ht="15.75" customHeight="1">
      <c r="A1" s="1" t="s">
        <v>0</v>
      </c>
    </row>
    <row r="2" ht="15.75" customHeight="1">
      <c r="A2" s="1" t="s">
        <v>1</v>
      </c>
      <c r="B2" s="1" t="s">
        <v>2</v>
      </c>
    </row>
  </sheetData>
  <mergeCells count="1">
    <mergeCell ref="A1:B1"/>
  </mergeCells>
  <drawing r:id="rId1"/>
</worksheet>`)
	worksheet := new(xlsxWorksheet)
	err := xml.NewDecoder(sheetxml).Decode(worksheet)
	c.Assert(err, IsNil)
	sst := new(xlsxSST)
	err = xml.NewDecoder(sharedstringsXML).Decode(sst)
	c.Assert(err, IsNil)
	file := new(File)
	file.referenceTable = MakeSharedStringRefTable(sst)
	sheet := new(Sheet)
	rows, _, _, _ := readRowsFromSheet(worksheet, file, sheet)
	row := rows[0] //
	cell1 := row.Cells[0]
	c.Assert(cell1.HMerge, Equals, 1)
	c.Assert(cell1.VMerge, Equals, 0)
}
Esempio n. 22
0
func (c *Cli) makeRequestWithContent(method string, uri string, content string) (*http.Response, error) {
	buffer := bytes.NewBufferString(content)
	req, _ := http.NewRequest(method, uri, buffer)

	log.Info("%s %s", req.Method, req.URL.String())
	if log.IsEnabledFor(logging.DEBUG) {
		logBuffer := bytes.NewBuffer(make([]byte, 0, len(content)))
		req.Write(logBuffer)
		log.Debug("%s", logBuffer)
		// need to recreate the buffer since the offset is now at the end
		// need to be able to rewind the buffer offset, dont know how yet
		req, _ = http.NewRequest(method, uri, bytes.NewBufferString(content))
	}

	if resp, err := c.makeRequest(req); err != nil {
		return nil, err
	} else {
		if resp.StatusCode == 401 {
			if err := c.CmdLogin(); err != nil {
				return nil, err
			}
			req, _ = http.NewRequest(method, uri, bytes.NewBufferString(content))
			return c.makeRequest(req)
		}
		return resp, err
	}
}
Esempio n. 23
0
func TestPutObject(t *testing.T) {
	gs, bucket := doConfig(t)

	now := time.Now()
	testKey := fmt.Sprintf("test-put-%v.%v.%v-%v.%v.%v",
		now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())

	shouldRetry, err := gs.PutObject(&Object{bucket, testKey},
		&BufferCloser{bytes.NewBufferString(testObjectContent)})
	if shouldRetry {
		shouldRetry, err = gs.PutObject(&Object{bucket, testKey},
			&BufferCloser{bytes.NewBufferString(testObjectContent)})
	}
	if err != nil {
		t.Fatalf("Failed to put object: %v", err)
	}

	// Just stat to check that it actually uploaded, don't bother reading back
	size, exists, err := gs.StatObject(&Object{bucket, testKey})
	if !exists {
		t.Errorf("Test object doesn't exist!")
	}
	if size != int64(len(testObjectContent)) {
		t.Errorf("Test object size is wrong: \nexpected: %v\nfound: %v\n",
			len(testObjectContent), size)
	}
}
Esempio n. 24
0
func TestFindIDInConfigurationsPayload(t *testing.T) {
	const (
		searchedName = "search-for-this-name"
		expected     = "The-42-id"
	)
	assert := assert.New(t)

	c := Client{}

	payload := fmt.Sprintf(
		`[{"dataset_id": "1-2-3", "metadata": {"name": "test"}}, {"dataset_id": "The-42-id", "metadata": {"name": "%s"}}]`,
		searchedName,
	)

	id, err := c.findIDInConfigurationsPayload(
		ioutil.NopCloser(bytes.NewBufferString(payload)), searchedName,
	)
	assert.NoError(err)
	assert.Equal(expected, id)

	id, err = c.findIDInConfigurationsPayload(
		ioutil.NopCloser(bytes.NewBufferString(payload)), "it will not be found",
	)
	assert.Equal(errConfigurationNotFound, err)

	id, err = c.findIDInConfigurationsPayload(
		ioutil.NopCloser(bytes.NewBufferString("invalid { json")), "",
	)
	assert.Error(err)
}
Esempio n. 25
0
func TestStrList(t *testing.T) {
	{
		msg := bytes.NewBufferString("*4\r\n+Key 1\r\n$4\r\n1234\r\n$5\r\nKey 2\r\n$8\r\n45678910\r\n")
		resp := Read(msg)
		if resp.Err != nil {
			t.Error(resp.Err)
			goto next
		}

		bl, err := resp.StrList()
		t.Logf("%#v", bl)
		if err != nil {
			t.Error("unexpected error converting string array to string list:", err)
		}
	}

next:
	{
		msg := bytes.NewBufferString("*4\r\n+Key 1\r\n$4\r\n1234\r\n$5\r\nKey 2\r\n:45678910\r\n")
		resp := Read(msg)
		if resp.Err != nil {
			t.Error(resp.Err)
			return
		}

		bl, err := resp.StrList()
		t.Logf("%#v err=%v", bl, err)
		if err == nil {
			t.Errorf("expected error in converting array of mixed types to string list")
		}
	}
}
Esempio n. 26
0
func (s *headersSuite) TestAppendEntryOmitting(c *C) {
	buf := bytes.NewBufferString("start: .")

	asserts.AppendEntry(buf, "bar:", []interface{}{}, 0)

	m, err := asserts.ParseHeaders(buf.Bytes())
	c.Assert(err, IsNil)
	c.Check(m, DeepEquals, map[string]interface{}{
		"start": ".",
	})

	lst := []interface{}{nil, []interface{}{}, "z"}

	buf = bytes.NewBufferString("start: .")

	asserts.AppendEntry(buf, "bar:", lst, 0)

	m, err = asserts.ParseHeaders(buf.Bytes())
	c.Assert(err, IsNil)
	c.Check(m, DeepEquals, map[string]interface{}{
		"start": ".",
		"bar":   []interface{}{"z"},
	})

	buf = bytes.NewBufferString("start: .")

	asserts.AppendEntry(buf, "bar:", map[string]interface{}{}, 0)

	m, err = asserts.ParseHeaders(buf.Bytes())
	c.Assert(err, IsNil)
	c.Check(m, DeepEquals, map[string]interface{}{
		"start": ".",
	})
}
Esempio n. 27
0
func TestShorterThanExpectedString(t *testing.T) {
	s1 := "one\ntwo\nthree\nfour\n"
	s2 := "one\ntwo\nthree\n"
	a, b := bytes.NewBufferString(s1), bytes.NewBufferString(s2)

	diffs, err := text.Compare(a, b)

	if err != nil {
		t.Error(err)
	}

	if len(diffs) != 1 {
		t.Errorf("Expected 1 diffs, got %d", len(diffs))
		for _, d := range diffs {
			t.Errorf(d.String())
		}
	}

	if len(diffs) > 0 {
		ed := core.Diff{Expected: "four", Actual: nil, Pos: []string{"4"}}
		ad := diffs[0]

		if !ad.Equals(ed) {
			t.Errorf("Expected %s but got %s", ed, ad)
		}
	}
}
Esempio n. 28
0
func TestAdminAdd(t *testing.T) {
	Convey("Test Admin Add Api", t, func() {
		bf := bytes.NewBufferString("topic=foo")
		body := ioutil.NopCloser(bf)
		req, err := http.NewRequest(
			"PUT",
			"http://127.0.0.1:8800/v1/queues",
			body,
		)
		So(err, ShouldBeNil)
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

		resp, err := client.Do(req)
		So(err, ShouldBeNil)
		So(resp.StatusCode, ShouldEqual, http.StatusCreated)

		bf = bytes.NewBufferString("topic=foo&line=x&recycle=10s")
		body = ioutil.NopCloser(bf)
		req, err = http.NewRequest(
			"PUT",
			"http://127.0.0.1:8800/v1/queues",
			body,
		)
		So(err, ShouldBeNil)
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

		resp, err = client.Do(req)
		So(err, ShouldBeNil)
		So(resp.StatusCode, ShouldEqual, http.StatusCreated)
	})
}
Esempio n. 29
0
func (o *Otama) Exists(id string) (r bool, err error) {
	var otama_id C.otama_id_t
	var ret C.otama_status_t
	var result C.int

	ret = C.otama_id_hexstr2bin(&otama_id, C.CString(id))
	if ret != C.OTAMA_STATUS_OK {
		buf := bytes.NewBufferString("Exists otama_id_hexstr2bin: ")
		buf.WriteString(get_status_message(ret))
		err = errors.New(buf.String())
		return false, err
	}

	ret = C.otama_exists(o.otama, &result, &otama_id)
	if ret != C.OTAMA_STATUS_OK {
		buf := bytes.NewBufferString("Exists otama_exists: ")
		buf.WriteString(get_status_message(ret))
		err = errors.New(buf.String())
		return false, err
	}

	if int(result) == 0 {
		return false, err
	}
	return true, err
}
Esempio n. 30
0
func (c createImageRequest) MarshalJSON() ([]byte, error) {
	output_buffer := bytes.NewBufferString(`{"createImage":{`)
	output_buffer.WriteString(fmt.Sprintf(`"name": "%s"`, c.C.Name))
	if c.C.Metadata != nil && len(*c.C.Metadata) > 0 {
		metadata_buffer := bytes.NewBufferString("metadata:{")
		cnt := 0
		for k, v := range *c.C.Metadata {
			if len(k) > 255 {
				return nil, errors.New(fmt.Sprintf("Key: %s has a length >255", k))
			}
			if len(v) > 255 {
				return nil, errors.New(fmt.Sprintf("Value: %s has a length >255", v))
			}
			metadata_buffer.WriteString(
				fmt.Sprintf(`"%s":"%s"`, k, v),
			)
			if cnt+1 != len(*c.C.Metadata) {
				metadata_buffer.WriteString(",")
				cnt++
			} else {
				metadata_buffer.WriteString("}")
			}
		}
		output_buffer.WriteString(",")
		output_buffer.WriteString(metadata_buffer.String())
	}
	output_buffer.WriteString("}}")
	return output_buffer.Bytes(), nil
}