Ejemplo n.º 1
5
//水印
func waterMark(picBytes []byte) []byte {
	// 打开水印图并解码
	img, fileType, _ := image.Decode(bytes.NewBuffer(picBytes))

	//读取水印图片
	watermark, _ := png.Decode(bytes.NewBuffer(wm))

	//原始图界限
	origin_size := img.Bounds()

	//创建新图层
	canvas := image.NewNRGBA(origin_size)

	//贴原始图
	draw.Draw(canvas, origin_size, img, image.ZP, draw.Src)
	//贴水印图
	draw.Draw(canvas, watermark.Bounds().Add(image.Pt(origin_size.Dx()-watermark.Bounds().Dx(), origin_size.Dy()-watermark.Bounds().Dy()-4)), watermark, image.ZP, draw.Over)

	//生成新图片
	buff := bytes.NewBuffer([]byte{})

	switch fileType {
	case "jpeg":
		jpeg.Encode(buff, canvas, &jpeg.Options{95})
	default:
		png.Encode(buff, canvas)
	}

	return buff.Bytes()
}
Ejemplo n.º 2
2
func postContainerExecCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := parseForm(r); err != nil {
		return nil
	}
	var (
		name         = vars["name"]
		job          = eng.Job("execCreate", name)
		stdoutBuffer = bytes.NewBuffer(nil)
		outWarnings  []string
		warnings     = bytes.NewBuffer(nil)
	)

	if err := job.DecodeEnv(r.Body); err != nil {
		return err
	}

	job.Stdout.Add(stdoutBuffer)
	// Read warnings from stderr
	job.Stderr.Add(warnings)
	// Register an instance of Exec in container.
	if err := job.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "Error setting up exec command in container %s: %s\n", name, err)
		return err
	}
	// Parse warnings from stderr
	scanner := bufio.NewScanner(warnings)
	for scanner.Scan() {
		outWarnings = append(outWarnings, scanner.Text())
	}

	return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{
		ID:       engine.Tail(stdoutBuffer, 1),
		Warnings: outWarnings,
	})
}
Ejemplo n.º 3
1
Archivo: task.go Proyecto: psev/atom
func (self *Task) Render() {
	for _, config := range self.Config.Templates {
		log.Printf("Render: %s", config.Dst)
		f, err := ioutil.ReadFile(self.Controller.Atom.Config.TmplDir + "/" + config.Src)
		if err != nil {
			log.Printf("Error:: Read - %s", err)
			continue
		}
		var output *bytes.Buffer
		if self.Controller.Atom.Config.Verbose {
			output = bytes.NewBuffer(nil)
		}
		src := bytes.NewBuffer(f)
		tmpl, err := template.New("").Funcs(self.Config.Store.FuncMap).Parse(src.String())
		if err != nil {
			log.Printf("Error:: Render - %s", err)
			continue
		}
		vars := map[string]interface{}{"cli": self.Controller.Atom.CLI}
		if self.Controller.Atom.Config.Verbose {
			if err := tmpl.Execute(output, vars); err != nil {
				log.Printf("Error:: Write - %s", err)
			}
			fmt.Print(output.String())
		}
		dst, err := os.Create(config.Dst)
		if err != nil {
			log.Printf("Error:: Open - %s", err)
			continue
		}
		if err := tmpl.Execute(dst, vars); err != nil {
			log.Printf("Error:: Write - %s", err)
		}
	}
}
Ejemplo n.º 4
1
func TestDecrypterClose(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "")
	assert.NoError(t, err)

	cd := newCloseDetector(bytes.NewBuffer(file16))
	fh, err := c.newDecrypter(cd)
	assert.NoError(t, err)
	assert.Equal(t, 0, cd.closed)

	// close before reading
	assert.Equal(t, nil, fh.err)
	err = fh.Close()
	assert.Equal(t, ErrorFileClosed, fh.err)
	assert.Equal(t, 1, cd.closed)

	// double close
	err = fh.Close()
	assert.Error(t, err, ErrorFileClosed.Error())
	assert.Equal(t, 1, cd.closed)

	// try again reading the file this time
	cd = newCloseDetector(bytes.NewBuffer(file1))
	fh, err = c.newDecrypter(cd)
	assert.NoError(t, err)
	assert.Equal(t, 0, cd.closed)

	// close after reading
	out, err := ioutil.ReadAll(fh)
	assert.NoError(t, err)
	assert.Equal(t, []byte{1}, out)
	assert.Equal(t, io.EOF, fh.err)
	err = fh.Close()
	assert.Equal(t, ErrorFileClosed, fh.err)
	assert.Equal(t, 1, cd.closed)
}
Ejemplo n.º 5
1
func (s *archiveDataSuite) SetUpTest(c *gc.C) {
	s.IsolationSuite.SetUpTest(c)

	meta, err := backups.NewMetadataJSONReader(bytes.NewBufferString(`{` +
		`"ID":"20140909-115934.asdf-zxcv-qwe",` +
		`"Checksum":"123af2cef",` +
		`"ChecksumFormat":"SHA-1, base64 encoded",` +
		`"Size":10,` +
		`"Stored":"0001-01-01T00:00:00Z",` +
		`"Started":"2014-09-09T11:59:34Z",` +
		`"Finished":"2014-09-09T12:00:34Z",` +
		`"Notes":"",` +
		`"Environment":"asdf-zxcv-qwe",` +
		`"Machine":"0",` +
		`"Hostname":"myhost",` +
		`"Version":"1.21-alpha3"` +
		`}` + "\n"))
	c.Assert(err, jc.ErrorIsNil)

	archiveFile := s.newArchiveFile(c, meta)
	compressed, err := ioutil.ReadAll(archiveFile)
	c.Assert(err, jc.ErrorIsNil)
	gzr, err := gzip.NewReader(bytes.NewBuffer(compressed))
	c.Assert(err, jc.ErrorIsNil)
	data, err := ioutil.ReadAll(gzr)
	c.Assert(err, jc.ErrorIsNil)

	s.archiveFile = bytes.NewBuffer(compressed)
	s.data = data
	s.meta = meta
}
Ejemplo n.º 6
1
func postContainersCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := parseForm(r); err != nil {
		return nil
	}
	var (
		out          engine.Env
		job          = eng.Job("create", r.Form.Get("name"))
		outWarnings  []string
		stdoutBuffer = bytes.NewBuffer(nil)
		warnings     = bytes.NewBuffer(nil)
	)
	if err := job.DecodeEnv(r.Body); err != nil {
		return err
	}
	// Read container ID from the first line of stdout
	job.Stdout.Add(stdoutBuffer)
	// Read warnings from stderr
	job.Stderr.Add(warnings)
	if err := job.Run(); err != nil {
		return err
	}
	// Parse warnings from stderr
	scanner := bufio.NewScanner(warnings)
	for scanner.Scan() {
		outWarnings = append(outWarnings, scanner.Text())
	}
	out.Set("Id", engine.Tail(stdoutBuffer, 1))
	out.SetList("Warnings", outWarnings)
	return writeJSON(w, http.StatusCreated, out)
}
Ejemplo n.º 7
1
func TestTeeReader(t *testing.T) {
	src := []byte("hello, world")
	dst := make([]byte, len(src))
	rb := bytes.NewBuffer(src)
	wb := new(bytes.Buffer)
	r := TeeReader(rb, wb)
	if n, err := ReadFull(r, dst); err != nil || n != len(src) {
		t.Fatalf("ReadFull(r, dst) = %d, %v; want %d, nil", n, err, len(src))
	}
	if !bytes.Equal(dst, src) {
		t.Errorf("bytes read = %q want %q", dst, src)
	}
	if !bytes.Equal(wb.Bytes(), src) {
		t.Errorf("bytes written = %q want %q", wb.Bytes(), src)
	}
	if n, err := r.Read(dst); n != 0 || err != EOF {
		t.Errorf("r.Read at EOF = %d, %v want 0, EOF", n, err)
	}
	rb = bytes.NewBuffer(src)
	pr, pw := Pipe()
	pr.Close()
	r = TeeReader(rb, pw)
	if n, err := ReadFull(r, dst); n != 0 || err != ErrClosedPipe {
		t.Errorf("closed tee: ReadFull(r, dst) = %d, %v; want 0, EPIPE", n, err)
	}
}
Ejemplo n.º 8
0
func (c *CrittercismAPIClient) RawRequest(method, path string, params *CrittercismAPIParams, handler CrittercismAPIClientResponseHandler) {
	// Construct REST Request
	url := fmt.Sprintf("%s/%s", crittercismAPIURL, path)

	var buffer *bytes.Buffer

	if params != nil {
		p, err := json.Marshal(map[string]interface{}{"params": params})

		if err != nil {
			handler(nil, err)
			return
		}

		buffer = bytes.NewBuffer(p)
	} else {
		buffer = bytes.NewBuffer([]byte{})
	}

	client := &http.Client{}
	req, _ := http.NewRequest(method, url, buffer)
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.accessToken))
	req.Header.Set("Content-Type", "application/json")

	// Make Request
	resp, err := client.Do(req)

	handler(resp, err)
}
Ejemplo n.º 9
0
func TestDeleteDirectory(t *testing.T) {
	_, _, rc := testData()

	f, tf, codec, _ := cmdtesting.NewAPIFactory()
	tf.Printer = &testPrinter{}
	tf.Client = &fake.RESTClient{
		NegotiatedSerializer: unstructuredSerializer,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			switch p, m := req.URL.Path, req.Method; {
			case strings.HasPrefix(p, "/namespaces/test/replicationcontrollers/") && m == "DELETE":
				return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil
			default:
				t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
				return nil, nil
			}
		}),
	}
	tf.Namespace = "test"
	buf, errBuf := bytes.NewBuffer([]byte{}), bytes.NewBuffer([]byte{})

	cmd := NewCmdDelete(f, buf, errBuf)
	cmd.Flags().Set("filename", "../../../examples/guestbook/legacy")
	cmd.Flags().Set("cascade", "false")
	cmd.Flags().Set("output", "name")
	cmd.Run(cmd, []string{})

	if buf.String() != "replicationcontroller/frontend\nreplicationcontroller/redis-master\nreplicationcontroller/redis-slave\n" {
		t.Errorf("unexpected output: %s", buf.String())
	}
}
Ejemplo n.º 10
0
func TestDeleteObjectIgnoreNotFound(t *testing.T) {
	f, tf, _, _ := cmdtesting.NewAPIFactory()
	tf.Printer = &testPrinter{}
	tf.Client = &fake.RESTClient{
		NegotiatedSerializer: unstructuredSerializer,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			switch p, m := req.URL.Path, req.Method; {
			case p == "/namespaces/test/replicationcontrollers/redis-master" && m == "DELETE":
				return &http.Response{StatusCode: 404, Header: defaultHeader(), Body: stringBody("")}, nil
			default:
				t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
				return nil, nil
			}
		}),
	}
	tf.Namespace = "test"
	buf, errBuf := bytes.NewBuffer([]byte{}), bytes.NewBuffer([]byte{})

	cmd := NewCmdDelete(f, buf, errBuf)
	cmd.Flags().Set("filename", "../../../examples/guestbook/legacy/redis-master-controller.yaml")
	cmd.Flags().Set("cascade", "false")
	cmd.Flags().Set("ignore-not-found", "true")
	cmd.Flags().Set("output", "name")
	cmd.Run(cmd, []string{})

	if buf.String() != "" {
		t.Errorf("unexpected output: %s", buf.String())
	}
}
Ejemplo n.º 11
0
func TestDeleteObjectNotFound(t *testing.T) {
	f, tf, _, _ := cmdtesting.NewAPIFactory()
	tf.Printer = &testPrinter{}
	tf.Client = &fake.RESTClient{
		NegotiatedSerializer: unstructuredSerializer,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			switch p, m := req.URL.Path, req.Method; {
			case p == "/namespaces/test/replicationcontrollers/redis-master" && m == "DELETE":
				return &http.Response{StatusCode: 404, Header: defaultHeader(), Body: stringBody("")}, nil
			default:
				t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
				return nil, nil
			}
		}),
	}
	tf.Namespace = "test"
	buf, errBuf := bytes.NewBuffer([]byte{}), bytes.NewBuffer([]byte{})

	cmd := NewCmdDelete(f, buf, errBuf)
	options := &resource.FilenameOptions{}
	options.Filenames = []string{"../../../examples/guestbook/legacy/redis-master-controller.yaml"}
	cmd.Flags().Set("cascade", "false")
	cmd.Flags().Set("output", "name")
	err := RunDelete(f, buf, errBuf, cmd, []string{}, options)
	if err == nil || !errors.IsNotFound(err) {
		t.Errorf("unexpected error: expected NotFound, got %v", err)
	}
}
Ejemplo n.º 12
0
func TestBufAPI(t *testing.T) {
	s := "0<a>1</a>2<b>3<a>4<a>5</a>6</b>7</a>8<a/>9"
	z := NewTokenizer(bytes.NewBuffer([]byte(s)))
	result := bytes.NewBuffer(nil)
	depth := 0
loop:
	for {
		tt := z.Next()
		switch tt {
		case ErrorToken:
			if z.Error() != os.EOF {
				t.Error(z.Error())
			}
			break loop
		case TextToken:
			if depth > 0 {
				result.Write(z.Text())
			}
		case StartTagToken, EndTagToken:
			tn, _ := z.TagName()
			if len(tn) == 1 && tn[0] == 'a' {
				if tt == StartTagToken {
					depth++
				} else {
					depth--
				}
			}
		}
	}
	u := "14567"
	v := string(result.Bytes())
	if u != v {
		t.Errorf("TestBufAPI: want %q got %q", u, v)
	}
}
Ejemplo n.º 13
0
func TestOutput(t *testing.T) {
	Convey("Default output rendering", t, func() {
		b := bytes.NewBuffer(nil)
		o := NewMonochromeOutput(b)
		o.Printf("With <headline>formatted<reset> input")
		So(b.String(), ShouldEqual, "With formatted input")
	})
	Convey("Fancy output rendering", t, func() {
		b := bytes.NewBuffer(nil)
		o := NewColorOutput(b)
		o.Printf("With <headline>formatted<reset> input")
		So(b.String(), ShouldEqual, "With \033[4;1mformatted\033[0m input")
	})
	Convey("Custom output rendering", t, func() {
		b := bytes.NewBuffer(nil)
		o := NewOutput(b, &testCustomFormatter{})
		o.Printf("With <headline>formatted<reset> input")
		So(b.String(), ShouldEqual, "WITH <HEADLINE>FORMATTED<RESET> INPUT")
	})
	Convey("Switching formatter later on", t, func() {
		b := bytes.NewBuffer(nil)
		o := NewMonochromeOutput(b)
		o.SetFormatter(&testCustomFormatter{})
		o.Printf("With <headline>formatted<reset> input")
		So(b.String(), ShouldEqual, "WITH <HEADLINE>FORMATTED<RESET> INPUT")
	})
	Convey("Multi-line rendering", t, func() {
		b := bytes.NewBuffer(nil)
		o := NewColorOutput(b)
		o.Printf("With <headline>formatted\nfoo\nbar\nbaz<reset> input")
		s := o.Sprintf("With <headline>formatted\nfoo\nbar\nbaz<reset> input")
		So(b.String(), ShouldEqual, "With \033[4;1mformatted\nfoo\nbar\nbaz\033[0m input")
		So(b.String(), ShouldEqual, s)
	})
}
Ejemplo n.º 14
0
func TestMultiLogger_Log(t *testing.T) {
	b1 := bytes.NewBuffer(nil)
	b2 := bytes.NewBuffer(nil)

	l1 := log.NewJSONLogger(b1)
	l2 := log.NewJSONLogger(b2)

	l := sklog.NewMultiLogger(l1, l2)

	sklog.Debug(l, "debug message")
	sklog.Info(l, "info message")
	sklog.Error(l, errors.New("sklog_test: example error message"))

	assert.Equal(t, b1.String(), b2.String())

	b1.Reset()
	b2.Reset()

	l1 = &faultyLogger{}
	l2 = log.NewJSONLogger(b2)

	l = sklog.NewMultiLogger(l1, l2)

	sklog.Debug(l, "debug message")
	sklog.Info(l, "info message")
	sklog.Error(l, errors.New("sklog_test: example error message"))

	assert.Contains(t, b2.String(), "debug message")
	assert.Contains(t, b2.String(), "msg")
	assert.Contains(t, b2.String(), "info message")
	assert.Contains(t, b2.String(), "info")
	assert.Contains(t, b2.String(), "debug")
	assert.Contains(t, b2.String(), "sklog_test: example error message")

}
Ejemplo n.º 15
0
func TestReadBytes(t *testing.T) {
	var bs []byte

	// data[0:4] gets interpreted as a big-endian int (=4) which specifies the number of bytes to be read
	// bytes data are then data[1:5], since int32(data[0:4])==4)
	data := []byte{0, 0, 0, 4, 1, 2, 3, 4}
	rdr := bytes.NewBuffer(data)

	bs, err = ReadBytes(rdr)
	ok(t, err)
	equals(t, 4, len(bs))
	equals(t, byte(1), bs[0])
	equals(t, byte(2), bs[1])
	equals(t, byte(3), bs[2])
	equals(t, byte(4), bs[3])

	// ensure more than 4 entries are not read
	data = []byte{0, 0, 0, 4, 1, 2, 3, 4, 5, 6}
	rdr = bytes.NewBuffer(data)

	bs, err = ReadBytes(rdr)
	ok(t, err)
	equals(t, 4, len(bs))
	equals(t, byte(1), bs[0])
	equals(t, byte(2), bs[1])
	equals(t, byte(3), bs[2])
	equals(t, byte(4), bs[3])
}
Ejemplo n.º 16
0
func (self *Shard) deleteRangeOfSeriesCommon(database, series string, startTimeBytes, endTimeBytes []byte) error {
	columns := self.getColumnNamesForSeries(database, series)
	fields, err := self.getFieldsForSeries(database, series, columns)
	if err != nil {
		// because a db is distributed across the cluster, it's possible we don't have the series indexed here. ignore
		switch err := err.(type) {
		case FieldLookupError:
			return nil
		default:
			return err
		}
	}
	startKey := bytes.NewBuffer(nil)
	endKey := bytes.NewBuffer(nil)
	for _, field := range fields {
		startKey.Reset()
		startKey.Write(field.Id)
		startKey.Write(startTimeBytes)
		startKey.Write([]byte{0, 0, 0, 0, 0, 0, 0, 0})
		endKey.Reset()
		endKey.Write(field.Id)
		endKey.Write(endTimeBytes)
		endKey.Write([]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff})

		err := self.db.Del(startKey.Bytes(), endKey.Bytes())
		if err != nil {
			return err
		}
	}
	return nil
}
Ejemplo n.º 17
0
func TestSnapshot_BadMethods(t *testing.T) {
	httpTest(t, func(srv *HTTPServer) {
		body := bytes.NewBuffer(nil)
		req, err := http.NewRequest("POST", "/v1/snapshot", body)
		if err != nil {
			t.Fatalf("err: %v", err)
		}

		resp := httptest.NewRecorder()
		_, err = srv.Snapshot(resp, req)
		if err != nil {
			t.Fatalf("err: %v", err)
		}
		if resp.Code != 405 {
			t.Fatalf("bad code: %d", resp.Code)
		}
	})

	httpTest(t, func(srv *HTTPServer) {
		body := bytes.NewBuffer(nil)
		req, err := http.NewRequest("DELETE", "/v1/snapshot", body)
		if err != nil {
			t.Fatalf("err: %v", err)
		}

		resp := httptest.NewRecorder()
		_, err = srv.Snapshot(resp, req)
		if err != nil {
			t.Fatalf("err: %v", err)
		}
		if resp.Code != 405 {
			t.Fatalf("bad code: %d", resp.Code)
		}
	})
}
Ejemplo n.º 18
0
func TestDeleteNamedObject(t *testing.T) {
	_, _, rc := testData()

	f, tf, codec, _ := cmdtesting.NewAPIFactory()
	tf.Printer = &testPrinter{}
	tf.Client = &fake.RESTClient{
		NegotiatedSerializer: unstructuredSerializer,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			switch p, m := req.URL.Path, req.Method; {
			case p == "/namespaces/test/replicationcontrollers/redis-master-controller" && m == "DELETE":
				return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil
			default:
				// Ensures no GET is performed when deleting by name
				t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
				return nil, nil
			}
		}),
	}
	tf.Namespace = "test"
	buf, errBuf := bytes.NewBuffer([]byte{}), bytes.NewBuffer([]byte{})

	cmd := NewCmdDelete(f, buf, errBuf)
	cmd.Flags().Set("namespace", "test")
	cmd.Flags().Set("cascade", "false")
	cmd.Flags().Set("output", "name")
	cmd.Run(cmd, []string{"replicationcontrollers", "redis-master-controller"})

	if buf.String() != "replicationcontroller/redis-master-controller\n" {
		t.Errorf("unexpected output: %s", buf.String())
	}
}
Ejemplo n.º 19
0
func BenchmarkDecodeStruct(b *testing.B) {
	type s1 struct {
		Atom   types.Atom
		priv0  int
		Uint8  uint8
		Uint16 uint16
		Uint32 uint32
		priv1  string
		Byte   byte
		Int    int
		priv2  *s1
		List   []s1
		Binary []byte
	}

	data := []byte{
		131, 104, 8, 100, 0, 12, 116, 104, 105, 115, 32, 105, 115, 32, 97, 116, 111,
		109, 97, 255, 98, 0, 0, 255, 255, 110, 4, 0, 255, 255, 255, 255, 97, 128, 98,
		255, 255, 253, 102, 106, 107, 0, 5, 1, 2, 3, 4, 5,
	}
	in := bytes.NewBuffer(data)

	var v s1
	err := Decode(in, &v)
	if err != nil {
		b.Fatal(err)
	} else if l := in.Len(); l != 0 {
		b.Fatalf("buffer len %d", l)
	}

	for i := 0; i < b.N; i++ {
		in = bytes.NewBuffer(data)
		err = Decode(in, &v)
	}
}
Ejemplo n.º 20
0
func newStdBuffers() *stdBuffers {
	return &stdBuffers{
		Stdin:  bytes.NewBuffer(nil),
		Stdout: bytes.NewBuffer(nil),
		Stderr: bytes.NewBuffer(nil),
	}
}
Ejemplo n.º 21
0
func TestEncryptData(t *testing.T) {
	for _, test := range []struct {
		in       []byte
		expected []byte
	}{
		{[]byte{}, file0},
		{[]byte{1}, file1},
		{[]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, file16},
	} {
		c, err := newCipher(NameEncryptionStandard, "", "")
		assert.NoError(t, err)
		c.cryptoRand = newRandomSource(1E8) // nodge the crypto rand generator

		// Check encode works
		buf := bytes.NewBuffer(test.in)
		encrypted, err := c.EncryptData(buf)
		assert.NoError(t, err)
		out, err := ioutil.ReadAll(encrypted)
		assert.NoError(t, err)
		assert.Equal(t, test.expected, out)

		// Check we can decode the data properly too...
		buf = bytes.NewBuffer(out)
		decrypted, err := c.DecryptData(ioutil.NopCloser(buf))
		assert.NoError(t, err)
		out, err = ioutil.ReadAll(decrypted)
		assert.NoError(t, err)
		assert.Equal(t, test.in, out)
	}
}
Ejemplo n.º 22
0
func Test030LexingPauseAndResume(t *testing.T) {

	cv.Convey(`to enable the repl to properly detect the end of a multiline expression (or an expression containing quoted parentheses), the lexer should be able to pause and resume when more input is available.`, t, func() {

		str := `(defn hello [] "greetings!(((")`
		str1 := `(defn hel`
		str2 := `lo [] "greetings!(((")`
		env := NewGlisp()
		defer env.parser.Stop()
		stream := bytes.NewBuffer([]byte(str1))
		env.parser.ResetAddNewInput(stream)
		ex, err := env.parser.ParseTokens()

		P("\n In lexer_test, after parsing with incomplete input, we should get 0 expressions back.\n")
		cv.So(len(ex), cv.ShouldEqual, 0)
		P("\n In lexer_test, after ParseTokens on incomplete fragment, expressions = '%v' and err = '%v'\n", (&SexpArray{Val: ex, Env: env}).SexpString(nil), err)

		P("\n In lexer_test: calling parser.NewInput() to provide str2='%s'\n", str2)
		env.parser.NewInput(bytes.NewBuffer([]byte(str2)))
		P("\n In lexer_test: done with parser.NewInput(), now calling parser.ParseTokens()\n")
		ex, err = env.parser.ParseTokens()
		P(`
 in lexer test: After providing the 2nd half of the input, we returned from env.parser.ParseTokens()
 with expressions = %v
 with err = %v
`, (&SexpArray{Val: ex, Env: env}).SexpString(nil), err)

		cv.So(len(ex), cv.ShouldEqual, 1)
		panicOn(err)

		P("str=%s\n", str)
	})
}
Ejemplo n.º 23
0
func TestDeleteNoObjects(t *testing.T) {
	f, tf, codec := NewAPIFactory()
	tf.Printer = &testPrinter{}
	tf.Client = &client.FakeRESTClient{
		Codec: codec,
		Client: client.HTTPClientFunc(func(req *http.Request) (*http.Response, error) {
			switch p, m := req.URL.Path, req.Method; {
			case p == "/ns/test/pods" && m == "GET":
				return &http.Response{StatusCode: 200, Body: objBody(codec, &api.PodList{})}, nil
			default:
				t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
				return nil, nil
			}
		}),
	}
	buf := bytes.NewBuffer([]byte{})
	stderr := bytes.NewBuffer([]byte{})

	cmd := f.NewCmdDelete(buf)
	cmd.SetOutput(stderr)
	cmd.Flags().String("namespace", "test", "")
	cmd.Run(cmd, []string{"pods"})

	if buf.String() != "" {
		t.Errorf("unexpected output: %s", buf.String())
	}
	if stderr.String() != "No resources found\n" {
		t.Errorf("unexpected output: %s", stderr.String())
	}
}
Ejemplo n.º 24
0
func testRun(t *testing.T, imageName string, commands []string, expectedStdout string, expectedStderr string) {
	client, err := newTestDockerClient()
	require.NoError(t, err)
	err = client.Pull(imageName, PullOptions{})
	require.NoError(t, err)
	containers, err := client.Create(
		imageName,
		CreateOptions{
			HasCommand: commands != nil,
		},
	)
	require.NoError(t, err)
	require.Equal(t, 1, len(containers))
	container := containers[0]
	err = client.Start(
		container,
		StartOptions{
			Commands: commands,
		},
	)
	require.NoError(t, err)
	err = client.Wait(container, WaitOptions{})
	require.NoError(t, err)
	stdout := bytes.NewBuffer(nil)
	stderr := bytes.NewBuffer(nil)
	err = client.Logs(container, LogsOptions{Stdout: stdout, Stderr: stderr})
	require.NoError(t, err)
	require.Equal(t, expectedStdout, stdout.String())
	require.Equal(t, expectedStderr, stderr.String())
	err = client.Remove(container, RemoveOptions{})
	require.NoError(t, err)
}
Ejemplo n.º 25
0
func TestString(t *testing.T) {
	s := MakeString([]byte(HARDSQL))
	b := bytes.NewBuffer(nil)
	s.EncodeSql(b)
	if b.String() != HARDESCAPED {
		t.Errorf("Expecting %s, received %s", HARDESCAPED, b.String())
	}
	b = bytes.NewBuffer(nil)
	s.EncodeAscii(b)
	if b.String() != HARDASCII {
		t.Errorf("Expecting %s, received %#v", HARDASCII, b.String())
	}
	s = MakeString([]byte("abcd"))

	// Now, just printable strings.
	s, err := BuildValue(PRINTABLE)
	if err != nil {
		t.Errorf("BuildValue failed on printable: %s", PRINTABLE)
	}
	b = bytes.NewBuffer(nil)
	s.EncodeSql(b)
	if b.String() != PRINTABLE_ESCAPED {
		t.Errorf("Expecting %s, received %s", PRINTABLE_ESCAPED, b.String())
	}
	b = bytes.NewBuffer(nil)
	s.EncodeAscii(b)
	if b.String() != PRINTABLE_ASCII {
		t.Errorf("Expecting %s, received %#v", PRINTABLE_ASCII, b.String())
	}
}
Ejemplo n.º 26
0
func TestBulkSetAckRead(t *testing.T) {
	vs := New(&Config{MsgRing: &msgRingPlaceholder{}})
	for i := 0; i < len(vs.bulkSetAckState.inBulkSetAckDoneChans); i++ {
		vs.bulkSetAckState.inMsgChan <- nil
	}
	for _, doneChan := range vs.bulkSetAckState.inBulkSetAckDoneChans {
		<-doneChan
	}
	n, err := vs.newInBulkSetAckMsg(bytes.NewBuffer(make([]byte, 100)), 100)
	if err != nil {
		t.Fatal(err)
	}
	if n != 100 {
		t.Fatal(n)
	}
	<-vs.bulkSetAckState.inMsgChan
	// Once again, but with an error in the body.
	n, err = vs.newInBulkSetAckMsg(bytes.NewBuffer(make([]byte, 10)), 100)
	if err != io.EOF {
		t.Fatal(err)
	}
	if n != 10 {
		t.Fatal(n)
	}
	select {
	case bsam := <-vs.bulkSetAckState.inMsgChan:
		t.Fatal(bsam)
	default:
	}
}
// Body makes the request use obj as the body. Optional.
// If obj is a string, try to read a file of that name.
// If obj is a []byte, send it directly.
// If obj is an io.Reader, use it directly.
// If obj is a runtime.Object, marshal it correctly.
// Otherwise, set an error.
func (r *Request) Body(obj interface{}) *Request {
	if r.err != nil {
		return r
	}
	switch t := obj.(type) {
	case string:
		data, err := ioutil.ReadFile(t)
		if err != nil {
			r.err = err
			return r
		}
		r.body = bytes.NewBuffer(data)
	case []byte:
		r.body = bytes.NewBuffer(t)
	case io.Reader:
		r.body = t
	case runtime.Object:
		data, err := r.codec.Encode(t)
		if err != nil {
			r.err = err
			return r
		}
		r.body = bytes.NewBuffer(data)
	default:
		r.err = fmt.Errorf("unknown type used for body: %+v", obj)
	}
	return r
}
Ejemplo n.º 28
0
func (s *ConfigSuite) TestDefaultType(c *gc.C) {
	assertDefault := func(type_ string, value string, expected interface{}) {
		config := fmt.Sprintf(`options: {t: {type: %s, default: %s}}`, type_, value)
		result, err := charm.ReadConfig(bytes.NewBuffer([]byte(config)))
		c.Assert(err, gc.IsNil)
		c.Assert(result.Options["t"].Default, gc.Equals, expected)
	}

	assertDefault("boolean", "true", true)
	assertDefault("string", "golden grahams", "golden grahams")
	assertDefault("string", `""`, "")
	assertDefault("float", "2.2e11", 2.2e11)
	assertDefault("int", "99", int64(99))

	assertTypeError := func(type_, str, value string) {
		config := fmt.Sprintf(`options: {t: {type: %s, default: %s}}`, type_, str)
		_, err := charm.ReadConfig(bytes.NewBuffer([]byte(config)))
		expected := fmt.Sprintf(`invalid config default: option "t" expected %s, got %s`, type_, value)
		c.Assert(err, gc.ErrorMatches, expected)
	}

	assertTypeError("boolean", "henry", `"henry"`)
	assertTypeError("string", "2.5", "2.5")
	assertTypeError("float", "123", "123")
	assertTypeError("int", "true", "true")
}
Ejemplo n.º 29
0
func saveServices(passwd string, services *Services) {
	sort.Sort(services)
	decryptedBuffer := bytes.NewBuffer(nil)
	err := json.NewEncoder(decryptedBuffer).Encode(services)
	gobro.CheckErr(err)

	blockCipher, err := blowfish.NewCipher([]byte(passwd))
	gobro.CheckErr(err)
	iv := make([]byte, 8)
	_, err = rand.Read(iv)
	gobro.CheckErr(err)

	enc := decryptedBuffer.Bytes()
	cipher.NewCFBEncrypter(blockCipher, iv).XORKeyStream(enc, enc)
	buff := bytes.NewBuffer(iv)
	_, err = buff.Write(enc)
	gobro.CheckErr(err)

	enc = append(iv, enc...)
	base64EncodedLen := base64.StdEncoding.EncodedLen(len(enc))
	base64Enc := make([]byte, base64EncodedLen)
	base64.StdEncoding.Encode(base64Enc, enc)

	err = ioutil.WriteFile(passwdFileName(), base64Enc, os.ModePerm)
	gobro.CheckErr(err)
}
Ejemplo n.º 30
0
func TestLogTapper(t *testing.T) {
	c := newBufferLogger()
	tapped := newLogTapper(c)

	assertWrite(t, tapped.Stdout(), "First line")

	r1 := tapped.TapStdout()
	b1 := bytes.NewBuffer(nil)
	done1 := make(chan error)
	go func() {
		defer close(done1)
		_, err := io.Copy(b1, r1)
		if err != nil {
			done1 <- err
		}
	}()

	assertWrite(t, tapped.Stdout(), "Second line")

	r2 := tapped.TapStdout()
	b2 := bytes.NewBuffer(nil)
	done2 := make(chan error)
	go func() {
		defer close(done2)
		_, err := io.Copy(b2, r2)
		if err != nil {
			done2 <- err
		}
	}()

	assertWrite(t, tapped.Stdout(), "Third line")

	if err := r2.Close(); err != nil {
		t.Fatal(err)
	}

	<-done2

	assertWrite(t, tapped.Stdout(), "Fourth line")

	if err := tapped.Close(); err != nil {
		t.Fatal(err)
	}

	<-done1

	expectedAll := []byte(`First line
Second line
Third line
Fourth line
`)

	expected1 := []byte("Second line\nThird line\nFourth line\n")
	expected2 := []byte("Third line\n")

	checkBuffer(t, c.stdout, expectedAll)
	checkBuffer(t, b1, expected1)
	checkBuffer(t, b2, expected2)

}