Ejemplo n.º 1
0
// Testing colors is kinda different. First we test for given colors and their
// escaped formatted results. Next we create some visual tests to be tested.
// Each visual test includes the color name to be compared.
func TestColor(t *testing.T) {
	rb := new(bytes.Buffer)
	Output = rb

	testColors := []struct {
		text string
		code Attribute
	}{
		{text: "black", code: FgBlack},
		{text: "red", code: FgRed},
		{text: "green", code: FgGreen},
		{text: "yellow", code: FgYellow},
		{text: "blue", code: FgBlue},
		{text: "magent", code: FgMagenta},
		{text: "cyan", code: FgCyan},
		{text: "white", code: FgWhite},
	}

	for _, c := range testColors {
		New(c.code).Print(c.text)

		line, _ := rb.ReadString('\n')
		scannedLine := fmt.Sprintf("%q", line)
		colored := fmt.Sprintf("\x1b[%dm%s\x1b[0m", c.code, c.text)
		escapedForm := fmt.Sprintf("%q", colored)

		fmt.Printf("%s\t: %s\n", c.text, line)

		if scannedLine != escapedForm {
			t.Errorf("Expecting %s, got '%s'\n", escapedForm, scannedLine)
		}
	}
}
Ejemplo n.º 2
0
Archivo: reader.go Proyecto: abema/m3u8
// Detect playlist type and decode it. May be used as decoder for both master and media playlists.
func decode(buf *bytes.Buffer, strict bool) (Playlist, ListType, error) {
	var eof bool
	var line string
	var master *MasterPlaylist
	var media *MediaPlaylist
	var listType ListType
	var err error

	state := new(decodingState)
	wv := new(WV)

	master = NewMasterPlaylist()
	media, err = NewMediaPlaylist(8, 1024) // TODO make it autoextendable
	if err != nil {
		return nil, 0, fmt.Errorf("Create media playlist failed: %s", err)
	}

	for !eof {
		if line, err = buf.ReadString('\n'); err == io.EOF {
			eof = true
		} else if err != nil {
			break
		}

		// fixes the issues https://github.com/grafov/m3u8/issues/25
		// TODO: the same should be done in decode functions of both Master- and MediaPlaylists
		// so some DRYing would be needed.
		if len(line) < 1 || line == "\r" {
			continue
		}

		err = decodeLineOfMasterPlaylist(master, state, line, strict)
		if strict && err != nil {
			return master, state.listType, err
		}

		err = decodeLineOfMediaPlaylist(media, wv, state, line, strict)
		if strict && err != nil {
			return media, state.listType, err
		}

	}
	if state.listType == MEDIA && state.tagWV {
		media.WV = wv
	}

	if strict && !state.m3u {
		return nil, listType, errors.New("#EXT3MU absent")
	}

	switch state.listType {
	case MASTER:
		return master, MASTER, nil
	case MEDIA:
		return media, MEDIA, nil
	default:
		return nil, state.listType, errors.New("Can't detect playlist type")
	}
	return nil, state.listType, errors.New("This return is impossible. Saved for compatibility with go 1.0")
}
Ejemplo n.º 3
0
Archivo: tests.go Proyecto: ohtufox/isa
// Start Selenium and wait for it to print some output before continuing.
func startSelenium() {
	var (
		out bytes.Buffer
		err error
	)

	cmd := exec.Command("java", "-jar", "selenium.jar")
	cmd.Stdout = &out

	if err = cmd.Start(); err != nil {
		log.Fatalln(err)
	}

	// Wait for Selenium to start
	start := time.Now()
	for line := ""; !strings.Contains(line, "SocketListener"); line, _ = out.ReadString('\n') {
		if time.Since(start) > time.Second*20 {
			stopSelenium()
			log.Println("FAIL: Starting selenium took too long")
			os.Exit(0) // XXX: There seems to be some bug preventing selenium from starting every now and then..
		}
		time.Sleep(time.Millisecond * 100)
		fmt.Print(".")
	}
	fmt.Println()
	time.Sleep(time.Millisecond * 1000)
	log.Println("Selenium is running")
}
Ejemplo n.º 4
0
// Helper function to handle log streams and massage them into a string representation.
func readerToChan(reader *bytes.Buffer, exit <-chan bool) <-chan string {
	c := make(chan string)

	go func() {
		for {
			select {
			case <-exit:
				close(c)
				return
			default:
				// This is going to keep our CPU limit down low.
				time.Sleep(100 * time.Millisecond)

				// This avoids issues when trying to ReadSring and causing a fatal.
				if reader.Len() <= 0 {
					continue
				}

				line, err := reader.ReadString('\n')
				if err != nil && err != io.EOF {
					close(c)
					return
				}

				line = strings.TrimSpace(line)
				if line != "" {
					c <- line
				}
			}
		}
	}()
	return c
}
Ejemplo n.º 5
0
func vstorageRunCmd(stdout io.Writer, args ...string) error {
	var stderr bytes.Buffer
	cmd := exec.Command("vstorage", args...)
	cmd.Stdout = stdout
	cmd.Stderr = &stderr

	logrus.Debugf("Run: %s\n", strings.Join([]string{cmd.Path, strings.Join(cmd.Args[1:], " ")}, " "))

	err := cmd.Run()
	if err == nil {
		return nil
	}

	// Command returned an error, get the first line of stderr
	errStr, _ := stderr.ReadString('\n')

	// Get the exit code (Unix-specific)
	if exiterr, ok := err.(*exec.ExitError); ok {
		if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
			errCode := status.ExitStatus()
			return &Err{c: errCode, s: errStr}
		}
	}
	// unknown exit code
	return &Err{c: -1, s: errStr}
}
Ejemplo n.º 6
0
func compareBuffers(t *testing.T, generatedFile string, existing, generated bytes.Buffer) bool {
	ok := true
	for {
		existingLine, existingErr := existing.ReadString('\n')
		generatedLine, generatedErr := generated.ReadString('\n')
		if existingErr == io.EOF && generatedErr == io.EOF {
			break
		}
		if existingErr != generatedErr {
			ok = false
			t.Errorf("reading errors: existing %v generated %v", existingErr, generatedErr)
			return ok
		}
		if existingErr != nil {
			ok = false
			t.Errorf("error while reading: %v", existingErr)
		}
		if existingLine != generatedLine {
			ok = false
			diff := fmt.Sprintf("\nexpected: %s\n     got: %s", generatedLine, existingLine)
			t.Errorf("please update conversion functions; generated: %s; first diff: %s", generatedFile, diff)
			return ok
		}
	}
	return ok
}
Ejemplo n.º 7
0
// Read a c string from the buffer
// and return a go-string without the NULL
// terminator
func rcstr(buf *bytes.Buffer) (string, error) {
	str, err := buf.ReadString(0x0)
	if err != nil {
		return str, err
	}
	return str[:len(str)-1], nil
}
Ejemplo n.º 8
0
func readCString(buffer *bytes.Buffer) (string, error) {
	name, err := buffer.ReadString('\000')
	if err == nil {
		name = name[:len(name)-1]
	}
	return name, err
}
Ejemplo n.º 9
0
func TestWriteCSV(t *testing.T) {
	d := []dumbStruct{
		{"Matt", "Palmer", 23, 40000.00},
		{"Robert", "Sesek", 23, 60000.00},
		{"Barack", "Obama", 51, 80000000.00},
		{"Mitt", "Romney", 59, 9950000000.00},
	}
	buf := new(bytes.Buffer)

	if err := WriteCSV(buf, d); err != nil {
		t.Fatalf("Unexpected error from WriteCSV: %v", err)
	}

	expected := []string{
		"FName,LName,Age,Worth\n",
		"Matt,Palmer,23,40000.00\n",
		"Robert,Sesek,23,60000.00\n",
		"Barack,Obama,51,80000000.00\n",
		"Mitt,Romney,59,9950000000.00\n",
	}
	for i := 0; i < 5; i++ {
		actual, err := buf.ReadString('\n')
		if err != nil {
			t.Fatalf("Unexpected output at line %d: %v", i, err)
		}
		if actual != expected[i] {
			t.Errorf("Row %d is wrong, expected %q, got %q", i, expected[i], actual)
		}
	}
	s, err := buf.ReadString('\n')
	if s != "" || err != io.EOF {
		t.Errorf("Got unexpected data %q where expected EOF", s)
	}
}
Ejemplo n.º 10
0
// parseThreadSample parses a symbolized or unsymbolized stack trace.
// Returns the first line after the traceback, the sample (or nil if
// it hits a 'same-as-previous' marker) and an error.
func parseThreadSample(b *bytes.Buffer) (nextl string, addrs []uint64, err error) {
	var l string
	sameAsPrevious := false
	for {
		if l, err = b.ReadString('\n'); err != nil {
			if err != io.EOF {
				return "", nil, err
			}
			if l == "" {
				break
			}
		}
		if l = strings.TrimSpace(l); l == "" {
			continue
		}

		if strings.HasPrefix(l, "---") {
			break
		}
		if strings.Contains(l, "same as previous thread") {
			sameAsPrevious = true
			continue
		}

		addrs = append(addrs, parseHexAddresses(l)...)
	}

	if sameAsPrevious {
		return l, nil, nil
	}
	return l, addrs, nil
}
Ejemplo n.º 11
0
func (gas *GameServer) acceptConn(c net.Conn) {
	fmt.Println("acceptConn")
	buf := make([]byte, common.BUF_SIZE)
	var data bytes.Buffer
	for {
		n, _ := c.Read(buf)
		if n == 0 {
			fmt.Println("close by peer")
			break
		}
		data.Write(buf[:n])

		cn := bytes.Count(data.Bytes(), []byte{common.DELIMITER})
		for ; cn > 0; cn-- {
			jn, err := data.ReadString(common.DELIMITER)
			fmt.Println(time.Now().String()[:19], jn)
			if err != nil {
				fmt.Println("err", err)
				continue
			}

			var unknow interface{}
			err = json.Unmarshal([]byte(jn), &unknow)
			if err != nil {
				fmt.Println("Unmarshal error")
				continue
			}

			switch unknow.(type) {
			case map[string]interface{}: //?
				gas.dispatchOp(unknow, c)
			}
		}
	}
}
Ejemplo n.º 12
0
func nextSSE(body *bytes.Buffer) []byte {
	// Have a deadline to make things easier to debug when there is an event
	// which never arrives.
	deadline := time.After(5 * time.Second)
	var data []byte
	for {
		line, err := body.ReadString(byte('\n'))
		if err != nil {
			if err != io.EOF {
				panic(err)
			}
			// Wait for some data to be written in the buffer. Buffers have no way of
			// signalling that data has been appended, so we just wait instead.
			select {
			case <-time.After(10 * time.Millisecond):
			case <-deadline:
				panic("Unable to get event, deadline exceeded.")
			}
			continue
		}
		if line == "\n" {
			break
		}
		if strings.HasPrefix(line, sseIDPrefix) {
			// drop it.
		} else if strings.HasPrefix(line, sseDataPrefix) {
			data = append(data, []byte(line[len(sseDataPrefix):])...)
		} else {
			panic(fmt.Sprintf("Unknown prefix; line: %q", line))
		}
	}
	return data
}
func aboutCommonInterfaces() {
	{
		in := new(bytes.Buffer)
		in.WriteString("hello world")

		out := new(bytes.Buffer)

		/*
		   Your code goes here.
		   Hint, use these resources:

		   $ godoc -http=:8080
		   $ open http://localhost:8080/pkg/io/
		   $ open http://localhost:8080/pkg/bytes/
		*/

		out.ReadFrom(in)
		assert(out.String() == "hello world") // get data from the io.Reader to the io.Writer
	}

	{
		in := new(bytes.Buffer)
		in.WriteString("hello world")

		out := new(bytes.Buffer)

		hello, _ := in.ReadString('o')
		out.WriteString(hello)
		assert(out.String() == "hello") // duplicate only a portion of the io.Reader
	}
}
Ejemplo n.º 14
0
func TestDelLogger(t *testing.T) {
	sink := new(bytes.Buffer)

	AddLogger("sinkDel", sink, DEBUG, false)

	testString := "test 123"
	testString2 := "test 456"

	Debug(testString)

	s, err := sink.ReadString('\n')
	if err != nil {
		t.Fatal(err)
	}

	if !strings.Contains(s, testString) {
		t.Fatal("sink got:", s)
	}

	DelLogger("sinkDel")

	Debug(testString2)

	s, err = sink.ReadString('\n')
	if err != nil && err != io.EOF {
		t.Fatal(err)
	}

	if len(s) != 0 {
		t.Fatal("sink got:", s)
	}
}
Ejemplo n.º 15
0
/*
Scenario: Plain text progress indicator
	Given a nested test group with 5 leaves
	When the tests finished but 3 of test panics
	Then I should see 2 dots with 3 F: "F.F.F"
*/
func Test3Pass2Fail(t *testing.T) {
	expect := exp.Alias(exp.TFail(t.FailNow))
	var buf bytes.Buffer
	NewController(NewTextProgresser(&buf)).Start(Path{}, true, func(s S) {
		g := s.Alias("")
		g("a", func() {
			g("a-b", func() {
			})
			g("a-c", func() {
				g("a-c-d", func() {
					s.Fail(errors.New("err: a-c-d"))
				})
			})
			g("a-e", func() {
				g("a-e-f", func() {
					s.Fail(errors.New("err: a-e-f"))
				})
				g("a-e-g", func() {
					s.Fail(errors.New("123"))
				})
			})
		})
		g("h", func() {
		})
	})
	out, _ := buf.ReadString('\n')
	expect(out).HasPrefix("^")
	expect(out).HasSuffix("$\n")
	out = out[1 : len(out)-2]
	expect(sortBytes(out)).Equal("..FFF")
}
Ejemplo n.º 16
0
func expect(expected string, buffer *bytes.Buffer, t *testing.T) {
	// Check whether the pid was reported
	recv, err := buffer.ReadString('\n')
	checkErr(err, t)
	if recv != expected+"\n" {
		t.Fatalf("Expected: %s, received: %s", expected, recv)
	}
}
Ejemplo n.º 17
0
func DecodeUpdate(data []byte) (add string, lang Lang) {
	var buff bytes.Buffer
	buff.Write(data)
	add, _ = buff.ReadString(ETB)
	add = strings.Replace(add, string(ETB), "", -1)
	lang = DecadeLang(buff.Bytes())
	return
}
Ejemplo n.º 18
0
func consumeValue(b *bytes.Buffer) (string, error) {
	value, err := b.ReadString(' ')
	if err != nil {
		return value, err
	}
	value = value[:len(value)-1]
	return value, nil
}
Ejemplo n.º 19
0
func consumeName(b *bytes.Buffer) (string, error) {
	name, err := b.ReadString('=')
	if err != nil {
		return name, err
	}
	name = name[:len(name)-1]
	return name, nil
}
Ejemplo n.º 20
0
func ParseString(data *bytes.Buffer) (string, uint32) {
	str, err := data.ReadString(0x0)
	if err != nil {
		panic("Could not parse string")
	}

	return str[:len(str)-1], uint32(len(str))
}
Ejemplo n.º 21
0
func tstring(t *testing.T, buff *bytes.Buffer, s string) {
	l, err := buff.ReadString('\n')
	if err != nil {
		t.Error(err)
	}
	if !strings.HasSuffix(l, s+"\n") {
		t.Errorf("Expected string to end with %s, found %s", s, l)
	}
}
Ejemplo n.º 22
0
func (d *Decoder) escapeString(Value string) string {
	var b *bytes.Buffer = bytes.NewBuffer([]byte{})
	var writer io.Writer = b
	var result string

	xml.Escape(writer, []byte(Value))
	result, _ = b.ReadString(0x00)

	return result
}
Ejemplo n.º 23
0
func parseMessage(buf *bytes.Buffer) []*Packet {
	var packetRegexp = regexp.MustCompile("^([^:]+):([0-9]+)\\|(g|c|ms)(\\|@([0-9\\.]+))?\n?$")

	var output []*Packet
	var err error
	var line string
	for {
		if err != nil {
			break
		}
		line, err = buf.ReadString('\n')
		if line != "" {
			item := packetRegexp.FindStringSubmatch(line)
			if len(item) == 0 {
				continue
			}

			var value interface{}
			modifier := item[3]
			switch modifier {
			case "c":
				value, err = strconv.ParseInt(item[2], 10, 64)
				if err != nil {
					log.Printf("ERROR: failed to ParseInt %s - %s", item[2], err.Error())
				}
			default:
				value, err = strconv.ParseUint(item[2], 10, 64)
				if err != nil {
					log.Printf("ERROR: failed to ParseUint %s - %s", item[2], err.Error())
				}
			}
			if err != nil {
				if modifier == "ms" {
					value = 0
				} else {
					value = 1
				}
			}

			sampleRate, err := strconv.ParseFloat(item[5], 32)
			if err != nil {
				sampleRate = 1
			}

			packet := &Packet{
				Bucket:   item[1],
				Value:    value,
				Modifier: modifier,
				Sampling: float32(sampleRate),
			}
			output = append(output, packet)
		}
	}
	return output
}
Ejemplo n.º 24
0
Archivo: reader.go Proyecto: dsnet/tar
// readGNUSparseMap1x0 reads the sparse map as stored in GNU's PAX sparse format
// version 1.0. The sparse map is stored just before the file data and padded
// out to the nearest block boundary.
//
// Note that the GNU manual says that numeric values should be encoded in octal
// format. However, the GNU tar utility itself outputs these values in decimal.
// As such, this library treats values as being encoded in decimal.
func readGNUSparseMap1x0(r io.Reader) (sparseDatas, error) {
	var cntNewline int64
	var buf bytes.Buffer
	var blk = make([]byte, blockSize)

	// feedTokens guarantees that at least cnt newlines exist in buf if there
	// are no errors encountered.
	var feedTokens = func(cnt int64) error {
		for cntNewline < cnt {
			if _, err := io.ReadFull(r, blk); err != nil {
				if err == io.EOF {
					err = io.ErrUnexpectedEOF
				}
				return err
			}
			buf.Write(blk)
			cntNewline += int64(bytes.Count(blk, []byte("\n")))
		}
		return nil
	}

	// nextToken gets the next token delimited by a newline. This assumes that
	// at least one newline exists in the buffer.
	var nextToken = func() string {
		cntNewline--
		tok, _ := buf.ReadString('\n')
		return tok[:len(tok)-1] // Cut off newline
	}

	// Parse for the number of entries.
	// Use integer overflow resistant math to check this.
	if err := feedTokens(1); err != nil {
		return nil, err
	}
	numEntries, err := strconv.ParseInt(nextToken(), 10, 0) // Intentionally parse as native int
	if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) {
		return nil, ErrHeader
	}

	// Parse for all member entries.
	if err := feedTokens(2 * numEntries); err != nil {
		return nil, err
	}
	var sp = make(sparseDatas, 0, numEntries) // numEntries is trusted now
	for i := int64(0); i < numEntries; i++ {
		offset, err1 := strconv.ParseInt(nextToken(), 10, 64)
		length, err2 := strconv.ParseInt(nextToken(), 10, 64)
		if err1 != nil || err2 != nil {
			return nil, ErrHeader
		}
		sp = append(sp, SparseEntry{Offset: offset, Length: length})
	}
	return sp, nil
}
Ejemplo n.º 25
0
func testb(b *testing.B, buf *bytes.Buffer, ss ...string) {
	str, err := buf.ReadString('\n')
	if err != nil {
		b.Error(e.Trace(e.Forward(err)))
	}
	for _, s := range ss {
		if !strings.Contains(str, s) {
			b.Error("log didn't log", str)
		}
	}
}
Ejemplo n.º 26
0
func handleInstallPlugin(b bytes.Buffer) {
	pluginName, err := b.ReadString(32)
	if err != nil {
		Log.WithFields(log.Fields{
			"pluginName": pluginName,
		}).Error("could not parse plugin name from invoker")
		return
	}
	pluginName = strings.TrimSpace(pluginName)
	pluginName = strings.ToLower(pluginName)
	InstallPlugin(pluginName)
}
Ejemplo n.º 27
0
func TestNoColor(t *testing.T) {
	rb := new(bytes.Buffer)
	Output = rb

	testColors := []struct {
		text string
		code Attribute
	}{
		{text: "black", code: FgBlack},
		{text: "red", code: FgRed},
		{text: "green", code: FgGreen},
		{text: "yellow", code: FgYellow},
		{text: "blue", code: FgBlue},
		{text: "magent", code: FgMagenta},
		{text: "cyan", code: FgCyan},
		{text: "white", code: FgWhite},
		{text: "hblack", code: FgHiBlack},
		{text: "hred", code: FgHiRed},
		{text: "hgreen", code: FgHiGreen},
		{text: "hyellow", code: FgHiYellow},
		{text: "hblue", code: FgHiBlue},
		{text: "hmagent", code: FgHiMagenta},
		{text: "hcyan", code: FgHiCyan},
		{text: "hwhite", code: FgHiWhite},
	}

	for _, c := range testColors {
		p := New(c.code)
		p.DisableColor()
		p.Print(c.text)

		line, _ := rb.ReadString('\n')
		if line != c.text {
			t.Errorf("Expecting %s, got '%s'\n", c.text, line)
		}
	}

	// global check
	NoColor = true
	defer func() {
		NoColor = false
	}()
	for _, c := range testColors {
		p := New(c.code)
		p.Print(c.text)

		line, _ := rb.ReadString('\n')
		if line != c.text {
			t.Errorf("Expecting %s, got '%s'\n", c.text, line)
		}
	}

}
Ejemplo n.º 28
0
func testerr(buf *bytes.Buffer, ss ...string) error {
	str, err := buf.ReadString('\n')
	if err != nil {
		return e.Forward(err)
	}
	for _, s := range ss {
		if !strings.Contains(str, s) {
			return e.New("log didn't log: %v", str)
		}
	}
	return nil
}
Ejemplo n.º 29
-7
Archivo: mpd.go Proyecto: mc2soft/mpd
// Encode generates MPD XML.
func (m *MPD) Encode() ([]byte, error) {
	x := new(bytes.Buffer)
	e := xml.NewEncoder(x)
	e.Indent("", "  ")
	err := e.Encode(m)
	if err != nil {
		return nil, err
	}

	// hacks for self-closing tags
	res := new(bytes.Buffer)
	res.WriteString(`<?xml version="1.0" encoding="utf-8"?>`)
	res.WriteByte('\n')
	for {
		s, err := x.ReadString('\n')
		if s != "" {
			s = emptyElementRE.ReplaceAllString(s, `/>`)
			res.WriteString(s)
		}
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}
	}
	res.WriteByte('\n')
	return res.Bytes(), err
}
Ejemplo n.º 30
-32
Archivo: reader.go Proyecto: abema/m3u8
func (p *MediaPlaylist) decode(buf *bytes.Buffer, strict bool) error {
	var eof bool
	var line string
	var err error

	state := new(decodingState)
	wv := new(WV)

	for !eof {
		if line, err = buf.ReadString('\n'); err == io.EOF {
			eof = true
		} else if err != nil {
			break
		}

		err = decodeLineOfMediaPlaylist(p, wv, state, line, strict)
		if strict && err != nil {
			return err
		}

	}
	if state.tagWV {
		p.WV = wv
	}
	if strict && !state.m3u {
		return errors.New("#EXT3MU absent")
	}
	return nil
}