Commit 45ca9f7a authored by Robert Griesemer's avatar Robert Griesemer

1) Change default gofmt default settings for

   parsing and printing to new syntax.

   Use -oldparser to parse the old syntax,
   use -oldprinter to print the old syntax.

2) Change default gofmt formatting settings
   to use tabs for indentation only and to use
   spaces for alignment. This will make the code
   alignment insensitive to an editor's tabwidth.

   Use -spaces=false to use tabs for alignment.

3) Manually changed src/exp/parser/parser_test.go
   so that it doesn't try to parse the parser's
   source files using the old syntax (they have
   new syntax now).

4) gofmt -w src misc test/bench

5th and last set of files.

R=rsc
CC=golang-dev
https://golang.org/cl/180050
parent d65a5cce
...@@ -9,10 +9,10 @@ ...@@ -9,10 +9,10 @@
package syslog package syslog
import ( import (
"fmt"; "fmt"
"log"; "log"
"net"; "net"
"os"; "os"
) )
type Priority int type Priority int
...@@ -20,21 +20,21 @@ type Priority int ...@@ -20,21 +20,21 @@ type Priority int
const ( const (
// From /usr/include/sys/syslog.h. // From /usr/include/sys/syslog.h.
// These are the same on Linux, BSD, and OS X. // These are the same on Linux, BSD, and OS X.
LOG_EMERG Priority = iota; LOG_EMERG Priority = iota
LOG_ALERT; LOG_ALERT
LOG_CRIT; LOG_CRIT
LOG_ERR; LOG_ERR
LOG_WARNING; LOG_WARNING
LOG_NOTICE; LOG_NOTICE
LOG_INFO; LOG_INFO
LOG_DEBUG; LOG_DEBUG
) )
// A Writer is a connection to a syslog server. // A Writer is a connection to a syslog server.
type Writer struct { type Writer struct {
priority Priority; priority Priority
prefix string; prefix string
conn net.Conn; conn net.Conn
} }
// New establishes a new connection to the system log daemon. // New establishes a new connection to the system log daemon.
...@@ -52,23 +52,23 @@ func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, e ...@@ -52,23 +52,23 @@ func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, e
if prefix == "" { if prefix == "" {
prefix = os.Args[0] prefix = os.Args[0]
} }
var conn net.Conn; var conn net.Conn
if network == "" { if network == "" {
conn, err = unixSyslog() conn, err = unixSyslog()
} else { } else {
conn, err = net.Dial(network, "", raddr) conn, err = net.Dial(network, "", raddr)
} }
return &Writer{priority, prefix, conn}, err; return &Writer{priority, prefix, conn}, err
} }
func unixSyslog() (conn net.Conn, err os.Error) { func unixSyslog() (conn net.Conn, err os.Error) {
logTypes := []string{"unixgram", "unix"}; logTypes := []string{"unixgram", "unix"}
logPaths := []string{"/dev/log", "/var/run/syslog"}; logPaths := []string{"/dev/log", "/var/run/syslog"}
var raddr string; var raddr string
for _, network := range logTypes { for _, network := range logTypes {
for _, path := range logPaths { for _, path := range logPaths {
raddr = path; raddr = path
conn, err := net.Dial(network, "", raddr); conn, err := net.Dial(network, "", raddr)
if err != nil { if err != nil {
continue continue
} else { } else {
...@@ -76,7 +76,7 @@ func unixSyslog() (conn net.Conn, err os.Error) { ...@@ -76,7 +76,7 @@ func unixSyslog() (conn net.Conn, err os.Error) {
} }
} }
} }
return nil, os.ErrorString("Unix syslog delivery error"); return nil, os.ErrorString("Unix syslog delivery error")
} }
// Write sends a log message to the syslog daemon. // Write sends a log message to the syslog daemon.
...@@ -84,7 +84,7 @@ func (w *Writer) Write(b []byte) (int, os.Error) { ...@@ -84,7 +84,7 @@ func (w *Writer) Write(b []byte) (int, os.Error) {
if w.priority > LOG_DEBUG || w.priority < LOG_EMERG { if w.priority > LOG_DEBUG || w.priority < LOG_EMERG {
return 0, os.EINVAL return 0, os.EINVAL
} }
return fmt.Fprintf(w.conn, "<%d>%s: %s\n", w.priority, w.prefix, b); return fmt.Fprintf(w.conn, "<%d>%s: %s\n", w.priority, w.prefix, b)
} }
func (w *Writer) writeString(p Priority, s string) (int, os.Error) { func (w *Writer) writeString(p Priority, s string) (int, os.Error) {
...@@ -95,40 +95,40 @@ func (w *Writer) Close() os.Error { return w.conn.Close() } ...@@ -95,40 +95,40 @@ func (w *Writer) Close() os.Error { return w.conn.Close() }
// Emerg logs a message using the LOG_EMERG priority. // Emerg logs a message using the LOG_EMERG priority.
func (w *Writer) Emerg(m string) (err os.Error) { func (w *Writer) Emerg(m string) (err os.Error) {
_, err = w.writeString(LOG_EMERG, m); _, err = w.writeString(LOG_EMERG, m)
return err; return err
} }
// Crit logs a message using the LOG_CRIT priority. // Crit logs a message using the LOG_CRIT priority.
func (w *Writer) Crit(m string) (err os.Error) { func (w *Writer) Crit(m string) (err os.Error) {
_, err = w.writeString(LOG_CRIT, m); _, err = w.writeString(LOG_CRIT, m)
return err; return err
} }
// ERR logs a message using the LOG_ERR priority. // ERR logs a message using the LOG_ERR priority.
func (w *Writer) Err(m string) (err os.Error) { func (w *Writer) Err(m string) (err os.Error) {
_, err = w.writeString(LOG_ERR, m); _, err = w.writeString(LOG_ERR, m)
return err; return err
} }
// Warning logs a message using the LOG_WARNING priority. // Warning logs a message using the LOG_WARNING priority.
func (w *Writer) Warning(m string) (err os.Error) { func (w *Writer) Warning(m string) (err os.Error) {
_, err = w.writeString(LOG_WARNING, m); _, err = w.writeString(LOG_WARNING, m)
return err; return err
} }
// Notice logs a message using the LOG_NOTICE priority. // Notice logs a message using the LOG_NOTICE priority.
func (w *Writer) Notice(m string) (err os.Error) { func (w *Writer) Notice(m string) (err os.Error) {
_, err = w.writeString(LOG_NOTICE, m); _, err = w.writeString(LOG_NOTICE, m)
return err; return err
} }
// Info logs a message using the LOG_INFO priority. // Info logs a message using the LOG_INFO priority.
func (w *Writer) Info(m string) (err os.Error) { func (w *Writer) Info(m string) (err os.Error) {
_, err = w.writeString(LOG_INFO, m); _, err = w.writeString(LOG_INFO, m)
return err; return err
} }
// Debug logs a message using the LOG_DEBUG priority. // Debug logs a message using the LOG_DEBUG priority.
func (w *Writer) Debug(m string) (err os.Error) { func (w *Writer) Debug(m string) (err os.Error) {
_, err = w.writeString(LOG_DEBUG, m); _, err = w.writeString(LOG_DEBUG, m)
return err; return err
} }
// NewLogger provides an object that implements the full log.Logger interface, // NewLogger provides an object that implements the full log.Logger interface,
...@@ -136,9 +136,9 @@ func (w *Writer) Debug(m string) (err os.Error) { ...@@ -136,9 +136,9 @@ func (w *Writer) Debug(m string) (err os.Error) {
// priority will be used for all messages sent using this interface. // priority will be used for all messages sent using this interface.
// All messages are logged with priority p. // All messages are logged with priority p.
func NewLogger(p Priority, flag int) *log.Logger { func NewLogger(p Priority, flag int) *log.Logger {
s, err := New(p, ""); s, err := New(p, "")
if err != nil { if err != nil {
return nil return nil
} }
return log.New(s, nil, "", flag); return log.New(s, nil, "", flag)
} }
...@@ -4,91 +4,91 @@ ...@@ -4,91 +4,91 @@
package syslog package syslog
import ( import (
"io"; "io"
"log"; "log"
"net"; "net"
"testing"; "testing"
) )
var serverAddr string var serverAddr string
func runSyslog(c net.PacketConn, done chan<- string) { func runSyslog(c net.PacketConn, done chan<- string) {
var buf [4096]byte; var buf [4096]byte
var rcvd string = ""; var rcvd string = ""
for { for {
n, _, err := c.ReadFrom(&buf); n, _, err := c.ReadFrom(&buf)
if err != nil || n == 0 { if err != nil || n == 0 {
break break
} }
rcvd += string(buf[0:n]); rcvd += string(buf[0:n])
} }
done <- rcvd; done <- rcvd
} }
func startServer(done chan<- string) { func startServer(done chan<- string) {
c, e := net.ListenPacket("udp", ":0"); c, e := net.ListenPacket("udp", ":0")
if e != nil { if e != nil {
log.Exitf("net.ListenPacket failed udp :0 %v", e) log.Exitf("net.ListenPacket failed udp :0 %v", e)
} }
serverAddr = c.LocalAddr().String(); serverAddr = c.LocalAddr().String()
c.SetReadTimeout(10e6); // 10ms c.SetReadTimeout(10e6) // 10ms
go runSyslog(c, done); go runSyslog(c, done)
} }
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
s, err := New(LOG_INFO, ""); s, err := New(LOG_INFO, "")
if err != nil { if err != nil {
t.Fatalf("New() failed: %s", err) t.Fatalf("New() failed: %s", err)
} }
// Don't send any messages. // Don't send any messages.
s.Close(); s.Close()
} }
func TestNewLogger(t *testing.T) { func TestNewLogger(t *testing.T) {
f := NewLogger(LOG_INFO, 0); f := NewLogger(LOG_INFO, 0)
if f == nil { if f == nil {
t.Errorf("NewLogger() failed\n") t.Errorf("NewLogger() failed\n")
} }
} }
func TestDial(t *testing.T) { func TestDial(t *testing.T) {
l, err := Dial("", "", LOG_ERR, "syslog_test"); l, err := Dial("", "", LOG_ERR, "syslog_test")
if err != nil { if err != nil {
t.Fatalf("Dial() failed: %s", err) t.Fatalf("Dial() failed: %s", err)
} }
l.Close(); l.Close()
} }
func TestUDPDial(t *testing.T) { func TestUDPDial(t *testing.T) {
done := make(chan string); done := make(chan string)
startServer(done); startServer(done)
l, err := Dial("udp", serverAddr, LOG_INFO, "syslog_test"); l, err := Dial("udp", serverAddr, LOG_INFO, "syslog_test")
if err != nil { if err != nil {
t.Fatalf("syslog.Dial() failed: %s", err) t.Fatalf("syslog.Dial() failed: %s", err)
} }
msg := "udp test"; msg := "udp test"
l.Info(msg); l.Info(msg)
expected := "<6>syslog_test: udp test\n"; expected := "<6>syslog_test: udp test\n"
rcvd := <-done; rcvd := <-done
if rcvd != expected { if rcvd != expected {
t.Fatalf("s.Info() = '%q', but wanted '%q'", rcvd, expected) t.Fatalf("s.Info() = '%q', but wanted '%q'", rcvd, expected)
} }
} }
func TestWrite(t *testing.T) { func TestWrite(t *testing.T) {
done := make(chan string); done := make(chan string)
startServer(done); startServer(done)
l, err := Dial("udp", serverAddr, LOG_ERR, "syslog_test"); l, err := Dial("udp", serverAddr, LOG_ERR, "syslog_test")
if err != nil { if err != nil {
t.Fatalf("syslog.Dial() failed: %s", err) t.Fatalf("syslog.Dial() failed: %s", err)
} }
msg := "write test"; msg := "write test"
_, err = io.WriteString(l, msg); _, err = io.WriteString(l, msg)
if err != nil { if err != nil {
t.Fatalf("WriteString() failed: %s", err) t.Fatalf("WriteString() failed: %s", err)
} }
expected := "<3>syslog_test: write test\n"; expected := "<3>syslog_test: write test\n"
rcvd := <-done; rcvd := <-done
if rcvd != expected { if rcvd != expected {
t.Fatalf("s.Info() = '%q', but wanted '%q'", rcvd, expected) t.Fatalf("s.Info() = '%q', but wanted '%q'", rcvd, expected)
} }
......
This diff is collapsed.
...@@ -5,14 +5,14 @@ ...@@ -5,14 +5,14 @@
package tabwriter package tabwriter
import ( import (
"io"; "io"
"os"; "os"
"testing"; "testing"
) )
type buffer struct { type buffer struct {
a []byte; a []byte
} }
...@@ -23,17 +23,17 @@ func (b *buffer) clear() { b.a = b.a[0:0] } ...@@ -23,17 +23,17 @@ func (b *buffer) clear() { b.a = b.a[0:0] }
func (b *buffer) Write(buf []byte) (written int, err os.Error) { func (b *buffer) Write(buf []byte) (written int, err os.Error) {
n := len(b.a); n := len(b.a)
m := len(buf); m := len(buf)
if n+m <= cap(b.a) { if n+m <= cap(b.a) {
b.a = b.a[0 : n+m]; b.a = b.a[0 : n+m]
for i := 0; i < m; i++ { for i := 0; i < m; i++ {
b.a[n+i] = buf[i] b.a[n+i] = buf[i]
} }
} else { } else {
panicln("buffer.Write: buffer too small", n, m, cap(b.a)) panicln("buffer.Write: buffer too small", n, m, cap(b.a))
} }
return len(buf), nil; return len(buf), nil
} }
...@@ -41,7 +41,7 @@ func (b *buffer) String() string { return string(b.a) } ...@@ -41,7 +41,7 @@ func (b *buffer) String() string { return string(b.a) }
func write(t *testing.T, testname string, w *Writer, src string) { func write(t *testing.T, testname string, w *Writer, src string) {
written, err := io.WriteString(w, src); written, err := io.WriteString(w, src)
if err != nil { if err != nil {
t.Errorf("--- test: %s\n--- src:\n%s\n--- write error: %v\n", testname, src, err) t.Errorf("--- test: %s\n--- src:\n%s\n--- write error: %v\n", testname, src, err)
} }
...@@ -52,12 +52,12 @@ func write(t *testing.T, testname string, w *Writer, src string) { ...@@ -52,12 +52,12 @@ func write(t *testing.T, testname string, w *Writer, src string) {
func verify(t *testing.T, testname string, w *Writer, b *buffer, src, expected string) { func verify(t *testing.T, testname string, w *Writer, b *buffer, src, expected string) {
err := w.Flush(); err := w.Flush()
if err != nil { if err != nil {
t.Errorf("--- test: %s\n--- src:\n%s\n--- flush error: %v\n", testname, src, err) t.Errorf("--- test: %s\n--- src:\n%s\n--- flush error: %v\n", testname, src, err)
} }
res := b.String(); res := b.String()
if res != expected { if res != expected {
t.Errorf("--- test: %s\n--- src:\n%s\n--- found:\n%s\n--- expected:\n%s\n", testname, src, res, expected) t.Errorf("--- test: %s\n--- src:\n%s\n--- found:\n%s\n--- expected:\n%s\n", testname, src, res, expected)
} }
...@@ -65,43 +65,43 @@ func verify(t *testing.T, testname string, w *Writer, b *buffer, src, expected s ...@@ -65,43 +65,43 @@ func verify(t *testing.T, testname string, w *Writer, b *buffer, src, expected s
func check(t *testing.T, testname string, minwidth, tabwidth, padding int, padchar byte, flags uint, src, expected string) { func check(t *testing.T, testname string, minwidth, tabwidth, padding int, padchar byte, flags uint, src, expected string) {
var b buffer; var b buffer
b.init(1000); b.init(1000)
var w Writer; var w Writer
w.Init(&b, minwidth, tabwidth, padding, padchar, flags); w.Init(&b, minwidth, tabwidth, padding, padchar, flags)
// write all at once // write all at once
b.clear(); b.clear()
write(t, testname, &w, src); write(t, testname, &w, src)
verify(t, testname, &w, &b, src, expected); verify(t, testname, &w, &b, src, expected)
// write byte-by-byte // write byte-by-byte
b.clear(); b.clear()
for i := 0; i < len(src); i++ { for i := 0; i < len(src); i++ {
write(t, testname, &w, src[i:i+1]) write(t, testname, &w, src[i:i+1])
} }
verify(t, testname, &w, &b, src, expected); verify(t, testname, &w, &b, src, expected)
// write using Fibonacci slice sizes // write using Fibonacci slice sizes
b.clear(); b.clear()
for i, d := 0, 0; i < len(src); { for i, d := 0, 0; i < len(src); {
write(t, testname, &w, src[i:i+d]); write(t, testname, &w, src[i:i+d])
i, d = i+d, d+1; i, d = i+d, d+1
if i+d > len(src) { if i+d > len(src) {
d = len(src) - i d = len(src) - i
} }
} }
verify(t, testname, &w, &b, src, expected); verify(t, testname, &w, &b, src, expected)
} }
type entry struct { type entry struct {
testname string; testname string
minwidth, tabwidth, padding int; minwidth, tabwidth, padding int
padchar byte; padchar byte
flags uint; flags uint
src, expected string; src, expected string
} }
......
...@@ -7,10 +7,10 @@ ...@@ -7,10 +7,10 @@
package template package template
import ( import (
"bytes"; "bytes"
"fmt"; "fmt"
"io"; "io"
"strings"; "strings"
) )
// StringFormatter formats into the default string representation. // StringFormatter formats into the default string representation.
...@@ -19,25 +19,25 @@ import ( ...@@ -19,25 +19,25 @@ import (
// under the name "" in your custom formatter map. // under the name "" in your custom formatter map.
func StringFormatter(w io.Writer, value interface{}, format string) { func StringFormatter(w io.Writer, value interface{}, format string) {
if b, ok := value.([]byte); ok { if b, ok := value.([]byte); ok {
w.Write(b); w.Write(b)
return; return
} }
fmt.Fprint(w, value); fmt.Fprint(w, value)
} }
var ( var (
esc_quot = strings.Bytes("&#34;"); // shorter than "&quot;" esc_quot = strings.Bytes("&#34;") // shorter than "&quot;"
esc_apos = strings.Bytes("&#39;"); // shorter than "&apos;" esc_apos = strings.Bytes("&#39;") // shorter than "&apos;"
esc_amp = strings.Bytes("&amp;"); esc_amp = strings.Bytes("&amp;")
esc_lt = strings.Bytes("&lt;"); esc_lt = strings.Bytes("&lt;")
esc_gt = strings.Bytes("&gt;"); esc_gt = strings.Bytes("&gt;")
) )
// HTMLEscape writes to w the properly escaped HTML equivalent // HTMLEscape writes to w the properly escaped HTML equivalent
// of the plain text data s. // of the plain text data s.
func HTMLEscape(w io.Writer, s []byte) { func HTMLEscape(w io.Writer, s []byte) {
var esc []byte; var esc []byte
last := 0; last := 0
for i, c := range s { for i, c := range s {
switch c { switch c {
case '"': case '"':
...@@ -53,16 +53,16 @@ func HTMLEscape(w io.Writer, s []byte) { ...@@ -53,16 +53,16 @@ func HTMLEscape(w io.Writer, s []byte) {
default: default:
continue continue
} }
w.Write(s[last:i]); w.Write(s[last:i])
w.Write(esc); w.Write(esc)
last = i + 1; last = i + 1
} }
w.Write(s[last:]); w.Write(s[last:])
} }
// HTMLFormatter formats arbitrary values for HTML // HTMLFormatter formats arbitrary values for HTML
func HTMLFormatter(w io.Writer, value interface{}, format string) { func HTMLFormatter(w io.Writer, value interface{}, format string) {
var b bytes.Buffer; var b bytes.Buffer
fmt.Fprint(&b, value); fmt.Fprint(&b, value)
HTMLEscape(w, b.Bytes()); HTMLEscape(w, b.Bytes())
} }
This diff is collapsed.
...@@ -5,65 +5,65 @@ ...@@ -5,65 +5,65 @@
package template package template
import ( import (
"bytes"; "bytes"
"container/vector"; "container/vector"
"fmt"; "fmt"
"io"; "io"
"strings"; "strings"
"testing"; "testing"
) )
type Test struct { type Test struct {
in, out, err string; in, out, err string
} }
type T struct { type T struct {
item string; item string
value string; value string
} }
type U struct { type U struct {
mp map[string]int; mp map[string]int
} }
type S struct { type S struct {
header string; header string
integer int; integer int
raw string; raw string
innerT T; innerT T
innerPointerT *T; innerPointerT *T
data []T; data []T
pdata []*T; pdata []*T
empty []*T; empty []*T
emptystring string; emptystring string
null []*T; null []*T
vec *vector.Vector; vec *vector.Vector
true bool; true bool
false bool; false bool
mp map[string]string; mp map[string]string
innermap U; innermap U
bytes []byte; bytes []byte
} }
var t1 = T{"ItemNumber1", "ValueNumber1"} var t1 = T{"ItemNumber1", "ValueNumber1"}
var t2 = T{"ItemNumber2", "ValueNumber2"} var t2 = T{"ItemNumber2", "ValueNumber2"}
func uppercase(v interface{}) string { func uppercase(v interface{}) string {
s := v.(string); s := v.(string)
t := ""; t := ""
for i := 0; i < len(s); i++ { for i := 0; i < len(s); i++ {
c := s[i]; c := s[i]
if 'a' <= c && c <= 'z' { if 'a' <= c && c <= 'z' {
c = c + 'A' - 'a' c = c + 'A' - 'a'
} }
t += string(c); t += string(c)
} }
return t; return t
} }
func plus1(v interface{}) string { func plus1(v interface{}) string {
i := v.(int); i := v.(int)
return fmt.Sprint(i + 1); return fmt.Sprint(i + 1)
} }
func writer(f func(interface{}) string) (func(io.Writer, interface{}, string)) { func writer(f func(interface{}) string) (func(io.Writer, interface{}, string)) {
...@@ -306,36 +306,36 @@ var tests = []*Test{ ...@@ -306,36 +306,36 @@ var tests = []*Test{
} }
func TestAll(t *testing.T) { func TestAll(t *testing.T) {
s := new(S); s := new(S)
// initialized by hand for clarity. // initialized by hand for clarity.
s.header = "Header"; s.header = "Header"
s.integer = 77; s.integer = 77
s.raw = "&<>!@ #$%^"; s.raw = "&<>!@ #$%^"
s.innerT = t1; s.innerT = t1
s.data = []T{t1, t2}; s.data = []T{t1, t2}
s.pdata = []*T{&t1, &t2}; s.pdata = []*T{&t1, &t2}
s.empty = []*T{}; s.empty = []*T{}
s.null = nil; s.null = nil
s.vec = new(vector.Vector); s.vec = new(vector.Vector)
s.vec.Push("elt1"); s.vec.Push("elt1")
s.vec.Push("elt2"); s.vec.Push("elt2")
s.true = true; s.true = true
s.false = false; s.false = false
s.mp = make(map[string]string); s.mp = make(map[string]string)
s.mp["mapkey"] = "Ahoy!"; s.mp["mapkey"] = "Ahoy!"
s.innermap.mp = make(map[string]int); s.innermap.mp = make(map[string]int)
s.innermap.mp["innerkey"] = 55; s.innermap.mp["innerkey"] = 55
s.bytes = strings.Bytes("hello"); s.bytes = strings.Bytes("hello")
var buf bytes.Buffer; var buf bytes.Buffer
for _, test := range tests { for _, test := range tests {
buf.Reset(); buf.Reset()
tmpl, err := Parse(test.in, formatters); tmpl, err := Parse(test.in, formatters)
if err != nil { if err != nil {
t.Error("unexpected parse error:", err); t.Error("unexpected parse error:", err)
continue; continue
} }
err = tmpl.Execute(s, &buf); err = tmpl.Execute(s, &buf)
if test.err == "" { if test.err == "" {
if err != nil { if err != nil {
t.Error("unexpected execute error:", err) t.Error("unexpected execute error:", err)
...@@ -352,60 +352,60 @@ func TestAll(t *testing.T) { ...@@ -352,60 +352,60 @@ func TestAll(t *testing.T) {
} }
func TestMapDriverType(t *testing.T) { func TestMapDriverType(t *testing.T) {
mp := map[string]string{"footer": "Ahoy!"}; mp := map[string]string{"footer": "Ahoy!"}
tmpl, err := Parse("template: {footer}", nil); tmpl, err := Parse("template: {footer}", nil)
if err != nil { if err != nil {
t.Error("unexpected parse error:", err) t.Error("unexpected parse error:", err)
} }
var b bytes.Buffer; var b bytes.Buffer
err = tmpl.Execute(mp, &b); err = tmpl.Execute(mp, &b)
if err != nil { if err != nil {
t.Error("unexpected execute error:", err) t.Error("unexpected execute error:", err)
} }
s := b.String(); s := b.String()
expected := "template: Ahoy!"; expected := "template: Ahoy!"
if s != expected { if s != expected {
t.Errorf("failed passing string as data: expected %q got %q", "template: Ahoy!", s) t.Errorf("failed passing string as data: expected %q got %q", "template: Ahoy!", s)
} }
} }
func TestStringDriverType(t *testing.T) { func TestStringDriverType(t *testing.T) {
tmpl, err := Parse("template: {@}", nil); tmpl, err := Parse("template: {@}", nil)
if err != nil { if err != nil {
t.Error("unexpected parse error:", err) t.Error("unexpected parse error:", err)
} }
var b bytes.Buffer; var b bytes.Buffer
err = tmpl.Execute("hello", &b); err = tmpl.Execute("hello", &b)
if err != nil { if err != nil {
t.Error("unexpected execute error:", err) t.Error("unexpected execute error:", err)
} }
s := b.String(); s := b.String()
if s != "template: hello" { if s != "template: hello" {
t.Errorf("failed passing string as data: expected %q got %q", "template: hello", s) t.Errorf("failed passing string as data: expected %q got %q", "template: hello", s)
} }
} }
func TestTwice(t *testing.T) { func TestTwice(t *testing.T) {
tmpl, err := Parse("template: {@}", nil); tmpl, err := Parse("template: {@}", nil)
if err != nil { if err != nil {
t.Error("unexpected parse error:", err) t.Error("unexpected parse error:", err)
} }
var b bytes.Buffer; var b bytes.Buffer
err = tmpl.Execute("hello", &b); err = tmpl.Execute("hello", &b)
if err != nil { if err != nil {
t.Error("unexpected parse error:", err) t.Error("unexpected parse error:", err)
} }
s := b.String(); s := b.String()
text := "template: hello"; text := "template: hello"
if s != text { if s != text {
t.Errorf("failed passing string as data: expected %q got %q", text, s) t.Errorf("failed passing string as data: expected %q got %q", text, s)
} }
err = tmpl.Execute("hello", &b); err = tmpl.Execute("hello", &b)
if err != nil { if err != nil {
t.Error("unexpected parse error:", err) t.Error("unexpected parse error:", err)
} }
s = b.String(); s = b.String()
text += text; text += text
if s != text { if s != text {
t.Errorf("failed passing string as data: expected %q got %q", text, s) t.Errorf("failed passing string as data: expected %q got %q", text, s)
} }
...@@ -415,29 +415,29 @@ func TestCustomDelims(t *testing.T) { ...@@ -415,29 +415,29 @@ func TestCustomDelims(t *testing.T) {
// try various lengths. zero should catch error. // try various lengths. zero should catch error.
for i := 0; i < 7; i++ { for i := 0; i < 7; i++ {
for j := 0; j < 7; j++ { for j := 0; j < 7; j++ {
tmpl := New(nil); tmpl := New(nil)
// first two chars deliberately the same to test equal left and right delims // first two chars deliberately the same to test equal left and right delims
ldelim := "$!#$%^&"[0:i]; ldelim := "$!#$%^&"[0:i]
rdelim := "$*&^%$!"[0:j]; rdelim := "$*&^%$!"[0:j]
tmpl.SetDelims(ldelim, rdelim); tmpl.SetDelims(ldelim, rdelim)
// if braces, this would be template: {@}{.meta-left}{.meta-right} // if braces, this would be template: {@}{.meta-left}{.meta-right}
text := "template: " + text := "template: " +
ldelim + "@" + rdelim + ldelim + "@" + rdelim +
ldelim + ".meta-left" + rdelim + ldelim + ".meta-left" + rdelim +
ldelim + ".meta-right" + rdelim; ldelim + ".meta-right" + rdelim
err := tmpl.Parse(text); err := tmpl.Parse(text)
if err != nil { if err != nil {
if i == 0 || j == 0 { // expected if i == 0 || j == 0 { // expected
continue continue
} }
t.Error("unexpected parse error:", err); t.Error("unexpected parse error:", err)
} else if i == 0 || j == 0 { } else if i == 0 || j == 0 {
t.Errorf("expected parse error for empty delimiter: %d %d %q %q", i, j, ldelim, rdelim); t.Errorf("expected parse error for empty delimiter: %d %d %q %q", i, j, ldelim, rdelim)
continue; continue
} }
var b bytes.Buffer; var b bytes.Buffer
err = tmpl.Execute("hello", &b); err = tmpl.Execute("hello", &b)
s := b.String(); s := b.String()
if s != "template: hello"+ldelim+rdelim { if s != "template: hello"+ldelim+rdelim {
t.Errorf("failed delim check(%q %q) %q got %q", ldelim, rdelim, text, s) t.Errorf("failed delim check(%q %q) %q got %q", ldelim, rdelim, text, s)
} }
...@@ -447,21 +447,21 @@ func TestCustomDelims(t *testing.T) { ...@@ -447,21 +447,21 @@ func TestCustomDelims(t *testing.T) {
// Test that a variable evaluates to the field itself and does not further indirection // Test that a variable evaluates to the field itself and does not further indirection
func TestVarIndirection(t *testing.T) { func TestVarIndirection(t *testing.T) {
s := new(S); s := new(S)
// initialized by hand for clarity. // initialized by hand for clarity.
s.innerPointerT = &t1; s.innerPointerT = &t1
var buf bytes.Buffer; var buf bytes.Buffer
input := "{.section @}{innerPointerT}{.end}"; input := "{.section @}{innerPointerT}{.end}"
tmpl, err := Parse(input, nil); tmpl, err := Parse(input, nil)
if err != nil { if err != nil {
t.Fatal("unexpected parse error:", err) t.Fatal("unexpected parse error:", err)
} }
err = tmpl.Execute(s, &buf); err = tmpl.Execute(s, &buf)
if err != nil { if err != nil {
t.Fatal("unexpected execute error:", err) t.Fatal("unexpected execute error:", err)
} }
expect := fmt.Sprintf("%v", &t1); // output should be hex address of t1 expect := fmt.Sprintf("%v", &t1) // output should be hex address of t1
if buf.String() != expect { if buf.String() != expect {
t.Errorf("for %q: expected %q got %q", input, expect, buf.String()) t.Errorf("for %q: expected %q got %q", input, expect, buf.String())
} }
......
...@@ -5,10 +5,10 @@ ...@@ -5,10 +5,10 @@
package testing package testing
import ( import (
"flag"; "flag"
"fmt"; "fmt"
"os"; "os"
"time"; "time"
) )
var matchBenchmarks = flag.String("benchmarks", "", "regular expression to select benchmarks to run") var matchBenchmarks = flag.String("benchmarks", "", "regular expression to select benchmarks to run")
...@@ -16,18 +16,18 @@ var matchBenchmarks = flag.String("benchmarks", "", "regular expression to selec ...@@ -16,18 +16,18 @@ var matchBenchmarks = flag.String("benchmarks", "", "regular expression to selec
// An internal type but exported because it is cross-package; part of the implementation // An internal type but exported because it is cross-package; part of the implementation
// of gotest. // of gotest.
type Benchmark struct { type Benchmark struct {
Name string; Name string
F func(b *B); F func(b *B)
} }
// B is a type passed to Benchmark functions to manage benchmark // B is a type passed to Benchmark functions to manage benchmark
// timing and to specify the number of iterations to run. // timing and to specify the number of iterations to run.
type B struct { type B struct {
N int; N int
benchmark Benchmark; benchmark Benchmark
ns int64; ns int64
bytes int64; bytes int64
start int64; start int64
} }
// StartTimer starts timing a test. This function is called automatically // StartTimer starts timing a test. This function is called automatically
...@@ -42,13 +42,13 @@ func (b *B) StopTimer() { ...@@ -42,13 +42,13 @@ func (b *B) StopTimer() {
if b.start > 0 { if b.start > 0 {
b.ns += time.Nanoseconds() - b.start b.ns += time.Nanoseconds() - b.start
} }
b.start = 0; b.start = 0
} }
// ResetTimer stops the timer and sets the elapsed benchmark time to zero. // ResetTimer stops the timer and sets the elapsed benchmark time to zero.
func (b *B) ResetTimer() { func (b *B) ResetTimer() {
b.start = 0; b.start = 0
b.ns = 0; b.ns = 0
} }
// SetBytes records the number of bytes processed in a single operation. // SetBytes records the number of bytes processed in a single operation.
...@@ -59,51 +59,51 @@ func (b *B) nsPerOp() int64 { ...@@ -59,51 +59,51 @@ func (b *B) nsPerOp() int64 {
if b.N <= 0 { if b.N <= 0 {
return 0 return 0
} }
return b.ns / int64(b.N); return b.ns / int64(b.N)
} }
// runN runs a single benchmark for the specified number of iterations. // runN runs a single benchmark for the specified number of iterations.
func (b *B) runN(n int) { func (b *B) runN(n int) {
b.N = n; b.N = n
b.ResetTimer(); b.ResetTimer()
b.StartTimer(); b.StartTimer()
b.benchmark.F(b); b.benchmark.F(b)
b.StopTimer(); b.StopTimer()
} }
func min(x, y int) int { func min(x, y int) int {
if x > y { if x > y {
return y return y
} }
return x; return x
} }
// roundDown10 rounds a number down to the nearest power of 10. // roundDown10 rounds a number down to the nearest power of 10.
func roundDown10(n int) int { func roundDown10(n int) int {
var tens = 0; var tens = 0
// tens = floor(log_10(n)) // tens = floor(log_10(n))
for n > 10 { for n > 10 {
n = n / 10; n = n / 10
tens++; tens++
} }
// result = 10^tens // result = 10^tens
result := 1; result := 1
for i := 0; i < tens; i++ { for i := 0; i < tens; i++ {
result *= 10 result *= 10
} }
return result; return result
} }
// roundUp rounds x up to a number of the form [1eX, 2eX, 5eX]. // roundUp rounds x up to a number of the form [1eX, 2eX, 5eX].
func roundUp(n int) int { func roundUp(n int) int {
base := roundDown10(n); base := roundDown10(n)
if n < (2 * base) { if n < (2 * base) {
return 2 * base return 2 * base
} }
if n < (5 * base) { if n < (5 * base) {
return 5 * base return 5 * base
} }
return 10 * base; return 10 * base
} }
// run times the benchmark function. It gradually increases the number // run times the benchmark function. It gradually increases the number
...@@ -112,11 +112,11 @@ func roundUp(n int) int { ...@@ -112,11 +112,11 @@ func roundUp(n int) int {
// testing.BenchmarkHello 100000 19 ns/op // testing.BenchmarkHello 100000 19 ns/op
func (b *B) run() { func (b *B) run() {
// Run the benchmark for a single iteration in case it's expensive. // Run the benchmark for a single iteration in case it's expensive.
n := 1; n := 1
b.runN(n); b.runN(n)
// Run the benchmark for at least a second. // Run the benchmark for at least a second.
for b.ns < 1e9 && n < 1e9 { for b.ns < 1e9 && n < 1e9 {
last := n; last := n
// Predict iterations/sec. // Predict iterations/sec.
if b.nsPerOp() == 0 { if b.nsPerOp() == 0 {
n = 1e9 n = 1e9
...@@ -125,17 +125,17 @@ func (b *B) run() { ...@@ -125,17 +125,17 @@ func (b *B) run() {
} }
// Run more iterations than we think we'll need for a second (1.5x). // Run more iterations than we think we'll need for a second (1.5x).
// Don't grow too fast in case we had timing errors previously. // Don't grow too fast in case we had timing errors previously.
n = min(int(1.5*float(n)), 100*last); n = min(int(1.5*float(n)), 100*last)
// Round up to something easy to read. // Round up to something easy to read.
n = roundUp(n); n = roundUp(n)
b.runN(n); b.runN(n)
} }
ns := b.nsPerOp(); ns := b.nsPerOp()
mb := ""; mb := ""
if ns > 0 && b.bytes > 0 { if ns > 0 && b.bytes > 0 {
mb = fmt.Sprintf("\t%7.2f MB/s", (float64(b.bytes)/1e6)/(float64(ns)/1e9)) mb = fmt.Sprintf("\t%7.2f MB/s", (float64(b.bytes)/1e6)/(float64(ns)/1e9))
} }
fmt.Printf("%s\t%8d\t%10d ns/op%s\n", b.benchmark.Name, b.N, b.nsPerOp(), mb); fmt.Printf("%s\t%8d\t%10d ns/op%s\n", b.benchmark.Name, b.N, b.nsPerOp(), mb)
} }
// An internal function but exported because it is cross-package; part of the implementation // An internal function but exported because it is cross-package; part of the implementation
...@@ -145,16 +145,16 @@ func RunBenchmarks(benchmarks []Benchmark) { ...@@ -145,16 +145,16 @@ func RunBenchmarks(benchmarks []Benchmark) {
if len(*matchBenchmarks) == 0 { if len(*matchBenchmarks) == 0 {
return return
} }
re, err := CompileRegexp(*matchBenchmarks); re, err := CompileRegexp(*matchBenchmarks)
if err != "" { if err != "" {
println("invalid regexp for -benchmarks:", err); println("invalid regexp for -benchmarks:", err)
os.Exit(1); os.Exit(1)
} }
for _, Benchmark := range benchmarks { for _, Benchmark := range benchmarks {
if !re.MatchString(Benchmark.Name) { if !re.MatchString(Benchmark.Name) {
continue continue
} }
b := &B{benchmark: Benchmark}; b := &B{benchmark: Benchmark}
b.run(); b.run()
} }
} }
...@@ -5,24 +5,24 @@ ...@@ -5,24 +5,24 @@
package iotest package iotest
import ( import (
"io"; "io"
"log"; "log"
"os"; "os"
) )
type writeLogger struct { type writeLogger struct {
prefix string; prefix string
w io.Writer; w io.Writer
} }
func (l *writeLogger) Write(p []byte) (n int, err os.Error) { func (l *writeLogger) Write(p []byte) (n int, err os.Error) {
n, err = l.w.Write(p); n, err = l.w.Write(p)
if err != nil { if err != nil {
log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err) log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err)
} else { } else {
log.Stdoutf("%s %x", l.prefix, p[0:n]) log.Stdoutf("%s %x", l.prefix, p[0:n])
} }
return; return
} }
// NewWriteLogger returns a writer that behaves like w except // NewWriteLogger returns a writer that behaves like w except
...@@ -33,18 +33,18 @@ func NewWriteLogger(prefix string, w io.Writer) io.Writer { ...@@ -33,18 +33,18 @@ func NewWriteLogger(prefix string, w io.Writer) io.Writer {
} }
type readLogger struct { type readLogger struct {
prefix string; prefix string
r io.Reader; r io.Reader
} }
func (l *readLogger) Read(p []byte) (n int, err os.Error) { func (l *readLogger) Read(p []byte) (n int, err os.Error) {
n, err = l.r.Read(p); n, err = l.r.Read(p)
if err != nil { if err != nil {
log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err) log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err)
} else { } else {
log.Stdoutf("%s %x", l.prefix, p[0:n]) log.Stdoutf("%s %x", l.prefix, p[0:n])
} }
return; return
} }
// NewReadLogger returns a reader that behaves like r except // NewReadLogger returns a reader that behaves like r except
......
...@@ -7,8 +7,8 @@ ...@@ -7,8 +7,8 @@
package iotest package iotest
import ( import (
"io"; "io"
"os"; "os"
) )
// OneByteReader returns a Reader that implements // OneByteReader returns a Reader that implements
...@@ -16,14 +16,14 @@ import ( ...@@ -16,14 +16,14 @@ import (
func OneByteReader(r io.Reader) io.Reader { return &oneByteReader{r} } func OneByteReader(r io.Reader) io.Reader { return &oneByteReader{r} }
type oneByteReader struct { type oneByteReader struct {
r io.Reader; r io.Reader
} }
func (r *oneByteReader) Read(p []byte) (int, os.Error) { func (r *oneByteReader) Read(p []byte) (int, os.Error) {
if len(p) == 0 { if len(p) == 0 {
return 0, nil return 0, nil
} }
return r.r.Read(p[0:1]); return r.r.Read(p[0:1])
} }
// HalfReader returns a Reader that implements Read // HalfReader returns a Reader that implements Read
...@@ -31,7 +31,7 @@ func (r *oneByteReader) Read(p []byte) (int, os.Error) { ...@@ -31,7 +31,7 @@ func (r *oneByteReader) Read(p []byte) (int, os.Error) {
func HalfReader(r io.Reader) io.Reader { return &halfReader{r} } func HalfReader(r io.Reader) io.Reader { return &halfReader{r} }
type halfReader struct { type halfReader struct {
r io.Reader; r io.Reader
} }
func (r *halfReader) Read(p []byte) (int, os.Error) { func (r *halfReader) Read(p []byte) (int, os.Error) {
...@@ -45,9 +45,9 @@ func (r *halfReader) Read(p []byte) (int, os.Error) { ...@@ -45,9 +45,9 @@ func (r *halfReader) Read(p []byte) (int, os.Error) {
func DataErrReader(r io.Reader) io.Reader { return &dataErrReader{r, nil, make([]byte, 1024)} } func DataErrReader(r io.Reader) io.Reader { return &dataErrReader{r, nil, make([]byte, 1024)} }
type dataErrReader struct { type dataErrReader struct {
r io.Reader; r io.Reader
unread []byte; unread []byte
data []byte; data []byte
} }
func (r *dataErrReader) Read(p []byte) (n int, err os.Error) { func (r *dataErrReader) Read(p []byte) (n int, err os.Error) {
...@@ -55,15 +55,15 @@ func (r *dataErrReader) Read(p []byte) (n int, err os.Error) { ...@@ -55,15 +55,15 @@ func (r *dataErrReader) Read(p []byte) (n int, err os.Error) {
// one to get data and a second to look for an error. // one to get data and a second to look for an error.
for { for {
if len(r.unread) == 0 { if len(r.unread) == 0 {
n1, err1 := r.r.Read(r.data); n1, err1 := r.r.Read(r.data)
r.unread = r.data[0:n1]; r.unread = r.data[0:n1]
err = err1; err = err1
} }
if n > 0 { if n > 0 {
break break
} }
n = copy(p, r.unread); n = copy(p, r.unread)
r.unread = r.unread[n:]; r.unread = r.unread[n:]
} }
return; return
} }
...@@ -5,8 +5,8 @@ ...@@ -5,8 +5,8 @@
package iotest package iotest
import ( import (
"io"; "io"
"os"; "os"
) )
// TruncateWriter returns a Writer that writes to w // TruncateWriter returns a Writer that writes to w
...@@ -16,8 +16,8 @@ func TruncateWriter(w io.Writer, n int64) io.Writer { ...@@ -16,8 +16,8 @@ func TruncateWriter(w io.Writer, n int64) io.Writer {
} }
type truncateWriter struct { type truncateWriter struct {
w io.Writer; w io.Writer
n int64; n int64
} }
func (t *truncateWriter) Write(p []byte) (n int, err os.Error) { func (t *truncateWriter) Write(p []byte) (n int, err os.Error) {
...@@ -25,14 +25,14 @@ func (t *truncateWriter) Write(p []byte) (n int, err os.Error) { ...@@ -25,14 +25,14 @@ func (t *truncateWriter) Write(p []byte) (n int, err os.Error) {
return len(p), nil return len(p), nil
} }
// real write // real write
n = len(p); n = len(p)
if int64(n) > t.n { if int64(n) > t.n {
n = int(t.n) n = int(t.n)
} }
n, err = t.w.Write(p[0:n]); n, err = t.w.Write(p[0:n])
t.n -= int64(n); t.n -= int64(n)
if err == nil { if err == nil {
n = len(p) n = len(p)
} }
return; return
} }
This diff is collapsed.
...@@ -5,10 +5,10 @@ ...@@ -5,10 +5,10 @@
package quick package quick
import ( import (
"rand"; "rand"
"reflect"; "reflect"
"testing"; "testing"
"os"; "os"
) )
func fBool(a bool) bool { return a } func fBool(a bool) bool { return a }
...@@ -38,8 +38,8 @@ func fSlice(a []byte) []byte { return a } ...@@ -38,8 +38,8 @@ func fSlice(a []byte) []byte { return a }
func fString(a string) string { return a } func fString(a string) string { return a }
type TestStruct struct { type TestStruct struct {
A int; A int
B string; B string
} }
func fStruct(a TestStruct) TestStruct { return a } func fStruct(a TestStruct) TestStruct { return a }
...@@ -57,8 +57,8 @@ func fUint(a uint) uint { return a } ...@@ -57,8 +57,8 @@ func fUint(a uint) uint { return a }
func fUintptr(a uintptr) uintptr { return a } func fUintptr(a uintptr) uintptr { return a }
func fIntptr(a *int) *int { func fIntptr(a *int) *int {
b := *a; b := *a
return &b; return &b
} }
func reportError(property string, err os.Error, t *testing.T) { func reportError(property string, err os.Error, t *testing.T) {
...@@ -68,34 +68,34 @@ func reportError(property string, err os.Error, t *testing.T) { ...@@ -68,34 +68,34 @@ func reportError(property string, err os.Error, t *testing.T) {
} }
func TestCheckEqual(t *testing.T) { func TestCheckEqual(t *testing.T) {
reportError("fBool", CheckEqual(fBool, fBool, nil), t); reportError("fBool", CheckEqual(fBool, fBool, nil), t)
reportError("fFloat32", CheckEqual(fFloat32, fFloat32, nil), t); reportError("fFloat32", CheckEqual(fFloat32, fFloat32, nil), t)
reportError("fFloat64", CheckEqual(fFloat64, fFloat64, nil), t); reportError("fFloat64", CheckEqual(fFloat64, fFloat64, nil), t)
reportError("fFloat", CheckEqual(fFloat, fFloat, nil), t); reportError("fFloat", CheckEqual(fFloat, fFloat, nil), t)
reportError("fInt16", CheckEqual(fInt16, fInt16, nil), t); reportError("fInt16", CheckEqual(fInt16, fInt16, nil), t)
reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t); reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t)
reportError("fInt64", CheckEqual(fInt64, fInt64, nil), t); reportError("fInt64", CheckEqual(fInt64, fInt64, nil), t)
reportError("fInt8", CheckEqual(fInt8, fInt8, nil), t); reportError("fInt8", CheckEqual(fInt8, fInt8, nil), t)
reportError("fInt", CheckEqual(fInt, fInt, nil), t); reportError("fInt", CheckEqual(fInt, fInt, nil), t)
reportError("fUInt8", CheckEqual(fUInt8, fUInt8, nil), t); reportError("fUInt8", CheckEqual(fUInt8, fUInt8, nil), t)
reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t); reportError("fInt32", CheckEqual(fInt32, fInt32, nil), t)
reportError("fMap", CheckEqual(fMap, fMap, nil), t); reportError("fMap", CheckEqual(fMap, fMap, nil), t)
reportError("fSlice", CheckEqual(fSlice, fSlice, nil), t); reportError("fSlice", CheckEqual(fSlice, fSlice, nil), t)
reportError("fString", CheckEqual(fString, fString, nil), t); reportError("fString", CheckEqual(fString, fString, nil), t)
reportError("fStruct", CheckEqual(fStruct, fStruct, nil), t); reportError("fStruct", CheckEqual(fStruct, fStruct, nil), t)
reportError("fUint16", CheckEqual(fUint16, fUint16, nil), t); reportError("fUint16", CheckEqual(fUint16, fUint16, nil), t)
reportError("fUint32", CheckEqual(fUint32, fUint32, nil), t); reportError("fUint32", CheckEqual(fUint32, fUint32, nil), t)
reportError("fUint64", CheckEqual(fUint64, fUint64, nil), t); reportError("fUint64", CheckEqual(fUint64, fUint64, nil), t)
reportError("fUint8", CheckEqual(fUint8, fUint8, nil), t); reportError("fUint8", CheckEqual(fUint8, fUint8, nil), t)
reportError("fUint", CheckEqual(fUint, fUint, nil), t); reportError("fUint", CheckEqual(fUint, fUint, nil), t)
reportError("fUintptr", CheckEqual(fUintptr, fUintptr, nil), t); reportError("fUintptr", CheckEqual(fUintptr, fUintptr, nil), t)
reportError("fIntptr", CheckEqual(fIntptr, fIntptr, nil), t); reportError("fIntptr", CheckEqual(fIntptr, fIntptr, nil), t)
} }
// This tests that ArbitraryValue is working by checking that all the arbitrary // This tests that ArbitraryValue is working by checking that all the arbitrary
// values of type MyStruct have x = 42. // values of type MyStruct have x = 42.
type myStruct struct { type myStruct struct {
x int; x int
} }
func (m myStruct) Generate(r *rand.Rand, _ int) reflect.Value { func (m myStruct) Generate(r *rand.Rand, _ int) reflect.Value {
...@@ -109,8 +109,8 @@ func TestCheckProperty(t *testing.T) { ...@@ -109,8 +109,8 @@ func TestCheckProperty(t *testing.T) {
} }
func TestFailure(t *testing.T) { func TestFailure(t *testing.T) {
f := func(x int) bool { return false }; f := func(x int) bool { return false }
err := Check(f, nil); err := Check(f, nil)
if err == nil { if err == nil {
t.Errorf("Check didn't return an error") t.Errorf("Check didn't return an error")
} }
...@@ -118,7 +118,7 @@ func TestFailure(t *testing.T) { ...@@ -118,7 +118,7 @@ func TestFailure(t *testing.T) {
t.Errorf("Error was not a CheckError: %s", err) t.Errorf("Error was not a CheckError: %s", err)
} }
err = CheckEqual(fUint, fUint32, nil); err = CheckEqual(fUint, fUint32, nil)
if err == nil { if err == nil {
t.Errorf("#1 CheckEqual didn't return an error") t.Errorf("#1 CheckEqual didn't return an error")
} }
...@@ -126,7 +126,7 @@ func TestFailure(t *testing.T) { ...@@ -126,7 +126,7 @@ func TestFailure(t *testing.T) {
t.Errorf("#1 Error was not a SetupError: %s", err) t.Errorf("#1 Error was not a SetupError: %s", err)
} }
err = CheckEqual(func(x, y int) {}, func(x int) {}, nil); err = CheckEqual(func(x, y int) {}, func(x int) {}, nil)
if err == nil { if err == nil {
t.Errorf("#2 CheckEqual didn't return an error") t.Errorf("#2 CheckEqual didn't return an error")
} }
...@@ -134,7 +134,7 @@ func TestFailure(t *testing.T) { ...@@ -134,7 +134,7 @@ func TestFailure(t *testing.T) {
t.Errorf("#2 Error was not a SetupError: %s", err) t.Errorf("#2 Error was not a SetupError: %s", err)
} }
err = CheckEqual(func(x int) int { return 0 }, func(x int) int32 { return 0 }, nil); err = CheckEqual(func(x int) int { return 0 }, func(x int) int32 { return 0 }, nil)
if err == nil { if err == nil {
t.Errorf("#3 CheckEqual didn't return an error") t.Errorf("#3 CheckEqual didn't return an error")
} }
......
This diff is collapsed.
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
package testing package testing
import ( import (
"strings"; "strings"
) )
var good_re = []string{ var good_re = []string{
...@@ -30,8 +30,8 @@ var good_re = []string{ ...@@ -30,8 +30,8 @@ var good_re = []string{
// TODO: nice to do this with a map // TODO: nice to do this with a map
type stringError struct { type stringError struct {
re string; re string
err string; err string
} }
var bad_re = []stringError{ var bad_re = []stringError{
...@@ -52,9 +52,9 @@ var bad_re = []stringError{ ...@@ -52,9 +52,9 @@ var bad_re = []stringError{
type vec []int type vec []int
type tester struct { type tester struct {
re string; re string
text string; text string
match vec; match vec
} }
var matches = []tester{ var matches = []tester{
...@@ -87,15 +87,15 @@ var matches = []tester{ ...@@ -87,15 +87,15 @@ var matches = []tester{
} }
func compileTest(t *T, expr string, error string) *Regexp { func compileTest(t *T, expr string, error string) *Regexp {
re, err := CompileRegexp(expr); re, err := CompileRegexp(expr)
if err != error { if err != error {
t.Error("compiling `", expr, "`; unexpected error: ", err) t.Error("compiling `", expr, "`; unexpected error: ", err)
} }
return re; return re
} }
func printVec(t *T, m []int) { func printVec(t *T, m []int) {
l := len(m); l := len(m)
if l == 0 { if l == 0 {
t.Log("\t<no match>") t.Log("\t<no match>")
} else { } else {
...@@ -106,7 +106,7 @@ func printVec(t *T, m []int) { ...@@ -106,7 +106,7 @@ func printVec(t *T, m []int) {
} }
func printStrings(t *T, m []string) { func printStrings(t *T, m []string) {
l := len(m); l := len(m)
if l == 0 { if l == 0 {
t.Log("\t<no match>") t.Log("\t<no match>")
} else { } else {
...@@ -117,7 +117,7 @@ func printStrings(t *T, m []string) { ...@@ -117,7 +117,7 @@ func printStrings(t *T, m []string) {
} }
func printBytes(t *T, b [][]byte) { func printBytes(t *T, b [][]byte) {
l := len(b); l := len(b)
if l == 0 { if l == 0 {
t.Log("\t<no match>") t.Log("\t<no match>")
} else { } else {
...@@ -128,7 +128,7 @@ func printBytes(t *T, b [][]byte) { ...@@ -128,7 +128,7 @@ func printBytes(t *T, b [][]byte) {
} }
func equal(m1, m2 []int) bool { func equal(m1, m2 []int) bool {
l := len(m1); l := len(m1)
if l != len(m2) { if l != len(m2) {
return false return false
} }
...@@ -137,11 +137,11 @@ func equal(m1, m2 []int) bool { ...@@ -137,11 +137,11 @@ func equal(m1, m2 []int) bool {
return false return false
} }
} }
return true; return true
} }
func equalStrings(m1, m2 []string) bool { func equalStrings(m1, m2 []string) bool {
l := len(m1); l := len(m1)
if l != len(m2) { if l != len(m2) {
return false return false
} }
...@@ -150,11 +150,11 @@ func equalStrings(m1, m2 []string) bool { ...@@ -150,11 +150,11 @@ func equalStrings(m1, m2 []string) bool {
return false return false
} }
} }
return true; return true
} }
func equalBytes(m1 [][]byte, m2 []string) bool { func equalBytes(m1 [][]byte, m2 []string) bool {
l := len(m1); l := len(m1)
if l != len(m2) { if l != len(m2) {
return false return false
} }
...@@ -163,28 +163,28 @@ func equalBytes(m1 [][]byte, m2 []string) bool { ...@@ -163,28 +163,28 @@ func equalBytes(m1 [][]byte, m2 []string) bool {
return false return false
} }
} }
return true; return true
} }
func executeTest(t *T, expr string, str string, match []int) { func executeTest(t *T, expr string, str string, match []int) {
re := compileTest(t, expr, ""); re := compileTest(t, expr, "")
if re == nil { if re == nil {
return return
} }
m := re.ExecuteString(str); m := re.ExecuteString(str)
if !equal(m, match) { if !equal(m, match) {
t.Error("ExecuteString failure on `", expr, "` matching `", str, "`:"); t.Error("ExecuteString failure on `", expr, "` matching `", str, "`:")
printVec(t, m); printVec(t, m)
t.Log("should be:"); t.Log("should be:")
printVec(t, match); printVec(t, match)
} }
// now try bytes // now try bytes
m = re.Execute(strings.Bytes(str)); m = re.Execute(strings.Bytes(str))
if !equal(m, match) { if !equal(m, match) {
t.Error("Execute failure on `", expr, "` matching `", str, "`:"); t.Error("Execute failure on `", expr, "` matching `", str, "`:")
printVec(t, m); printVec(t, m)
t.Log("should be:"); t.Log("should be:")
printVec(t, match); printVec(t, match)
} }
} }
...@@ -202,22 +202,22 @@ func TestBadCompile(t *T) { ...@@ -202,22 +202,22 @@ func TestBadCompile(t *T) {
func TestExecute(t *T) { func TestExecute(t *T) {
for i := 0; i < len(matches); i++ { for i := 0; i < len(matches); i++ {
test := &matches[i]; test := &matches[i]
executeTest(t, test.re, test.text, test.match); executeTest(t, test.re, test.text, test.match)
} }
} }
func matchTest(t *T, expr string, str string, match []int) { func matchTest(t *T, expr string, str string, match []int) {
re := compileTest(t, expr, ""); re := compileTest(t, expr, "")
if re == nil { if re == nil {
return return
} }
m := re.MatchString(str); m := re.MatchString(str)
if m != (len(match) > 0) { if m != (len(match) > 0) {
t.Error("MatchString failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0) t.Error("MatchString failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0)
} }
// now try bytes // now try bytes
m = re.Match(strings.Bytes(str)); m = re.Match(strings.Bytes(str))
if m != (len(match) > 0) { if m != (len(match) > 0) {
t.Error("Match failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0) t.Error("Match failure on `", expr, "` matching `", str, "`:", m, "should be", len(match) > 0)
} }
...@@ -225,46 +225,46 @@ func matchTest(t *T, expr string, str string, match []int) { ...@@ -225,46 +225,46 @@ func matchTest(t *T, expr string, str string, match []int) {
func TestMatch(t *T) { func TestMatch(t *T) {
for i := 0; i < len(matches); i++ { for i := 0; i < len(matches); i++ {
test := &matches[i]; test := &matches[i]
matchTest(t, test.re, test.text, test.match); matchTest(t, test.re, test.text, test.match)
} }
} }
func matchStringsTest(t *T, expr string, str string, match []int) { func matchStringsTest(t *T, expr string, str string, match []int) {
re := compileTest(t, expr, ""); re := compileTest(t, expr, "")
if re == nil { if re == nil {
return return
} }
strs := make([]string, len(match)/2); strs := make([]string, len(match)/2)
for i := 0; i < len(match); i++ { for i := 0; i < len(match); i++ {
strs[i/2] = str[match[i]:match[i+1]] strs[i/2] = str[match[i]:match[i+1]]
} }
m := re.MatchStrings(str); m := re.MatchStrings(str)
if !equalStrings(m, strs) { if !equalStrings(m, strs) {
t.Error("MatchStrings failure on `", expr, "` matching `", str, "`:"); t.Error("MatchStrings failure on `", expr, "` matching `", str, "`:")
printStrings(t, m); printStrings(t, m)
t.Log("should be:"); t.Log("should be:")
printStrings(t, strs); printStrings(t, strs)
} }
// now try bytes // now try bytes
s := re.MatchSlices(strings.Bytes(str)); s := re.MatchSlices(strings.Bytes(str))
if !equalBytes(s, strs) { if !equalBytes(s, strs) {
t.Error("MatchSlices failure on `", expr, "` matching `", str, "`:"); t.Error("MatchSlices failure on `", expr, "` matching `", str, "`:")
printBytes(t, s); printBytes(t, s)
t.Log("should be:"); t.Log("should be:")
printStrings(t, strs); printStrings(t, strs)
} }
} }
func TestMatchStrings(t *T) { func TestMatchStrings(t *T) {
for i := 0; i < len(matches); i++ { for i := 0; i < len(matches); i++ {
test := &matches[i]; test := &matches[i]
matchTest(t, test.re, test.text, test.match); matchTest(t, test.re, test.text, test.match)
} }
} }
func matchFunctionTest(t *T, expr string, str string, match []int) { func matchFunctionTest(t *T, expr string, str string, match []int) {
m, err := MatchString(expr, str); m, err := MatchString(expr, str)
if err == "" { if err == "" {
return return
} }
...@@ -275,15 +275,15 @@ func matchFunctionTest(t *T, expr string, str string, match []int) { ...@@ -275,15 +275,15 @@ func matchFunctionTest(t *T, expr string, str string, match []int) {
func TestMatchFunction(t *T) { func TestMatchFunction(t *T) {
for i := 0; i < len(matches); i++ { for i := 0; i < len(matches); i++ {
test := &matches[i]; test := &matches[i]
matchFunctionTest(t, test.re, test.text, test.match); matchFunctionTest(t, test.re, test.text, test.match)
} }
} }
func BenchmarkSimpleMatch(b *B) { func BenchmarkSimpleMatch(b *B) {
b.StopTimer(); b.StopTimer()
re, _ := CompileRegexp("a"); re, _ := CompileRegexp("a")
b.StartTimer(); b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
re.MatchString("a") re.MatchString("a")
...@@ -291,9 +291,9 @@ func BenchmarkSimpleMatch(b *B) { ...@@ -291,9 +291,9 @@ func BenchmarkSimpleMatch(b *B) {
} }
func BenchmarkUngroupedMatch(b *B) { func BenchmarkUngroupedMatch(b *B) {
b.StopTimer(); b.StopTimer()
re, _ := CompileRegexp("[a-z]+ [0-9]+ [a-z]+"); re, _ := CompileRegexp("[a-z]+ [0-9]+ [a-z]+")
b.StartTimer(); b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
re.MatchString("word 123 other") re.MatchString("word 123 other")
...@@ -301,9 +301,9 @@ func BenchmarkUngroupedMatch(b *B) { ...@@ -301,9 +301,9 @@ func BenchmarkUngroupedMatch(b *B) {
} }
func BenchmarkGroupedMatch(b *B) { func BenchmarkGroupedMatch(b *B) {
b.StopTimer(); b.StopTimer()
re, _ := CompileRegexp("([a-z]+) ([0-9]+) ([a-z]+)"); re, _ := CompileRegexp("([a-z]+) ([0-9]+) ([a-z]+)")
b.StartTimer(); b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
re.MatchString("word 123 other") re.MatchString("word 123 other")
......
...@@ -6,37 +6,37 @@ ...@@ -6,37 +6,37 @@
package script package script
import ( import (
"fmt"; "fmt"
"os"; "os"
"rand"; "rand"
"reflect"; "reflect"
"strings"; "strings"
) )
// An Event is an element in a partially ordered set that either sends a value // An Event is an element in a partially ordered set that either sends a value
// to a channel or expects a value from a channel. // to a channel or expects a value from a channel.
type Event struct { type Event struct {
name string; name string
occurred bool; occurred bool
predecessors []*Event; predecessors []*Event
action action; action action
} }
type action interface { type action interface {
// getSend returns nil if the action is not a send action. // getSend returns nil if the action is not a send action.
getSend() sendAction; getSend() sendAction
// getRecv returns nil if the action is not a receive action. // getRecv returns nil if the action is not a receive action.
getRecv() recvAction; getRecv() recvAction
// getChannel returns the channel that the action operates on. // getChannel returns the channel that the action operates on.
getChannel() interface{}; getChannel() interface{}
} }
type recvAction interface { type recvAction interface {
recvMatch(interface{}) bool; recvMatch(interface{}) bool
} }
type sendAction interface { type sendAction interface {
send(); send()
} }
// isReady returns true if all the predecessors of an Event have occurred. // isReady returns true if all the predecessors of an Event have occurred.
...@@ -47,14 +47,14 @@ func (e Event) isReady() bool { ...@@ -47,14 +47,14 @@ func (e Event) isReady() bool {
} }
} }
return true; return true
} }
// A Recv action reads a value from a channel and uses reflect.DeepMatch to // A Recv action reads a value from a channel and uses reflect.DeepMatch to
// compare it with an expected value. // compare it with an expected value.
type Recv struct { type Recv struct {
Channel interface{}; Channel interface{}
Expected interface{}; Expected interface{}
} }
func (r Recv) getRecv() recvAction { return r } func (r Recv) getRecv() recvAction { return r }
...@@ -64,19 +64,19 @@ func (Recv) getSend() sendAction { return nil } ...@@ -64,19 +64,19 @@ func (Recv) getSend() sendAction { return nil }
func (r Recv) getChannel() interface{} { return r.Channel } func (r Recv) getChannel() interface{} { return r.Channel }
func (r Recv) recvMatch(chanEvent interface{}) bool { func (r Recv) recvMatch(chanEvent interface{}) bool {
c, ok := chanEvent.(channelRecv); c, ok := chanEvent.(channelRecv)
if !ok || c.channel != r.Channel { if !ok || c.channel != r.Channel {
return false return false
} }
return reflect.DeepEqual(c.value, r.Expected); return reflect.DeepEqual(c.value, r.Expected)
} }
// A RecvMatch action reads a value from a channel and calls a function to // A RecvMatch action reads a value from a channel and calls a function to
// determine if the value matches. // determine if the value matches.
type RecvMatch struct { type RecvMatch struct {
Channel interface{}; Channel interface{}
Match func(interface{}) bool; Match func(interface{}) bool
} }
func (r RecvMatch) getRecv() recvAction { return r } func (r RecvMatch) getRecv() recvAction { return r }
...@@ -86,19 +86,19 @@ func (RecvMatch) getSend() sendAction { return nil } ...@@ -86,19 +86,19 @@ func (RecvMatch) getSend() sendAction { return nil }
func (r RecvMatch) getChannel() interface{} { return r.Channel } func (r RecvMatch) getChannel() interface{} { return r.Channel }
func (r RecvMatch) recvMatch(chanEvent interface{}) bool { func (r RecvMatch) recvMatch(chanEvent interface{}) bool {
c, ok := chanEvent.(channelRecv); c, ok := chanEvent.(channelRecv)
if !ok || c.channel != r.Channel { if !ok || c.channel != r.Channel {
return false return false
} }
return r.Match(c.value); return r.Match(c.value)
} }
// A Closed action matches if the given channel is closed. The closing is // A Closed action matches if the given channel is closed. The closing is
// treated as an event, not a state, thus Closed will only match once for a // treated as an event, not a state, thus Closed will only match once for a
// given channel. // given channel.
type Closed struct { type Closed struct {
Channel interface{}; Channel interface{}
} }
func (r Closed) getRecv() recvAction { return r } func (r Closed) getRecv() recvAction { return r }
...@@ -108,19 +108,19 @@ func (Closed) getSend() sendAction { return nil } ...@@ -108,19 +108,19 @@ func (Closed) getSend() sendAction { return nil }
func (r Closed) getChannel() interface{} { return r.Channel } func (r Closed) getChannel() interface{} { return r.Channel }
func (r Closed) recvMatch(chanEvent interface{}) bool { func (r Closed) recvMatch(chanEvent interface{}) bool {
c, ok := chanEvent.(channelClosed); c, ok := chanEvent.(channelClosed)
if !ok || c.channel != r.Channel { if !ok || c.channel != r.Channel {
return false return false
} }
return true; return true
} }
// A Send action sends a value to a channel. The value must match the // A Send action sends a value to a channel. The value must match the
// type of the channel exactly unless the channel if of type chan interface{}. // type of the channel exactly unless the channel if of type chan interface{}.
type Send struct { type Send struct {
Channel interface{}; Channel interface{}
Value interface{}; Value interface{}
} }
func (Send) getRecv() recvAction { return nil } func (Send) getRecv() recvAction { return nil }
...@@ -137,19 +137,19 @@ func (s Send) send() { ...@@ -137,19 +137,19 @@ func (s Send) send() {
// With reflect.ChanValue.Send, we must match the types exactly. So, if // With reflect.ChanValue.Send, we must match the types exactly. So, if
// s.Channel is a chan interface{} we convert s.Value to an interface{} // s.Channel is a chan interface{} we convert s.Value to an interface{}
// first. // first.
c := reflect.NewValue(s.Channel).(*reflect.ChanValue); c := reflect.NewValue(s.Channel).(*reflect.ChanValue)
var v reflect.Value; var v reflect.Value
if iface, ok := c.Type().(*reflect.ChanType).Elem().(*reflect.InterfaceType); ok && iface.NumMethod() == 0 { if iface, ok := c.Type().(*reflect.ChanType).Elem().(*reflect.InterfaceType); ok && iface.NumMethod() == 0 {
v = newEmptyInterface(s.Value) v = newEmptyInterface(s.Value)
} else { } else {
v = reflect.NewValue(s.Value) v = reflect.NewValue(s.Value)
} }
c.Send(v); c.Send(v)
} }
// A Close action closes the given channel. // A Close action closes the given channel.
type Close struct { type Close struct {
Channel interface{}; Channel interface{}
} }
func (Close) getRecv() recvAction { return nil } func (Close) getRecv() recvAction { return nil }
...@@ -163,16 +163,16 @@ func (s Close) send() { reflect.NewValue(s.Channel).(*reflect.ChanValue).Close() ...@@ -163,16 +163,16 @@ func (s Close) send() { reflect.NewValue(s.Channel).(*reflect.ChanValue).Close()
// A ReceivedUnexpected error results if no active Events match a value // A ReceivedUnexpected error results if no active Events match a value
// received from a channel. // received from a channel.
type ReceivedUnexpected struct { type ReceivedUnexpected struct {
Value interface{}; Value interface{}
ready []*Event; ready []*Event
} }
func (r ReceivedUnexpected) String() string { func (r ReceivedUnexpected) String() string {
names := make([]string, len(r.ready)); names := make([]string, len(r.ready))
for i, v := range r.ready { for i, v := range r.ready {
names[i] = v.name names[i] = v.name
} }
return fmt.Sprintf("received unexpected value on one of the channels: %#v. Runnable events: %s", r.Value, strings.Join(names, ", ")); return fmt.Sprintf("received unexpected value on one of the channels: %#v. Runnable events: %s", r.Value, strings.Join(names, ", "))
} }
// A SetupError results if there is a error with the configuration of a set of // A SetupError results if there is a error with the configuration of a set of
...@@ -182,8 +182,8 @@ type SetupError string ...@@ -182,8 +182,8 @@ type SetupError string
func (s SetupError) String() string { return string(s) } func (s SetupError) String() string { return string(s) }
func NewEvent(name string, predecessors []*Event, action action) *Event { func NewEvent(name string, predecessors []*Event, action action) *Event {
e := &Event{name, false, predecessors, action}; e := &Event{name, false, predecessors, action}
return e; return e
} }
// Given a set of Events, Perform repeatedly iterates over the set and finds the // Given a set of Events, Perform repeatedly iterates over the set and finds the
...@@ -220,20 +220,20 @@ func NewEvent(name string, predecessors []*Event, action action) *Event { ...@@ -220,20 +220,20 @@ func NewEvent(name string, predecessors []*Event, action action) *Event {
// thus Perform may see a value from a channel that is not in the current ready // thus Perform may see a value from a channel that is not in the current ready
// set and fail. // set and fail.
func Perform(seed int64, events []*Event) (err os.Error) { func Perform(seed int64, events []*Event) (err os.Error) {
r := rand.New(rand.NewSource(seed)); r := rand.New(rand.NewSource(seed))
channels, err := getChannels(events); channels, err := getChannels(events)
if err != nil { if err != nil {
return return
} }
multiplex := make(chan interface{}); multiplex := make(chan interface{})
for _, channel := range channels { for _, channel := range channels {
go recvValues(multiplex, channel) go recvValues(multiplex, channel)
} }
Outer: Outer:
for { for {
ready, err := readyEvents(events); ready, err := readyEvents(events)
if err != nil { if err != nil {
return err return err
} }
...@@ -243,113 +243,113 @@ Outer: ...@@ -243,113 +243,113 @@ Outer:
break break
} }
event := ready[r.Intn(len(ready))]; event := ready[r.Intn(len(ready))]
if send := event.action.getSend(); send != nil { if send := event.action.getSend(); send != nil {
send.send(); send.send()
event.occurred = true; event.occurred = true
continue; continue
} }
v := <-multiplex; v := <-multiplex
for _, event := range ready { for _, event := range ready {
if recv := event.action.getRecv(); recv != nil && recv.recvMatch(v) { if recv := event.action.getRecv(); recv != nil && recv.recvMatch(v) {
event.occurred = true; event.occurred = true
continue Outer; continue Outer
} }
} }
return ReceivedUnexpected{v, ready}; return ReceivedUnexpected{v, ready}
} }
return nil; return nil
} }
// getChannels returns all the channels listed in any receive events. // getChannels returns all the channels listed in any receive events.
func getChannels(events []*Event) ([]interface{}, os.Error) { func getChannels(events []*Event) ([]interface{}, os.Error) {
channels := make([]interface{}, len(events)); channels := make([]interface{}, len(events))
j := 0; j := 0
for _, event := range events { for _, event := range events {
if recv := event.action.getRecv(); recv == nil { if recv := event.action.getRecv(); recv == nil {
continue continue
} }
c := event.action.getChannel(); c := event.action.getChannel()
if _, ok := reflect.NewValue(c).(*reflect.ChanValue); !ok { if _, ok := reflect.NewValue(c).(*reflect.ChanValue); !ok {
return nil, SetupError("one of the channel values is not a channel") return nil, SetupError("one of the channel values is not a channel")
} }
duplicate := false; duplicate := false
for _, other := range channels[0:j] { for _, other := range channels[0:j] {
if c == other { if c == other {
duplicate = true; duplicate = true
break; break
} }
} }
if !duplicate { if !duplicate {
channels[j] = c; channels[j] = c
j++; j++
} }
} }
return channels[0:j], nil; return channels[0:j], nil
} }
// recvValues is a multiplexing helper function. It reads values from the given // recvValues is a multiplexing helper function. It reads values from the given
// channel repeatedly, wrapping them up as either a channelRecv or // channel repeatedly, wrapping them up as either a channelRecv or
// channelClosed structure, and forwards them to the multiplex channel. // channelClosed structure, and forwards them to the multiplex channel.
func recvValues(multiplex chan<- interface{}, channel interface{}) { func recvValues(multiplex chan<- interface{}, channel interface{}) {
c := reflect.NewValue(channel).(*reflect.ChanValue); c := reflect.NewValue(channel).(*reflect.ChanValue)
for { for {
v := c.Recv(); v := c.Recv()
if c.Closed() { if c.Closed() {
multiplex <- channelClosed{channel}; multiplex <- channelClosed{channel}
return; return
} }
multiplex <- channelRecv{channel, v.Interface()}; multiplex <- channelRecv{channel, v.Interface()}
} }
} }
type channelClosed struct { type channelClosed struct {
channel interface{}; channel interface{}
} }
type channelRecv struct { type channelRecv struct {
channel interface{}; channel interface{}
value interface{}; value interface{}
} }
// readyEvents returns the subset of events that are ready. // readyEvents returns the subset of events that are ready.
func readyEvents(events []*Event) ([]*Event, os.Error) { func readyEvents(events []*Event) ([]*Event, os.Error) {
ready := make([]*Event, len(events)); ready := make([]*Event, len(events))
j := 0; j := 0
eventsWaiting := false; eventsWaiting := false
for _, event := range events { for _, event := range events {
if event.occurred { if event.occurred {
continue continue
} }
eventsWaiting = true; eventsWaiting = true
if event.isReady() { if event.isReady() {
ready[j] = event; ready[j] = event
j++; j++
} }
} }
if j == 0 && eventsWaiting { if j == 0 && eventsWaiting {
names := make([]string, len(events)); names := make([]string, len(events))
for _, event := range events { for _, event := range events {
if event.occurred { if event.occurred {
continue continue
} }
names[j] = event.name; names[j] = event.name
} }
return nil, SetupError("dependency cycle in events. These events are waiting to run but cannot: " + strings.Join(names, ", ")); return nil, SetupError("dependency cycle in events. These events are waiting to run but cannot: " + strings.Join(names, ", "))
} }
return ready[0:j], nil; return ready[0:j], nil
} }
...@@ -5,37 +5,37 @@ ...@@ -5,37 +5,37 @@
package script package script
import ( import (
"testing"; "testing"
) )
func TestNoop(t *testing.T) { func TestNoop(t *testing.T) {
err := Perform(0, nil); err := Perform(0, nil)
if err != nil { if err != nil {
t.Errorf("Got error: %s", err) t.Errorf("Got error: %s", err)
} }
} }
func TestSimple(t *testing.T) { func TestSimple(t *testing.T) {
c := make(chan int); c := make(chan int)
defer close(c); defer close(c)
a := NewEvent("send", nil, Send{c, 1}); a := NewEvent("send", nil, Send{c, 1})
b := NewEvent("recv", []*Event{a}, Recv{c, 1}); b := NewEvent("recv", []*Event{a}, Recv{c, 1})
err := Perform(0, []*Event{a, b}); err := Perform(0, []*Event{a, b})
if err != nil { if err != nil {
t.Errorf("Got error: %s", err) t.Errorf("Got error: %s", err)
} }
} }
func TestFail(t *testing.T) { func TestFail(t *testing.T) {
c := make(chan int); c := make(chan int)
defer close(c); defer close(c)
a := NewEvent("send", nil, Send{c, 2}); a := NewEvent("send", nil, Send{c, 2})
b := NewEvent("recv", []*Event{a}, Recv{c, 1}); b := NewEvent("recv", []*Event{a}, Recv{c, 1})
err := Perform(0, []*Event{a, b}); err := Perform(0, []*Event{a, b})
if err == nil { if err == nil {
t.Errorf("Failed to get expected error") t.Errorf("Failed to get expected error")
} else if _, ok := err.(ReceivedUnexpected); !ok { } else if _, ok := err.(ReceivedUnexpected); !ok {
...@@ -44,12 +44,12 @@ func TestFail(t *testing.T) { ...@@ -44,12 +44,12 @@ func TestFail(t *testing.T) {
} }
func TestClose(t *testing.T) { func TestClose(t *testing.T) {
c := make(chan int); c := make(chan int)
a := NewEvent("close", nil, Close{c}); a := NewEvent("close", nil, Close{c})
b := NewEvent("closed", []*Event{a}, Closed{c}); b := NewEvent("closed", []*Event{a}, Closed{c})
err := Perform(0, []*Event{a, b}); err := Perform(0, []*Event{a, b})
if err != nil { if err != nil {
t.Errorf("Got error: %s", err) t.Errorf("Got error: %s", err)
} }
...@@ -59,16 +59,16 @@ func matchOne(v interface{}) bool { ...@@ -59,16 +59,16 @@ func matchOne(v interface{}) bool {
if i, ok := v.(int); ok && i == 1 { if i, ok := v.(int); ok && i == 1 {
return true return true
} }
return false; return false
} }
func TestRecvMatch(t *testing.T) { func TestRecvMatch(t *testing.T) {
c := make(chan int); c := make(chan int)
a := NewEvent("send", nil, Send{c, 1}); a := NewEvent("send", nil, Send{c, 1})
b := NewEvent("recv", []*Event{a}, RecvMatch{c, matchOne}); b := NewEvent("recv", []*Event{a}, RecvMatch{c, matchOne})
err := Perform(0, []*Event{a, b}); err := Perform(0, []*Event{a, b})
if err != nil { if err != nil {
t.Errorf("Got error: %s", err) t.Errorf("Got error: %s", err)
} }
......
...@@ -39,10 +39,10 @@ ...@@ -39,10 +39,10 @@
package testing package testing
import ( import (
"flag"; "flag"
"fmt"; "fmt"
"os"; "os"
"runtime"; "runtime"
) )
// Report as tests are run; default is silent for success. // Report as tests are run; default is silent for success.
...@@ -52,25 +52,25 @@ var match = flag.String("match", "", "regular expression to select tests to run" ...@@ -52,25 +52,25 @@ var match = flag.String("match", "", "regular expression to select tests to run"
// Insert final newline if needed and tabs after internal newlines. // Insert final newline if needed and tabs after internal newlines.
func tabify(s string) string { func tabify(s string) string {
n := len(s); n := len(s)
if n > 0 && s[n-1] != '\n' { if n > 0 && s[n-1] != '\n' {
s += "\n"; s += "\n"
n++; n++
} }
for i := 0; i < n-1; i++ { // -1 to avoid final newline for i := 0; i < n-1; i++ { // -1 to avoid final newline
if s[i] == '\n' { if s[i] == '\n' {
return s[0:i+1] + "\t" + tabify(s[i+1:n]) return s[0:i+1] + "\t" + tabify(s[i+1:n])
} }
} }
return s; return s
} }
// T is a type passed to Test functions to manage test state and support formatted test logs. // T is a type passed to Test functions to manage test state and support formatted test logs.
// Logs are accumulated during execution and dumped to standard error when done. // Logs are accumulated during execution and dumped to standard error when done.
type T struct { type T struct {
errors string; errors string
failed bool; failed bool
ch chan *T; ch chan *T
} }
// Fail marks the Test function as having failed but continues execution. // Fail marks the Test function as having failed but continues execution.
...@@ -82,9 +82,9 @@ func (t *T) Failed() bool { return t.failed } ...@@ -82,9 +82,9 @@ func (t *T) Failed() bool { return t.failed }
// FailNow marks the Test function as having failed and stops its execution. // FailNow marks the Test function as having failed and stops its execution.
// Execution will continue at the next Test. // Execution will continue at the next Test.
func (t *T) FailNow() { func (t *T) FailNow() {
t.Fail(); t.Fail()
t.ch <- t; t.ch <- t
runtime.Goexit(); runtime.Goexit()
} }
// Log formats its arguments using default formatting, analogous to Print(), // Log formats its arguments using default formatting, analogous to Print(),
...@@ -99,52 +99,52 @@ func (t *T) Logf(format string, args ...) { ...@@ -99,52 +99,52 @@ func (t *T) Logf(format string, args ...) {
// Error is equivalent to Log() followed by Fail(). // Error is equivalent to Log() followed by Fail().
func (t *T) Error(args ...) { func (t *T) Error(args ...) {
t.Log(args); t.Log(args)
t.Fail(); t.Fail()
} }
// Errorf is equivalent to Logf() followed by Fail(). // Errorf is equivalent to Logf() followed by Fail().
func (t *T) Errorf(format string, args ...) { func (t *T) Errorf(format string, args ...) {
t.Logf(format, args); t.Logf(format, args)
t.Fail(); t.Fail()
} }
// Fatal is equivalent to Log() followed by FailNow(). // Fatal is equivalent to Log() followed by FailNow().
func (t *T) Fatal(args ...) { func (t *T) Fatal(args ...) {
t.Log(args); t.Log(args)
t.FailNow(); t.FailNow()
} }
// Fatalf is equivalent to Logf() followed by FailNow(). // Fatalf is equivalent to Logf() followed by FailNow().
func (t *T) Fatalf(format string, args ...) { func (t *T) Fatalf(format string, args ...) {
t.Logf(format, args); t.Logf(format, args)
t.FailNow(); t.FailNow()
} }
// An internal type but exported because it is cross-package; part of the implementation // An internal type but exported because it is cross-package; part of the implementation
// of gotest. // of gotest.
type Test struct { type Test struct {
Name string; Name string
F func(*T); F func(*T)
} }
func tRunner(t *T, test *Test) { func tRunner(t *T, test *Test) {
test.F(t); test.F(t)
t.ch <- t; t.ch <- t
} }
// An internal function but exported because it is cross-package; part of the implementation // An internal function but exported because it is cross-package; part of the implementation
// of gotest. // of gotest.
func Main(tests []Test) { func Main(tests []Test) {
flag.Parse(); flag.Parse()
ok := true; ok := true
if len(tests) == 0 { if len(tests) == 0 {
println("testing: warning: no tests to run") println("testing: warning: no tests to run")
} }
re, err := CompileRegexp(*match); re, err := CompileRegexp(*match)
if err != "" { if err != "" {
println("invalid regexp for -match:", err); println("invalid regexp for -match:", err)
os.Exit(1); os.Exit(1)
} }
for i := 0; i < len(tests); i++ { for i := 0; i < len(tests); i++ {
if !re.MatchString(tests[i].Name) { if !re.MatchString(tests[i].Name) {
...@@ -153,22 +153,22 @@ func Main(tests []Test) { ...@@ -153,22 +153,22 @@ func Main(tests []Test) {
if *chatty { if *chatty {
println("=== RUN ", tests[i].Name) println("=== RUN ", tests[i].Name)
} }
t := new(T); t := new(T)
t.ch = make(chan *T); t.ch = make(chan *T)
go tRunner(t, &tests[i]); go tRunner(t, &tests[i])
<-t.ch; <-t.ch
if t.failed { if t.failed {
println("--- FAIL:", tests[i].Name); println("--- FAIL:", tests[i].Name)
print(t.errors); print(t.errors)
ok = false; ok = false
} else if *chatty { } else if *chatty {
println("--- PASS:", tests[i].Name); println("--- PASS:", tests[i].Name)
print(t.errors); print(t.errors)
} }
} }
if !ok { if !ok {
println("FAIL"); println("FAIL")
os.Exit(1); os.Exit(1)
} }
println("PASS"); println("PASS")
} }
...@@ -5,8 +5,8 @@ ...@@ -5,8 +5,8 @@
package time package time
import ( import (
"os"; "os"
"syscall"; "syscall"
) )
// Sleep pauses the current goroutine for ns nanoseconds. // Sleep pauses the current goroutine for ns nanoseconds.
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -9,5 +9,5 @@ func IsDigit(rune int) bool { ...@@ -9,5 +9,5 @@ func IsDigit(rune int) bool {
if rune < 0x100 { // quick ASCII (Latin-1, really) check if rune < 0x100 { // quick ASCII (Latin-1, really) check
return '0' <= rune && rune <= '9' return '0' <= rune && rune <= '9'
} }
return Is(Digit, rune); return Is(Digit, rune)
} }
...@@ -5,8 +5,8 @@ ...@@ -5,8 +5,8 @@
package unicode_test package unicode_test
import ( import (
"testing"; "testing"
. "unicode"; . "unicode"
) )
var testDigit = []int{ var testDigit = []int{
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment