diff --git a/.gitignore b/.gitignore index 136c6a6..44f88f4 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ config/private.json config/local.json Godeps/Readme *.iml -bamboo +/bamboo node_modules .sass-cache builder/build diff --git a/.travis.yml b/.travis.yml index 5dc472c..c39ba98 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,13 @@ language: go sudo: false +addons: + apt: + packages: + - zookeeperd + go: - - 1.4 + - 1.7 install: # WORKING DIR @@ -11,7 +16,7 @@ install: - export PATH=$PATH:$HOME/gopath/bin # Install build dependencies - - go get bitbucket.org/tebeka/go2xunit + - go get github.com/tebeka/go2xunit - go get github.com/smartystreets/assertions - go get -t github.com/smartystreets/goconvey - go get -v -u github.com/tools/godep @@ -20,10 +25,11 @@ install: # Tests should fail if go fmt is required script: + - godep restore - '[[ -z "$(go fmt ./... | tee -a /dev/stderr)" ]]' - go vet ./... - go test -v ./... - - overalls -project=github.com/QubitProducts/bamboo -covermode=count -debug -ignore=Godeps,webapp,builder,.git + - overalls -project=github.com/QubitProducts/bamboo -covermode=count -debug -ignore=Godeps,webapp,builder,.git,vendor - goveralls -coverprofile=./overalls.coverprofile -service=travis-ci notifications: diff --git a/Dockerfile b/Dockerfile index 3cb0a8c..265e08d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,25 +1,47 @@ -FROM ubuntu:15.10 +# Need latest haproxy +FROM ubuntu:xenial ENV DEBIAN_FRONTEND noninteractive -ENV GOPATH /opt/go + +# gcc for cgo +RUN apt-get update && apt-get install -y --no-install-recommends \ + g++ \ + gcc \ + libc6-dev \ + make curl openssl ca-certificates + +ENV GOLANG_VERSION 1.7.1 +ENV GOLANG_DOWNLOAD_URL https://golang.org/dl/go$GOLANG_VERSION.linux-amd64.tar.gz +ENV GOLANG_DOWNLOAD_SHA256 43ad621c9b014cde8db17393dc108378d37bc853aa351a6c74bf6432c1bbd182 + +RUN curl -fsSL "$GOLANG_DOWNLOAD_URL" -o golang.tar.gz \ + && echo "$GOLANG_DOWNLOAD_SHA256 golang.tar.gz" | sha256sum -c - \ + && tar -C /usr/local -xzf golang.tar.gz \ + && rm golang.tar.gz + +ENV GOPATH /go +ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH + +RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" +WORKDIR $GOPATH + RUN apt-get update -yqq && \ apt-get install -yqq software-properties-common && \ - add-apt-repository -y ppa:vbernat/haproxy-1.5 && \ - apt-get update -yqq && \ - apt-get install -yqq haproxy golang git mercurial supervisor && \ + apt-get install -yqq haproxy git mercurial supervisor && \ rm -rf /var/lib/apt/lists/* -ADD . /opt/go/src/github.com/QubitProducts/bamboo + +ADD . /go/src/github.com/QubitProducts/bamboo ADD builder/supervisord.conf /etc/supervisor/conf.d/supervisord.conf ADD builder/run.sh /run.sh -WORKDIR /opt/go/src/github.com/QubitProducts/bamboo +WORKDIR /go/src/github.com/QubitProducts/bamboo RUN go get github.com/tools/godep && \ go get -t github.com/smartystreets/goconvey && \ go build && \ - ln -s /opt/go/src/github.com/QubitProducts/bamboo /var/bamboo && \ + ln -s /go/src/github.com/QubitProducts/bamboo /var/bamboo && \ mkdir -p /run/haproxy && \ mkdir -p /var/log/supervisor diff --git a/Dockerfile-deb b/Dockerfile-deb index ad7ba89..de1a73e 100644 --- a/Dockerfile-deb +++ b/Dockerfile-deb @@ -1,16 +1,14 @@ -FROM ubuntu:14.04 +FROM golang:1.7.0 ENV DEBIAN_FRONTEND noninteractive -ENV GOPATH /opt/go RUN apt-get update -yqq -RUN apt-get install -yqq software-properties-common curl git mercurial ruby-dev gcc make -RUN add-apt-repository -y ppa:ethereum/ethereum && apt-get update && apt-get -y install golang +RUN apt-get install -yqq software-properties-common curl git mercurial ruby-dev gcc make rubygems RUN gem install fpm -ADD . /opt/go/src/github.com/QubitProducts/bamboo +ADD . /go/src/github.com/QubitProducts/bamboo -WORKDIR /opt/go/src/github.com/QubitProducts/bamboo +WORKDIR /go/src/github.com/QubitProducts/bamboo RUN go get github.com/tools/godep && \ go get -t github.com/smartystreets/goconvey && \ go build diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index cfd109c..d25faa1 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,9 +1,7 @@ { "ImportPath": "github.com/QubitProducts/bamboo", - "GoVersion": "go1.4.2", - "Packages": [ - "./..." - ], + "GoVersion": "go1.7", + "GodepVersion": "v74", "Deps": [ { "ImportPath": "github.com/codegangsta/inject", @@ -15,10 +13,6 @@ "Comment": "v1.0-117-g2047b73", "Rev": "2047b7394d319aa3feb49db1452202336fb66fb6" }, - { - "ImportPath": "github.com/jtolds/gls", - "Rev": "f1ac7f4f24f50328e6bc838ca4437d1612a0243c" - }, { "ImportPath": "github.com/kardianos/osext", "Rev": "0af7634e455e7ecd558a196743d8a3f700b945c0" @@ -35,16 +29,6 @@ { "ImportPath": "github.com/samuel/go-zookeeper/zk", "Rev": "041700315ab94d5f506317d8798adc9a6674c547" - }, - { - "ImportPath": "github.com/smartystreets/assertions", - "Comment": "1.5.0-379-g75acd40", - "Rev": "75acd402ca38dc205641a826bb58b9de014926dd" - }, - { - "ImportPath": "github.com/smartystreets/goconvey/convey", - "Comment": "1.5.0-379-g01b2fc9", - "Rev": "01b2fc9c34e7acc187a4f4218ed695dd7f76c361" } ] } diff --git a/Godeps/_workspace/.gitignore b/Godeps/_workspace/.gitignore deleted file mode 100644 index f037d68..0000000 --- a/Godeps/_workspace/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/pkg -/bin diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/inject_test.go b/Godeps/_workspace/src/github.com/codegangsta/inject/inject_test.go deleted file mode 100644 index edcc94d..0000000 --- a/Godeps/_workspace/src/github.com/codegangsta/inject/inject_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package inject_test - -import ( - "fmt" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" - "reflect" - "testing" -) - -type SpecialString interface { -} - -type TestStruct struct { - Dep1 string `inject:"t" json:"-"` - Dep2 SpecialString `inject` - Dep3 string -} - -type Greeter struct { - Name string -} - -func (g *Greeter) String() string { - return "Hello, My name is" + g.Name -} - -/* Test Helpers */ -func expect(t *testing.T, a interface{}, b interface{}) { - if a != b { - t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) - } -} - -func refute(t *testing.T, a interface{}, b interface{}) { - if a == b { - t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) - } -} - -func Test_InjectorInvoke(t *testing.T) { - injector := inject.New() - expect(t, injector == nil, false) - - dep := "some dependency" - injector.Map(dep) - dep2 := "another dep" - injector.MapTo(dep2, (*SpecialString)(nil)) - dep3 := make(chan *SpecialString) - dep4 := make(chan *SpecialString) - typRecv := reflect.ChanOf(reflect.RecvDir, reflect.TypeOf(dep3).Elem()) - typSend := reflect.ChanOf(reflect.SendDir, reflect.TypeOf(dep4).Elem()) - injector.Set(typRecv, reflect.ValueOf(dep3)) - injector.Set(typSend, reflect.ValueOf(dep4)) - - _, err := injector.Invoke(func(d1 string, d2 SpecialString, d3 <-chan *SpecialString, d4 chan<- *SpecialString) { - expect(t, d1, dep) - expect(t, d2, dep2) - expect(t, reflect.TypeOf(d3).Elem(), reflect.TypeOf(dep3).Elem()) - expect(t, reflect.TypeOf(d4).Elem(), reflect.TypeOf(dep4).Elem()) - expect(t, reflect.TypeOf(d3).ChanDir(), reflect.RecvDir) - expect(t, reflect.TypeOf(d4).ChanDir(), reflect.SendDir) - }) - - expect(t, err, nil) -} - -func Test_InjectorInvokeReturnValues(t *testing.T) { - injector := inject.New() - expect(t, injector == nil, false) - - dep := "some dependency" - injector.Map(dep) - dep2 := "another dep" - injector.MapTo(dep2, (*SpecialString)(nil)) - - result, err := injector.Invoke(func(d1 string, d2 SpecialString) string { - expect(t, d1, dep) - expect(t, d2, dep2) - return "Hello world" - }) - - expect(t, result[0].String(), "Hello world") - expect(t, err, nil) -} - -func Test_InjectorApply(t *testing.T) { - injector := inject.New() - - injector.Map("a dep").MapTo("another dep", (*SpecialString)(nil)) - - s := TestStruct{} - err := injector.Apply(&s) - expect(t, err, nil) - - expect(t, s.Dep1, "a dep") - expect(t, s.Dep2, "another dep") - expect(t, s.Dep3, "") -} - -func Test_InterfaceOf(t *testing.T) { - iType := inject.InterfaceOf((*SpecialString)(nil)) - expect(t, iType.Kind(), reflect.Interface) - - iType = inject.InterfaceOf((**SpecialString)(nil)) - expect(t, iType.Kind(), reflect.Interface) - - // Expecting nil - defer func() { - rec := recover() - refute(t, rec, nil) - }() - iType = inject.InterfaceOf((*testing.T)(nil)) -} - -func Test_InjectorSet(t *testing.T) { - injector := inject.New() - typ := reflect.TypeOf("string") - typSend := reflect.ChanOf(reflect.SendDir, typ) - typRecv := reflect.ChanOf(reflect.RecvDir, typ) - - // instantiating unidirectional channels is not possible using reflect - // http://golang.org/src/pkg/reflect/value.go?s=60463:60504#L2064 - chanRecv := reflect.MakeChan(reflect.ChanOf(reflect.BothDir, typ), 0) - chanSend := reflect.MakeChan(reflect.ChanOf(reflect.BothDir, typ), 0) - - injector.Set(typSend, chanSend) - injector.Set(typRecv, chanRecv) - - expect(t, injector.Get(typSend).IsValid(), true) - expect(t, injector.Get(typRecv).IsValid(), true) - expect(t, injector.Get(chanSend.Type()).IsValid(), false) -} - -func Test_InjectorGet(t *testing.T) { - injector := inject.New() - - injector.Map("some dependency") - - expect(t, injector.Get(reflect.TypeOf("string")).IsValid(), true) - expect(t, injector.Get(reflect.TypeOf(11)).IsValid(), false) -} - -func Test_InjectorSetParent(t *testing.T) { - injector := inject.New() - injector.MapTo("another dep", (*SpecialString)(nil)) - - injector2 := inject.New() - injector2.SetParent(injector) - - expect(t, injector2.Get(inject.InterfaceOf((*SpecialString)(nil))).IsValid(), true) -} - -func TestInjectImplementors(t *testing.T) { - injector := inject.New() - g := &Greeter{"Jeremy"} - injector.Map(g) - - expect(t, injector.Get(inject.InterfaceOf((*fmt.Stringer)(nil))).IsValid(), true) -} diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/translations/README_zh_cn.md b/Godeps/_workspace/src/github.com/codegangsta/inject/translations/README_zh_cn.md deleted file mode 100644 index 0ac3d3f..0000000 --- a/Godeps/_workspace/src/github.com/codegangsta/inject/translations/README_zh_cn.md +++ /dev/null @@ -1,85 +0,0 @@ -# inject --- - import "github.com/codegangsta/inject" - -inject包提供了多种对实体的映射和依赖注入方式。 - -## 用法 - -#### func InterfaceOf - -```go -func InterfaceOf(value interface{}) reflect.Type -``` -函数InterfaceOf返回指向接口类型的指针。如果传入的value值不是指向接口的指针,将抛出一个panic异常。 - -#### type Applicator - -```go -type Applicator interface { - // 在Type map中维持对结构体中每个域的引用并用'inject'来标记 - // 如果注入失败将会返回一个error. - Apply(interface{}) error -} -``` - -Applicator接口表示到结构体的依赖映射关系。 - -#### type Injector - -```go -type Injector interface { - Applicator - Invoker - TypeMapper - // SetParent用来设置父injector. 如果在当前injector的Type map中找不到依赖, - // 将会继续从它的父injector中找,直到返回error. - SetParent(Injector) -} -``` - -Injector接口表示对结构体、函数参数的映射和依赖注入。 - -#### func New - -```go -func New() Injector -``` -New创建并返回一个Injector. - -#### type Invoker - -```go -type Invoker interface { - // Invoke尝试将interface{}作为一个函数来调用,并基于Type为函数提供参数。 - // 它将返回reflect.Value的切片,其中存放原函数的返回值。 - // 如果注入失败则返回error. - Invoke(interface{}) ([]reflect.Value, error) -} -``` - -Invoker接口表示通过反射进行函数调用。 - -#### type TypeMapper - -```go -type TypeMapper interface { - // 基于调用reflect.TypeOf得到的类型映射interface{}的值。 - Map(interface{}) TypeMapper - // 基于提供的接口的指针映射interface{}的值。 - // 该函数仅用来将一个值映射为接口,因为接口无法不通过指针而直接引用到。 - MapTo(interface{}, interface{}) TypeMapper - // 为直接插入基于类型和值的map提供一种可能性。 - // 它使得这一类直接映射成为可能:无法通过反射直接实例化的类型参数,如单向管道。 - Set(reflect.Type, reflect.Value) TypeMapper - // 返回映射到当前类型的Value. 如果Type没被映射,将返回对应的零值。 - Get(reflect.Type) reflect.Value -} -``` - -TypeMapper接口用来表示基于类型到接口值的映射。 - - -## 译者 - -张强 (qqbunny@yeah.net) \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/env_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/env_test.go deleted file mode 100644 index d82351e..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/env_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package martini - -import ( - "testing" -) - -func Test_SetENV(t *testing.T) { - tests := []struct { - in string - out string - }{ - {"", "development"}, - {"not_development", "not_development"}, - } - - for _, test := range tests { - setENV(test.in) - if Env != test.out { - expect(t, Env, test.out) - } - } -} - -func Test_Root(t *testing.T) { - if len(Root) == 0 { - t.Errorf("Expected root path will be set") - } -} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/logger_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/logger_test.go deleted file mode 100644 index 156b149..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/logger_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package martini - -import ( - "bytes" - "log" - "net/http" - "net/http/httptest" - "testing" -) - -func Test_Logger(t *testing.T) { - buff := bytes.NewBufferString("") - recorder := httptest.NewRecorder() - - m := New() - // replace log for testing - m.Map(log.New(buff, "[martini] ", 0)) - m.Use(Logger()) - m.Use(func(res http.ResponseWriter) { - res.WriteHeader(http.StatusNotFound) - }) - - req, err := http.NewRequest("GET", "http://localhost:3000/foobar", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(recorder, req) - expect(t, recorder.Code, http.StatusNotFound) - refute(t, len(buff.String()), 0) -} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/martini_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/martini_test.go deleted file mode 100644 index f16bf3e..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/martini_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package martini - -import ( - "net/http" - "net/http/httptest" - "reflect" - "testing" -) - -/* Test Helpers */ -func expect(t *testing.T, a interface{}, b interface{}) { - if a != b { - t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) - } -} - -func refute(t *testing.T, a interface{}, b interface{}) { - if a == b { - t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) - } -} - -func Test_New(t *testing.T) { - m := New() - if m == nil { - t.Error("martini.New() cannot return nil") - } -} - -func Test_Martini_RunOnAddr(t *testing.T) { - // just test that Run doesn't bomb - go New().RunOnAddr("127.0.0.1:8080") -} - -func Test_Martini_Run(t *testing.T) { - go New().Run() -} - -func Test_Martini_ServeHTTP(t *testing.T) { - result := "" - response := httptest.NewRecorder() - - m := New() - m.Use(func(c Context) { - result += "foo" - c.Next() - result += "ban" - }) - m.Use(func(c Context) { - result += "bar" - c.Next() - result += "baz" - }) - m.Action(func(res http.ResponseWriter, req *http.Request) { - result += "bat" - res.WriteHeader(http.StatusBadRequest) - }) - - m.ServeHTTP(response, (*http.Request)(nil)) - - expect(t, result, "foobarbatbazban") - expect(t, response.Code, http.StatusBadRequest) -} - -func Test_Martini_Handlers(t *testing.T) { - result := "" - response := httptest.NewRecorder() - - batman := func(c Context) { - result += "batman!" - } - - m := New() - m.Use(func(c Context) { - result += "foo" - c.Next() - result += "ban" - }) - m.Handlers( - batman, - batman, - batman, - ) - m.Action(func(res http.ResponseWriter, req *http.Request) { - result += "bat" - res.WriteHeader(http.StatusBadRequest) - }) - - m.ServeHTTP(response, (*http.Request)(nil)) - - expect(t, result, "batman!batman!batman!bat") - expect(t, response.Code, http.StatusBadRequest) -} - -func Test_Martini_EarlyWrite(t *testing.T) { - result := "" - response := httptest.NewRecorder() - - m := New() - m.Use(func(res http.ResponseWriter) { - result += "foobar" - res.Write([]byte("Hello world")) - }) - m.Use(func() { - result += "bat" - }) - m.Action(func(res http.ResponseWriter) { - result += "baz" - res.WriteHeader(http.StatusBadRequest) - }) - - m.ServeHTTP(response, (*http.Request)(nil)) - - expect(t, result, "foobar") - expect(t, response.Code, http.StatusOK) -} - -func Test_Martini_Written(t *testing.T) { - response := httptest.NewRecorder() - - m := New() - m.Handlers(func(res http.ResponseWriter) { - res.WriteHeader(http.StatusOK) - }) - - ctx := m.createContext(response, (*http.Request)(nil)) - expect(t, ctx.Written(), false) - - ctx.run() - expect(t, ctx.Written(), true) -} - -func Test_Martini_Basic_NoRace(t *testing.T) { - m := New() - handlers := []Handler{func() {}, func() {}} - // Ensure append will not realloc to trigger the race condition - m.handlers = handlers[:1] - req, _ := http.NewRequest("GET", "/", nil) - for i := 0; i < 2; i++ { - go func() { - response := httptest.NewRecorder() - m.ServeHTTP(response, req) - }() - } -} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/recovery_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/recovery_test.go deleted file mode 100644 index 17e2e01..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/recovery_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package martini - -import ( - "bytes" - "log" - "net/http" - "net/http/httptest" - "testing" -) - -func Test_Recovery(t *testing.T) { - buff := bytes.NewBufferString("") - recorder := httptest.NewRecorder() - - setENV(Dev) - m := New() - // replace log for testing - m.Map(log.New(buff, "[martini] ", 0)) - m.Use(func(res http.ResponseWriter, req *http.Request) { - res.Header().Set("Content-Type", "unpredictable") - }) - m.Use(Recovery()) - m.Use(func(res http.ResponseWriter, req *http.Request) { - panic("here is a panic!") - }) - m.ServeHTTP(recorder, (*http.Request)(nil)) - expect(t, recorder.Code, http.StatusInternalServerError) - expect(t, recorder.HeaderMap.Get("Content-Type"), "text/html") - refute(t, recorder.Body.Len(), 0) - refute(t, len(buff.String()), 0) -} - -func Test_Recovery_ResponseWriter(t *testing.T) { - recorder := httptest.NewRecorder() - recorder2 := httptest.NewRecorder() - - setENV(Dev) - m := New() - m.Use(Recovery()) - m.Use(func(c Context) { - c.MapTo(recorder2, (*http.ResponseWriter)(nil)) - panic("here is a panic!") - }) - m.ServeHTTP(recorder, (*http.Request)(nil)) - - expect(t, recorder2.Code, http.StatusInternalServerError) - expect(t, recorder2.HeaderMap.Get("Content-Type"), "text/html") - refute(t, recorder2.Body.Len(), 0) -} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/response_writer_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/response_writer_test.go deleted file mode 100644 index 6ccb9e0..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/response_writer_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package martini - -import ( - "bufio" - "io" - "net" - "net/http" - "net/http/httptest" - "testing" - "time" -) - -type closeNotifyingRecorder struct { - *httptest.ResponseRecorder - closed chan bool -} - -func newCloseNotifyingRecorder() *closeNotifyingRecorder { - return &closeNotifyingRecorder{ - httptest.NewRecorder(), - make(chan bool, 1), - } -} - -func (c *closeNotifyingRecorder) close() { - c.closed <- true -} - -func (c *closeNotifyingRecorder) CloseNotify() <-chan bool { - return c.closed -} - -type hijackableResponse struct { - Hijacked bool -} - -func newHijackableResponse() *hijackableResponse { - return &hijackableResponse{} -} - -func (h *hijackableResponse) Header() http.Header { return nil } -func (h *hijackableResponse) Write(buf []byte) (int, error) { return 0, nil } -func (h *hijackableResponse) WriteHeader(code int) {} -func (h *hijackableResponse) Flush() {} -func (h *hijackableResponse) Hijack() (net.Conn, *bufio.ReadWriter, error) { - h.Hijacked = true - return nil, nil, nil -} - -func Test_ResponseWriter_WritingString(t *testing.T) { - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - - rw.Write([]byte("Hello world")) - - expect(t, rec.Code, rw.Status()) - expect(t, rec.Body.String(), "Hello world") - expect(t, rw.Status(), http.StatusOK) - expect(t, rw.Size(), 11) - expect(t, rw.Written(), true) -} - -func Test_ResponseWriter_WritingStrings(t *testing.T) { - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - - rw.Write([]byte("Hello world")) - rw.Write([]byte("foo bar bat baz")) - - expect(t, rec.Code, rw.Status()) - expect(t, rec.Body.String(), "Hello worldfoo bar bat baz") - expect(t, rw.Status(), http.StatusOK) - expect(t, rw.Size(), 26) -} - -func Test_ResponseWriter_WritingHeader(t *testing.T) { - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - - rw.WriteHeader(http.StatusNotFound) - - expect(t, rec.Code, rw.Status()) - expect(t, rec.Body.String(), "") - expect(t, rw.Status(), http.StatusNotFound) - expect(t, rw.Size(), 0) -} - -func Test_ResponseWriter_Before(t *testing.T) { - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - result := "" - - rw.Before(func(ResponseWriter) { - result += "foo" - }) - rw.Before(func(ResponseWriter) { - result += "bar" - }) - - rw.WriteHeader(http.StatusNotFound) - - expect(t, rec.Code, rw.Status()) - expect(t, rec.Body.String(), "") - expect(t, rw.Status(), http.StatusNotFound) - expect(t, rw.Size(), 0) - expect(t, result, "barfoo") -} - -func Test_ResponseWriter_Hijack(t *testing.T) { - hijackable := newHijackableResponse() - rw := NewResponseWriter(hijackable) - hijacker, ok := rw.(http.Hijacker) - expect(t, ok, true) - _, _, err := hijacker.Hijack() - if err != nil { - t.Error(err) - } - expect(t, hijackable.Hijacked, true) -} - -func Test_ResponseWrite_Hijack_NotOK(t *testing.T) { - hijackable := new(http.ResponseWriter) - rw := NewResponseWriter(*hijackable) - hijacker, ok := rw.(http.Hijacker) - expect(t, ok, true) - _, _, err := hijacker.Hijack() - - refute(t, err, nil) -} - -func Test_ResponseWriter_CloseNotify(t *testing.T) { - rec := newCloseNotifyingRecorder() - rw := NewResponseWriter(rec) - closed := false - notifier := rw.(http.CloseNotifier).CloseNotify() - rec.close() - select { - case <-notifier: - closed = true - case <-time.After(time.Second): - } - expect(t, closed, true) -} - -func Test_ResponseWriter_Flusher(t *testing.T) { - - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - - _, ok := rw.(http.Flusher) - expect(t, ok, true) -} - -func Test_ResponseWriter_FlusherHandler(t *testing.T) { - - // New martini instance - m := Classic() - - m.Get("/events", func(w http.ResponseWriter, r *http.Request) { - - f, ok := w.(http.Flusher) - expect(t, ok, true) - - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - - for i := 0; i < 2; i++ { - time.Sleep(10 * time.Millisecond) - io.WriteString(w, "data: Hello\n\n") - f.Flush() - } - - }) - - recorder := httptest.NewRecorder() - r, _ := http.NewRequest("GET", "/events", nil) - m.ServeHTTP(recorder, r) - - if recorder.Code != 200 { - t.Error("Response not 200") - } - - if recorder.Body.String() != "data: Hello\n\ndata: Hello\n\n" { - t.Error("Didn't receive correct body, got:", recorder.Body.String()) - } - -} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/router_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/router_test.go deleted file mode 100644 index eb80b7a..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/router_test.go +++ /dev/null @@ -1,468 +0,0 @@ -package martini - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func Test_Routing(t *testing.T) { - router := NewRouter() - recorder := httptest.NewRecorder() - - req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) - context := New().createContext(recorder, req) - - req2, _ := http.NewRequest("POST", "http://localhost:3000/bar/bat", nil) - context2 := New().createContext(recorder, req2) - - req3, _ := http.NewRequest("DELETE", "http://localhost:3000/baz", nil) - context3 := New().createContext(recorder, req3) - - req4, _ := http.NewRequest("PATCH", "http://localhost:3000/bar/foo", nil) - context4 := New().createContext(recorder, req4) - - req5, _ := http.NewRequest("GET", "http://localhost:3000/fez/this/should/match", nil) - context5 := New().createContext(recorder, req5) - - req6, _ := http.NewRequest("PUT", "http://localhost:3000/pop/blah/blah/blah/bap/foo/", nil) - context6 := New().createContext(recorder, req6) - - req7, _ := http.NewRequest("DELETE", "http://localhost:3000/wap//pow", nil) - context7 := New().createContext(recorder, req7) - - req8, _ := http.NewRequest("HEAD", "http://localhost:3000/wap//pow", nil) - context8 := New().createContext(recorder, req8) - - req9, _ := http.NewRequest("OPTIONS", "http://localhost:3000/opts", nil) - context9 := New().createContext(recorder, req9) - - req10, _ := http.NewRequest("HEAD", "http://localhost:3000/foo", nil) - context10 := New().createContext(recorder, req10) - - req11, _ := http.NewRequest("GET", "http://localhost:3000/bazz/inga", nil) - context11 := New().createContext(recorder, req11) - - req12, _ := http.NewRequest("POST", "http://localhost:3000/bazz/inga", nil) - context12 := New().createContext(recorder, req12) - - req13, _ := http.NewRequest("GET", "http://localhost:3000/bazz/in/ga", nil) - context13 := New().createContext(recorder, req13) - - req14, _ := http.NewRequest("GET", "http://localhost:3000/bzz", nil) - context14 := New().createContext(recorder, req14) - - result := "" - router.Get("/foo", func(req *http.Request) { - result += "foo" - }) - router.Patch("/bar/:id", func(params Params) { - expect(t, params["id"], "foo") - result += "barfoo" - }) - router.Post("/bar/:id", func(params Params) { - expect(t, params["id"], "bat") - result += "barbat" - }) - router.Put("/fizzbuzz", func() { - result += "fizzbuzz" - }) - router.Delete("/bazzer", func(c Context) { - result += "baz" - }) - router.Get("/fez/**", func(params Params) { - expect(t, params["_1"], "this/should/match") - result += "fez" - }) - router.Put("/pop/**/bap/:id/**", func(params Params) { - expect(t, params["id"], "foo") - expect(t, params["_1"], "blah/blah/blah") - expect(t, params["_2"], "") - result += "popbap" - }) - router.Delete("/wap/**/pow", func(params Params) { - expect(t, params["_1"], "") - result += "wappow" - }) - router.Options("/opts", func() { - result += "opts" - }) - router.Head("/wap/**/pow", func(params Params) { - expect(t, params["_1"], "") - result += "wappow" - }) - router.Group("/bazz", func(r Router) { - r.Get("/inga", func() { - result += "get" - }) - - r.Post("/inga", func() { - result += "post" - }) - - r.Group("/in", func(r Router) { - r.Get("/ga", func() { - result += "ception" - }) - }, func() { - result += "group" - }) - }, func() { - result += "bazz" - }, func() { - result += "inga" - }) - router.AddRoute("GET", "/bzz", func(c Context) { - result += "bzz" - }) - - router.Handle(recorder, req, context) - router.Handle(recorder, req2, context2) - router.Handle(recorder, req3, context3) - router.Handle(recorder, req4, context4) - router.Handle(recorder, req5, context5) - router.Handle(recorder, req6, context6) - router.Handle(recorder, req7, context7) - router.Handle(recorder, req8, context8) - router.Handle(recorder, req9, context9) - router.Handle(recorder, req10, context10) - router.Handle(recorder, req11, context11) - router.Handle(recorder, req12, context12) - router.Handle(recorder, req13, context13) - router.Handle(recorder, req14, context14) - expect(t, result, "foobarbatbarfoofezpopbapwappowwappowoptsfoobazzingagetbazzingapostbazzingagroupceptionbzz") - expect(t, recorder.Code, http.StatusNotFound) - expect(t, recorder.Body.String(), "404 page not found\n") -} - -func Test_RouterHandlerStatusCode(t *testing.T) { - router := NewRouter() - router.Get("/foo", func() string { - return "foo" - }) - router.Get("/bar", func() (int, string) { - return http.StatusForbidden, "bar" - }) - router.Get("/baz", func() (string, string) { - return "baz", "BAZ!" - }) - router.Get("/bytes", func() []byte { - return []byte("Bytes!") - }) - router.Get("/interface", func() interface{} { - return "Interface!" - }) - - // code should be 200 if none is returned from the handler - recorder := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) - context := New().createContext(recorder, req) - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusOK) - expect(t, recorder.Body.String(), "foo") - - // if a status code is returned, it should be used - recorder = httptest.NewRecorder() - req, _ = http.NewRequest("GET", "http://localhost:3000/bar", nil) - context = New().createContext(recorder, req) - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusForbidden) - expect(t, recorder.Body.String(), "bar") - - // shouldn't use the first returned value as a status code if not an integer - recorder = httptest.NewRecorder() - req, _ = http.NewRequest("GET", "http://localhost:3000/baz", nil) - context = New().createContext(recorder, req) - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusOK) - expect(t, recorder.Body.String(), "baz") - - // Should render bytes as a return value as well. - recorder = httptest.NewRecorder() - req, _ = http.NewRequest("GET", "http://localhost:3000/bytes", nil) - context = New().createContext(recorder, req) - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusOK) - expect(t, recorder.Body.String(), "Bytes!") - - // Should render interface{} values. - recorder = httptest.NewRecorder() - req, _ = http.NewRequest("GET", "http://localhost:3000/interface", nil) - context = New().createContext(recorder, req) - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusOK) - expect(t, recorder.Body.String(), "Interface!") -} - -func Test_RouterHandlerStacking(t *testing.T) { - router := NewRouter() - recorder := httptest.NewRecorder() - - req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) - context := New().createContext(recorder, req) - - result := "" - - f1 := func() { - result += "foo" - } - - f2 := func(c Context) { - result += "bar" - c.Next() - result += "bing" - } - - f3 := func() string { - result += "bat" - return "Hello world" - } - - f4 := func() { - result += "baz" - } - - router.Get("/foo", f1, f2, f3, f4) - - router.Handle(recorder, req, context) - expect(t, result, "foobarbatbing") - expect(t, recorder.Body.String(), "Hello world") -} - -var routeTests = []struct { - // in - method string - path string - - // out - ok bool - params map[string]string -}{ - {"GET", "/foo/123/bat/321", true, map[string]string{"bar": "123", "baz": "321"}}, - {"POST", "/foo/123/bat/321", false, map[string]string{}}, - {"GET", "/foo/hello/bat/world", true, map[string]string{"bar": "hello", "baz": "world"}}, - {"GET", "foo/hello/bat/world", false, map[string]string{}}, - {"GET", "/foo/123/bat/321/", true, map[string]string{"bar": "123", "baz": "321"}}, - {"GET", "/foo/123/bat/321//", false, map[string]string{}}, - {"GET", "/foo/123//bat/321/", false, map[string]string{}}, -} - -func Test_RouteMatching(t *testing.T) { - route := newRoute("GET", "/foo/:bar/bat/:baz", nil) - for _, tt := range routeTests { - ok, params := route.Match(tt.method, tt.path) - if ok != tt.ok || params["bar"] != tt.params["bar"] || params["baz"] != tt.params["baz"] { - t.Errorf("expected: (%v, %v) got: (%v, %v)", tt.ok, tt.params, ok, params) - } - } -} - -func Test_MethodsFor(t *testing.T) { - router := NewRouter() - recorder := httptest.NewRecorder() - - req, _ := http.NewRequest("POST", "http://localhost:3000/foo", nil) - context := New().createContext(recorder, req) - context.MapTo(router, (*Routes)(nil)) - router.Post("/foo/bar", func() { - }) - - router.Post("/fo", func() { - }) - - router.Get("/foo", func() { - }) - - router.Put("/foo", func() { - }) - - router.NotFound(func(routes Routes, w http.ResponseWriter, r *http.Request) { - methods := routes.MethodsFor(r.URL.Path) - if len(methods) != 0 { - w.Header().Set("Allow", strings.Join(methods, ",")) - w.WriteHeader(http.StatusMethodNotAllowed) - } - }) - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusMethodNotAllowed) - expect(t, recorder.Header().Get("Allow"), "GET,PUT") -} - -func Test_NotFound(t *testing.T) { - router := NewRouter() - recorder := httptest.NewRecorder() - - req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) - context := New().createContext(recorder, req) - - router.NotFound(func(res http.ResponseWriter) { - http.Error(res, "Nope", http.StatusNotFound) - }) - - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusNotFound) - expect(t, recorder.Body.String(), "Nope\n") -} - -func Test_NotFoundAsHandler(t *testing.T) { - router := NewRouter() - recorder := httptest.NewRecorder() - - req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) - context := New().createContext(recorder, req) - - router.NotFound(func() string { - return "not found" - }) - - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusOK) - expect(t, recorder.Body.String(), "not found") - - recorder = httptest.NewRecorder() - - context = New().createContext(recorder, req) - - router.NotFound(func() (int, string) { - return 404, "not found" - }) - - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusNotFound) - expect(t, recorder.Body.String(), "not found") - - recorder = httptest.NewRecorder() - - context = New().createContext(recorder, req) - - router.NotFound(func() (int, string) { - return 200, "" - }) - - router.Handle(recorder, req, context) - expect(t, recorder.Code, http.StatusOK) - expect(t, recorder.Body.String(), "") -} - -func Test_NotFoundStacking(t *testing.T) { - router := NewRouter() - recorder := httptest.NewRecorder() - - req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) - context := New().createContext(recorder, req) - - result := "" - - f1 := func() { - result += "foo" - } - - f2 := func(c Context) { - result += "bar" - c.Next() - result += "bing" - } - - f3 := func() string { - result += "bat" - return "Not Found" - } - - f4 := func() { - result += "baz" - } - - router.NotFound(f1, f2, f3, f4) - - router.Handle(recorder, req, context) - expect(t, result, "foobarbatbing") - expect(t, recorder.Body.String(), "Not Found") -} - -func Test_Any(t *testing.T) { - router := NewRouter() - router.Any("/foo", func(res http.ResponseWriter) { - http.Error(res, "Nope", http.StatusNotFound) - }) - - recorder := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) - context := New().createContext(recorder, req) - router.Handle(recorder, req, context) - - expect(t, recorder.Code, http.StatusNotFound) - expect(t, recorder.Body.String(), "Nope\n") - - recorder = httptest.NewRecorder() - req, _ = http.NewRequest("PUT", "http://localhost:3000/foo", nil) - context = New().createContext(recorder, req) - router.Handle(recorder, req, context) - - expect(t, recorder.Code, http.StatusNotFound) - expect(t, recorder.Body.String(), "Nope\n") -} - -func Test_URLFor(t *testing.T) { - router := NewRouter() - - router.Get("/foo", func() { - // Nothing - }).Name("foo") - - router.Post("/bar/:id", func(params Params) { - // Nothing - }).Name("bar") - - router.Get("/baz/:id/(?P[a-z]*)", func(params Params, routes Routes) { - // Nothing - }).Name("baz_id") - - router.Get("/bar/:id/:name", func(params Params, routes Routes) { - expect(t, routes.URLFor("foo", nil), "/foo") - expect(t, routes.URLFor("bar", 5), "/bar/5") - expect(t, routes.URLFor("baz_id", 5, "john"), "/baz/5/john") - expect(t, routes.URLFor("bar_id", 5, "john"), "/bar/5/john") - }).Name("bar_id") - - // code should be 200 if none is returned from the handler - recorder := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "http://localhost:3000/bar/foo/bar", nil) - context := New().createContext(recorder, req) - context.MapTo(router, (*Routes)(nil)) - router.Handle(recorder, req, context) -} - -func Test_AllRoutes(t *testing.T) { - router := NewRouter() - - patterns := []string{"/foo", "/fee", "/fii"} - methods := []string{"GET", "POST", "DELETE"} - names := []string{"foo", "fee", "fii"} - - router.Get("/foo", func() {}).Name("foo") - router.Post("/fee", func() {}).Name("fee") - router.Delete("/fii", func() {}).Name("fii") - - for i, r := range router.All() { - expect(t, r.Pattern(), patterns[i]) - expect(t, r.Method(), methods[i]) - expect(t, r.GetName(), names[i]) - } -} - -func Test_ActiveRoute(t *testing.T) { - router := NewRouter() - - router.Get("/foo", func(r Route) { - expect(t, r.Pattern(), "/foo") - expect(t, r.GetName(), "foo") - }).Name("foo") - - // code should be 200 if none is returned from the handler - recorder := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) - context := New().createContext(recorder, req) - context.MapTo(router, (*Routes)(nil)) - router.Handle(recorder, req, context) -} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/static_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/static_test.go deleted file mode 100644 index 4d7613c..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/static_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package martini - -import ( - "bytes" - "io/ioutil" - "log" - "net/http" - "net/http/httptest" - "os" - "path" - "testing" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" -) - -var currentRoot, _ = os.Getwd() - -func Test_Static(t *testing.T) { - response := httptest.NewRecorder() - response.Body = new(bytes.Buffer) - - m := New() - r := NewRouter() - - m.Use(Static(currentRoot)) - m.Action(r.Handle) - - req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) - if err != nil { - t.Error(err) - } - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - expect(t, response.Header().Get("Expires"), "") - if response.Body.Len() == 0 { - t.Errorf("Got empty body for GET request") - } -} - -func Test_Static_Local_Path(t *testing.T) { - Root = os.TempDir() - response := httptest.NewRecorder() - response.Body = new(bytes.Buffer) - - m := New() - r := NewRouter() - - m.Use(Static(".")) - f, err := ioutil.TempFile(Root, "static_content") - if err != nil { - t.Error(err) - } - f.WriteString("Expected Content") - f.Close() - m.Action(r.Handle) - - req, err := http.NewRequest("GET", "http://localhost:3000/"+path.Base(f.Name()), nil) - if err != nil { - t.Error(err) - } - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - expect(t, response.Header().Get("Expires"), "") - expect(t, response.Body.String(), "Expected Content") -} - -func Test_Static_Head(t *testing.T) { - response := httptest.NewRecorder() - response.Body = new(bytes.Buffer) - - m := New() - r := NewRouter() - - m.Use(Static(currentRoot)) - m.Action(r.Handle) - - req, err := http.NewRequest("HEAD", "http://localhost:3000/martini.go", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - if response.Body.Len() != 0 { - t.Errorf("Got non-empty body for HEAD request") - } -} - -func Test_Static_As_Post(t *testing.T) { - response := httptest.NewRecorder() - - m := New() - r := NewRouter() - - m.Use(Static(currentRoot)) - m.Action(r.Handle) - - req, err := http.NewRequest("POST", "http://localhost:3000/martini.go", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusNotFound) -} - -func Test_Static_BadDir(t *testing.T) { - response := httptest.NewRecorder() - - m := Classic() - - req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(response, req) - refute(t, response.Code, http.StatusOK) -} - -func Test_Static_Options_Logging(t *testing.T) { - response := httptest.NewRecorder() - - var buffer bytes.Buffer - m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} - m.Map(m.logger) - m.Map(defaultReturnHandler()) - - opt := StaticOptions{} - m.Use(Static(currentRoot, opt)) - - req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") - - // Now without logging - m.Handlers() - buffer.Reset() - - // This should disable logging - opt.SkipLogging = true - m.Use(Static(currentRoot, opt)) - - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - expect(t, buffer.String(), "") -} - -func Test_Static_Options_ServeIndex(t *testing.T) { - response := httptest.NewRecorder() - - var buffer bytes.Buffer - m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} - m.Map(m.logger) - m.Map(defaultReturnHandler()) - - opt := StaticOptions{IndexFile: "martini.go"} // Define martini.go as index file - m.Use(Static(currentRoot, opt)) - - req, err := http.NewRequest("GET", "http://localhost:3000/", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") -} - -func Test_Static_Options_Prefix(t *testing.T) { - response := httptest.NewRecorder() - - var buffer bytes.Buffer - m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} - m.Map(m.logger) - m.Map(defaultReturnHandler()) - - // Serve current directory under /public - m.Use(Static(currentRoot, StaticOptions{Prefix: "/public"})) - - // Check file content behaviour - req, err := http.NewRequest("GET", "http://localhost:3000/public/martini.go", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") -} - -func Test_Static_Options_Expires(t *testing.T) { - response := httptest.NewRecorder() - - var buffer bytes.Buffer - m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} - m.Map(m.logger) - m.Map(defaultReturnHandler()) - - // Serve current directory under /public - m.Use(Static(currentRoot, StaticOptions{Expires: func() string { return "46" }})) - - // Check file content behaviour - req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(response, req) - expect(t, response.Header().Get("Expires"), "46") -} - -func Test_Static_Options_Fallback(t *testing.T) { - response := httptest.NewRecorder() - - var buffer bytes.Buffer - m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} - m.Map(m.logger) - m.Map(defaultReturnHandler()) - - // Serve current directory under /public - m.Use(Static(currentRoot, StaticOptions{Fallback: "/martini.go"})) - - // Check file content behaviour - req, err := http.NewRequest("GET", "http://localhost:3000/initram.go", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") -} - -func Test_Static_Redirect(t *testing.T) { - response := httptest.NewRecorder() - - m := New() - m.Use(Static(currentRoot, StaticOptions{Prefix: "/public"})) - - req, err := http.NewRequest("GET", "http://localhost:3000/public?param=foo#bar", nil) - if err != nil { - t.Error(err) - } - - m.ServeHTTP(response, req) - expect(t, response.Code, http.StatusFound) - expect(t, response.Header().Get("Location"), "/public/?param=foo#bar") -} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_de_DE.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_de_DE.md deleted file mode 100644 index 7a6e6eb..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_de_DE.md +++ /dev/null @@ -1,369 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -Martini ist eine mächtiges Package zur schnellen Entwicklung von modularen Webanwendungen und -services in Golang. - -## Ein Projekt starten - -Nach der Installation von Go und dem Einrichten des [GOPATH](http://golang.org/doc/code.html#GOPATH), erstelle Deine erste `.go`-Datei. Speichere sie unter `server.go`. - -~~~ go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hallo Welt!" - }) - m.Run() -} -~~~ - -Installiere anschließend das Martini Package (**Go 1.1** oder höher wird vorausgesetzt): -~~~ -go get github.com/go-martini/martini -~~~ - -Starte den Server: -~~~ -go run server.go -~~~ - -Der Martini-Webserver ist nun unter `localhost:3000` erreichbar. - -## Hilfe - -Aboniere den [Emailverteiler](https://groups.google.com/forum/#!forum/martini-go) - -Schaue das [Demovideo](http://martini.codegangsta.io/#demo) - -Stelle Fragen auf Stackoverflow mit dem [Martini-Tag](http://stackoverflow.com/questions/tagged/martini) - -GoDoc [Dokumentation](http://godoc.org/github.com/go-martini/martini) - - -## Eigenschaften -* Sehr einfach nutzbar -* Nicht-intrusives Design -* Leicht kombinierbar mit anderen Golang Packages -* Ausgezeichnetes Path Matching und Routing -* Modulares Design - einfaches Hinzufügen und Entfernen von Funktionen -* Eine Vielzahl von guten Handlern/Middlewares nutzbar -* Großer Funktionsumfang mitgeliefert -* **Voll kompatibel mit dem [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) Interface.** -* Standardmäßges ausliefern von Dateien (z.B. von AngularJS-Apps im HTML5-Modus) - -## Mehr Middleware -Mehr Informationen zur Middleware und Funktionalität findest Du in den Repositories der [martini-contrib](https://github.com/martini-contrib) Gruppe. - -## Inhaltsverzeichnis -* [Classic Martini](#classic-martini) - * [Handler](#handler) - * [Routing](#routing) - * [Services](#services) - * [Statische Dateien bereitstellen](#statische-dateien-bereitstellen) -* [Middleware Handler](#middleware-handler) - * [Next()](#next) -* [Martini Env](#martini-env) -* [FAQ](#faq) - -## Classic Martini -Einen schnellen Start in ein Projekt ermöglicht [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic), dessen Voreinstellungen sich für die meisten Webanwendungen eignen: -~~~ go - m := martini.Classic() - // ... Middleware und Routing hier einfügen - m.Run() -~~~ - -Aufgelistet findest Du einige Aspekte, die [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) automatich berücksichtigt: - - * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) - * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) - * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) - * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - -### Handler -Handler sind das Herz und die Seele von Martini. Ein Handler ist grundsätzlich jede Art von aufrufbaren Funktionen: -~~~ go -m.Get("/", func() { - println("Hallo Welt") -}) -~~~ - -#### Rückgabewerte -Wenn ein Handler Rückgabewerte beinhaltet, übergibt Martini diese an den aktuellen [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) in Form eines String: -~~~ go -m.Get("/", func() string { - return "Hallo Welt" // HTTP 200 : "Hallo Welt" -}) -~~~ - -Die Rückgabe eines Statuscode ist optional: -~~~ go -m.Get("/", func() (int, string) { - return 418, "Ich bin eine Teekanne" // HTTP 418 : "Ich bin eine Teekanne" -}) -~~~ - -#### Service Injection -Handler werden per Reflection aufgerufen. Martini macht Gebrauch von *Dependency Injection*, um Abhängigkeiten in der Argumentliste von Handlern aufzulösen. **Dies macht Martini komplett inkompatibel mit Golangs `http.HandlerFunc` Interface.** - -Fügst Du einem Handler ein Argument hinzu, sucht Martini in seiner Liste von Services und versucht, die Abhängigkeiten via Type Assertion aufzulösen. -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res und req wurden von Martini injiziert - res.WriteHeader(200) // HTTP 200 -}) -~~~ - -Die Folgenden Services sind Bestandteil von [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): - - * [*log.Logger](http://godoc.org/log#Logger) - Globaler Logger für Martini. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` von benannten Parametern, welche durch Route Matching gefunden wurden. - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Routen Hilfeservice. - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. - * [*http.Request](http://godoc.org/net/http/#Request) - http Request. - -### Routing -Eine Route ist in Martini eine HTTP-Methode gepaart mit einem URL-Matching-Pattern. Jede Route kann eine oder mehrere Handler-Methoden übernehmen: -~~~ go -m.Get("/", func() { - // zeige etwas an -}) - -m.Patch("/", func() { - // aktualisiere etwas -}) - -m.Post("/", func() { - // erstelle etwas -}) - -m.Put("/", func() { - // ersetzte etwas -}) - -m.Delete("/", func() { - // lösche etwas -}) - -m.Options("/", func() { - // HTTP Optionen -}) - -m.NotFound(func() { - // bearbeite 404-Fehler -}) -~~~ - -Routen werden in der Reihenfolge, in welcher sie definiert wurden, zugeordnet. Die bei einer Anfrage zuerst zugeordnete Route wird daraufhin aufgerufen. - -Routenmuster enhalten ggf. benannte Parameter, die über den [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) Service abrufbar sind: -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hallo " + params["name"] -}) -~~~ - -Routen können mit Globs versehen werden: -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hallo " + params["_1"] -}) -~~~ - -Reguläre Ausdrücke sind ebenfalls möglich: -~~~go -m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { - return fmt.Sprintf ("Hallo %s", params["name"]) -}) -~~~ -Weitere Informationen zum Syntax regulärer Ausdrücke findest Du in der [Go Dokumentation](http://golang.org/pkg/regexp/syntax/). - -Routen-Handler können auch in einander verschachtelt werden. Dies ist bei der Authentifizierung und Berechtigungen nützlich. -~~~ go -m.Get("/secret", authorize, func() { - // wird ausgeführt, solange authorize nichts zurückgibt -}) -~~~ - -Routengruppen können durch die Group-Methode hinzugefügt werden. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}) -~~~ - -Sowohl Handlern als auch Middlewares können Gruppen übergeben werden. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}, MyMiddleware1, MyMiddleware2) -~~~ - -### Services -Services sind Okjekte, welche der Argumentliste von Handlern beigefügt werden können. -Du kannst einem Service der *Global* oder *Request* Ebene zuordnen. - -#### Global Mapping -Eine Martini-Instanz implementiert das inject.Injector Interface, sodass ein Service leicht zugeordnet werden kann: -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // der Service ist allen Handlern unter *MyDatabase verfügbar -// ... -m.Run() -~~~ - -#### Request-Level Mapping -Das Zuordnen auf der Request-Ebene kann in einem Handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) realisiert werden: -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // zugeordnet als *MyCustomLogger -} -~~~ - -#### Werten einem Interface zuordnen -Einer der mächtigsten Aspekte von Services ist dessen Fähigkeit, einen Service einem Interface zuzuordnen. Möchtest Du den [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) mit einem Decorator (Objekt) und dessen Zusatzfunktionen überschreiben, definiere den Handler wie folgt: -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // überschribe ResponseWriter mit dem ResponseWriter Decorator -} -~~~ - -### Statische Dateien bereitstellen -Eine [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) Instanz übertragt automatisch statische Dateien aus dem "public"-Ordner im Stammverzeichnis Deines Servers. Dieses Verhalten lässt sich durch weitere [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) Handler auf andere Verzeichnisse übertragen. -~~~ go -m.Use(martini.Static("assets")) // überträgt auch vom "assets"-Verzeichnis -~~~ - -#### Eine voreingestelle Datei übertragen -Du kannst die URL zu einer lokalen Datei angeben, sollte die URL einer Anfrage nicht gefunden werden. Durch einen Präfix können bestimmte URLs ignoriert werden. -Dies ist für Server nützlich, welche statische Dateien übertragen und ggf. zusätzliche Handler defineren (z.B. eine REST-API). Ist dies der Fall, so ist das Anlegen eines Handlers in der NotFound-Reihe nützlich. - -Das gezeigte Beispiel zeigt die `/index.html` immer an, wenn die angefrage URL keiner lokalen Datei zugeordnet werden kann bzw. wenn sie nicht mit `/api/v` beginnt: -~~~ go -static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) -m.NotFound(static, http.NotFound) -~~~ - -## Middleware Handler -Middleware-Handler befinden sich logisch zwischen einer Anfrage via HTTP und dem Router. Im wesentlichen unterscheiden sie sich nicht von anderen Handlern in Martini. -Du kannst einen Middleware-Handler dem Stack folgendermaßen anfügen: -~~~ go -m.Use(func() { - // durchlaufe die Middleware -}) -~~~ - -Volle Kontrolle über den Middleware Stack erlangst Du mit der `Handlers`-Funktion. -Sie ersetzt jeden zuvor definierten Handler: -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ - -Middleware Handler arbeiten gut mit Aspekten wie Logging, Berechtigungen, Authentifizierung, Sessions, Komprimierung durch gzip, Fehlerseiten und anderen Operationen zusammen, die vor oder nach einer Anfrage passieren. -~~~ go -// überprüfe einen API-Schlüssel -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "secret123" { - res.WriteHeader(http.StatusUnauthorized) - } -}) -~~~ - -### Next() -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) ist eine optionale Funktion, die Middleware-Handler aufrufen können, um sie nach dem Beenden der anderen Handler auszuführen. Dies funktioniert besonders gut, wenn Operationen nach einer HTTP-Anfrage ausgeführt werden müssen. -~~~ go -// protokolliere vor und nach einer Anfrage -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("vor einer Anfrage") - - c.Next() - - log.Println("nach einer Anfrage") -}) -~~~ - -## Martini Env - -Einige Martini-Handler machen von der globalen `martini.Env` Variable gebrauch, die der Entwicklungsumgebung erweiterte Funktionen bietet, welche die Produktivumgebung nicht enthält. Es wird empfohlen, die `MARTINI_ENV=production` Umgebungsvariable zu setzen, sobald der Martini-Server in den Live-Betrieb übergeht. - -## FAQ - -### Wo finde ich eine bestimmte Middleware? - -Starte die Suche mit einem Blick in die Projekte von [martini-contrib](https://github.com/martini-contrib). Solltest Du nicht fündig werden, kontaktiere ein Mitglied des martini-contrib Teams, um eine neue Repository anzulegen. - -* [auth](https://github.com/martini-contrib/auth) - Handler zur Authentifizierung. -* [binding](https://github.com/martini-contrib/binding) - Handler zum Zuordnen/Validieren einer Anfrage zu einem Struct. -* [gzip](https://github.com/martini-contrib/gzip) - Handler zum Ermöglichen von gzip-Kompression bei Anfragen. -* [render](https://github.com/martini-contrib/render) - Handler der einen einfachen Service zum Rendern von JSON und HTML Templates bereitstellt. -* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler zum Parsen des `Accept-Language` HTTP-Header. -* [sessions](https://github.com/martini-contrib/sessions) - Handler mit einem Session service. -* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. -* [method](https://github.com/martini-contrib/method) - Überschreibe eine HTTP-Method via Header oder Formularfelder. -* [secure](https://github.com/martini-contrib/secure) - Implementation von Sicherheitsfunktionen -* [encoder](https://github.com/martini-contrib/encoder) - Encoderservice zum Datenrendering in den verschiedensten Formaten. -* [cors](https://github.com/martini-contrib/cors) - Handler der CORS ermöglicht. -* [oauth2](https://github.com/martini-contrib/oauth2) - Handler der den Login mit OAuth 2.0 in Martinianwendungen ermöglicht. Google Sign-in, Facebook Connect und Github werden ebenfalls unterstützt. -* [vauth](https://github.com/rafecolton/vauth) - Handlers zur Webhook Authentifizierung (momentan nur GitHub und TravisCI) - -### Wie integriere ich in bestehende Systeme? - -Eine Martiniinstanz implementiert `http.Handler`, sodass Subrouten in bestehenden Servern einfach genutzt werden können. Hier ist eine funktionierende Martinianwendungen für die Google App Engine: - -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hallo Welt!" - }) - http.Handle("/", m) -} -~~~ - -### Wie ändere ich den Port/Host? - -Martinis `Run` Funktion sucht automatisch nach den PORT und HOST Umgebungsvariablen, um diese zu nutzen. Andernfalls ist localhost:3000 voreingestellt. -Für mehr Flexibilität über den Port und den Host nutze stattdessen die `martini.RunOnAddr` Funktion. - -~~~ go - m := martini.Classic() - // ... - log.Fatal(m.RunOnAddr(":8080")) -~~~ - -### Automatisches Aktualisieren? - -[Gin](https://github.com/codegangsta/gin) und [Fresh](https://github.com/pilu/fresh) aktualisieren Martini-Apps live. - -## Bei Martini mitwirken - -Martinis Maxime ist Minimalismus und sauberer Code. Die meisten Beiträge sollten sich in den Repositories der [martini-contrib](https://github.com/martini-contrib) Gruppe wiederfinden. Beinhaltet Dein Beitrag Veränderungen am Kern von Martini, zögere nicht, einen Pull Request zu machen. - -## Über das Projekt - -Inspiriert von [Express](https://github.com/visionmedia/express) und [Sinatra](https://github.com/sinatra/sinatra) - -Martini wird leidenschaftlich von Niemand gerigeren als dem [Code Gangsta](http://codegangsta.io/) entwickelt diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_es_ES.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_es_ES.md deleted file mode 100644 index 3a76a66..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_es_ES.md +++ /dev/null @@ -1,353 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -Martini es un poderoso paquete para escribir rápidamente aplicaciones/servicios web modulares en Golang. - - -## Vamos a iniciar - -Antes de instalar Go y de configurar su [GOPATH](http://golang.org/doc/code.html#GOPATH), cree su primer archivo `.go`. Vamos a llamar a este `server.go`. - -~~~ go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hola Mundo!" - }) - m.Run() -} -~~~ - -Luego instale el paquete Martini (Es necesario **go 1.1** o superior): -~~~ -go get github.com/go-martini/martini -~~~ - -Después corra su servidor: -~~~ -go run server.go -~~~ - -Ahora tendrá un webserver Martini corriendo en el puerto `localhost:3000`. - -## Obtenga ayuda - -Suscribase a la [Lista de email](https://groups.google.com/forum/#!forum/martini-go) - -Observe el [Video demostrativo](http://martini.codegangsta.io/#demo) - -Use la etiqueta [martini](http://stackoverflow.com/questions/tagged/martini) para preguntas en Stackoverflow - -GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) - - -## Caracteríticas -* Extremadamente simple de usar. -* Diseño no intrusivo. -* Buena integración con otros paquetes Golang. -* Enrutamiento impresionante. -* Diseño modular - Fácil de añadir y remover funcionalidades. -* Muy buen uso de handlers/middlewares. -* Grandes características innovadoras. -* **Compatibilidad total con la interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** - -## Más Middlewares -Para más middlewares y funcionalidades, revisar los repositorios en [martini-contrib](https://github.com/martini-contrib). - -## Lista de contenidos -* [Classic Martini](#classic-martini) - * [Handlers](#handlers) - * [Routing](#routing) - * [Services](#services) - * [Serving Static Files](#serving-static-files) -* [Middleware Handlers](#middleware-handlers) - * [Next()](#next) -* [Martini Env](#martini-env) -* [FAQ](#faq) - -## Classic Martini -Para iniciar rápidamente, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) prevee algunas herramientas que funcionan bien para la mayoría de aplicaciones web: -~~~ go - m := martini.Classic() - // middlewares y rutas aquí - m.Run() -~~~ - -Algunas funcionalidades que [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) ofrece automáticamente son: - * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) - * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) - * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) - * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - -### Handlers -Handlers son el corazón y el alma de Martini. Un handler es básicamente cualquier tipo de función que puede ser llamada. -~~~ go -m.Get("/", func() { - println("hola mundo") -}) -~~~ - -#### Retorno de Valores -Si un handler retorna cualquier cosa, Martini escribirá el valor retornado como una cadena [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter): -~~~ go -m.Get("/", func() string { - return "hola mundo" // HTTP 200 : "hola mundo" -}) -~~~ - -Usted también puede retornar un código de estado: -~~~ go -m.Get("/", func() (int, string) { - return 418, "soy una tetera" // HTTP 418 : "soy una tetera" -}) -~~~ - -#### Inyección de Servicios -Handlers son invocados vía reflexión. Martini utiliza *Inyección de Dependencia* para resolver dependencias en la lista de argumentos Handlers. **Esto hace que Martini sea completamente compatible con la interface `http.HandlerFunc` de golang.** - -Si agrega un argumento a su Handler, Martini buscará en su lista de servicios e intentará resolver su dependencia vía su tipo de aserción: -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res e req son inyectados por Martini - res.WriteHeader(200) // HTTP 200 -}) -~~~ - -Los siguientes servicios son incluidos con [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): - * [*log.Logger](http://godoc.org/log#Logger) - Log Global para Martini. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` de nombres de los parámetros buscados por la ruta. - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Servicio de ayuda para las Rutas. - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response escribe la interfaz. - * [*http.Request](http://godoc.org/net/http/#Request) - http Request. - -### Rutas -En Martini, una ruta es un método HTTP emparejado con un patrón URL. Cada ruta puede tener uno o más métodos handler: -~~~ go -m.Get("/", func() { - // mostrar algo -}) - -m.Patch("/", func() { - // actualizar algo -}) - -m.Post("/", func() { - // crear algo -}) - -m.Put("/", func() { - // reemplazar algo -}) - -m.Delete("/", func() { - // destruir algo -}) - -m.Options("/", func() { - // opciones HTTP -}) - -m.NotFound(func() { - // manipula 404 -}) -~~~ - -Las rutas son emparejadas en el orden en que son definidas. La primera ruta que coincide con la solicitud es invocada. - -Los patrones de rutas puede incluir nombres como parámetros accesibles vía el servicio [martini.Params](http://godoc.org/github.com/go-martini/martini#Params): -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hello " + params["name"] -}) -~~~ - -Las rutas se pueden combinar con globs: -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hello " + params["_1"] -}) -~~~ - -Las expresiones regulares puede ser usadas también: -~~~go -m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { - return fmt.Sprintf ("Hello %s", params["name"]) -}) -~~~ -Observe la [documentación](http://golang.org/pkg/regexp/syntax/) para mayor información sobre la sintaxis de expresiones regulares. - - -Handlers de ruta pueden ser empilados en la cima de otros, la cual es útil para cosas como autenticación y autorización: -~~~ go -m.Get("/secret", authorize, func() { - // será ejecutado cuando autorice escribir una respuesta -}) -~~~ - -Grupos de rutas puede ser añadidas usando el método Group. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}) -~~~ - -Igualmente como puede pasar middlewares para un handler, usted puede pasar middlewares para grupos. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}, MyMiddleware1, MyMiddleware2) -~~~ - -### Servicios -Servicios son objetos que están disponibles para ser inyectados en una lista de argumentos Handler. Usted puede mapear un servicios a nivel *Global* o *Request*. - -#### Mapeamento Global -Una instancia de Martini implementa la interface inject.Injector, entonces un mapeamiento de un servicio es fácil: -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // el servicio estará disponible para todos los handlers como *MyDatabase. -// ... -m.Run() -~~~ - -#### Mapeamiento por Request -Mapeamiento a nivel de request se puede realizar un handler vía [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // mapeado como *MyCustomLogger -} -~~~ - -#### Valores de Mapeamiento para Interfaces -Una de las partes mas poderosas sobre servicios es la capadidad de mapear un servicio para una interface. Por ejemplo, si desea sobreescribir [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) con un objeto que envuelva y realice operaciones extra, puede escribir el siguiente handler: -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // sobreescribir ResponseWriter con nuestro ResponseWriter -} -~~~ - -### Sirviendo Archivos Estáticos -Una instancia de [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) sirve automáticamente archivos estáticos del directorio "public" en la raíz de su servidor. -Usted puede servir más directorios, añadiendo más [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers. -~~~ go -m.Use(martini.Static("assets")) // sirviendo los archivos del directorio "assets" -~~~ - -## Middleware Handlers -Middleware Handlers se sitúan entre una solicitud HTTP y un router. En esencia, ellos no son diferentes de cualquier otro Handler en Martini. Usted puede añadir un handler de middleware para la pila de la siguiente forma: -~~~ go -m.Use(func() { - // Hacer algo con middleware -}) -~~~ - -Puede tener el control total sobre la pila de middleware con la función `Handlers`. Esto reemplazará a cualquier handler que se ha establecido previamente: -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ - -Middleware Handlers trabaja realmente bien como logging, autorización, autenticación, sessión, gzipping, páginas de errores y una serie de otras operaciones que deben suceder antes de una solicitud http: -~~~ go -// Valida una llave de api -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "secret123" { - res.WriteHeader(http.StatusUnauthorized) - } -}) -~~~ - -### Next() -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) es una función opcional que Middleware Handlers puede llamar para aguardar una ejecución de otros Handlers. Esto trabaja muy bien para calquier operación que debe suceder antes de una solicitud http: -~~~ go -// log antes y después de una solicitud -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("antes de una solicitud") - - c.Next() - - log.Println("luego de una solicitud") -}) -~~~ - -## Martini Env - -Martini handlers hace uso de `martini.Env`, una variable global para proveer funcionalidad especial en ambientes de desarrollo y ambientes de producción. Es recomendado que una variable `MARTINI_ENV=production` sea definida cuando se despliegue en un ambiente de producción. - -## FAQ - -### ¿Dónde puedo encontrar una middleware X? - -Inicie su búsqueda en los proyectos [martini-contrib](https://github.com/martini-contrib). Si no esta allí, no dude en contactar a algún miembro del equipo martini-contrib para adicionar un nuevo repositorio para la organización. - -* [auth](https://github.com/martini-contrib/auth) - Handlers para autenticación. -* [binding](https://github.com/martini-contrib/binding) - Handler para mapeamiento/validación de un request en una estrutura. -* [gzip](https://github.com/martini-contrib/gzip) - Handler para agregar gzip comprimidos para requests -* [render](https://github.com/martini-contrib/render) - Handler que provee un servicio de fácil renderizado JSON y plantillas HTML. -* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler para analizar `Accept-Language` header HTTP. -* [sessions](https://github.com/martini-contrib/sessions) - Handler que provee un servicio de sesión. -* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. -* [method](https://github.com/martini-contrib/method) - HTTP método de sobreescritura vía header o campos de formulario. -* [secure](https://github.com/martini-contrib/secure) - Implementa rápidamente items de seguridad. -* [encoder](https://github.com/martini-contrib/encoder) - Servicio de encoder para renderización de datos en varios formatos y negocios de contenidos. -* [cors](https://github.com/martini-contrib/cors) - Handler que habilita suporte a CORS. -* [oauth2](https://github.com/martini-contrib/oauth2) - Handler que provee sistema de login OAuth 2.0 para aplicaciones Martini. Google Sign-in, Facebook Connect y Github login son soportados. - -### ¿Cómo se integra con los servidores existentes? - -Una instancia de Martini implementa `http.Handler`, de modo que puede ser fácilmente utilizado para servir sub-rutas y directorios en servidores Go existentes. Por ejemplo, este es un aplicativo Martini trabajando para Google App Engine: - -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hola Mundo!" - }) - http.Handle("/", m) -} -~~~ - -### ¿Cómo cambiar el puerto/host? - -La función `Run` de Martini observa las variables PORT e HOST para utilizarlas. Caso contrário, Martini asume por defecto localhost:3000. Para tener maayor flexibilidad sobre el puerto y host, use la función `martini.RunOnAddr`. - -~~~ go - m := martini.Classic() - // ... - log.Fatal(m.RunOnAddr(":8080")) -~~~ - -### ¿Servidor con autoreload? - -[gin](https://github.com/codegangsta/gin) y [fresh](https://github.com/pilu/fresh) son aplicaciones para autorecarga de Martini. - -## Contribuyendo -Martini se desea mantener pequeño y limpio. La mayoría de contribuciones deben realizarse en el repositorio [martini-contrib](https://github.com/martini-contrib). Si desea hacer una contribución al core de Martini es libre de realizar un Pull Request. - -## Sobre - -Inspirado por [express](https://github.com/visionmedia/express) y [sinatra](https://github.com/sinatra/sinatra) - -Martini está diseñoado obsesivamente por nada menos que [Code Gangsta](http://codegangsta.io/) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_fr_FR.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_fr_FR.md deleted file mode 100644 index 8381bf2..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_fr_FR.md +++ /dev/null @@ -1,344 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -Martini est une puissante bibliothèque pour développer rapidement des applications et services web en Golang. - - -## Pour commencer - -Après avoir installé Go et configuré le chemin d'accès pour [GOPATH](http://golang.org/doc/code.html#GOPATH), créez votre premier fichier '.go'. Nous l'appellerons 'server.go'. - -~~~ go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - m.Run() -} -~~~ - -Installez ensuite le paquet Martini (**go 1.1** ou supérieur est requis) : - -~~~ -go get github.com/go-martini/martini -~~~ - -La commande suivante vous permettra de lancer votre serveur : -~~~ -go run server.go -~~~ - -Vous avez à présent un serveur web Martini à l'écoute sur l'adresse et le port suivants : `localhost:3000`. - -## Besoin d'aide -- Souscrivez à la [Liste d'emails](https://groups.google.com/forum/#!forum/martini-go) -- Regardez les vidéos [Demo en vidéo](http://martini.codegangsta.io/#demo) -- Posez vos questions sur StackOverflow.com en utilisant le tag [martini](http://stackoverflow.com/questions/tagged/martini) -- La documentation GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) - - -## Caractéristiques -* Simple d'utilisation -* Design non-intrusif -* Compatible avec les autres paquets Golang -* Gestionnaire d'URL et routeur disponibles -* Modulable, permettant l'ajout et le retrait de fonctionnalités -* Un grand nombre de handlers/middlewares disponibles -* Prêt pour une utilisation immédiate -* **Entièrement compatible avec l'interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** - -## Plus de Middleware -Pour plus de middlewares et de fonctionnalités, consultez le dépôt [martini-contrib](https://github.com/martini-contrib). - -## Table des matières -* [Classic Martini](#classic-martini) - * [Handlers](#handlers) - * [Routage](#routing) - * [Services](#services) - * [Serveur de fichiers statiques](#serving-static-files) -* [Middleware Handlers](#middleware-handlers) - * [Next()](#next) -* [Martini Env](#martini-env) -* [FAQ](#faq) - -## Classic Martini -Pour vous faire gagner un temps précieux, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) est configuré avec des paramètres qui devraient couvrir les besoins de la plupart des applications web : - -~~~ go - m := martini.Classic() - // ... les middlewares and le routage sont insérés ici... - m.Run() -~~~ - -Voici quelques handlers/middlewares que [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) intègre par défault : - * Logging des requêtes/réponses - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) - * Récupération sur erreur - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) - * Serveur de fichiers statiques - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) - * Routage - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - -### Handlers -Les Handlers sont le coeur et l'âme de Martini. N'importe quelle fonction peut être utilisée comme un handler. -~~~ go -m.Get("/", func() { - println("hello world") -}) -~~~ - -#### Valeurs retournées -Si un handler retourne une valeur, Martini écrira le résultat dans l'instance [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) courante sous forme de ```string```: -~~~ go -m.Get("/", func() string { - return "hello world" // HTTP 200 : "hello world" -}) -~~~ -Vous pouvez aussi optionnellement renvoyer un code de statut HTTP : -~~~ go -m.Get("/", func() (int, string) { - return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" -}) -~~~ - -#### Injection de services -Les handlers sont appelés via réflexion. Martini utilise "l'injection par dépendance" pour résoudre les dépendances des handlers dans la liste d'arguments. **Cela permet à Martini d'être parfaitement compatible avec l'interface golang ```http.HandlerFunc```.** - -Si vous ajoutez un argument à votre Handler, Martini parcourera la liste des services et essayera de déterminer ses dépendances selon son type : -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini - res.WriteHeader(200) // HTTP 200 -}) -~~~ -Les services suivants sont inclus avec [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): - * [log.Logger](http://godoc.org/log#Logger) - Global logger for Martini. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - Contexte d'une requête HTTP. - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` contenant les paramètres retrouvés par correspondance des routes. - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Service d'aide au routage. - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - Interface d'écriture de réponses HTTP. - * [*http.Request](http://godoc.org/net/http/#Request) - Requête HTTP. - -### Routeur -Dans Martini, un chemin est une méthode HTTP liée à un modèle d'adresse URL. -Chaque chemin peut avoir un seul ou plusieurs méthodes *handler* : -~~~ go -m.Get("/", func() { - // show something -}) - -m.Patch("/", func() { - // update something -}) - -m.Post("/", func() { - // create something -}) - -m.Put("/", func() { - // replace something -}) - -m.Delete("/", func() { - // destroy something -}) - -m.Options("/", func() { - // http options -}) - -m.NotFound(func() { - // handle 404 -}) -~~~ -Les chemins seront traités dans l'ordre dans lequel ils auront été définis. Le *handler* du premier chemin trouvé qui correspondra à la requête sera invoqué. - - -Les chemins peuvent inclure des paramètres nommés, accessibles avec le service [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) : -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hello " + params["name"] -}) -~~~ - -Les chemins peuvent correspondre à des globs : -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hello " + params["_1"] -}) -~~~ -Les expressions régulières peuvent aussi être utilisées : -~~~go -m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { - return fmt.Sprintf ("Hello %s", params["name"]) -}) -~~~ -Jetez un oeil à la documentation [Go documentation](http://golang.org/pkg/regexp/syntax/) pour plus d'informations sur la syntaxe des expressions régulières. - -Les handlers d'un chemins peuvent être superposés, ce qui s'avère particulièrement pratique pour des tâches comme la gestion de l'authentification et des autorisations : -~~~ go -m.Get("/secret", authorize, func() { - // this will execute as long as authorize doesn't write a response -}) -~~~ - -Un groupe de chemins peut aussi être ajouté en utilisant la méthode ```Group``` : -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}) -~~~ - -Comme vous pouvez passer des middlewares à un handler, vous pouvez également passer des middlewares à des groupes : -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}, MyMiddleware1, MyMiddleware2) -~~~ - -### Services -Les services sont des objets injectés dans la liste d'arguments d'un handler. Un service peut être défini pour une *requête*, ou de manière *globale*. - - -#### Global Mapping -Les instances Martini implémentent l'interace inject.Injector, ce qui facilite grandement le mapping de services : -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // the service will be available to all handlers as *MyDatabase -// ... -m.Run() -~~~ - -#### Requête-Level Mapping -Pour une déclaration au niveau d'une requête, il suffit d'utiliser un handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) : -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // mapped as *MyCustomLogger -} -~~~ - -#### Mapping de valeurs à des interfaces -L'un des aspects les plus intéressants des services réside dans le fait qu'ils peuvent être liés à des interfaces. Par exemple, pour surcharger [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) avec un objet qui l'enveloppe et étend ses fonctionnalités, vous pouvez utiliser le handler suivant : -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter -} -~~~ - -### Serveur de fichiers statiques -Une instance [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) est déjà capable de servir les fichiers statiques qu'elle trouvera dans le dossier *public* à la racine de votre serveur. -Vous pouvez indiquer d'autres dossiers sources à l'aide du handler [martini.Static](http://godoc.org/github.com/go-martini/martini#Static). -~~~ go -m.Use(martini.Static("assets")) // serve from the "assets" directory as well -~~~ - -## Les middleware Handlers -Les *middleware handlers* sont placés entre la requête HTTP entrante et le routeur. Ils ne sont aucunement différents des autres handlers présents dans Martini. Vous pouvez ajouter un middleware handler comme ceci : -~~~ go -m.Use(func() { - // do some middleware stuff -}) -~~~ -Vous avez un contrôle total sur la structure middleware avec la fonction ```Handlers```. Son exécution écrasera tous les handlers configurés précédemment : -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ -Middleware Handlers est très pratique pour automatiser des fonctions comme le logging, l'autorisation, l'authentification, sessions, gzipping, pages d'erreur, et toutes les opérations qui se font avant ou après chaque requête HTTP : -~~~ go -// validate an api key -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "secret123" { - res.WriteHeader(http.StatusUnauthorized) - } -}) -~~~ - -### Next() (Suivant) -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) est une fonction optionnelle que les Middleware Handlers peuvent appeler pour patienter jusqu'à ce que tous les autres handlers aient été exécutés. Cela fonctionne très bien pour toutes opérations qui interviennent après une requête HTTP : -~~~ go -// log before and after a request -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("avant la requête") - - c.Next() - - log.Println("après la requête") -}) -~~~ - -## Martini Env -Plusieurs Martini handlers utilisent 'martini.Env' comme variable globale pour fournir des fonctionnalités particulières qui diffèrent entre l'environnement de développement et l'environnement de production. Il est recommandé que la variable 'MARTINI_ENV=production' soit définie pour déployer un serveur Martini en environnement de production. - -## FAQ (Foire aux questions) - -### Où puis-je trouver des middleware ? -Commencer par regarder dans le [martini-contrib](https://github.com/martini-contrib) projet. S'il n'y est pas, n'hésitez pas à contacter un membre de l'équipe martini-contrib pour ajouter un nouveau dépôt à l'organisation. - -* [auth](https://github.com/martini-contrib/auth) - Handlers for authentication. -* [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure. -* [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests -* [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates. -* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header. -* [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service. -* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. -* [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields. -* [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins. -* [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation. -* [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support. -* [oauth2](https://github.com/martini-contrib/oauth2) - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported. -* [vauth](https://github.com/rafecolton/vauth) - Handlers for vender webhook authentication (currently GitHub and TravisCI) - -### Comment puis-je m'intègrer avec des serveurs existants ? -Une instance Martini implémente ```http.Handler```. Elle peut donc utilisée pour alimenter des sous-arbres sur des serveurs Go existants. Voici l'exemple d'une application Martini pour Google App Engine : - -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - http.Handle("/", m) -} -~~~ - -### Comment changer le port/adresse ? - -La fonction ```Run``` de Martini utilise le port et l'adresse spécifiés dans les variables d'environnement. Si elles ne peuvent y être trouvées, Martini utilisera *localhost:3000* par default. -Pour avoir plus de flexibilité sur le port et l'adresse, utilisez la fonction `martini.RunOnAddr` à la place. - -~~~ go - m := martini.Classic() - // ... - log.Fatal(m.RunOnAddr(":8080")) -~~~ - -### Rechargement du code en direct ? - -[gin](https://github.com/codegangsta/gin) et [fresh](https://github.com/pilu/fresh) sont tous les capables de recharger le code des applications martini chaque fois qu'il est modifié. - -## Contribuer -Martini est destiné à rester restreint et épuré. Toutes les contributions doivent finir dans un dépot dans l'organisation [martini-contrib](https://github.com/martini-contrib). Si vous avez une contribution pour le noyau de Martini, n'hésitez pas à envoyer une Pull Request. - -## A propos de Martini - -Inspiré par [express](https://github.com/visionmedia/express) et [Sinatra](https://github.com/sinatra/sinatra), Martini est l'oeuvre de nul d'autre que [Code Gangsta](http://codegangsta.io/), votre serviteur. diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ja_JP.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ja_JP.md deleted file mode 100644 index e5fdd90..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ja_JP.md +++ /dev/null @@ -1,356 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -MartiniはGolangによる、モジュール形式のウェブアプリケーション/サービスを作成するパワフルなパッケージです。 - -## はじめに - -Goをインストールし、[GOPATH](http://golang.org/doc/code.html#GOPATH)を設定した後、Martiniを始める最初の`.go`ファイルを作りましょう。これを`server.go`とします。 - -~~~ go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - m.Run() -} -~~~ - -そのあとで、Martini パッケージをインストールします。(**go 1.1**か、それ以上のバーションが必要です。) - -~~~ -go get github.com/go-martini/martini -~~~ - -インストールが完了したら、サーバを起動しましょう。 -~~~ -go run server.go -~~~ - -そうすれば`localhost:3000`でMartiniのサーバが起動します。 - -## 分からないことがあったら? - -[メーリングリスト](https://groups.google.com/forum/#!forum/martini-go)に入る - -[デモビデオ](http://martini.codegangsta.io/#demo)をみる - -Stackoverflowで[martini tag](http://stackoverflow.com/questions/tagged/martini)を使い質問する - -GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) - - -## 特徴 -* 非常にシンプルに使用できる -* 押し付けがましくないデザイン -* 他のGolangパッケージとの協調性 -* 素晴らしいパスマッチングとルーティング -* モジュラーデザイン - 機能性の付け外しが簡単 -* たくさんの良いハンドラ/ミドルウェア -* 優れた 'すぐに使える' 機能たち -* **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc)との完全な互換性** - -## もっとミドルウェアについて知るには? -さらに多くのミドルウェアとその機能について知りたいときは、[martini-contrib](https://github.com/martini-contrib) オーガナイゼーションにあるリポジトリを確認してください。 - -## 目次(Table of Contents) -* [Classic Martini](#classic-martini) - * [ハンドラ](#handlers) - * [ルーティング](#routing) - * [サービス](#services) - * [静的ファイル配信](#serving-static-files) -* [ミドルウェアハンドラ](#middleware-handlers) - * [Next()](#next) -* [Martini Env](#martini-env) -* [FAQ](#faq) - -## Classic Martini -立ち上げ、すぐ実行できるように、[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) はほとんどのウェブアプリケーションで機能する、標準的な機能を提供します。 -~~~ go - m := martini.Classic() - // ... middleware and routing goes here - m.Run() -~~~ - -下記が[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)が自動的に読み込む機能の一覧です。 - * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) - * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) - * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) - * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - -### ハンドラ -ハンドラはMartiniのコアであり、存在意義でもあります。ハンドラには基本的に、呼び出し可能な全ての関数が適応できます。 -~~~ go -m.Get("/", func() { - println("hello world") -}) -~~~ - -#### Return Values -もしハンドラが何かを返す場合、Martiniはその結果を現在の[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)にstringとして書き込みます。 -~~~ go -m.Get("/", func() string { - return "hello world" // HTTP 200 : "hello world" -}) -~~~ - -任意でステータスコードを返すこともできます。 -~~~ go -m.Get("/", func() (int, string) { - return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" -}) -~~~ - -#### Service Injection -ハンドラはリフレクションによって実行されます。Martiniはハンドラの引数内の依存関係を**依存性の注入(Dependency Injection)**を使って解決しています。**これによって、Martiniはgolangの`http.HandlerFunc`と完全な互換性を備えています。** - -ハンドラに引数を追加すると、Martiniは内部のサービスを検索し、依存性をtype assertionによって解決しようと試みます。 -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini - res.WriteHeader(200) // HTTP 200 -}) -~~~ - -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)にはこれらのサービスが内包されています: - * [*log.Logger](http://godoc.org/log#Logger) - Martiniのためのグローバルなlogger. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string`型の、ルートマッチングによって検出されたパラメータ - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service. - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. - * [*http.Request](http://godoc.org/net/http/#Request) - http Request. - -### ルーティング -Martiniでは、ルーティングはHTTPメソッドとURL-matching patternによって対になっており、それぞれが一つ以上のハンドラメソッドを持つことができます。 -~~~ go -m.Get("/", func() { - // show something -}) - -m.Patch("/", func() { - // update something -}) - -m.Post("/", func() { - // create something -}) - -m.Put("/", func() { - // replace something -}) - -m.Delete("/", func() { - // destroy something -}) - -m.Options("/", func() { - // http options -}) - -m.NotFound(func() { - // handle 404 -}) -~~~ - -ルーティングはそれらの定義された順番に検索され、最初にマッチしたルーティングが呼ばれます。 - -名前付きパラメータを定義することもできます。これらのパラメータは[martini.Params](http://godoc.org/github.com/go-martini/martini#Params)サービスを通じてアクセスすることができます: -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hello " + params["name"] -}) -~~~ - -ワイルドカードを使用することができます: -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hello " + params["_1"] -}) -~~~ - -正規表現も、このように使うことができます: -~~~go -m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { - return fmt.Sprintf ("Hello %s", params["name"]) -}) -~~~ - -もっと正規表現の構文をしりたい場合は、[Go documentation](http://golang.org/pkg/regexp/syntax/) を見てください。 - - -ハンドラは互いの上に積み重ねてることができます。これは、認証や承認処理の際に便利です: -~~~ go -m.Get("/secret", authorize, func() { - // this will execute as long as authorize doesn't write a response -}) -~~~ - -ルーティンググループも、Groupメソッドを使用することで追加できます。 -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}) -~~~ - -ハンドラにミドルウェアを渡せるのと同じように、グループにもミドルウェアを渡すことができます: -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}, MyMiddleware1, MyMiddleware2) -~~~ - -### サービス -サービスはハンドラの引数として注入されることで利用可能になるオブジェクトです。これらは*グローバル*、または*リクエスト*のレベルでマッピングすることができます。 - -#### Global Mapping -Martiniのインスタンスはinject.Injectorのインターフェースを実装しています。なので、サービスをマッピングすることは簡単です: -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // the service will be available to all handlers as *MyDatabase -// ... -m.Run() -~~~ - -#### Request-Level Mapping -リクエストレベルでのマッピングは[martini.Context](http://godoc.org/github.com/go-martini/martini#Context)を使い、ハンドラ内で行うことができます: -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // mapped as *MyCustomLogger -} -~~~ - -#### Mapping values to Interfaces -サービスの最も強力なことの一つは、インターフェースにサービスをマッピングできる機能です。例えば、[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)を機能を追加して上書きしたい場合、このようにハンドラを書くことができます: -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter -} -~~~ - -### 静的ファイル配信 - -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) インスタンスは、自動的にルート直下の "public" ディレクトリ以下の静的ファイルを配信します。[martini.Static](http://godoc.org/github.com/go-martini/martini#Static)を追加することで、もっと多くのディレクトリを配信することもできます: -~~~ go -m.Use(martini.Static("assets")) // serve from the "assets" directory as well -~~~ - -## ミドルウェア ハンドラ -ミドルウェア ハンドラは次に来るhttpリクエストとルーターの間に位置します。本質的には、その他のハンドラとの違いはありません。ミドルウェア ハンドラの追加はこのように行います: -~~~ go -m.Use(func() { - // do some middleware stuff -}) -~~~ - -`Handlers`関数を使えば、ミドルウェアスタックを完全に制御できます。これは以前に設定されている全てのハンドラを置き換えます: - -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ - -ミドルウェア ハンドラはロギング、認証、承認プロセス、セッション、gzipping、エラーページの表示、その他httpリクエストの前後で怒らなければならないような場合に素晴らしく効果を発揮します。 -~~~ go -// validate an api key -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "secret123" { - res.WriteHeader(http.StatusUnauthorized) - } -}) -~~~ - -### Next() - -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) は他のハンドラが実行されたことを取得するために使用する機能です。これはhttpリクエストのあとに実行したい任意の関数があるときに素晴らしく機能します: -~~~ go -// log before and after a request -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("before a request") - - c.Next() - - log.Println("after a request") -}) -~~~ - -## Martini Env - -いくつかのMartiniのハンドラはdevelopment環境とproduction環境で別々の動作を提供するために`martini.Env`グローバル変数を使用しています。Martiniサーバを本番環境にデプロイする際には、`MARTINI_ENV=production`環境変数をセットすることをおすすめします。 - -## FAQ - -### Middlewareを見つけるには? - -[martini-contrib](https://github.com/martini-contrib)プロジェクトをみることから始めてください。もし望みのものがなければ、新しいリポジトリをオーガナイゼーションに追加するために、martini-contribチームのメンバーにコンタクトを取ってみてください。 - -* [auth](https://github.com/martini-contrib/auth) - Handlers for authentication. -* [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure. -* [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests -* [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates. -* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header. -* [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service. -* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. -* [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields. -* [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins. -* [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation. -* [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support. -* [oauth2](https://github.com/martini-contrib/oauth2) - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported. - -### 既存のサーバに組み込むには? - -Martiniのインスタンスは`http.Handler`を実装しているので、既存のGoサーバ上でサブツリーを提供するのは簡単です。例えばこれは、Google App Engine上で動くMartiniアプリです: - -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - http.Handle("/", m) -} -~~~ - -### どうやってポート/ホストをかえるの? - -Martiniの`Run`関数はPORTとHOSTという環境変数を探し、その値を使用します。見つからない場合はlocalhost:3000がデフォルトで使用されます。もっと柔軟性をもとめるなら、`martini.RunOnAddr`関数が役に立ちます: - -~~~ go - m := martini.Classic() - // ... - log.Fatal(m.RunOnAddr(":8080")) -~~~ - -### Live code reload? - -[gin](https://github.com/codegangsta/gin) と [fresh](https://github.com/pilu/fresh) 両方がMartiniアプリケーションを自動リロードできます。 - -## Contributing -Martini本体は小さく、クリーンであるべきであり、ほとんどのコントリビューションは[martini-contrib](https://github.com/martini-contrib) オーガナイゼーション内で完結すべきですが、もしMartiniのコアにコントリビュートすることがあるなら、自由に行ってください。 - -## About - -Inspired by [express](https://github.com/visionmedia/express) and [sinatra](https://github.com/sinatra/sinatra) - -Martini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ko_kr.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ko_kr.md deleted file mode 100644 index 8b5a1fa..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ko_kr.md +++ /dev/null @@ -1,359 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -마티니(Martini)는 강력하고 손쉬운 웹애플리케이션 / 웹서비스개발을 위한 Golang 패키지입니다. - -## 시작하기 - -Go 인스톨 및 [GOPATH](http://golang.org/doc/code.html#GOPATH) 환경변수 설정 이후에, `.go` 파일 하나를 만들어 보죠..흠... 일단 `server.go`라고 부르겠습니다. -~~~go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello, 세계!" - }) - m.Run() -} -~~~ - -마티니 패키지를 인스톨 합니다. (**go 1.1** 혹은 그 이상 버젼 필요): -~~~ -go get github.com/go-martini/martini -~~~ - -이제 서버를 돌려 봅시다: -~~~ -go run server.go -~~~ - -마티니 웹서버가 `localhost:3000`에서 돌아가고 있는 것을 확인하실 수 있을 겁니다. - -## 도움이 필요하다면? - -[메일링 리스트](https://groups.google.com/forum/#!forum/martini-go)에 가입해 주세요 - -[데모 비디오](http://martini.codegangsta.io/#demo)도 있어요. - -혹은 Stackoverflow에 [마티니 태크](http://stackoverflow.com/questions/tagged/martini)를 이용해서 물어봐 주세요 - -GoDoc [문서(documentation)](http://godoc.org/github.com/go-martini/martini) - -문제는 전부다 영어로 되어 있다는 건데요 -_-;;; -나는 한글 아니면 보기 싫다! 하는 분들은 아래 링크를 참조하세요 -- [golang-korea](https://code.google.com/p/golang-korea/) -- 혹은 ([RexK](http://github.com/RexK))의 이메일로 연락주세요. - -## 주요기능 -* 사용하기 엄청 쉽습니다. -* 비간섭(Non-intrusive) 디자인 -* 다른 Golang 패키지들과 잘 어울립니다. -* 끝내주는 경로 매칭과 라우팅. -* 모듈 형 디자인 - 기능추가 쉽고, 코드 꺼내오기도 쉬움. -* 쓸모있는 핸들러와 미들웨어가 많음. -* 훌률한 패키지화(out of the box) 기능들 -* **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) 인터페이스와 호환율 100%** - -## 미들웨어(Middleware) -미들웨어들과 추가기능들은 [martini-contrib](https://github.com/martini-contrib)에서 확인해 주세요. - -## 목차 -* [Classic Martini](#classic-martini) - * [핸들러](#핸들러handlers) - * [라우팅](#라우팅routing) - * [서비스](#서비스services) - * [정적파일 서빙](#정적파일-서빙serving-static-files) -* [미들웨어 핸들러](#미들웨어-핸들러middleware-handlers) - * [Next()](#next) -* [Martini Env](#martini-env) -* [FAQ](#faq) - -## Classic Martini -마티니를 쉽고 빠르게 이용하시려면, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)를 이용해 보세요. 보통 웹애플리케이션에서 사용하는 설정들이 이미 포함되어 있습니다. -~~~ go - m := martini.Classic() - // ... 미들웨어와 라우팅 설정은 이곳에 오면 작성하면 됩니다. - m.Run() -~~~ - -아래는 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)의 자동으로 장착하는 기본 기능들입니다. - - * Request/Response 로그 기능 - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) - * 패닉 리커버리 (Panic Recovery) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) - * 정적 파일 서빙 - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) - * 라우팅(Routing) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - -### 핸들러(Handlers) - -핸들러(Handlers)는 마티니의 핵심입니다. 핸들러는 기본적으로 실행 가능한 모든형태의 함수들입니다. -~~~ go -m.Get("/", func() { - println("hello 세계") -}) -~~~ - -#### 반환 값 (Return Values) -핸들러가 반환을 하는 함수라면, 마티니는 반환 값을 [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)에 스트링으로 입력 할 것입니다. -~~~ go -m.Get("/", func() string { - return "hello 세계" // HTTP 200 : "hello 세계" -}) -~~~ - -원하신다면, 선택적으로 상태코드도 함께 반화 할 수 있습니다. -~~~ go -m.Get("/", func() (int, string) { - return 418, "난 주전자야!" // HTTP 418 : "난 주전자야!" -}) -~~~ - -#### 서비스 주입(Service Injection) -핸들러들은 리플렉션을 통해 호출됩니다. 마티니는 *의존성 주입*을 이용해서 핸들러의 인수들을 주입합니다. **이것이 마티니를 `http.HandlerFunc` 인터페이스와 100% 호환할 수 있게 해줍니다.** - -핸들러의 인수를 입력했다면, 마티니가 서비스 목록들을 살펴본 후 타입확인(type assertion)을 통해 의존성을 해결을 시도 할 것입니다. -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res와 req는 마티니에 의해 주입되었다. - res.WriteHeader(200) // HTTP 200 -}) -~~~ - -아래 서비스들은 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):에 포함되어 있습니다. - * [*log.Logger](http://godoc.org/log#Logger) - 마티니의 글러벌(전역) 로그. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http 요청 컨텍스트. - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - 루트 매칭으로 찾은 인자를 `map[string]string`으로 변형. - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - 루트 도우미 서미스. - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer 인터페이스. - * [*http.Request](http://godoc.org/net/http/#Request) - http 리퀘스트. - -### 라우팅(Routing) -마티니에서 루트는 HTTP 메소드와 URL매칭 패턴의 페어입니다. -각 루트는 하나 혹은 그 이상의 핸들러 메소드를 가질 수 있습니다. -~~~ go -m.Get("/", func() { - // 보여줘 봐 -}) - -m.Patch("/", func() { - // 업데이트 좀 해 -}) - -m.Post("/", func() { - // 만들어봐 -}) - -m.Put("/", func() { - // 교환해봐 -}) - -m.Delete("/", func() { - // 없애버려! -}) - -m.Options("/", func() { - // http 옵션 메소드 -}) - -m.NotFound(func() { - // 404 해결하기 -}) -~~~ - -루트들은 정의된 순서대로 매칭된다. 들어온 요그에 첫번째 매칭된 루트가 호출된다. - -루트 패턴은 [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) service로 액세스 가능한 인자들을 포함하기도 한다: -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hello " + params["name"] // :name을 Params인자에서 추출 -}) -~~~ - -루트는 별표식(\*)으로 매칭 될 수도 있습니다: -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hello " + params["_1"] -}) -~~~ - -Regular expressions can be used as well: -정규식도 사용가능합니다: -~~~go -m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { - return fmt.Sprintf ("Hello %s", params["name"]) -}) -~~~ -정규식에 관하여 더 자세히 알고 싶다면 [Go documentation](http://golang.org/pkg/regexp/syntax/)을 참조해 주세요. - -루트 핸들러는 스택을 쌓아 올릴 수 있습니다. 특히 유저 인증작업이나, 허가작업에 유용히 쓰일 수 있죠. -~~~ go -m.Get("/secret", authorize, func() { - // 이 함수는 authorize 함수가 resopnse에 결과를 쓰지 않는이상 실행 될 거에요. -}) -~~~ - -루트그룹은 루트들을 한 곳에 모아 정리하는데 유용합니다. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}) -~~~ - -핸들러에 미들웨어를 집어넣을 수 있었듯이, 그룹에도 미들웨어 집어넣는게 가능합니다. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}, MyMiddleware1, MyMiddleware2) -~~~ - -### 서비스(Services) -서비스는 핸들러의 인수목록에 주입될수 있는 오브젝트들을 말합니다. 서비스는 *글로벌* 혹은 *리퀘스트* 레벨단위로 주입이 가능합니다. - -#### 글로벌 맵핑(Global Mapping) -마타니 인스턴스는 서비스 맵핑을 쉽게 하기 위해서 inject.Injector 인터페이스를 반형합니다: -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // 서비스가 모든 핸들러에서 *MyDatabase로서 사용될 수 있습니다. -// ... -m.Run() -~~~ - -#### 리퀘스트 레벨 맵핑(Request-Level Mapping) -리퀘스트 레벨 맵핑은 핸들러안에서 [martini.Context](http://godoc.org/github.com/go-martini/martini#Context)를 사용하면 됩니다: -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // *MyCustomLogger로서 맵핑 됨 -} -~~~ - -#### 인터페이스로 값들 맵핑(Mapping values to Interfaces) -서비스의 강력한 기능중 하나는 서비스를 인터페이스로 맵핑이 가능하다는 것입니다. 예를들어, [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)를 치환(override)해서 부가 기능들을 수행하게 하고 싶으시다면, 아래와 같은 핸들러를 작성 하시면 됩니다. - -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // ResponseWriter를 NewResponseWriter로 치환(override) -} -~~~ - -### 정적파일 서빙(Serving Static Files) -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 인스턴스는 "public" 폴더안에 있는 파일들은 정적파일로서 자동으로 서빙합니다. 더 많은 폴더들은 정적파일 폴더에 포함시키시려면 [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 핸들러를 이용하시면 됩니다. - -~~~ go -m.Use(martini.Static("assets")) // "assets" 폴더에서도 정적파일 서빙. -~~~ - -## 미들웨어 핸들러(Middleware Handlers) -미들웨어 핸들러는 http request와 라우팅 사이에서 작동합니다. 미들웨어 핸들러는 근본적으로 다른 핸들러들과는 다릅니다. 사용방법은 아래와 같습니다: -~~~ go -m.Use(func() { - // 미들웨어 임무 수행! -}) -~~~ - -`Handlers`를 이용하여 미들웨어 스택들의 완전 컨트롤이 가능합니다. 다만, 이렇게 설정하시면 이전에 `Handlers`를 이용하여 설정한 핸들러들은 사라집니다: -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ - -미들웨어 핸들러는 로깅(logging), 허가(authorization), 인가(authentication), 세션, 압축(gzipping), 에러 페이지 등 등, http request의 전후로 실행되어야 할 일들을 처리하기 아주 좋습니다: -~~~ go -// API 키 확인작업 -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "비밀암호!!!" { - res.WriteHeader(http.StatusUnauthorized) // HTTP 401 - } -}) -~~~ - -### Next() -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context)는 선택적 함수입니다. 이 함수는 http request가 다 작동 될때까지 기다립니다.따라서 http request 이후에 실행 되어야 할 업무들을 수행하기 좋은 함수입니다. -~~~ go -// log before and after a request -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("request전입니다.") - - c.Next() - - log.Println("request후 입니다.") -}) -~~~ - -## Martini Env -마티니 핸들러들은 `martini.Env` 글로벌 변수를 사용하여 개발환경에서는 프로덕션 환경과는 다르게 작동하기도 합니다. 따라서, 프로덕션 서버로 마티니 서보를 배포하시게 된다면 꼭 환경변수 `MARTINI_ENV=production`를 세팅해주시기 바랍니다. - -## FAQ - -### 미들웨어들을 어디서 찾아야 하나요? - -깃헙에서 [martini-contrib](https://github.com/martini-contrib) 프로젝트들을 탖아보세요. 만약에 못 찾으시겠으면, martini-contrib 팀원들에게 연락해서 하나 만들어 달라고 해보세요. -* [auth](https: //github.com/martini-contrib/auth) - 인증작업을 도와주는 핸들러. -* [binding](https://github.com/martini-contrib/binding) - request를 맵핑하고 검사하는 핸들러. -* [gzip](https://github.com/martini-contrib/gzip) - gzip 핸들러. -* [render](https://github.com/martini-contrib/render) - HTML 템플레이트들과 JSON를 사용하기 편하게 해주는 핸들러. -* [acceptlang](https://github.com/martini-contrib/acceptlang) - `Accept-Language` HTTP 해더를 파싱할때 유용한 핸들러. -* [sessions](https://github.com/martini-contrib/sessions) - 세션 서비스를 제공하는 핸들러. -* [strip](https://github.com/martini-contrib/strip) - URL 프리틱스를 없애주는 핸들러. -* [method](https://github.com/martini-contrib/method) - 해더나 폼필드를 이용한 HTTP 메소드 치환. -* [secure](https://github.com/martini-contrib/secure) - 몇몇 보안설정을 위한 핸들러. -* [encoder](https://github.com/martini-contrib/encoder) - 데이터 렌더링과 컨텐트 타엽을위한 인코딩 서비스. -* [cors](https://github.com/martini-contrib/cors) - CORS 서포트를 위한 핸들러. -* [oauth2](https://github.com/martini-contrib/oauth2) - OAuth2.0 로그인 핸들러. 페이스북, 구글, 깃헙 지원. - -### 현재 작동중인 서버에 마티니를 적용하려면? - -마티니 인스턴스는 `http.Handler` 인터페이스를 차용합니다. 따라서 Go 서버 서브트리로 쉽게 사용될 수 있습니다. 아래 코드는 구글 앱 엔진에서 작동하는 마티니 앱입니다: - -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello 세계!" - }) - http.Handle("/", m) -} -~~~ - -### 포트와 호스트는 어떻게 바꾸나요? - -마티니의 `Run` 함수는 PORT와 HOST 환경변수를 이용하는데, 설정이 안되어 있다면 localhost:3000으로 설정 되어 집니다. -좀더 유연하게 설정을 하고 싶다면, `martini.RunOnAddr`를 활용해 주세요. - -~~~ go - m := martini.Classic() - // ... - log.Fatal(m.RunOnAddr(":8080")) -~~~ - -### 라이브 포드 리로드? - -[gin](https://github.com/codegangsta/gin) and [fresh](https://github.com/pilu/fresh) 마티니 앱의 라이브 리로드를 도와줍니다. - -## 공헌하기(Contributing) - -마티니는 간단하고 가벼운 패키지로 남을 것입니다. 따라서 보통 대부분의 공헌들은 [martini-contrib](https://github.com/martini-contrib) 그룹의 저장소로 가게 됩니다. 만약 마티니 코어에 기여하고 싶으시다면 주저없이 Pull Request를 해주세요. - -## About - -[express](https://github.com/visionmedia/express) 와 [sinatra](https://github.com/sinatra/sinatra)의 영향을 받았습니다. - -마티니는 [Code Gangsta](http://codegangsta.io/)가 디자인 했습니다. diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_pt_br.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_pt_br.md deleted file mode 100644 index 2c0da51..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_pt_br.md +++ /dev/null @@ -1,355 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -Martini é um poderoso pacote para escrever aplicações/serviços modulares em Golang.. - - -## Vamos começar - -Após a instalação do Go e de configurar o [GOPATH](http://golang.org/doc/code.html#GOPATH), crie seu primeiro arquivo `.go`. Vamos chamá-lo de `server.go`. - -~~~ go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - m.Run() -} -~~~ - -Então instale o pacote do Martini (É necessário **go 1.1** ou superior): -~~~ -go get github.com/go-martini/martini -~~~ - -Então rode o servidor: -~~~ -go run server.go -~~~ - -Agora você tem um webserver Martini rodando na porta `localhost:3000`. - -## Obtenha ajuda - -Assine a [Lista de email](https://groups.google.com/forum/#!forum/martini-go) - -Veja o [Vídeo demonstrativo](http://martini.codegangsta.io/#demo) - -Use a tag [martini](http://stackoverflow.com/questions/tagged/martini) para perguntas no Stackoverflow - - - -## Caracteríticas -* Extrema simplicidade de uso. -* Design não intrusivo. -* Boa integração com outros pacotes Golang. -* Router impressionante. -* Design modular - Fácil para adicionar e remover funcionalidades. -* Muito bom no uso handlers/middlewares. -* Grandes caracteríticas inovadoras. -* **Completa compatibilidade com a interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** - -## Mais Middleware -Para mais middleware e funcionalidades, veja os repositórios em [martini-contrib](https://github.com/martini-contrib). - -## Tabela de Conteudos -* [Classic Martini](#classic-martini) - * [Handlers](#handlers) - * [Routing](#routing) - * [Services](#services) - * [Serving Static Files](#serving-static-files) -* [Middleware Handlers](#middleware-handlers) - * [Next()](#next) -* [Martini Env](#martini-env) -* [FAQ](#faq) - -## Classic Martini -Para iniciar rapidamente, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) provê algumas ferramentas razoáveis para maioria das aplicações web: -~~~ go - m := martini.Classic() - // ... middleware e rota aqui - m.Run() -~~~ - -Algumas das funcionalidade que o [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) oferece automaticamente são: - * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) - * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) - * Servidor de arquivos státicos - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) - * Rotas - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - -### Handlers -Handlers são o coração e a alma do Martini. Um handler é basicamente qualquer função que pode ser chamada: -~~~ go -m.Get("/", func() { - println("hello world") -}) -~~~ - -#### Retorno de Valores -Se um handler retornar alguma coisa, Martini irá escrever o valor retornado como uma string ao [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter): -~~~ go -m.Get("/", func() string { - return "hello world" // HTTP 200 : "hello world" -}) -~~~ - -Você também pode retornar o código de status: -~~~ go -m.Get("/", func() (int, string) { - return 418, "Eu sou um bule" // HTTP 418 : "Eu sou um bule" -}) -~~~ - -#### Injeção de Serviços -Handlers são chamados via reflexão. Martini utiliza *Injeção de Dependencia* para resolver as dependencias nas listas de argumentos dos Handlers . **Isso faz Martini ser completamente compatível com a interface `http.HandlerFunc` do golang.** - -Se você adicionar um argumento ao seu Handler, Martini ira procurar na sua lista de serviços e tentar resolver sua dependencia pelo seu tipo: -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res e req são injetados pelo Martini - res.WriteHeader(200) // HTTP 200 -}) -~~~ - -Os seguintes serviços são incluídos com [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): - * [*log.Logger](http://godoc.org/log#Logger) - Log Global para Martini. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` de nomes dos parâmetros buscados pela rota. - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Serviço de auxílio as rotas. - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response escreve a interface. - * [*http.Request](http://godoc.org/net/http/#Request) - http Request. - -### Rotas -No Martini, uma rota é um método HTTP emparelhado com um padrão de URL de correspondência. -Cada rota pode ter um ou mais métodos handler: -~~~ go -m.Get("/", func() { - // mostra alguma coisa -}) - -m.Patch("/", func() { - // altera alguma coisa -}) - -m.Post("/", func() { - // cria alguma coisa -}) - -m.Put("/", func() { - // sobrescreve alguma coisa -}) - -m.Delete("/", func() { - // destrói alguma coisa -}) - -m.Options("/", func() { - // opções do HTTP -}) - -m.NotFound(func() { - // manipula 404 -}) -~~~ - -As rotas são combinadas na ordem em que são definidas. A primeira rota que corresponde a solicitação é chamada. - -O padrão de rotas pode incluir parâmetros que podem ser acessados via [martini.Params](http://godoc.org/github.com/go-martini/martini#Params): -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hello " + params["name"] -}) -~~~ - -As rotas podem ser combinados com expressões regulares e globs: -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hello " + params["_1"] -}) -~~~ - -Expressões regulares podem ser bem usadas: -~~~go -m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { - return fmt.Sprintf ("Hello %s", params["name"]) -}) -~~~ -Dê uma olhada na [documentação](http://golang.org/pkg/regexp/syntax/) para mais informações sobre expressões regulares. - - -Handlers de rota podem ser empilhados em cima uns dos outros, o que é útil para coisas como autenticação e autorização: -~~~ go -m.Get("/secret", authorize, func() { - // Será executado quando authorize não escrever uma resposta -}) -~~~ - -Grupos de rota podem ser adicionados usando o método Group. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}) -~~~ - -Assim como você pode passar middlewares para um manipulador você pode passar middlewares para grupos. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}, MyMiddleware1, MyMiddleware2) -~~~ - -### Serviços -Serviços são objetos que estão disponíveis para ser injetado em uma lista de argumentos de Handler. Você pode mapear um serviço num nível *Global* ou *Request*. - -#### Mapeamento Global -Um exemplo onde o Martini implementa a interface inject.Injector, então o mapeamento de um serviço é fácil: -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // o serviço estará disponível para todos os handlers *MyDatabase. -// ... -m.Run() -~~~ - -#### Mapeamento por requisição -Mapeamento do nível de request pode ser feito via handler através [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // mapeamento é *MyCustomLogger -} -~~~ - -#### Valores de Mapeamento para Interfaces -Uma das partes mais poderosas sobre os serviços é a capacidade para mapear um serviço de uma interface. Por exemplo, se você quiser substituir o [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) com um objeto que envolveu-o e realizou operações extras, você pode escrever o seguinte handler: -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // substituir ResponseWriter com nosso ResponseWriter invólucro -} -~~~ - -### Servindo Arquivos Estáticos -Uma instância de [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) serve automaticamente arquivos estáticos do diretório "public" na raiz do seu servidor. -Você pode servir de mais diretórios, adicionando mais [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers. -~~~ go -m.Use(martini.Static("assets")) // servindo os arquivos do diretório "assets" -~~~ - -## Middleware Handlers -Middleware Handlers ficam entre a solicitação HTTP e o roteador. Em essência, eles não são diferentes de qualquer outro Handler no Martini. Você pode adicionar um handler de middleware para a pilha assim: -~~~ go -m.Use(func() { - // faz algo com middleware -}) -~~~ - -Você pode ter o controle total sobre a pilha de middleware com a função `Handlers`. Isso irá substituir quaisquer manipuladores que foram previamente definidos: -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ - -Middleware Handlers trabalham muito bem com princípios com logging, autorização, autenticação, sessão, gzipping, páginas de erros e uma série de outras operações que devem acontecer antes ou depois de uma solicitação HTTP: -~~~ go -// Valida uma chave de API -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "secret123" { - res.WriteHeader(http.StatusUnauthorized) - } -}) -~~~ - -### Next() -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) é uma função opcional que Middleware Handlers podem chamar para aguardar a execução de outros Handlers. Isso funciona muito bem para operações que devem acontecer após uma requisição: -~~~ go -// log antes e depois do request -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("antes do request") - - c.Next() - - log.Println("depois do request") -}) -~~~ - -## Martini Env - -Martini handlers fazem uso do `martini.Env`, uma variável global para fornecer funcionalidade especial para ambientes de desenvolvimento e ambientes de produção. É recomendado que a variável `MARTINI_ENV=production` seja definida quando a implementação estiver em um ambiente de produção. - -## FAQ - -### Onde posso encontrar o middleware X? - -Inicie sua busca nos projetos [martini-contrib](https://github.com/martini-contrib). Se ele não estiver lá não hesite em contactar um membro da equipe martini-contrib sobre como adicionar um novo repo para a organização. - -* [auth](https://github.com/martini-contrib/auth) - Handlers para autenticação. -* [binding](https://github.com/martini-contrib/binding) - Handler para mapeamento/validação de um request a estrutura. -* [gzip](https://github.com/martini-contrib/gzip) - Handler para adicionar compreção gzip para o requests -* [render](https://github.com/martini-contrib/render) - Handler que providencia uma rederização simples para JSON e templates HTML. -* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler para parsing do `Accept-Language` no header HTTP. -* [sessions](https://github.com/martini-contrib/sessions) - Handler que prove o serviço de sessão. -* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. -* [method](https://github.com/martini-contrib/method) - HTTP método de substituição via cabeçalho ou campos do formulário. -* [secure](https://github.com/martini-contrib/secure) - Implementa rapidamente itens de segurança. -* [encoder](https://github.com/martini-contrib/encoder) - Serviço Encoder para renderização de dados em vários formatos e negociação de conteúdo. -* [cors](https://github.com/martini-contrib/cors) - Handler que habilita suporte a CORS. -* [oauth2](https://github.com/martini-contrib/oauth2) - Handler que prove sistema de login OAuth 2.0 para aplicações Martini. Google Sign-in, Facebook Connect e Github login são suportados. - -### Como faço para integrar com os servidores existentes? - -Uma instância do Martini implementa `http.Handler`, de modo que pode ser facilmente utilizado para servir sub-rotas e diretórios -em servidores Go existentes. Por exemplo, este é um aplicativo Martini trabalhando para Google App Engine: - -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - http.Handle("/", m) -} -~~~ - -### Como faço para alterar a porta/host? - -A função `Run` do Martini olha para as variáveis PORT e HOST para utilizá-las. Caso contrário o Martini assume como padrão localhost:3000. -Para ter mais flexibilidade sobre a porta e host use a função `martini.RunOnAddr`. - -~~~ go - m := martini.Classic() - // ... - log.Fatal(m.RunOnAddr(":8080")) -~~~ - -### Servidor com autoreload? - -[gin](https://github.com/codegangsta/gin) e [fresh](https://github.com/pilu/fresh) são aplicativos para autoreload do Martini. - -## Contribuindo -Martini é feito para ser mantido pequeno e limpo. A maioria das contribuições devem ser feitas no repositório [martini-contrib](https://github.com/martini-contrib). Se quiser contribuir com o core do Martini fique livre para fazer um Pull Request. - -## Sobre - -Inspirado por [express](https://github.com/visionmedia/express) e [sinatra](https://github.com/sinatra/sinatra) - -Martini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ru_RU.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ru_RU.md deleted file mode 100644 index 2cf00ea..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ru_RU.md +++ /dev/null @@ -1,354 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -Martini - мощный пакет для быстрой разработки веб приложений и сервисов на Golang. - -## Начало работы - -После установки Golang и настройки вашего [GOPATH](http://golang.org/doc/code.html#GOPATH), создайте ваш первый `.go` файл. Назовем его `server.go`. - -~~~ go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - m.Run() -} -~~~ - -Потом установите пакет Martini (требуется **go 1.1** или выше): -~~~ -go get github.com/go-martini/martini -~~~ - -Потом запустите ваш сервер: -~~~ -go run server.go -~~~ - -И вы получите запущенный Martini сервер на `localhost:3000`. - -## Помощь - -Присоединяйтесь к [рассылке](https://groups.google.com/forum/#!forum/martini-go) - -Смотрите [демо видео](http://martini.codegangsta.io/#demo) - -Задавайте вопросы на Stackoverflow используя [тэг martini](http://stackoverflow.com/questions/tagged/martini) - -GoDoc [документация](http://godoc.org/github.com/go-martini/martini) - - -## Возможности -* Очень прост в использовании. -* Ненавязчивый дизайн. -* Хорошо сочетается с другими пакетами. -* Потрясающий роутинг и маршрутизация. -* Модульный дизайн - легко добавлять и исключать функциональность. -* Большое количество хороших обработчиков/middlewares, готовых к использованию. -* Отличный набор 'из коробки'. -* **Полностью совместим с интерфейсом [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** - -## Больше Middleware -Смотрите репозитории организации [martini-contrib](https://github.com/martini-contrib), для большей информации о функциональности и middleware. - -## Содержание -* [Classic Martini](#classic-martini) - * [Обработчики](#%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8) - * [Роутинг](#%D0%A0%D0%BE%D1%83%D1%82%D0%B8%D0%BD%D0%B3) - * [Сервисы](#%D0%A1%D0%B5%D1%80%D0%B2%D0%B8%D1%81%D1%8B) - * [Отдача статических файлов](#%D0%9E%D1%82%D0%B4%D0%B0%D1%87%D0%B0-%D1%81%D1%82%D0%B0%D1%82%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B8%D1%85-%D1%84%D0%B0%D0%B9%D0%BB%D0%BE%D0%B2) -* [Middleware обработчики](#middleware-%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8) - * [Next()](#next) -* [Окружение](#%D0%9E%D0%BA%D1%80%D1%83%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5) -* [FAQ](#faq) - -## Classic Martini -Для быстрого старта [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) предлагает несколько предустановок, это используется для большинства веб приложений: -~~~ go - m := martini.Classic() - // ... middleware и роутинг здесь - m.Run() -~~~ - -Ниже представлена уже подключенная [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) функциональность: - - * Request/Response логгирование - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) - * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) - * Отдача статики - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) - * Роутинг - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - -### Обработчики -Обработчики - это сердце и душа Martini. Обработчик - любая функция, которая может быть вызвана: -~~~ go -m.Get("/", func() { - println("hello world") -}) -~~~ - -#### Возвращаемые значения -Если обработчик возвращает что либо, Martini запишет это как результат в текущий [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), в виде строки: -~~~ go -m.Get("/", func() string { - return "hello world" // HTTP 200 : "hello world" -}) -~~~ - -Так же вы можете возвращать код статуса, опционально: -~~~ go -m.Get("/", func() (int, string) { - return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" -}) -~~~ - -#### Внедрение сервисов -Обработчики вызываются посредством рефлексии. Martini использует **Внедрение зависимости** для разрешения зависимостей в списке аргумента обработчика. **Это делает Martini полностью совместимым с интерфейсом `http.HandlerFunc`.** - -Если вы добавите аргументы в ваш обработчик, Martini будет пытаться найти этот список сервисов за счет проверки типов(type assertion): -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res и req будут внедрены Martini - res.WriteHeader(200) // HTTP 200 -}) -~~~ - -Следующие сервисы включены в [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): - - * [*log.Logger](http://godoc.org/log#Logger) - Глобальный логгер для Martini. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request контекст. - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` именованых аргументов из роутера. - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Хэлпер роутеров. - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer интерфейс. - * [*http.Request](http://godoc.org/net/http/#Request) - http Request. - -### Роутинг -В Martini, роут - это объединенные паттерн и HTTP метод. -Каждый роут может принимать один или несколько обработчиков: -~~~ go -m.Get("/", func() { - // показать что-то -}) - -m.Patch("/", func() { - // обновить что-то -}) - -m.Post("/", func() { - // создать что-то -}) - -m.Put("/", func() { - // изменить что-то -}) - -m.Delete("/", func() { - // удалить что-то -}) - -m.Options("/", func() { - // http опции -}) - -m.NotFound(func() { - // обработчик 404 -}) -~~~ - -Роуты могут сопоставляться с http запросами только в порядке объявления. Вызывается первый роут, который соответствует запросу. - -Паттерны роутов могут включать именованные параметры, доступные через [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) сервис: -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hello " + params["name"] -}) -~~~ - -Роуты можно объявлять как glob'ы: -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hello " + params["_1"] -}) -~~~ - -Так же могут использоваться регулярные выражения: -~~~go -m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { - return fmt.Sprintf ("Hello %s", params["name"]) -}) -~~~ -Синтаксис регулярных выражений смотрите [Go documentation](http://golang.org/pkg/regexp/syntax/). - -Обработчики роутов так же могут быть выстроены в стек, друг перед другом. Это очень удобно для таких задач как авторизация и аутентификация: -~~~ go -m.Get("/secret", authorize, func() { - // будет вызываться, в случае если authorize ничего не записал в ответ -}) -~~~ - -Роуты так же могут быть объединены в группы, посредством метода Group: -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}) -~~~ - -Так же как вы можете добавить middleware для обычного обработчика, вы можете добавить middleware и для группы. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}, MyMiddleware1, MyMiddleware2) -~~~ - -### Сервисы -Сервисы - это объекты, которые доступны для внедрения в аргументы обработчиков. Вы можете замапить сервисы на уровне всего приложения либо на уровне запроса. - -#### Глобальный маппинг -Экземпляр Martini реализует интерфейс inject.Injector, поэтому замаппить сервис легко: -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // сервис будет доступен для всех обработчиков как *MyDatabase -// ... -m.Run() -~~~ - -#### Маппинг уровня запроса -Маппинг на уровне запроса можно сделать при помощи [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // как *MyCustomLogger -} -~~~ - -#### Маппинг на определенный интерфейс -Одна из мощных частей, того что касается сервисов - маппинг сервиса на определенный интерфейс. Например, если вы хотите переопределить [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) объектом, который оборачивает и добавляет новые операции, вы можете написать следующее: -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // переопределить ResponseWriter нашей оберткой -} -~~~ - -### Отдача статических файлов -Экземпляр [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) автоматически отдает статические файлы из директории "public" в корне, рядом с вашим файлом `server.go`. -Вы можете добавить еще директорий, добавляя [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) обработчики. -~~~ go -m.Use(martini.Static("assets")) // отдача файлов из "assets" директории -~~~ - -## Middleware Обработчики -Middleware обработчики находятся между входящим http запросом и роутом. По сути, они ничем не отличаются от любого другого обработчика Martini. Вы можете добавить middleware обработчик в стек следующим образом: -~~~ go -m.Use(func() { - // делать какую то middleware работу -}) -~~~ - -Для полного контроля над стеком middleware существует метод `Handlers`. В этом примере будут заменены все обработчики, которые были до этого: -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ - -Middleware обработчики очень хорошо работают для таких вещей как логгирование, авторизация, аутентификация, сессии, сжатие, страницы ошибок и любые другие операции, которые должны быть выполнены до или после http запроса: -~~~ go -// валидация api ключа -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "secret123" { - res.WriteHeader(http.StatusUnauthorized) - } -}) -~~~ - -### Next() -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) опциональная функция, которая может быть вызвана в Middleware обработчике, для выхода из контекста, и возврата в него, после вызова всего стека обработчиков. Это можно использовать для операций, которые должны быть выполнены после http запроса: -~~~ go -// логгирование до и после http запроса -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("до запроса") - - c.Next() - - log.Println("после запроса") -}) -~~~ - -## Окружение -Некоторые Martini обработчики используют глобальную переменную `martini.Env` для того, чтоб предоставить специальную функциональность для девелопмент и продакшн окружения. Рекомендуется устанавливать `MARTINI_ENV=production`, когда вы деплоите приложение на продакшн. - -## FAQ - -### Где найти готовые middleware? - -Начните поиск с [martini-contrib](https://github.com/martini-contrib) проектов. Если нет ничего подходящего, без колебаний пишите члену команды martini-contrib о добавлении нового репозитория в организацию. - -* [auth](https://github.com/martini-contrib/auth) - Обработчики для аутентификации. -* [binding](https://github.com/martini-contrib/binding) - Обработчик для маппинга/валидации сырого запроса в определенную структуру(struct). -* [gzip](https://github.com/martini-contrib/gzip) - Обработчик, добавляющий gzip сжатие для запросов. -* [render](https://github.com/martini-contrib/render) - Обработчик, которые предоставляет сервис для легкого рендеринга JSON и HTML шаблонов. -* [acceptlang](https://github.com/martini-contrib/acceptlang) - Обработчик для парсинга `Accept-Language` HTTP заголовка. -* [sessions](https://github.com/martini-contrib/sessions) - Сервис сессий. -* [strip](https://github.com/martini-contrib/strip) - Удаление префиксов из URL. -* [method](https://github.com/martini-contrib/method) - Подмена HTTP метода через заголовок. -* [secure](https://github.com/martini-contrib/secure) - Набор для безопасности. -* [encoder](https://github.com/martini-contrib/encoder) - Сервис для представления данных в нескольких форматах и взаимодействия с контентом. -* [cors](https://github.com/martini-contrib/cors) - Поддержка CORS. -* [oauth2](https://github.com/martini-contrib/oauth2) - Обработчик, предоставляющий OAuth 2.0 логин для Martini приложений. Вход через Google, Facebook и через Github поддерживаются. - -### Как интегрироваться с существуюшими серверами? - -Экземпляр Martini реализует интерфейс `http.Handler`, потому - это очень просто использовать вместе с существующим Go проектом. Например, это работает для платформы Google App Engine: -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - http.Handle("/", m) -} -~~~ - -### Как изменить порт и/или хост? -Функция `Run` смотрит переменные окружиения PORT и HOST, и использует их. -В противном случае Martini по умолчанию будет использовать `localhost:3000`. -Для большей гибкости используйте вместо этого функцию `martini.RunOnAddr`. - -~~~ go - m := martini.Classic() - // ... - log.Fatal(m.RunOnAddr(":8080")) -~~~ - -### Живая перезагрузка кода? - -[gin](https://github.com/codegangsta/gin) и [fresh](https://github.com/pilu/fresh) могут работать вместе с Martini. - -## Вклад в обшее дело - -Подразумевается что Martini чистый и маленький. Большинство улучшений должны быть в организации [martini-contrib](https://github.com/martini-contrib). Но если вы хотите улучшить ядро Martini, отправляйте пулл реквесты. - -## О проекте - -Вдохновлен [express](https://github.com/visionmedia/express) и [sinatra](https://github.com/sinatra/sinatra) - -Martini создан [Code Gangsta](http://codegangsta.io/) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_tr_TR.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_tr_TR.md deleted file mode 100644 index 9221b34..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_tr_TR.md +++ /dev/null @@ -1,387 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -Martini Go dilinde hızlı ve modüler web uygulamaları ve servisleri için güçlü bir pakettir. - - -## Başlangıç - -Go kurulumu ve [GOPATH](http://golang.org/doc/code.html#GOPATH) ayarını yaptıktan sonra, ilk `.go` uzantılı dosyamızı oluşturuyoruz. Bu oluşturduğumuz dosyayı `server.go` olarak adlandıracağız. - -~~~ go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - m.Run() -} -~~~ - -Martini paketini kurduktan sonra (**go 1.1** ve daha üst go sürümü gerekmektedir.): - -~~~ -go get github.com/go-martini/martini -~~~ - -Daha sonra server'ımızı çalıştırıyoruz: - -~~~ -go run server.go -~~~ - -Şimdi elimizde çalışan bir adet Martini webserver `localhost:3000` adresinde bulunmaktadır. - - -## Yardım Almak İçin - -[Mail Listesi](https://groups.google.com/forum/#!forum/martini-go) - -[Örnek Video](http://martini.codegangsta.io/#demo) - -Stackoverflow üzerinde [martini etiketine](http://stackoverflow.com/questions/tagged/martini) sahip sorular - -[GO Diline ait Dökümantasyonlar](http://godoc.org/github.com/go-martini/martini) - - -## Özellikler -* Oldukça basit bir kullanıma sahip. -* Kısıtlama yok. -* Golang paketleri ile rahat bir şekilde kullanılıyor. -* Müthiş bir şekilde path eşleştirme ve yönlendirme. -* Modüler dizayn - Kolay eklenen fonksiyonellik. -* handlers/middlewares kullanımı çok iyi. -* Büyük 'kutu dışarı' özellik seti. -* **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) arayüzü ile tam uyumludur.** -* Varsayılan belgelendirme işlemleri (örnek olarak, AngularJS uygulamalarının HTML5 modunda servis edilmesi). - -## Daha Fazla Middleware(Ara Katman) - -Daha fazla ara katman ve fonksiyonellik için, şu repoları inceleyin [martini-contrib](https://github.com/martini-contrib). - -## Tablo İçerikleri -* [Classic Martini](#classic-martini) - * [İşleyiciler / Handlers](#handlers) - * [Yönlendirmeler / Routing](#routing) - * [Servisler](#services) - * [Statik Dosyaların Sunumu](#serving-static-files) -* [Katman İşleyiciler / Middleware Handlers](#middleware-handlers) - * [Next()](#next) -* [Martini Env](#martini-env) -* [FAQ](#faq) - -## Classic Martini -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) hızlıca projeyi çalıştırır ve çoğu web uygulaması için iyi çalışan bazı makul varsayılanlar sağlar: - -~~~ go - m := martini.Classic() - // ... middleware and routing goes here - m.Run() -~~~ - -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) aşağıdaki bazı fonsiyonelleri otomatik olarak çeker: - - * İstek/Yanıt Kayıtları (Request/Response Logging) - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) - * Hataların Düzeltilmesi (Panic Recovery) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) - * Statik Dosyaların Sunumu (Static File serving) - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) - * Yönlendirmeler (Routing) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - -### İşleyiciler (Handlers) -İşleyiciler Martini'nin ruhu ve kalbidir. Bir işleyici temel olarak her türlü fonksiyonu çağırabilir: - -~~~ go -m.Get("/", func() { - println("hello world") -}) -~~~ - -#### Geriye Dönen Değerler - -Eğer bir işleyici geriye bir şey dönderiyorsa, Martini string olarak sonucu [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) ile yazacaktır: - -~~~ go -m.Get("/", func() string { - return "hello world" // HTTP 200 : "hello world" -}) -~~~ - -Ayrıca isteğe bağlı bir durum kodu dönderebilir: -~~~ go -m.Get("/", func() (int, string) { - return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" -}) -~~~ - -#### Service Injection -İşlemciler yansıma yoluyla çağrılır. Martini *Dependency Injection* kullanarak arguman listesindeki bağımlıkları giderir.**Bu sayede Martini go programlama dilinin `http.HandlerFunc` arayüzü ile tamamen uyumlu hale getirilir.** - -Eğer işleyiciye bir arguman eklersek, Martini "type assertion" ile servis listesinde arayacak ve bağımlılıkları çözmek için girişimde bulunacaktır: - -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini - res.WriteHeader(200) // HTTP 200 -}) -~~~ - -Aşağıdaki servislerin içerikleri - -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): - * [*log.Logger](http://godoc.org/log#Logger) - Martini için Global loglayıcı. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request içereği. - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` ile yol eşleme tarafından params olarak isimlendirilen yapılar bulundu. - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Yönledirilme için yardımcı olan yapıdır. - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http yanıtlarını yazacak olan yapıdır. - * [*http.Request](http://godoc.org/net/http/#Request) - http Request(http isteği yapar). - -### Yönlendirme - Routing -Martini'de bir yol HTTP metodu URL-matching pattern'i ile eşleştirilir. -Her bir yol bir veya daha fazla işleyici metod alabilir: -~~~ go -m.Get("/", func() { - // show something -}) - -m.Patch("/", func() { - // update something -}) - -m.Post("/", func() { - // create something -}) - -m.Put("/", func() { - // replace something -}) - -m.Delete("/", func() { - // destroy something -}) - -m.Options("/", func() { - // http options -}) - -m.NotFound(func() { - // handle 404 -}) -~~~ - -Yollar sırayla tanımlandıkları şekilde eşleştirilir.Request ile eşleşen ilk rota çağrılır. - -Yol patternleri [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) servisi tarafından adlandırılan parametreleri içerebilir: -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hello " + params["name"] -}) -~~~ - -Yollar globaller ile eşleşebilir: -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hello " + params["_1"] -}) -~~~ - -Düzenli ifadeler kullanılabilir: -~~~go -m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { - return fmt.Sprintf ("Hello %s", params["name"]) -}) -~~~ -Düzenli ifadeler hakkında daha fazla bilgiyi [Go dökümanlarından](http://golang.org/pkg/regexp/syntax/) elde edebilirsiniz. - -Yol işleyicileri birbirlerinin üstüne istiflenebilir. Bu durum doğrulama ve yetkilendirme(authentication and authorization) işlemleri için iyi bir yöntemdir: -~~~ go -m.Get("/secret", authorize, func() { - // this will execute as long as authorize doesn't write a response -}) -~~~ - -Yol grupları Grup metodlar kullanılarak eklenebilir. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}) -~~~ - -Tıpkı ara katmanların işleyiciler için bazı ara katman işlemlerini atlayabileceği gibi gruplar içinde atlayabilir. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}, MyMiddleware1, MyMiddleware2) -~~~ - -### Servisler - -Servisler işleyicilerin arguman listesine enjekte edilecek kullanılabilir nesnelerdir. İstenildiği taktirde bir servis *Global* ve *Request* seviyesinde eşlenebilir. - -#### Global Eşleme - Global Mapping - -Bir martini örneği(instance) projeye enjekte edilir. -A Martini instance implements the inject.Enjekte arayüzü, çok kolay bir şekilde servis eşlemesi yapar: -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // the service will be available to all handlers as *MyDatabase -// ... -m.Run() -~~~ - -#### Request-Level Mapping -Request düzeyinde eşleme yapmak üzere işleyici [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) ile oluşturulabilir: -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // mapped as *MyCustomLogger -} -~~~ - -#### Arayüz Eşleme Değerleri -Servisler hakkındaki en güçlü şeylerden birisi bir arabirim ile bir servis eşleşmektedir. Örneğin, istenirse [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) yapısı paketlenmiş ve ekstra işlemleri gerçekleştirilen bir nesne ile override edilebilir. Şu işleyici yazılabilir: - -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter -} -~~~ - -### Statik Dosyaların Sunumu - -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) örneği otomatik olarak statik dosyaları serverda root içinde yer alan "public" dizininden servis edilir. - -Eğer istenirse daha fazla [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) işleyicisi eklenerek daha fazla dizin servis edilebilir. -~~~ go -m.Use(martini.Static("assets")) // serve from the "assets" directory as well -~~~ - -#### Standart Dökümanların Sunulması - Serving a Default Document - -Eğer istenilen URL bulunamaz ise özel bir URL dönderilebilir. Ayrıca bir dışlama(exclusion) ön eki ile bazı URL'ler göz ardı edilir. Bu durum statik dosyaların ve ilave işleyiciler için kullanışlıdır(Örneğin, REST API). Bunu yaparken, bu işlem ile NotFound zincirinin bir parçası olan statik işleyiciyi tanımlamak kolaydır. - -Herhangi bir URL isteği bir local dosya ile eşleşmediği ve `/api/v` ile başlamadığı zaman aşağıdaki örnek `/index.html` dosyasını sonuç olarak geriye döndürecektir. -~~~ go -static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) -m.NotFound(static, http.NotFound) -~~~ - -## Ara Katman İşleyicileri -Ara katmana ait işleyiciler http isteği ve yönlendirici arasında bulunmaktadır. Özünde onlar diğer Martini işleyicilerinden farklı değildirler. İstenildiği taktirde bir yığına ara katman işleyicisi şu şekilde eklenebilir: -~~~ go -m.Use(func() { - // do some middleware stuff -}) -~~~ - -`Handlers` fonksiyonu ile ara katman yığını üzerinde tüm kontrole sahip olunabilir. Bu daha önceden ayarlanmış herhangi bir işleyicinin yerini alacaktır: -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ - -Orta katman işleyicileri loglama, giriş , yetkilendirme , sessionlar, sıkıştırma(gzipping) , hata sayfaları ve HTTP isteklerinden önce ve sonra herhangi bir olay sonucu oluşan durumlar için gerçekten iyi bir yapıya sahiptir: - -~~~ go -// validate an api key -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "secret123" { - res.WriteHeader(http.StatusUnauthorized) - } -}) -~~~ - -### Next() -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) orta katman işleyicilerinin diğer işleyiciler yok edilmeden çağrılmasını sağlayan opsiyonel bir fonksiyondur.Bu iş http işlemlerinden sonra gerçekleşecek işlemler için gerçekten iyidir: -~~~ go -// log before and after a request -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("before a request") - - c.Next() - - log.Println("after a request") -}) -~~~ - -## Martini Env - -Bazı Martini işleyicileri `martini.Env` yapısının özel fonksiyonlarını kullanmak için geliştirici ortamları, üretici ortamları vs. kullanır.Bu üretim ortamına Martini sunucu kurulurken `MARTINI_ENV=production` şeklinde ortam değişkeninin ayarlanması gerekir. - -## FAQ - -### Ara Katmanda X'i Nerede Bulurum? - -[martini-contrib](https://github.com/martini-contrib) projelerine bakarak başlayın. Eğer aradığınız şey orada mevcut değil ise yeni bir repo eklemek için martini-contrib takım üyeleri ile iletişime geçin. - -* [auth](https://github.com/martini-contrib/auth) - Kimlik doğrulama için işleyiciler. -* [binding](https://github.com/martini-contrib/binding) - Mapping/Validating yapısı içinde ham request'i doğrulamak için kullanılan işleyici(handler) -* [gzip](https://github.com/martini-contrib/gzip) - İstekleri gzip sıkışıtırıp eklemek için kullanılan işleyici -* [render](https://github.com/martini-contrib/render) - Kolay bir şekilde JSON ve HTML şablonları oluşturmak için kullanılan işleyici. -* [acceptlang](https://github.com/martini-contrib/acceptlang) - `Kabul edilen dile` göre HTTP başlığını oluşturmak için kullanılan işleyici. -* [sessions](https://github.com/martini-contrib/sessions) - Oturum hizmeti vermek için kullanılır. -* [strip](https://github.com/martini-contrib/strip) - İşleyicilere gitmeden önce URL'ye ait ön şeriti değiştirme işlemini yapar. -* [method](https://github.com/martini-contrib/method) - Formlar ve başlık için http metodunu override eder. -* [secure](https://github.com/martini-contrib/secure) - Birkaç hızlı güvenlik uygulaması ile kazanımda bulundurur. -* [encoder](https://github.com/martini-contrib/encoder) - Encoder servis veri işlemleri için çeşitli format ve içerik sağlar. -* [cors](https://github.com/martini-contrib/cors) - İşleyicilerin CORS desteği bulunur. -* [oauth2](https://github.com/martini-contrib/oauth2) - İşleyiciler OAuth 2.0 için Martini uygulamalarına giriş sağlar. Google , Facebook ve Github için desteği mevcuttur. -* [vauth](https://github.com/rafecolton/vauth) - Webhook için giriş izni sağlar. (şimdilik sadece GitHub ve TravisCI ile) - -### Mevcut Sunucular ile Nasıl Entegre Edilir? - -Bir martini örneği `http.Handler`'ı projeye dahil eder, bu sayde kolay bir şekilde mevcut olan Go sunucularında bulunan alt ağaçlarda kullanabilir. Örnek olarak, bu olay Google App Engine için hazırlanmış Martini uygulamalarında kullanılmaktadır: - -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - http.Handle("/", m) -} -~~~ - -### port/hostu nasıl değiştiririm? - -Martini'ye ait `Run` fonksiyounu PORT ve HOST'a ait ortam değişkenlerini arar ve bunları kullanır. Aksi taktirde standart olarak localhost:3000 adresini port ve host olarak kullanacaktır. - -Port ve host için daha fazla esneklik isteniyorsa `martini.RunOnAddr` fonksiyonunu kullanın. - -~~~ go - m := martini.Classic() - // ... - log.Fatal(m.RunOnAddr(":8080")) -~~~ - -### Anlık Kod Yüklemesi? - -[gin](https://github.com/codegangsta/gin) ve [fresh](https://github.com/pilu/fresh) anlık kod yüklemeleri yapan martini uygulamalarıdır. - -## Katkıda Bulunmak -Martini'nin temiz ve düzenli olaması gerekiyordu. -Martini is meant to be kept tiny and clean. Tüm kullanıcılar katkı yapmak için [martini-contrib](https://github.com/martini-contrib) organizasyonunda yer alan repoları bitirmelidirler. Eğer martini core için katkıda bulunacaksanız fork işlemini yaparak başlayabilirsiniz. - -## Hakkında - -[express](https://github.com/visionmedia/express) ve [sinatra](https://github.com/sinatra/sinatra) projelerinden esinlenmiştir. - -Martini [Code Gangsta](http://codegangsta.io/) tarafından tasarlanılmıştır. diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_cn.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_cn.md deleted file mode 100644 index 3fa2c1b..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_cn.md +++ /dev/null @@ -1,315 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/174bef7e3c999e103cacfe2770102266 "wercker status")](https://app.wercker.com/project/bykey/174bef7e3c999e103cacfe2770102266) [![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -Martini是一个强大为了编写模块化Web应用而生的GO语言框架. - -## 第一个应用 - -在你安装了GO语言和设置了你的[GOPATH](http://golang.org/doc/code.html#GOPATH)之后, 创建你的自己的`.go`文件, 这里我们假设它的名字叫做 `server.go`. - -~~~ go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - m.Run() -} -~~~ - -然后安装Martini的包. (注意Martini需要Go语言1.1或者以上的版本支持): -~~~ -go get github.com/go-martini/martini -~~~ - -最后运行你的服务: -~~~ -go run server.go -~~~ - -这时你将会有一个Martini的服务监听了, 地址是: `localhost:3000`. - -## 获得帮助 - -请加入: [邮件列表](https://groups.google.com/forum/#!forum/martini-go) - -或者可以查看在线演示地址: [演示视频](http://martini.codegangsta.io/#demo) - -## 功能列表 -* 使用极其简单. -* 无侵入式的设计. -* 很好的与其他的Go语言包协同使用. -* 超赞的路径匹配和路由. -* 模块化的设计 - 容易插入功能件,也容易将其拔出来. -* 已有很多的中间件可以直接使用. -* 框架内已拥有很好的开箱即用的功能支持. -* **完全兼容[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc)接口.** - -## 更多中间件 -更多的中间件和功能组件, 请查看代码仓库: [martini-contrib](https://github.com/martini-contrib). - -## 目录 -* [核心 Martini](#classic-martini) - * [处理器](#handlers) - * [路由](#routing) - * [服务](#services) - * [服务静态文件](#serving-static-files) -* [中间件处理器](#middleware-handlers) - * [Next()](#next) -* [常见问答](#faq) - -## 核心 Martini -为了更快速的启用Martini, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 提供了一些默认的方便Web开发的工具: -~~~ go - m := martini.Classic() - // ... middleware and routing goes here - m.Run() -~~~ - -下面是Martini核心已经包含的功能 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): - * Request/Response Logging (请求/响应日志) - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) - * Panic Recovery (容错) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) - * Static File serving (静态文件服务) - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) - * Routing (路由) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - -### 处理器 -处理器是Martini的灵魂和核心所在. 一个处理器基本上可以是任何的函数: -~~~ go -m.Get("/", func() { - println("hello world") -}) -~~~ - -#### 返回值 -当一个处理器返回结果的时候, Martini将会把返回值作为字符串写入到当前的[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)里面: -~~~ go -m.Get("/", func() string { - return "hello world" // HTTP 200 : "hello world" -}) -~~~ - -另外你也可以选择性的返回多一个状态码: -~~~ go -m.Get("/", func() (int, string) { - return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" -}) -~~~ - -#### 服务的注入 -处理器是通过反射来调用的. Martini 通过*Dependency Injection* *(依赖注入)* 来为处理器注入参数列表. **这样使得Martini与Go语言的`http.HandlerFunc`接口完全兼容.** - -如果你加入一个参数到你的处理器, Martini将会搜索它参数列表中的服务,并且通过类型判断来解决依赖关系: -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res 和 req 是通过Martini注入的 - res.WriteHeader(200) // HTTP 200 -}) -~~~ - -下面的这些服务已经被包含在核心Martini中: [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): - * [*log.Logger](http://godoc.org/log#Logger) - Martini的全局日志. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context (请求上下文). - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching. (名字和参数键值对的参数列表) - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service. (路由协助处理) - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. (响应结果的流接口) - * [*http.Request](http://godoc.org/net/http/#Request) - http Request. (http请求) - -### 路由 -在Martini中, 路由是一个HTTP方法配对一个URL匹配模型. 每一个路由可以对应一个或多个处理器方法: -~~~ go -m.Get("/", func() { - // 显示 -}) - -m.Patch("/", func() { - // 更新 -}) - -m.Post("/", func() { - // 创建 -}) - -m.Put("/", func() { - // 替换 -}) - -m.Delete("/", func() { - // 删除 -}) - -m.Options("/", func() { - // http 选项 -}) - -m.NotFound(func() { - // 处理 404 -}) -~~~ - -路由匹配的顺序是按照他们被定义的顺序执行的. 最先被定义的路由将会首先被用户请求匹配并调用. - -路由模型可能包含参数列表, 可以通过[martini.Params](http://godoc.org/github.com/go-martini/martini#Params)服务来获取: -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hello " + params["name"] -}) -~~~ - -路由匹配可以通过正则表达式或者glob的形式: -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hello " + params["_1"] -}) -~~~ - -路由处理器可以被相互叠加使用, 例如很有用的地方可以是在验证和授权的时候: -~~~ go -m.Get("/secret", authorize, func() { - // 该方法将会在authorize方法没有输出结果的时候执行. -}) -~~~ - -### 服务 -服务即是被注入到处理器中的参数. 你可以映射一个服务到 *全局* 或者 *请求* 的级别. - - -#### 全局映射 -如果一个Martini实现了inject.Injector的接口, 那么映射成为一个服务就非常简单: -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // *MyDatabase 这个服务将可以在所有的处理器中被使用到. -// ... -m.Run() -~~~ - -#### 请求级别的映射 -映射在请求级别的服务可以用[martini.Context](http://godoc.org/github.com/go-martini/martini#Context)来完成: -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // 映射成为了 *MyCustomLogger -} -~~~ - -#### 映射值到接口 -关于服务最强悍的地方之一就是它能够映射服务到接口. 例如说, 假设你想要覆盖[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)成为一个对象, 那么你可以封装它并包含你自己的额外操作, 你可以如下这样来编写你的处理器: -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // 覆盖 ResponseWriter 成为我们封装过的 ResponseWriter -} -~~~ - -### 服务静态文件 -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 默认会服务位于你服务器环境根目录下的"public"文件夹. -你可以通过加入[martini.Static](http://godoc.org/github.com/go-martini/martini#Static)的处理器来加入更多的静态文件服务的文件夹. -~~~ go -m.Use(martini.Static("assets")) // 也会服务静态文件于"assets"的文件夹 -~~~ - -## 中间件处理器 -中间件处理器是工作于请求和路由之间的. 本质上来说和Martini其他的处理器没有分别. 你可以像如下这样添加一个中间件处理器到它的堆中: -~~~ go -m.Use(func() { - // 做一些中间件该做的事情 -}) -~~~ - -你可以通过`Handlers`函数对中间件堆有完全的控制. 它将会替换掉之前的任何设置过的处理器: -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ - -中间件处理器可以非常好处理一些功能,像logging(日志), authorization(授权), authentication(认证), sessions(会话), error pages(错误页面), 以及任何其他的操作需要在http请求发生之前或者之后的: - -~~~ go -// 验证api密匙 -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "secret123" { - res.WriteHeader(http.StatusUnauthorized) - } -}) -~~~ - -### Next() -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context)是一个可选的函数用于中间件处理器暂时放弃执行直到其他的处理器都执行完毕. 这样就可以很好的处理在http请求完成后需要做的操作. -~~~ go -// log 记录请求完成前后 (*译者注: 很巧妙,掌声鼓励.) -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("before a request") - - c.Next() - - log.Println("after a request") -}) -~~~ - -## 常见问答 - -### 我在哪里可以找到中间件资源? - -可以查看 [martini-contrib](https://github.com/martini-contrib) 项目. 如果看了觉得没有什么好货色, 可以联系martini-contrib的团队成员为你创建一个新的代码资源库. - -* [auth](https://github.com/martini-contrib/auth) - 认证处理器。 -* [binding](https://github.com/martini-contrib/binding) - 映射/验证raw请求到结构体(structure)里的处理器。 -* [gzip](https://github.com/martini-contrib/gzip) - 通过giz方式压缩请求信息的处理器。 -* [render](https://github.com/martini-contrib/render) - 渲染JSON和HTML模板的处理器。 -* [acceptlang](https://github.com/martini-contrib/acceptlang) - 解析`Accept-Language` HTTP报头的处理器。 -* [sessions](https://github.com/martini-contrib/sessions) - 提供`Session`服务支持的处理器。 -* [strip](https://github.com/martini-contrib/strip) - 用于过滤指定的URL前缀。 -* [method](https://github.com/martini-contrib/method) - 通过请求头或表单域覆盖HTTP方法。 -* [secure](https://github.com/martini-contrib/secure) - 提供一些安全方面的速效方案。 -* [encoder](https://github.com/martini-contrib/encoder) - 提供用于多种格式的数据渲染或内容协商的编码服务。 -* [cors](https://github.com/martini-contrib/cors) - 提供支持 CORS 的处理器。 -* [oauth2](https://github.com/martini-contrib/oauth2) - 基于 OAuth 2.0 的应用登录处理器。支持谷歌、Facebook和Github的登录。 -* [vauth](https://github.com/rafecolton/vauth) - 负责webhook认证的处理器(目前支持GitHub和TravisCI)。 - - -### 我如何整合到我现有的服务器中? - -由于Martini实现了 `http.Handler`, 所以它可以很简单的应用到现有Go服务器的子集中. 例如说这是一段在Google App Engine中的示例: - -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - http.Handle("/", m) -} -~~~ - -### 我如何修改port/host? - -Martini的`Run`函数会检查PORT和HOST的环境变量并使用它们. 否则Martini将会默认使用localhost:3000 -如果想要自定义PORT和HOST, 使用`martini.RunOnAddr`函数来代替. - -~~~ go - m := martini.Classic() - // ... - m.RunOnAddr(":8080") -~~~ - -## 贡献 -Martini项目想要保持简单且干净的代码. 大部分的代码应该贡献到[martini-contrib](https://github.com/martini-contrib)组织中作为一个项目. 如果你想要贡献Martini的核心代码也可以发起一个Pull Request. - -## 关于 - -灵感来自于 [express](https://github.com/visionmedia/express) 和 [sinatra](https://github.com/sinatra/sinatra) - -Martini作者 [Code Gangsta](http://codegangsta.io/) -译者: [Leon](http://github.com/leonli) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_tw.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_tw.md deleted file mode 100644 index 8d19dbe..0000000 --- a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_tw.md +++ /dev/null @@ -1,381 +0,0 @@ -# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) - -Martini 是一個使用 Go 語言來快速開發模組化 Web 應用程式或服務的強大套件 - -## 開始 - -在您安裝Go語言以及設定好 -[GOPATH](http://golang.org/doc/code.html#GOPATH)環境變數後, -開始寫您第一支`.go`檔, 我們將稱它為`server.go` - -~~~ go -package main - -import "github.com/go-martini/martini" - -func main() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello 世界!" - }) - m.Run() -} -~~~ - -然後安裝Martini套件 (**go 1.1**以上的版本是必要的) -~~~ -go get github.com/go-martini/martini -~~~ - -然後利用以下指令執行你的程式: -~~~ -go run server.go -~~~ - -此時, 您將會看到一個 Martini Web 伺服器在`localhost:3000`上執行 - -## 尋求幫助 - -可以加入 [Mailing list](https://groups.google.com/forum/#!forum/martini-go) - -觀看 [Demo Video](http://martini.codegangsta.io/#demo) - -## 功能 - -* 超容易使用 -* 非侵入式設計 -* 很容易跟其他Go套件同時使用 -* 很棒的路徑matching和routing方式 -* 模組化設計 - 容易增加或移除功能 -* 有很多handlers或middlewares可以直接使用 -* 已經提供很多內建功能 -* **跟[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) 介面**完全相容 -* 預設document服務 (例如, 提供AngularJS在HTML5模式的服務) - -## 其他Middleware -尋找更多的middleware或功能, 請到 [martini-contrib](https://github.com/martini-contrib)程式集搜尋 - -## 目錄 -* [Classic Martini](#classic-martini) -* [Handlers](#handlers) -* [Routing](#routing) -* [Services (服務)](#services) -* [Serving Static Files (伺服靜態檔案)](#serving-static-files) -* [Middleware Handlers](#middleware-handlers) -* [Next()](#next) -* [Martini Env](#martini-env) -* [FAQ (常見問題與答案)](#faq) - -## Classic Martini - -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) -提供大部份web應用程式所需要的基本預設功能: - -~~~ go - m := martini.Classic() - // ... middleware 或 routing 寫在這裡 - m.Run() -~~~ -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) - 會自動提供以下功能 -* Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) -* Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) -* Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) -* Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) - - -### Handlers -Handlers 是 Martini 的核心, 每個 handler 就是一個基本的呼叫函式, 例如: -~~~ go -m.Get("/", func() { - println("hello 世界") -}) -~~~ - -#### 回傳值 -如果一個 handler 有回傳值, Martini就會用字串的方式將結果寫回現在的 -[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), 例如: -~~~ go -m.Get("/", func() string { - return "hello 世界" // HTTP 200 : "hello 世界" -}) -~~~ - -你也可以選擇回傳狀態碼, 例如: -~~~ go -m.Get("/", func() (int, string) { - return 418, "我是一個茶壺" // HTTP 418 : "我是一個茶壺" -}) -~~~ - -#### 注入服務 (Service Injection) -Handlers 是透過 reflection 方式被喚起, Martini 使用 *Dependency Injection* 的方法 -載入 Handler 變數所需要的相關物件 **這也是 Martini 跟 Go 語言`http.HandlerFunc`介面 -完全相容的原因** - -如果你在 Handler 裡加入一個變數, Martini 會嘗試著從它的服務清單裡透過 type assertion -方式將相關物件載入 -~~~ go -m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res 和 req 是由 Martini 注入 - res.WriteHeader(200) // HTTP 200 -}) -~~~ - -[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 包含以下物件: - * [*log.Logger](http://godoc.org/log#Logger) - Martini 的全區域 Logger. - * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request 內文. - * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching. - * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper 服務. - * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http 回應 writer 介面. - * [*http.Request](http://godoc.org/net/http/#Request) - http 請求. - -### Routing -在 Martini 裡, 一個 route 就是一個 HTTP 方法與其 URL 的比對模式. -每個 route 可以有ㄧ或多個 handler 方法: -~~~ go -m.Get("/", func() { - // 顯示(值) -}) - -m.Patch("/", func() { - // 更新 -}) - -m.Post("/", func() { - // 產生 -}) - -m.Put("/", func() { - // 取代 -}) - -m.Delete("/", func() { - // 刪除 -}) - -m.Options("/", func() { - // http 選項 -}) - -m.NotFound(func() { - // handle 404 -}) -~~~ - -Routes 依照它們被定義時的順序做比對. 第一個跟請求 (request) 相同的 route 就被執行. - -Route 比對模式可以包含變數部分, 可以透過 [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) 物件來取值: -~~~ go -m.Get("/hello/:name", func(params martini.Params) string { - return "Hello " + params["name"] -}) -~~~ - -Routes 也可以用 "**" 來配對, 例如: -~~~ go -m.Get("/hello/**", func(params martini.Params) string { - return "Hello " + params["_1"] -}) -~~~ - -也可以用正規表示法 (regular expressions) 來做比對, 例如: -~~~go -m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { - return fmt.Sprintf ("Hello %s", params["name"]) -}) -~~~ -更多有關正規表示法文法的資訊, 請參考 [Go 文件](http://golang.org/pkg/regexp/syntax/). - -Route handlers 也可以相互堆疊, 尤其是認證與授權相當好用: -~~~ go -m.Get("/secret", authorize, func() { - // 這裏開始處理授權問題, 而非寫出回應 -}) -~~~ - -也可以用 Group 方法, 將 route 編成一組. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}) -~~~ - -跟對 handler 增加 middleware 方法一樣, 你也可以為一組 routes 增加 middleware. -~~~ go -m.Group("/books", func(r martini.Router) { - r.Get("/:id", GetBooks) - r.Post("/new", NewBook) - r.Put("/update/:id", UpdateBook) - r.Delete("/delete/:id", DeleteBook) -}, MyMiddleware1, MyMiddleware2) -~~~ - -### Services -服務是一些物件可以被注入 Handler 變數裡的東西, 可以分對應到 *Global* 或 *Request* 兩種等級. - -#### Global Mapping (全域級對應) -一個 Martini 實體 (instance) 實現了 inject.Injector 介面, 所以非常容易對應到所需要的服務, 例如: -~~~ go -db := &MyDatabase{} -m := martini.Classic() -m.Map(db) // 所以 *MyDatabase 就可以被所有的 handlers 使用 -// ... -m.Run() -~~~ - -#### Request-Level Mapping (請求級對應) -如果只在一個 handler 裡定義, 透由 [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) 獲得一個請求 (request) 級的對應: -~~~ go -func MyCustomLoggerHandler(c martini.Context, req *http.Request) { - logger := &MyCustomLogger{req} - c.Map(logger) // 對應到 *MyCustomLogger -} -~~~ - -#### 透由介面對應 -有關服務, 最強的部分是它還能對應到一個介面 (interface), 例如, -如果你想要包裹並增加一個變數而改寫 (override) 原有的 [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), 你的 handler 可以寫成: -~~~ go -func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { - rw := NewSpecialResponseWriter(res) - c.MapTo(rw, (*http.ResponseWriter)(nil)) // 我們包裹的 ResponseWriter 蓋掉原始的 ResponseWrite -} -~~~ - -### Serving Static Files -一個[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 實體會將伺服器根目錄下 public 子目錄裡的檔案自動當成靜態檔案處理. 你也可以手動用 [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 增加其他目錄, 例如. -~~~ go -m.Use(martini.Static("assets")) // "assets" 子目錄裡, 也視為靜態檔案 -~~~ - -#### Serving a Default Document -當某些 URL 找不到時, 你也可以指定本地檔案的 URL 來顯示. -你也可以用開頭除外 (exclusion prefix) 的方式, 來忽略某些 URLs, -它尤其在某些伺服器同時伺服靜態檔案, 而且還有額外 handlers 處理 (例如 REST API) 時, 特別好用. -比如說, 在比對找不到之後, 想要用靜態檔來處理特別好用. - -以下範例, 就是在 URL 開頭不是`/api/v`而且也不是本地檔案的情況下, 顯示`/index.html`檔: -~~~ go -static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) -m.NotFound(static, http.NotFound) -~~~ - -## Middleware Handlers -Middleware Handlers 位於進來的 http 請求與 router 之間, 在 Martini 裡, 本質上它跟其他 - Handler 沒有什麼不同, 例如, 你可加入一個 middleware 方法如下 -~~~ go -m.Use(func() { - // 做 middleware 的事 -}) -~~~ - -你也可以用`Handlers`完全控制 middelware 層, 把先前設定的 handlers 都替換掉, 例如: -~~~ go -m.Handlers( - Middleware1, - Middleware2, - Middleware3, -) -~~~ - -Middleware Handlers 成被拿來處理 http 請求之前和之後的事, 尤其是用來紀錄logs, 授權, 認證, -sessions, 壓縮 (gzipping), 顯示錯誤頁面等等, 都非常好用, 例如: -~~~ go -// validate an api key -m.Use(func(res http.ResponseWriter, req *http.Request) { - if req.Header.Get("X-API-KEY") != "secret123" { - res.WriteHeader(http.StatusUnauthorized) - } -}) -~~~ - -### Next() -[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) 是 Middleware Handlers 可以呼叫的選項功能, 用來等到其他 handlers 處理完再開始執行. -它常常被用來處理那些必須在 http 請求之後才能發生的事件, 例如: -~~~ go -// 在請求前後加 logs -m.Use(func(c martini.Context, log *log.Logger){ - log.Println("before a request") - - c.Next() - - log.Println("after a request") -}) -~~~ - -## Martini Env - -有些 Martini handlers 使用 `martini.Env` 全區域變數, 來當成開發環境或是上架 (production) -環境的設定判斷. 建議用 `MARTINI_ENV=production` 環境變數來設定 Martini 伺服器是上架與否. - -## FAQ - -### 我去哪可以找到 middleware X? - -可以從 [martini-contrib](https://github.com/martini-contrib) 裡的專案找起. -如果那裡沒有, 請與 martini-contrib 團隊聯絡, 將它加入. - -* [auth](https://github.com/martini-contrib/auth) - 處理認證的 Handler. -* [binding](https://github.com/martini-contrib/binding) - -處理一個單純的請求對應到一個結構體與確認內容正確與否的 Handler. -* [gzip](https://github.com/martini-contrib/gzip) - 對請求加 gzip 壓縮的 Handler. -* [render](https://github.com/martini-contrib/render) - 提供簡單處理 JSON 和 -HTML 樣板成形 (rendering) 的 Handler. -* [acceptlang](https://github.com/martini-contrib/acceptlang) - 解析 `Accept-Language` HTTP 檔頭的 Handler. -* [sessions](https://github.com/martini-contrib/sessions) - 提供 Session 服務的 Handler. -* [strip](https://github.com/martini-contrib/strip) - URL 字頭處理 (Prefix stripping). -* [method](https://github.com/martini-contrib/method) - 透過 Header 或表格 (form) 欄位蓋過 HTTP 方法 (method). -* [secure](https://github.com/martini-contrib/secure) - 提供一些簡單的安全機制. -* [encoder](https://github.com/martini-contrib/encoder) - 轉換資料格式之 Encoder 服務. -* [cors](https://github.com/martini-contrib/cors) - 啟動支援 CORS 之 Handler. -* [oauth2](https://github.com/martini-contrib/oauth2) - 讓 Martini 應用程式能提供 OAuth 2.0 登入的 Handler. 其中支援 Google 登錄, Facebook Connect 與 Github 的登入等. -* [vauth](https://github.com/rafecolton/vauth) - 處理 vender webhook 認證的 Handler (目前支援 GitHub 以及 TravisCI) - -### 我如何整合到現有的伺服器? - -Martini 實作 `http.Handler`,所以可以非常容易整合到現有的 Go 伺服器裡. -以下寫法, 是一個能在 Google App Engine 上運行的 Martini 應用程式: - -~~~ go -package hello - -import ( - "net/http" - "github.com/go-martini/martini" -) - -func init() { - m := martini.Classic() - m.Get("/", func() string { - return "Hello world!" - }) - http.Handle("/", m) -} -~~~ - -### 我要如何改變 port/host? - -Martini 的 `Run` 功能會看 PORT 及 HOST 當時的環境變數, 否則 Martini 會用 localhost:3000 -當預設值. 讓 port 及 host 更有彈性, 可以用 `martini.RunOnAddr` 取代. - -~~~ go - m := martini.Classic() - // ... - log.Fatal(m.RunOnAddr(":8080")) -~~~ - -### 可以線上更新 (live reload) 嗎? - -[gin](https://github.com/codegangsta/gin) 和 [fresh](https://github.com/pilu/fresh) 可以幫 Martini 程式做到線上更新. - -## 貢獻 -Martini 盡量保持小而美的精神, 大多數的程式貢獻者可以在 [martini-contrib](https://github.com/martini-contrib) 組織提供代碼. 如果你想要對 Martini 核心提出貢獻, 請丟出 Pull Request. - -## 關於 - -靈感來自與 [express](https://github.com/visionmedia/express) 以及 [sinatra](https://github.com/sinatra/sinatra) - -Martini 由 [Code Gangsta](http://codegangsta.io/) 公司設計出品 (著魔地) diff --git a/Godeps/_workspace/src/github.com/jtolds/gls/LICENSE b/Godeps/_workspace/src/github.com/jtolds/gls/LICENSE deleted file mode 100644 index 9b4a822..0000000 --- a/Godeps/_workspace/src/github.com/jtolds/gls/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) 2013, Space Monkey, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/jtolds/gls/README.md b/Godeps/_workspace/src/github.com/jtolds/gls/README.md deleted file mode 100644 index 1272b65..0000000 --- a/Godeps/_workspace/src/github.com/jtolds/gls/README.md +++ /dev/null @@ -1,64 +0,0 @@ -gls -=== - -Goroutine local storage - -### Huhwaht? Why? ### - -Every so often, a thread shows up on the -[golang-nuts](https://groups.google.com/d/forum/golang-nuts) asking for some -form of goroutine-local-storage, or some kind of goroutine id, or some kind of -context. There are a few valid use cases for goroutine-local-storage, one of -the most prominent being log line context. One poster was interested in being -able to log an HTTP request context id in every log line in the same goroutine -as the incoming HTTP request, without having to change every library and -function call he was interested in logging. - -This would be pretty useful. Provided that you could get some kind of -goroutine-local-storage, you could call -[log.SetOutput](http://golang.org/pkg/log/#SetOutput) with your own logging -writer that checks goroutine-local-storage for some context information and -adds that context to your log lines. - -But alas, Andrew Gerrand's typically diplomatic answer to the question of -goroutine-local variables was: - -> We wouldn't even be having this discussion if thread local storage wasn't -> useful. But every feature comes at a cost, and in my opinion the cost of -> threadlocals far outweighs their benefits. They're just not a good fit for -> Go. - -So, yeah, that makes sense. That's a pretty good reason for why the language -won't support a specific and (relatively) unuseful feature that requires some -runtime changes, just for the sake of a little bit of log improvement. - -But does Go require runtime changes? - -### How it works ### - -Go has pretty fantastic introspective and reflective features, but one thing Go -doesn't give you is any kind of access to the stack pointer, or frame pointer, -or goroutine id, or anything contextual about your current stack. It gives you -access to your list of callers, but only along with program counters, which are -fixed at compile time. - -But it does give you the stack. - -So, we define 16 special functions and embed base-16 tags into the stack using -the call order of those 16 functions. Then, we can read our tags back out of -the stack looking at the callers list. - -We then use these tags as an index into a traditional map for implementing -this library. - -### What are people saying? ### - -"Wow, that's horrifying." - -"This is the most terrible thing I have seen in a very long time." - -"Where is it getting a context from? Is this serializing all the requests? What the heck is the client being bound to? What are these tags? Why does he need callers? Oh god no. No no no." - -### Docs ### - -Please see the docs at http://godoc.org/github.com/jtolds/gls diff --git a/Godeps/_workspace/src/github.com/jtolds/gls/context.go b/Godeps/_workspace/src/github.com/jtolds/gls/context.go deleted file mode 100644 index 94d7fbb..0000000 --- a/Godeps/_workspace/src/github.com/jtolds/gls/context.go +++ /dev/null @@ -1,150 +0,0 @@ -// Package gls implements goroutine-local storage. -package gls - -import ( - "runtime" - "sync" -) - -const ( - maxCallers = 64 -) - -var ( - stackTagPool = &idPool{} - mgrRegistry = make(map[*ContextManager]bool) - mgrRegistryMtx sync.RWMutex -) - -// Values is simply a map of key types to value types. Used by SetValues to -// set multiple values at once. -type Values map[interface{}]interface{} - -func currentStack(skip int) []uintptr { - stack := make([]uintptr, maxCallers) - return stack[:runtime.Callers(2+skip, stack)] -} - -// ContextManager is the main entrypoint for interacting with -// Goroutine-local-storage. You can have multiple independent ContextManagers -// at any given time. ContextManagers are usually declared globally for a given -// class of context variables. You should use NewContextManager for -// construction. -type ContextManager struct { - mtx sync.RWMutex - values map[uint]Values -} - -// NewContextManager returns a brand new ContextManager. It also registers the -// new ContextManager in the ContextManager registry which is used by the Go -// method. ContextManagers are typically defined globally at package scope. -func NewContextManager() *ContextManager { - mgr := &ContextManager{values: make(map[uint]Values)} - mgrRegistryMtx.Lock() - defer mgrRegistryMtx.Unlock() - mgrRegistry[mgr] = true - return mgr -} - -// Unregister removes a ContextManager from the global registry, used by the -// Go method. Only intended for use when you're completely done with a -// ContextManager. Use of Unregister at all is rare. -func (m *ContextManager) Unregister() { - mgrRegistryMtx.Lock() - defer mgrRegistryMtx.Unlock() - delete(mgrRegistry, m) -} - -// SetValues takes a collection of values and a function to call for those -// values to be set in. Anything further down the stack will have the set -// values available through GetValue. SetValues will add new values or replace -// existing values of the same key and will not mutate or change values for -// previous stack frames. -// SetValues is slow (makes a copy of all current and new values for the new -// gls-context) in order to reduce the amount of lookups GetValue requires. -func (m *ContextManager) SetValues(new_values Values, context_call func()) { - if len(new_values) == 0 { - context_call() - return - } - - tags := readStackTags(currentStack(1)) - - m.mtx.Lock() - values := new_values - for _, tag := range tags { - if existing_values, ok := m.values[tag]; ok { - // oh, we found existing values, let's make a copy - values = make(Values, len(existing_values)+len(new_values)) - for key, val := range existing_values { - values[key] = val - } - for key, val := range new_values { - values[key] = val - } - break - } - } - new_tag := stackTagPool.Acquire() - m.values[new_tag] = values - m.mtx.Unlock() - defer func() { - m.mtx.Lock() - delete(m.values, new_tag) - m.mtx.Unlock() - stackTagPool.Release(new_tag) - }() - - addStackTag(new_tag, context_call) -} - -// GetValue will return a previously set value, provided that the value was set -// by SetValues somewhere higher up the stack. If the value is not found, ok -// will be false. -func (m *ContextManager) GetValue(key interface{}) (value interface{}, ok bool) { - - tags := readStackTags(currentStack(1)) - m.mtx.RLock() - defer m.mtx.RUnlock() - for _, tag := range tags { - if values, ok := m.values[tag]; ok { - value, ok := values[key] - return value, ok - } - } - return "", false -} - -func (m *ContextManager) getValues() Values { - tags := readStackTags(currentStack(2)) - m.mtx.RLock() - defer m.mtx.RUnlock() - for _, tag := range tags { - if values, ok := m.values[tag]; ok { - return values - } - } - return nil -} - -// Go preserves ContextManager values and Goroutine-local-storage across new -// goroutine invocations. The Go method makes a copy of all existing values on -// all registered context managers and makes sure they are still set after -// kicking off the provided function in a new goroutine. If you don't use this -// Go method instead of the standard 'go' keyword, you will lose values in -// ContextManagers, as goroutines have brand new stacks. -func Go(cb func()) { - mgrRegistryMtx.RLock() - defer mgrRegistryMtx.RUnlock() - - for mgr, _ := range mgrRegistry { - values := mgr.getValues() - if len(values) > 0 { - mgr_copy := mgr - cb_copy := cb - cb = func() { mgr_copy.SetValues(values, cb_copy) } - } - } - - go cb() -} diff --git a/Godeps/_workspace/src/github.com/jtolds/gls/context_test.go b/Godeps/_workspace/src/github.com/jtolds/gls/context_test.go deleted file mode 100644 index ae5bde4..0000000 --- a/Godeps/_workspace/src/github.com/jtolds/gls/context_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package gls - -import ( - "fmt" - "sync" - "testing" -) - -func TestContexts(t *testing.T) { - mgr1 := NewContextManager() - mgr2 := NewContextManager() - - CheckVal := func(mgr *ContextManager, key, exp_val string) { - val, ok := mgr.GetValue(key) - if len(exp_val) == 0 { - if ok { - t.Fatalf("expected no value for key %s, got %s", key, val) - } - return - } - if !ok { - t.Fatalf("expected value %s for key %s, got no value", - exp_val, key) - } - if exp_val != val { - t.Fatalf("expected value %s for key %s, got %s", exp_val, key, - val) - } - - } - - Check := func(exp_m1v1, exp_m1v2, exp_m2v1, exp_m2v2 string) { - CheckVal(mgr1, "key1", exp_m1v1) - CheckVal(mgr1, "key2", exp_m1v2) - CheckVal(mgr2, "key1", exp_m2v1) - CheckVal(mgr2, "key2", exp_m2v2) - } - - Check("", "", "", "") - mgr2.SetValues(Values{"key1": "val1c"}, func() { - Check("", "", "val1c", "") - mgr1.SetValues(Values{"key1": "val1a"}, func() { - Check("val1a", "", "val1c", "") - mgr1.SetValues(Values{"key2": "val1b"}, func() { - Check("val1a", "val1b", "val1c", "") - var wg sync.WaitGroup - wg.Add(2) - go func() { - defer wg.Done() - Check("", "", "", "") - }() - Go(func() { - defer wg.Done() - Check("val1a", "val1b", "val1c", "") - }) - wg.Wait() - }) - }) - }) -} - -func ExampleContextManager_SetValues() { - var ( - mgr = NewContextManager() - request_id_key = GenSym() - ) - - MyLog := func() { - if request_id, ok := mgr.GetValue(request_id_key); ok { - fmt.Println("My request id is:", request_id) - } else { - fmt.Println("No request id found") - } - } - - mgr.SetValues(Values{request_id_key: "12345"}, func() { - MyLog() - }) - MyLog() - - // Output: My request id is: 12345 - // No request id found -} - -func ExampleGo() { - var ( - mgr = NewContextManager() - request_id_key = GenSym() - ) - - MyLog := func() { - if request_id, ok := mgr.GetValue(request_id_key); ok { - fmt.Println("My request id is:", request_id) - } else { - fmt.Println("No request id found") - } - } - - mgr.SetValues(Values{request_id_key: "12345"}, func() { - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - MyLog() - }() - wg.Wait() - wg.Add(1) - Go(func() { - defer wg.Done() - MyLog() - }) - wg.Wait() - }) - - // Output: No request id found - // My request id is: 12345 -} - -func BenchmarkGetValue(b *testing.B) { - mgr := NewContextManager() - mgr.SetValues(Values{"test_key": "test_val"}, func() { - b.ResetTimer() - for i := 0; i < b.N; i++ { - val, ok := mgr.GetValue("test_key") - if !ok || val != "test_val" { - b.FailNow() - } - } - }) -} - -func BenchmarkSetValues(b *testing.B) { - mgr := NewContextManager() - for i := 0; i < b.N/2; i++ { - mgr.SetValues(Values{"test_key": "test_val"}, func() { - mgr.SetValues(Values{"test_key2": "test_val2"}, func() {}) - }) - } -} diff --git a/Godeps/_workspace/src/github.com/jtolds/gls/gen_sym.go b/Godeps/_workspace/src/github.com/jtolds/gls/gen_sym.go deleted file mode 100644 index 8d5fc24..0000000 --- a/Godeps/_workspace/src/github.com/jtolds/gls/gen_sym.go +++ /dev/null @@ -1,13 +0,0 @@ -package gls - -var ( - symPool = &idPool{} -) - -// ContextKey is a throwaway value you can use as a key to a ContextManager -type ContextKey struct{ id uint } - -// GenSym will return a brand new, never-before-used ContextKey -func GenSym() ContextKey { - return ContextKey{id: symPool.Acquire()} -} diff --git a/Godeps/_workspace/src/github.com/jtolds/gls/id_pool.go b/Godeps/_workspace/src/github.com/jtolds/gls/id_pool.go deleted file mode 100644 index b7974ae..0000000 --- a/Godeps/_workspace/src/github.com/jtolds/gls/id_pool.go +++ /dev/null @@ -1,34 +0,0 @@ -package gls - -// though this could probably be better at keeping ids smaller, the goal of -// this class is to keep a registry of the smallest unique integer ids -// per-process possible - -import ( - "sync" -) - -type idPool struct { - mtx sync.Mutex - released []uint - max_id uint -} - -func (p *idPool) Acquire() (id uint) { - p.mtx.Lock() - defer p.mtx.Unlock() - if len(p.released) > 0 { - id = p.released[len(p.released)-1] - p.released = p.released[:len(p.released)-1] - return id - } - id = p.max_id - p.max_id++ - return id -} - -func (p *idPool) Release(id uint) { - p.mtx.Lock() - defer p.mtx.Unlock() - p.released = append(p.released, id) -} diff --git a/Godeps/_workspace/src/github.com/jtolds/gls/stack_tags.go b/Godeps/_workspace/src/github.com/jtolds/gls/stack_tags.go deleted file mode 100644 index 562a2fa..0000000 --- a/Godeps/_workspace/src/github.com/jtolds/gls/stack_tags.go +++ /dev/null @@ -1,93 +0,0 @@ -package gls - -// so, basically, we're going to encode integer tags in base-16 on the stack - -import ( - "reflect" - "runtime" -) - -const ( - bitWidth = 4 -) - -func addStackTag(tag uint, context_call func()) { - if context_call == nil { - return - } - markS(tag, context_call) -} - -func markS(tag uint, cb func()) { _m(tag, cb) } -func mark0(tag uint, cb func()) { _m(tag, cb) } -func mark1(tag uint, cb func()) { _m(tag, cb) } -func mark2(tag uint, cb func()) { _m(tag, cb) } -func mark3(tag uint, cb func()) { _m(tag, cb) } -func mark4(tag uint, cb func()) { _m(tag, cb) } -func mark5(tag uint, cb func()) { _m(tag, cb) } -func mark6(tag uint, cb func()) { _m(tag, cb) } -func mark7(tag uint, cb func()) { _m(tag, cb) } -func mark8(tag uint, cb func()) { _m(tag, cb) } -func mark9(tag uint, cb func()) { _m(tag, cb) } -func markA(tag uint, cb func()) { _m(tag, cb) } -func markB(tag uint, cb func()) { _m(tag, cb) } -func markC(tag uint, cb func()) { _m(tag, cb) } -func markD(tag uint, cb func()) { _m(tag, cb) } -func markE(tag uint, cb func()) { _m(tag, cb) } -func markF(tag uint, cb func()) { _m(tag, cb) } - -var pc_lookup = make(map[uintptr]int8, 17) -var mark_lookup [16]func(uint, func()) - -func init() { - setEntries := func(f func(uint, func()), v int8) { - pc_lookup[reflect.ValueOf(f).Pointer()] = v - if v >= 0 { - mark_lookup[v] = f - } - } - setEntries(markS, -0x1) - setEntries(mark0, 0x0) - setEntries(mark1, 0x1) - setEntries(mark2, 0x2) - setEntries(mark3, 0x3) - setEntries(mark4, 0x4) - setEntries(mark5, 0x5) - setEntries(mark6, 0x6) - setEntries(mark7, 0x7) - setEntries(mark8, 0x8) - setEntries(mark9, 0x9) - setEntries(markA, 0xa) - setEntries(markB, 0xb) - setEntries(markC, 0xc) - setEntries(markD, 0xd) - setEntries(markE, 0xe) - setEntries(markF, 0xf) -} - -func _m(tag_remainder uint, cb func()) { - if tag_remainder == 0 { - cb() - } else { - mark_lookup[tag_remainder&0xf](tag_remainder>>bitWidth, cb) - } -} - -func readStackTags(stack []uintptr) (tags []uint) { - var current_tag uint - for _, pc := range stack { - pc = runtime.FuncForPC(pc).Entry() - val, ok := pc_lookup[pc] - if !ok { - continue - } - if val < 0 { - tags = append(tags, current_tag) - current_tag = 0 - continue - } - current_tag <<= bitWidth - current_tag += uint(val) - } - return -} diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go b/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go deleted file mode 100644 index dc661db..0000000 --- a/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin linux freebsd netbsd windows - -package osext - -import ( - "fmt" - "os" - oexec "os/exec" - "path/filepath" - "runtime" - "testing" -) - -const execPath_EnvVar = "OSTEST_OUTPUT_EXECPATH" - -func TestExecPath(t *testing.T) { - ep, err := Executable() - if err != nil { - t.Fatalf("ExecPath failed: %v", err) - } - // we want fn to be of the form "dir/prog" - dir := filepath.Dir(filepath.Dir(ep)) - fn, err := filepath.Rel(dir, ep) - if err != nil { - t.Fatalf("filepath.Rel: %v", err) - } - cmd := &oexec.Cmd{} - // make child start with a relative program path - cmd.Dir = dir - cmd.Path = fn - // forge argv[0] for child, so that we can verify we could correctly - // get real path of the executable without influenced by argv[0]. - cmd.Args = []string{"-", "-test.run=XXXX"} - cmd.Env = []string{fmt.Sprintf("%s=1", execPath_EnvVar)} - out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("exec(self) failed: %v", err) - } - outs := string(out) - if !filepath.IsAbs(outs) { - t.Fatalf("Child returned %q, want an absolute path", out) - } - if !sameFile(outs, ep) { - t.Fatalf("Child returned %q, not the same file as %q", out, ep) - } -} - -func sameFile(fn1, fn2 string) bool { - fi1, err := os.Stat(fn1) - if err != nil { - return false - } - fi2, err := os.Stat(fn2) - if err != nil { - return false - } - return os.SameFile(fi1, fi2) -} - -func init() { - if e := os.Getenv(execPath_EnvVar); e != "" { - // first chdir to another path - dir := "/" - if runtime.GOOS == "windows" { - dir = filepath.VolumeName(".") - } - os.Chdir(dir) - if ep, err := Executable(); err != nil { - fmt.Fprint(os.Stderr, "ERROR: ", err) - } else { - fmt.Fprint(os.Stderr, ep) - } - os.Exit(0) - } -} diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/example_test.go b/Godeps/_workspace/src/github.com/natefinch/lumberjack/example_test.go deleted file mode 100644 index 96b1567..0000000 --- a/Godeps/_workspace/src/github.com/natefinch/lumberjack/example_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package lumberjack_test - -import ( - "log" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/natefinch/lumberjack" -) - -// To use lumberjack with the standard library's log package, just pass it into -// the SetOutput function when your application starts. -func Example() { - log.SetOutput(&lumberjack.Logger{ - Filename: "/var/log/myapp/foo.log", - MaxSize: 500, // megabytes - MaxBackups: 3, - MaxAge: 28, // days - }) -} diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/linux_test.go b/Godeps/_workspace/src/github.com/natefinch/lumberjack/linux_test.go deleted file mode 100644 index 40f3446..0000000 --- a/Godeps/_workspace/src/github.com/natefinch/lumberjack/linux_test.go +++ /dev/null @@ -1,104 +0,0 @@ -// +build linux - -package lumberjack - -import ( - "os" - "syscall" - "testing" -) - -func TestMaintainMode(t *testing.T) { - currentTime = fakeTime - dir := makeTempDir("TestMaintainMode", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - - mode := os.FileMode(0770) - f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, mode) - isNil(err, t) - f.Close() - - l := &Logger{ - Filename: filename, - MaxBackups: 1, - MaxSize: 100, // megabytes - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - newFakeTime() - - err = l.Rotate() - isNil(err, t) - - filename2 := backupFile(dir) - info, err := os.Stat(filename) - isNil(err, t) - info2, err := os.Stat(filename2) - isNil(err, t) - equals(mode, info.Mode(), t) - equals(mode, info2.Mode(), t) -} - -func TestMaintainOwner(t *testing.T) { - fakeC := fakeChown{} - os_Chown = fakeC.Set - os_Stat = fakeStat - defer func() { - os_Chown = os.Chown - os_Stat = os.Stat - }() - currentTime = fakeTime - dir := makeTempDir("TestMaintainOwner", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - - l := &Logger{ - Filename: filename, - MaxBackups: 1, - MaxSize: 100, // megabytes - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - newFakeTime() - - err = l.Rotate() - isNil(err, t) - - equals(555, fakeC.uid, t) - equals(666, fakeC.gid, t) -} - -type fakeChown struct { - name string - uid int - gid int -} - -func (f *fakeChown) Set(name string, uid, gid int) error { - f.name = name - f.uid = uid - f.gid = gid - return nil -} - -func fakeStat(name string) (os.FileInfo, error) { - info, err := os.Stat(name) - if err != nil { - return info, err - } - stat := info.Sys().(*syscall.Stat_t) - stat.Uid = 555 - stat.Gid = 666 - return info, nil -} diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/lumberjack_test.go b/Godeps/_workspace/src/github.com/natefinch/lumberjack/lumberjack_test.go deleted file mode 100644 index e9984f8..0000000 --- a/Godeps/_workspace/src/github.com/natefinch/lumberjack/lumberjack_test.go +++ /dev/null @@ -1,634 +0,0 @@ -package lumberjack - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "testing" - "time" - - "github.com/BurntSushi/toml" - "gopkg.in/yaml.v1" -) - -// !!!NOTE!!! -// -// Running these tests in parallel will almost certainly cause sporadic (or even -// regular) failures, because they're all messing with the same global variable -// that controls the logic's mocked time.Now. So... don't do that. - -// Since all the tests uses the time to determine filenames etc, we need to -// control the wall clock as much as possible, which means having a wall clock -// that doesn't change unless we want it to. -var fakeCurrentTime = time.Now() - -func fakeTime() time.Time { - return fakeCurrentTime -} - -func TestNewFile(t *testing.T) { - currentTime = fakeTime - - dir := makeTempDir("TestNewFile", t) - defer os.RemoveAll(dir) - l := &Logger{ - Filename: logFile(dir), - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - existsWithLen(logFile(dir), n, t) - fileCount(dir, 1, t) -} - -func TestOpenExisting(t *testing.T) { - currentTime = fakeTime - dir := makeTempDir("TestOpenExisting", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - data := []byte("foo!") - err := ioutil.WriteFile(filename, data, 0644) - isNil(err, t) - existsWithLen(filename, len(data), t) - - l := &Logger{ - Filename: filename, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - // make sure the file got appended - existsWithLen(filename, len(data)+n, t) - - // make sure no other files were created - fileCount(dir, 1, t) -} - -func TestWriteTooLong(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - dir := makeTempDir("TestWriteTooLong", t) - defer os.RemoveAll(dir) - l := &Logger{ - Filename: logFile(dir), - MaxSize: 5, - } - defer l.Close() - b := []byte("booooooooooooooo!") - n, err := l.Write(b) - notNil(err, t) - equals(0, n, t) - equals(err.Error(), - fmt.Sprintf("write length %d exceeds maximum file size %d", len(b), l.MaxSize), t) - _, err = os.Stat(logFile(dir)) - assert(os.IsNotExist(err), t, "File exists, but should not have been created") -} - -func TestMakeLogDir(t *testing.T) { - currentTime = fakeTime - dir := time.Now().Format("TestMakeLogDir" + backupTimeFormat) - dir = filepath.Join(os.TempDir(), dir) - defer os.RemoveAll(dir) - filename := logFile(dir) - l := &Logger{ - Filename: filename, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - existsWithLen(logFile(dir), n, t) - fileCount(dir, 1, t) -} - -func TestDefaultFilename(t *testing.T) { - currentTime = fakeTime - dir := os.TempDir() - filename := filepath.Join(dir, filepath.Base(os.Args[0])+"-lumberjack.log") - defer os.Remove(filename) - l := &Logger{} - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - - isNil(err, t) - equals(len(b), n, t) - existsWithLen(filename, n, t) -} - -func TestAutoRotate(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - - dir := makeTempDir("TestAutoRotate", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - l := &Logger{ - Filename: filename, - MaxSize: 10, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - fileCount(dir, 1, t) - - newFakeTime() - - b2 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // the old logfile should be moved aside and the main logfile should have - // only the last write in it. - existsWithLen(filename, n, t) - - // the backup file will use the current fake time and have the old contents. - existsWithLen(backupFile(dir), len(b), t) - - fileCount(dir, 2, t) -} - -func TestFirstWriteRotate(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - dir := makeTempDir("TestFirstWriteRotate", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - l := &Logger{ - Filename: filename, - MaxSize: 10, - } - defer l.Close() - - start := []byte("boooooo!") - err := ioutil.WriteFile(filename, start, 0600) - isNil(err, t) - - newFakeTime() - - // this would make us rotate - b := []byte("fooo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - existsWithLen(backupFile(dir), len(start), t) - - fileCount(dir, 2, t) -} - -func TestMaxBackups(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - dir := makeTempDir("TestMaxBackups", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - l := &Logger{ - Filename: filename, - MaxSize: 10, - MaxBackups: 1, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - fileCount(dir, 1, t) - - newFakeTime() - - // this will put us over the max - b2 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // this will use the new fake time - secondFilename := backupFile(dir) - existsWithLen(secondFilename, len(b), t) - - // make sure the old file still exists with the same size. - existsWithLen(filename, n, t) - - fileCount(dir, 2, t) - - newFakeTime() - - // this will make us rotate again - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // this will use the new fake time - thirdFilename := backupFile(dir) - existsWithLen(thirdFilename, len(b2), t) - - existsWithLen(filename, n, t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(time.Millisecond * 10) - - // should only have two files in the dir still - fileCount(dir, 2, t) - - // second file name should still exist - existsWithLen(thirdFilename, len(b2), t) - - // should have deleted the first backup - notExist(secondFilename, t) - - // now test that we don't delete directories or non-logfile files - - newFakeTime() - - // create a file that is close to but different from the logfile name. - // It shouldn't get caught by our deletion filters. - notlogfile := logFile(dir) + ".foo" - err = ioutil.WriteFile(notlogfile, []byte("data"), 0644) - isNil(err, t) - - // Make a directory that exactly matches our log file filters... it still - // shouldn't get caught by the deletion filter since it's a directory. - notlogfiledir := backupFile(dir) - err = os.Mkdir(notlogfiledir, 0700) - isNil(err, t) - - newFakeTime() - - // this will make us rotate again - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // this will use the new fake time - fourthFilename := backupFile(dir) - existsWithLen(fourthFilename, len(b2), t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(time.Millisecond * 10) - - // We should have four things in the directory now - the 2 log files, the - // not log file, and the directory - fileCount(dir, 4, t) - - // third file name should still exist - existsWithLen(filename, n, t) - - existsWithLen(fourthFilename, len(b2), t) - - // should have deleted the first filename - notExist(thirdFilename, t) - - // the not-a-logfile should still exist - exists(notlogfile, t) - - // the directory - exists(notlogfiledir, t) -} - -func TestMaxAge(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - - dir := makeTempDir("TestMaxAge", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - l := &Logger{ - Filename: filename, - MaxSize: 10, - MaxAge: 1, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - fileCount(dir, 1, t) - - // two days later - newFakeTime() - - b2 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - existsWithLen(backupFile(dir), len(b), t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(10 * time.Millisecond) - - // We should still have 2 log files, since the most recent backup was just - // created. - fileCount(dir, 2, t) - - existsWithLen(filename, len(b2), t) - - // we should have deleted the old file due to being too old - existsWithLen(backupFile(dir), len(b), t) - - // two days later - newFakeTime() - - b3 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b3), n, t) - existsWithLen(backupFile(dir), len(b2), t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(10 * time.Millisecond) - - // We should have 2 log files - the main log file, and the most recent - // backup. The earlier backup is past the cutoff and should be gone. - fileCount(dir, 2, t) - - existsWithLen(filename, len(b3), t) - - // we should have deleted the old file due to being too old - existsWithLen(backupFile(dir), len(b2), t) - -} - -func TestOldLogFiles(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - - dir := makeTempDir("TestOldLogFiles", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - data := []byte("data") - err := ioutil.WriteFile(filename, data, 07) - isNil(err, t) - - // This gives us a time with the same precision as the time we get from the - // timestamp in the name. - t1, err := time.Parse(backupTimeFormat, fakeTime().UTC().Format(backupTimeFormat)) - isNil(err, t) - - backup := backupFile(dir) - err = ioutil.WriteFile(backup, data, 07) - isNil(err, t) - - newFakeTime() - - t2, err := time.Parse(backupTimeFormat, fakeTime().UTC().Format(backupTimeFormat)) - isNil(err, t) - - backup2 := backupFile(dir) - err = ioutil.WriteFile(backup2, data, 07) - isNil(err, t) - - l := &Logger{Filename: filename} - files, err := l.oldLogFiles() - isNil(err, t) - equals(2, len(files), t) - - // should be sorted by newest file first, which would be t2 - equals(t2, files[0].timestamp, t) - equals(t1, files[1].timestamp, t) -} - -func TestTimeFromName(t *testing.T) { - l := &Logger{Filename: "/var/log/myfoo/foo.log"} - prefix, ext := l.prefixAndExt() - val := l.timeFromName("foo-2014-05-04T14-44-33.555.log", prefix, ext) - equals("2014-05-04T14-44-33.555", val, t) - - val = l.timeFromName("foo-2014-05-04T14-44-33.555", prefix, ext) - equals("", val, t) - - val = l.timeFromName("2014-05-04T14-44-33.555.log", prefix, ext) - equals("", val, t) - - val = l.timeFromName("foo.log", prefix, ext) - equals("", val, t) -} - -func TestLocalTime(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - - dir := makeTempDir("TestLocalTime", t) - defer os.RemoveAll(dir) - - l := &Logger{ - Filename: logFile(dir), - MaxSize: 10, - LocalTime: true, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - b2 := []byte("fooooooo!") - n2, err := l.Write(b2) - isNil(err, t) - equals(len(b2), n2, t) - - existsWithLen(logFile(dir), n2, t) - existsWithLen(backupFileLocal(dir), n, t) -} - -func TestRotate(t *testing.T) { - currentTime = fakeTime - dir := makeTempDir("TestRotate", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - - l := &Logger{ - Filename: filename, - MaxBackups: 1, - MaxSize: 100, // megabytes - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - fileCount(dir, 1, t) - - newFakeTime() - - err = l.Rotate() - isNil(err, t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(10 * time.Millisecond) - - filename2 := backupFile(dir) - existsWithLen(filename2, n, t) - existsWithLen(filename, 0, t) - fileCount(dir, 2, t) - newFakeTime() - - err = l.Rotate() - isNil(err, t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(10 * time.Millisecond) - - filename3 := backupFile(dir) - existsWithLen(filename3, 0, t) - existsWithLen(filename, 0, t) - fileCount(dir, 2, t) - - b2 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // this will use the new fake time - existsWithLen(filename, n, t) -} - -func TestJson(t *testing.T) { - data := []byte(` -{ - "filename": "foo", - "maxsize": 5, - "maxage": 10, - "maxbackups": 3, - "localtime": true -}`[1:]) - - l := Logger{} - err := json.Unmarshal(data, &l) - isNil(err, t) - equals("foo", l.Filename, t) - equals(5, l.MaxSize, t) - equals(10, l.MaxAge, t) - equals(3, l.MaxBackups, t) - equals(true, l.LocalTime, t) -} - -func TestYaml(t *testing.T) { - data := []byte(` -filename: foo -maxsize: 5 -maxage: 10 -maxbackups: 3 -localtime: true`[1:]) - - l := Logger{} - err := yaml.Unmarshal(data, &l) - isNil(err, t) - equals("foo", l.Filename, t) - equals(5, l.MaxSize, t) - equals(10, l.MaxAge, t) - equals(3, l.MaxBackups, t) - equals(true, l.LocalTime, t) -} - -func TestToml(t *testing.T) { - data := ` -filename = "foo" -maxsize = 5 -maxage = 10 -maxbackups = 3 -localtime = true`[1:] - - l := Logger{} - md, err := toml.Decode(data, &l) - isNil(err, t) - equals("foo", l.Filename, t) - equals(5, l.MaxSize, t) - equals(10, l.MaxAge, t) - equals(3, l.MaxBackups, t) - equals(true, l.LocalTime, t) - equals(0, len(md.Undecoded()), t) -} - -// makeTempDir creates a file with a semi-unique name in the OS temp directory. -// It should be based on the name of the test, to keep parallel tests from -// colliding, and must be cleaned up after the test is finished. -func makeTempDir(name string, t testing.TB) string { - dir := time.Now().Format(name + backupTimeFormat) - dir = filepath.Join(os.TempDir(), dir) - isNilUp(os.Mkdir(dir, 0777), t, 1) - return dir -} - -// existsWithLen checks that the given file exists and has the correct length. -func existsWithLen(path string, length int, t testing.TB) { - info, err := os.Stat(path) - isNilUp(err, t, 1) - equalsUp(int64(length), info.Size(), t, 1) -} - -// logFile returns the log file name in the given directory for the current fake -// time. -func logFile(dir string) string { - return filepath.Join(dir, "foobar.log") -} - -func backupFile(dir string) string { - return filepath.Join(dir, "foobar-"+fakeTime().UTC().Format(backupTimeFormat)+".log") -} - -func backupFileLocal(dir string) string { - return filepath.Join(dir, "foobar-"+fakeTime().Format(backupTimeFormat)+".log") -} - -// logFileLocal returns the log file name in the given directory for the current -// fake time using the local timezone. -func logFileLocal(dir string) string { - return filepath.Join(dir, fakeTime().Format(backupTimeFormat)) -} - -// fileCount checks that the number of files in the directory is exp. -func fileCount(dir string, exp int, t testing.TB) { - files, err := ioutil.ReadDir(dir) - isNilUp(err, t, 1) - // Make sure no other files were created. - equalsUp(exp, len(files), t, 1) -} - -// newFakeTime sets the fake "current time" to two days later. -func newFakeTime() { - fakeCurrentTime = fakeCurrentTime.Add(time.Hour * 24 * 2) -} - -func notExist(path string, t testing.TB) { - _, err := os.Stat(path) - assertUp(os.IsNotExist(err), t, 1, "expected to get os.IsNotExist, but instead got %v", err) -} - -func exists(path string, t testing.TB) { - _, err := os.Stat(path) - assertUp(err == nil, t, 1, "expected file to exist, but got error from os.Stat: %v", err) -} diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/rotate_test.go b/Godeps/_workspace/src/github.com/natefinch/lumberjack/rotate_test.go deleted file mode 100644 index fbb14d1..0000000 --- a/Godeps/_workspace/src/github.com/natefinch/lumberjack/rotate_test.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build linux - -package lumberjack_test - -import ( - "log" - "os" - "os/signal" - "syscall" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/natefinch/lumberjack" -) - -// Example of how to rotate in response to SIGHUP. -func ExampleLogger_Rotate() { - l := &lumberjack.Logger{} - log.SetOutput(l) - c := make(chan os.Signal, 1) - signal.Notify(c, syscall.SIGHUP) - - go func() { - for { - <-c - l.Rotate() - } - }() -} diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/testing_test.go b/Godeps/_workspace/src/github.com/natefinch/lumberjack/testing_test.go deleted file mode 100644 index 8e89c08..0000000 --- a/Godeps/_workspace/src/github.com/natefinch/lumberjack/testing_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package lumberjack - -import ( - "fmt" - "path/filepath" - "reflect" - "runtime" - "testing" -) - -// assert will log the given message if condition is false. -func assert(condition bool, t testing.TB, msg string, v ...interface{}) { - assertUp(condition, t, 1, msg, v...) -} - -// assertUp is like assert, but used inside helper functions, to ensure that -// the file and line number reported by failures corresponds to one or more -// levels up the stack. -func assertUp(condition bool, t testing.TB, caller int, msg string, v ...interface{}) { - if !condition { - _, file, line, _ := runtime.Caller(caller + 1) - v = append([]interface{}{filepath.Base(file), line}, v...) - fmt.Printf("%s:%d: "+msg+"\n", v...) - t.FailNow() - } -} - -// equals tests that the two values are equal according to reflect.DeepEqual. -func equals(exp, act interface{}, t testing.TB) { - equalsUp(exp, act, t, 1) -} - -// equalsUp is like equals, but used inside helper functions, to ensure that the -// file and line number reported by failures corresponds to one or more levels -// up the stack. -func equalsUp(exp, act interface{}, t testing.TB, caller int) { - if !reflect.DeepEqual(exp, act) { - _, file, line, _ := runtime.Caller(caller + 1) - fmt.Printf("%s:%d: exp: %v (%T), got: %v (%T)\n", - filepath.Base(file), line, exp, exp, act, act) - t.FailNow() - } -} - -// isNil reports a failure if the given value is not nil. Note that values -// which cannot be nil will always fail this check. -func isNil(obtained interface{}, t testing.TB) { - isNilUp(obtained, t, 1) -} - -// isNilUp is like isNil, but used inside helper functions, to ensure that the -// file and line number reported by failures corresponds to one or more levels -// up the stack. -func isNilUp(obtained interface{}, t testing.TB, caller int) { - if !_isNil(obtained) { - _, file, line, _ := runtime.Caller(caller + 1) - fmt.Printf("%s:%d: expected nil, got: %v\n", filepath.Base(file), line, obtained) - t.FailNow() - } -} - -// notNil reports a failure if the given value is nil. -func notNil(obtained interface{}, t testing.TB) { - notNilUp(obtained, t, 1) -} - -// notNilUp is like notNil, but used inside helper functions, to ensure that the -// file and line number reported by failures corresponds to one or more levels -// up the stack. -func notNilUp(obtained interface{}, t testing.TB, caller int) { - if _isNil(obtained) { - _, file, line, _ := runtime.Caller(caller + 1) - fmt.Printf("%s:%d: expected non-nil, got: %v\n", filepath.Base(file), line, obtained) - t.FailNow() - } -} - -// _isNil is a helper function for isNil and notNil, and should not be used -// directly. -func _isNil(obtained interface{}) bool { - if obtained == nil { - return true - } - - switch v := reflect.ValueOf(obtained); v.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - - return false -} diff --git a/Godeps/_workspace/src/github.com/peterbourgon/g2s/g2s_test.go b/Godeps/_workspace/src/github.com/peterbourgon/g2s/g2s_test.go deleted file mode 100644 index e66eeb4..0000000 --- a/Godeps/_workspace/src/github.com/peterbourgon/g2s/g2s_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package g2s - -import ( - "bytes" - "math/rand" - "strconv" - "strings" - "testing" - "time" -) - -func TestCounter(t *testing.T) { - b := &bytes.Buffer{} - s, err := New(b) - if err != nil { - t.Fatal(err) - } - - s.Counter(1.0, "gorets", 1) - - if expected, got := "gorets:1|c", b.String(); expected != got { - t.Errorf("expected '%s', got '%s'", expected, got) - } -} - -func TestTiming(t *testing.T) { - b := &bytes.Buffer{} - s, err := New(b) - if err != nil { - t.Fatal(err) - } - - s.Timing(1.0, "glork", 320*time.Millisecond) - - if expected, got := "glork:320|ms", b.String(); expected != got { - t.Errorf("expected '%s', got '%s'", expected, got) - } -} - -func TestGauge(t *testing.T) { - b := &bytes.Buffer{} - s, err := New(b) - if err != nil { - t.Fatal(err) - } - - s.Gauge(1.0, "gaugor", "333") - - if expected, got := "gaugor:333|g", b.String(); expected != got { - t.Errorf("expected '%s', got '%s'", expected, got) - } -} - -func TestMany(t *testing.T) { - b := &bytes.Buffer{} - s, err := New(b) - if err != nil { - t.Fatal(err) - } - - s.Counter(1.0, "foo", 1, 2, 3) - s.Timing(1.0, "bar", 4*time.Millisecond, 5*time.Millisecond) - - expected := "foo:1|c\nfoo:2|c\nfoo:3|cbar:4|ms\nbar:5|ms" - got := b.String() - if expected != got { - t.Errorf("expected '%s', got '%s'", expected, got) - } -} - -func TestSamplingZero(t *testing.T) { - b := &bytes.Buffer{} - s, err := New(b) - if err != nil { - t.Fatal(err) - } - - s.Counter(0.0, "nobucket", 1) // should never succeed - - if expected, got := "", b.String(); expected != got { - t.Errorf("expected '%s', got '%s'", expected, got) - } -} - -type SliceWriter struct { - data []string -} - -func (this *SliceWriter) Write(bytes []byte) (int, error) { - this.data = append(this.data, string(bytes)) - return len(bytes), nil -} - -func TestSampling(t *testing.T) { - b := &SliceWriter{} - s, err := New(b) - if err != nil { - t.Fatal(err) - } - - rate, n := float32(0.5), 10000 - rand.Seed(time.Now().UnixNano()) - for i := 0; i < n; i++ { - s.Counter(rate, "foo", 1) - } - - middle, threshold := n/2, n/10 - expectedMin, expectedMax := middle-threshold, middle+threshold - got := b.data - - rateToks := strings.Split(got[0], "@") - if len(rateToks) != 2 { - t.Fatalf("splitting packet on '@': expected 2, got %d", len(rateToks)) - } - gotRate, err := strconv.ParseFloat(rateToks[1], 32) - if err != nil { - t.Fatalf("%s: %s", rateToks[1], err) - } - if float32(gotRate) != rate { - t.Errorf("sampling rate: expected %f, got %f", rate, gotRate) - } - - packetCount := len(got) - if packetCount < expectedMin || packetCount > expectedMax { - t.Errorf("got %d packets, but expected between %d and %d", packetCount, expectedMin, expectedMax) - } - - t.Logf("got %d < %d < %d OK", expectedMin, packetCount, expectedMax) -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/cluster_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/cluster_test.go deleted file mode 100644 index 83d7e0a..0000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/cluster_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package zk - -import ( - "testing" -) - -func TestBasicCluster(t *testing.T) { - ts, err := StartTestCluster(3) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk1, err := ts.Connect(0) - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk1.Close() - zk2, err := ts.Connect(1) - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk2.Close() - - if _, err := zk1.Create("/gozk-test", []byte("foo-cluster"), 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create failed on node 1: %+v", err) - } - if by, _, err := zk2.Get("/gozk-test"); err != nil { - t.Fatalf("Get failed on node 2: %+v", err) - } else if string(by) != "foo-cluster" { - t.Fatal("Wrong data for node 2") - } -} - -func TestClientClusterFailover(t *testing.T) { - ts, err := StartTestCluster(3) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - if _, err := zk.Create("/gozk-test", []byte("foo-cluster"), 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create failed on node 1: %+v", err) - } - - ts.Servers[0].Srv.Stop() - - if by, _, err := zk.Get("/gozk-test"); err != nil { - t.Fatalf("Get failed on node 2: %+v", err) - } else if string(by) != "foo-cluster" { - t.Fatal("Wrong data for node 2") - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock_test.go deleted file mode 100644 index 2475e8b..0000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package zk - -import ( - "testing" - "time" -) - -func TestLock(t *testing.T) { - ts, err := StartTestCluster(1) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - acls := WorldACL(PermAll) - - l := NewLock(zk, "/test", acls) - if err := l.Lock(); err != nil { - t.Fatal(err) - } - if err := l.Unlock(); err != nil { - t.Fatal(err) - } - - val := make(chan int, 3) - - if err := l.Lock(); err != nil { - t.Fatal(err) - } - - l2 := NewLock(zk, "/test", acls) - go func() { - if err := l2.Lock(); err != nil { - t.Fatal(err) - } - val <- 2 - if err := l2.Unlock(); err != nil { - t.Fatal(err) - } - val <- 3 - }() - time.Sleep(time.Millisecond * 100) - - val <- 1 - if err := l.Unlock(); err != nil { - t.Fatal(err) - } - if x := <-val; x != 1 { - t.Fatalf("Expected 1 instead of %d", x) - } - if x := <-val; x != 2 { - t.Fatalf("Expected 2 instead of %d", x) - } - if x := <-val; x != 3 { - t.Fatalf("Expected 3 instead of %d", x) - } -} - -// This tests creating a lock with a path that's more than 1 node deep (e.g. "/test-multi-level/lock"), -// when a part of that path already exists (i.e. "/test-multi-level" node already exists). -func TestMultiLevelLock(t *testing.T) { - ts, err := StartTestCluster(1) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - acls := WorldACL(PermAll) - path := "/test-multi-level" - if p, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if p != path { - t.Fatalf("Create returned different path '%s' != '%s'", p, path) - } - l := NewLock(zk, "/test-multi-level/lock", acls) - defer zk.Delete("/test-multi-level", -1) // Clean up what we've created for this test - defer zk.Delete("/test-multi-level/lock", -1) - if err := l.Lock(); err != nil { - t.Fatal(err) - } - if err := l.Unlock(); err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go deleted file mode 100644 index 64f18e8..0000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package zk - -import ( - "reflect" - "testing" -) - -func TestEncodeDecodePacket(t *testing.T) { - encodeDecodeTest(t, &requestHeader{-2, 5}) - encodeDecodeTest(t, &connectResponse{1, 2, 3, nil}) - encodeDecodeTest(t, &connectResponse{1, 2, 3, []byte{4, 5, 6}}) - encodeDecodeTest(t, &getAclResponse{[]ACL{{12, "s", "anyone"}}, Stat{}}) - encodeDecodeTest(t, &getChildrenResponse{[]string{"foo", "bar"}}) - encodeDecodeTest(t, &pathWatchRequest{"path", true}) - encodeDecodeTest(t, &pathWatchRequest{"path", false}) - encodeDecodeTest(t, &CheckVersionRequest{"/", -1}) - encodeDecodeTest(t, &multiRequest{Ops: []multiRequestOp{{multiHeader{opCheck, false, -1}, &CheckVersionRequest{"/", -1}}}}) -} - -func encodeDecodeTest(t *testing.T, r interface{}) { - buf := make([]byte, 1024) - n, err := encodePacket(buf, r) - if err != nil { - t.Errorf("encodePacket returned non-nil error %+v\n", err) - return - } - t.Logf("%+v %x", r, buf[:n]) - r2 := reflect.New(reflect.ValueOf(r).Elem().Type()).Interface() - n2, err := decodePacket(buf[:n], r2) - if err != nil { - t.Errorf("decodePacket returned non-nil error %+v\n", err) - return - } - if n != n2 { - t.Errorf("sizes don't match: %d != %d", n, n2) - return - } - if !reflect.DeepEqual(r, r2) { - t.Errorf("results don't match: %+v != %+v", r, r2) - return - } -} - -func TestEncodeShortBuffer(t *testing.T) { - buf := make([]byte, 0) - _, err := encodePacket(buf, &requestHeader{1, 2}) - if err != ErrShortBuffer { - t.Errorf("encodePacket should return ErrShortBuffer on a short buffer instead of '%+v'", err) - return - } -} - -func TestDecodeShortBuffer(t *testing.T) { - buf := make([]byte, 0) - _, err := decodePacket(buf, &responseHeader{}) - if err != ErrShortBuffer { - t.Errorf("decodePacket should return ErrShortBuffer on a short buffer instead of '%+v'", err) - return - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/zk_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/zk_test.go deleted file mode 100644 index 718b448..0000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/zk_test.go +++ /dev/null @@ -1,398 +0,0 @@ -package zk - -import ( - "testing" - "time" -) - -func TestCreate(t *testing.T) { - ts, err := StartTestCluster(1) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - path := "/gozk-test" - - if err := zk.Delete(path, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - if p, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if p != path { - t.Fatalf("Create returned different path '%s' != '%s'", p, path) - } - if data, stat, err := zk.Get(path); err != nil { - t.Fatalf("Get returned error: %+v", err) - } else if stat == nil { - t.Fatal("Get returned nil stat") - } else if len(data) < 4 { - t.Fatal("Get returned wrong size data") - } -} - -func TestMulti(t *testing.T) { - ts, err := StartTestCluster(1) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - path := "/gozk-test" - - if err := zk.Delete(path, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - ops := MultiOps{ - Create: []CreateRequest{ - {Path: path, Data: []byte{1, 2, 3, 4}, Acl: WorldACL(PermAll)}, - }, - SetData: []SetDataRequest{ - {Path: path, Data: []byte{1, 2, 3, 4}, Version: -1}, - }, - // Delete: []DeleteRequest{ - // {Path: path, Version: -1}, - // }, - } - if err := zk.Multi(ops); err != nil { - t.Fatalf("Multi returned error: %+v", err) - } - if data, stat, err := zk.Get(path); err != nil { - t.Fatalf("Get returned error: %+v", err) - } else if stat == nil { - t.Fatal("Get returned nil stat") - } else if len(data) < 4 { - t.Fatal("Get returned wrong size data") - } -} - -func TestGetSetACL(t *testing.T) { - ts, err := StartTestCluster(1) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - if err := zk.AddAuth("digest", []byte("blah")); err != nil { - t.Fatalf("AddAuth returned error %+v", err) - } - - path := "/gozk-test" - - if err := zk.Delete(path, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - if path, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if path != "/gozk-test" { - t.Fatalf("Create returned different path '%s' != '/gozk-test'", path) - } - - expected := WorldACL(PermAll) - - if acl, stat, err := zk.GetACL(path); err != nil { - t.Fatalf("GetACL returned error %+v", err) - } else if stat == nil { - t.Fatalf("GetACL returned nil Stat") - } else if len(acl) != 1 || expected[0] != acl[0] { - t.Fatalf("GetACL mismatch expected %+v instead of %+v", expected, acl) - } - - expected = []ACL{{PermAll, "ip", "127.0.0.1"}} - - if stat, err := zk.SetACL(path, expected, -1); err != nil { - t.Fatalf("SetACL returned error %+v", err) - } else if stat == nil { - t.Fatalf("SetACL returned nil Stat") - } - - if acl, stat, err := zk.GetACL(path); err != nil { - t.Fatalf("GetACL returned error %+v", err) - } else if stat == nil { - t.Fatalf("GetACL returned nil Stat") - } else if len(acl) != 1 || expected[0] != acl[0] { - t.Fatalf("GetACL mismatch expected %+v instead of %+v", expected, acl) - } -} - -func TestAuth(t *testing.T) { - ts, err := StartTestCluster(1) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - path := "/gozk-digest-test" - if err := zk.Delete(path, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - acl := DigestACL(PermAll, "user", "password") - - if p, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, acl); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if p != path { - t.Fatalf("Create returned different path '%s' != '%s'", p, path) - } - - if a, stat, err := zk.GetACL(path); err != nil { - t.Fatalf("GetACL returned error %+v", err) - } else if stat == nil { - t.Fatalf("GetACL returned nil Stat") - } else if len(a) != 1 || acl[0] != a[0] { - t.Fatalf("GetACL mismatch expected %+v instead of %+v", acl, a) - } - - if _, _, err := zk.Get(path); err != ErrNoAuth { - t.Fatalf("Get returned error %+v instead of ErrNoAuth", err) - } - - if err := zk.AddAuth("digest", []byte("user:password")); err != nil { - t.Fatalf("AddAuth returned error %+v", err) - } - - if data, stat, err := zk.Get(path); err != nil { - t.Fatalf("Get returned error %+v", err) - } else if stat == nil { - t.Fatalf("Get returned nil Stat") - } else if len(data) != 4 { - t.Fatalf("Get returned wrong data length") - } -} - -func TestChildWatch(t *testing.T) { - ts, err := StartTestCluster(1) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - children, stat, childCh, err := zk.ChildrenW("/") - if err != nil { - t.Fatalf("Children returned error: %+v", err) - } else if stat == nil { - t.Fatal("Children returned nil stat") - } else if len(children) < 1 { - t.Fatal("Children should return at least 1 child") - } - - if path, err := zk.Create("/gozk-test", []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if path != "/gozk-test" { - t.Fatalf("Create returned different path '%s' != '/gozk-test'", path) - } - - select { - case ev := <-childCh: - if ev.Err != nil { - t.Fatalf("Child watcher error %+v", ev.Err) - } - if ev.Path != "/" { - t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/") - } - case _ = <-time.After(time.Second * 2): - t.Fatal("Child watcher timed out") - } - - // Delete of the watched node should trigger the watch - - children, stat, childCh, err = zk.ChildrenW("/gozk-test") - if err != nil { - t.Fatalf("Children returned error: %+v", err) - } else if stat == nil { - t.Fatal("Children returned nil stat") - } else if len(children) != 0 { - t.Fatal("Children should return 0 children") - } - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - select { - case ev := <-childCh: - if ev.Err != nil { - t.Fatalf("Child watcher error %+v", ev.Err) - } - if ev.Path != "/gozk-test" { - t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/") - } - case _ = <-time.After(time.Second * 2): - t.Fatal("Child watcher timed out") - } -} - -func TestSetWatchers(t *testing.T) { - ts, err := StartTestCluster(1) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - zk.reconnectDelay = time.Second - - zk2, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk2.Close() - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - testPath, err := zk.Create("/gozk-test-2", []byte{}, 0, WorldACL(PermAll)) - if err != nil { - t.Fatalf("Create returned: %+v", err) - } - - _, _, testEvCh, err := zk.GetW(testPath) - if err != nil { - t.Fatalf("GetW returned: %+v", err) - } - - children, stat, childCh, err := zk.ChildrenW("/") - if err != nil { - t.Fatalf("Children returned error: %+v", err) - } else if stat == nil { - t.Fatal("Children returned nil stat") - } else if len(children) < 1 { - t.Fatal("Children should return at least 1 child") - } - - zk.conn.Close() - if err := zk2.Delete(testPath, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - time.Sleep(time.Millisecond * 100) - - if path, err := zk2.Create("/gozk-test", []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if path != "/gozk-test" { - t.Fatalf("Create returned different path '%s' != '/gozk-test'", path) - } - - select { - case ev := <-testEvCh: - if ev.Err != nil { - t.Fatalf("GetW watcher error %+v", ev.Err) - } - if ev.Path != testPath { - t.Fatalf("GetW watcher wrong path %s instead of %s", ev.Path, testPath) - } - case <-time.After(2 * time.Second): - t.Fatal("GetW watcher timed out") - } - - select { - case ev := <-childCh: - if ev.Err != nil { - t.Fatalf("Child watcher error %+v", ev.Err) - } - if ev.Path != "/" { - t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/") - } - case <-time.After(2 * time.Second): - t.Fatal("Child watcher timed out") - } -} - -func TestExpiringWatch(t *testing.T) { - ts, err := StartTestCluster(1) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - children, stat, childCh, err := zk.ChildrenW("/") - if err != nil { - t.Fatalf("Children returned error: %+v", err) - } else if stat == nil { - t.Fatal("Children returned nil stat") - } else if len(children) < 1 { - t.Fatal("Children should return at least 1 child") - } - - zk.sessionID = 99999 - zk.conn.Close() - - select { - case ev := <-childCh: - if ev.Err != ErrSessionExpired { - t.Fatalf("Child watcher error %+v instead of expected ErrSessionExpired", ev.Err) - } - if ev.Path != "/" { - t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/") - } - case <-time.After(2 * time.Second): - t.Fatal("Child watcher timed out") - } -} - -func TestRequestFail(t *testing.T) { - // If connecting fails to all servers in the list then pending requests - // should be errored out so they don't hang forever. - - zk, _, err := Connect([]string{"127.0.0.1:32444"}, time.Second*15) - if err != nil { - t.Fatal(err) - } - defer zk.Close() - - ch := make(chan error) - go func() { - _, _, err := zk.Get("/blah") - ch <- err - }() - select { - case err := <-ch: - if err == nil { - t.Fatal("Expected non-nil error on failed request due to connection failure") - } - case <-time.After(time.Second * 2): - t.Fatal("Get hung when connection could not be made") - } -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/.gitignore b/Godeps/_workspace/src/github.com/smartystreets/assertions/.gitignore deleted file mode 100644 index fafff2e..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.DS_Store -Thumbs.db diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/.travis.yml b/Godeps/_workspace/src/github.com/smartystreets/assertions/.travis.yml deleted file mode 100644 index 4aa2c6d..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -go: - - 1.2 - - 1.3 - - 1.4 - -install: - - go get golang.org/x/tools/cover diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/LICENSE.md b/Godeps/_workspace/src/github.com/smartystreets/assertions/LICENSE.md deleted file mode 100644 index 48a3731..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/LICENSE.md +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015 SmartyStreets, LLC - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -NOTE: Various optional and subordinate components carry their own licensing -requirements and restrictions. Use of those components is subject to the terms -and conditions outlined the respective license of each component. diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/README.md b/Godeps/_workspace/src/github.com/smartystreets/assertions/README.md deleted file mode 100644 index 3c62389..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/README.md +++ /dev/null @@ -1,481 +0,0 @@ -# assertions --- - import "github.com/smartystreets/assertions" - -Package assertions contains the implementations for all assertions which are -referenced in goconvey's `convey` package -(github.com/smartystreets/goconvey/convey) for use with the So(...) method. They -can also be used in traditional Go test functions and even in applicaitons. - -## Usage - -#### func So - -```go -func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string) -``` -So is a convenience function for running assertions on arbitrary arguments in -any context, be it for testing or even application logging. It allows you to -perform assertion-like behavior (and get nicely formatted messages detailing -discrepancies) but without the program blowing up or panicking. All that is -required is to import this package and call `So` with one of the assertions -exported by this package as the second parameter. The first return parameter is -a boolean indicating if the assertion was true. The second return parameter is -the well-formatted message showing why an assertion was incorrect, or blank if -the assertion was correct. - -Example: - - if ok, message := So(x, ShouldBeGreaterThan, y); !ok { - log.Println(message) - } - -#### func GoConveyMode - -```go -func GoConveyMode(yes bool) -``` -GoConveyMode provides control over JSON serialization of failures. When using -the assertions in this package from the convey package JSON results are very -helpful and can be rendered in a DIFF view. In that case, this function will be -called with a true value to enable the JSON serialization. By default, the -assertions in this package will not serializer a JSON result, making standalone -ussage more convenient. - -#### func ShouldAlmostEqual - -```go -func ShouldAlmostEqual(actual interface{}, expected ...interface{}) string -``` -ShouldAlmostEqual makes sure that two parameters are close enough to being -equal. The acceptable delta may be specified with a third argument, or a very -small default delta will be used. - -#### func ShouldBeBetween - -```go -func ShouldBeBetween(actual interface{}, expected ...interface{}) string -``` -ShouldBeBetween receives exactly three parameters: an actual value, a lower -bound, and an upper bound. It ensures that the actual value is between both -bounds (but not equal to either of them). - -#### func ShouldBeBetweenOrEqual - -```go -func ShouldBeBetweenOrEqual(actual interface{}, expected ...interface{}) string -``` -ShouldBeBetweenOrEqual receives exactly three parameters: an actual value, a -lower bound, and an upper bound. It ensures that the actual value is between -both bounds or equal to one of them. - -#### func ShouldBeBlank - -```go -func ShouldBeBlank(actual interface{}, expected ...interface{}) string -``` -ShouldBeBlank receives exactly 1 string parameter and ensures that it is equal -to "". - -#### func ShouldBeChronological - -```go -func ShouldBeChronological(actual interface{}, expected ...interface{}) string -``` -ShouldBeChronological receives a []time.Time slice and asserts that the are in -chronological order starting with the first time.Time as the earliest. - -#### func ShouldBeEmpty - -```go -func ShouldBeEmpty(actual interface{}, expected ...interface{}) string -``` -ShouldBeEmpty receives a single parameter (actual) and determines whether or not -calling len(actual) would return `0`. It obeys the rules specified by the len -function for determining length: http://golang.org/pkg/builtin/#len - -#### func ShouldBeFalse - -```go -func ShouldBeFalse(actual interface{}, expected ...interface{}) string -``` -ShouldBeFalse receives a single parameter and ensures that it is false. - -#### func ShouldBeGreaterThan - -```go -func ShouldBeGreaterThan(actual interface{}, expected ...interface{}) string -``` -ShouldBeGreaterThan receives exactly two parameters and ensures that the first -is greater than the second. - -#### func ShouldBeGreaterThanOrEqualTo - -```go -func ShouldBeGreaterThanOrEqualTo(actual interface{}, expected ...interface{}) string -``` -ShouldBeGreaterThanOrEqualTo receives exactly two parameters and ensures that -the first is greater than or equal to the second. - -#### func ShouldBeIn - -```go -func ShouldBeIn(actual interface{}, expected ...interface{}) string -``` -ShouldBeIn receives at least 2 parameters. The first is a proposed member of the -collection that is passed in either as the second parameter, or of the -collection that is comprised of all the remaining parameters. This assertion -ensures that the proposed member is in the collection (using ShouldEqual). - -#### func ShouldBeLessThan - -```go -func ShouldBeLessThan(actual interface{}, expected ...interface{}) string -``` -ShouldBeLessThan receives exactly two parameters and ensures that the first is -less than the second. - -#### func ShouldBeLessThanOrEqualTo - -```go -func ShouldBeLessThanOrEqualTo(actual interface{}, expected ...interface{}) string -``` -ShouldBeLessThan receives exactly two parameters and ensures that the first is -less than or equal to the second. - -#### func ShouldBeNil - -```go -func ShouldBeNil(actual interface{}, expected ...interface{}) string -``` -ShouldBeNil receives a single parameter and ensures that it is nil. - -#### func ShouldBeTrue - -```go -func ShouldBeTrue(actual interface{}, expected ...interface{}) string -``` -ShouldBeTrue receives a single parameter and ensures that it is true. - -#### func ShouldBeZeroValue - -```go -func ShouldBeZeroValue(actual interface{}, expected ...interface{}) string -``` -ShouldBeZeroValue receives a single parameter and ensures that it is the Go -equivalent of the default value, or "zero" value. - -#### func ShouldContain - -```go -func ShouldContain(actual interface{}, expected ...interface{}) string -``` -ShouldContain receives exactly two parameters. The first is a slice and the -second is a proposed member. Membership is determined using ShouldEqual. - -#### func ShouldContainSubstring - -```go -func ShouldContainSubstring(actual interface{}, expected ...interface{}) string -``` -ShouldContainSubstring receives exactly 2 string parameters and ensures that the -first contains the second as a substring. - -#### func ShouldEndWith - -```go -func ShouldEndWith(actual interface{}, expected ...interface{}) string -``` -ShouldEndWith receives exactly 2 string parameters and ensures that the first -ends with the second. - -#### func ShouldEqual - -```go -func ShouldEqual(actual interface{}, expected ...interface{}) string -``` -ShouldEqual receives exactly two parameters and does an equality check. - -#### func ShouldHappenAfter - -```go -func ShouldHappenAfter(actual interface{}, expected ...interface{}) string -``` -ShouldHappenAfter receives exactly 2 time.Time arguments and asserts that the -first happens after the second. - -#### func ShouldHappenBefore - -```go -func ShouldHappenBefore(actual interface{}, expected ...interface{}) string -``` -ShouldHappenBefore receives exactly 2 time.Time arguments and asserts that the -first happens before the second. - -#### func ShouldHappenBetween - -```go -func ShouldHappenBetween(actual interface{}, expected ...interface{}) string -``` -ShouldHappenBetween receives exactly 3 time.Time arguments and asserts that the -first happens between (not on) the second and third. - -#### func ShouldHappenOnOrAfter - -```go -func ShouldHappenOnOrAfter(actual interface{}, expected ...interface{}) string -``` -ShouldHappenOnOrAfter receives exactly 2 time.Time arguments and asserts that -the first happens on or after the second. - -#### func ShouldHappenOnOrBefore - -```go -func ShouldHappenOnOrBefore(actual interface{}, expected ...interface{}) string -``` -ShouldHappenOnOrBefore receives exactly 2 time.Time arguments and asserts that -the first happens on or before the second. - -#### func ShouldHappenOnOrBetween - -```go -func ShouldHappenOnOrBetween(actual interface{}, expected ...interface{}) string -``` -ShouldHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that -the first happens between or on the second and third. - -#### func ShouldHappenWithin - -```go -func ShouldHappenWithin(actual interface{}, expected ...interface{}) string -``` -ShouldHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 -arguments) and asserts that the first time.Time happens within or on the -duration specified relative to the other time.Time. - -#### func ShouldHaveSameTypeAs - -```go -func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string -``` -ShouldHaveSameTypeAs receives exactly two parameters and compares their -underlying types for equality. - -#### func ShouldImplement - -```go -func ShouldImplement(actual interface{}, expectedList ...interface{}) string -``` -ShouldImplement receives exactly two parameters and ensures that the first -implements the interface type of the second. - -#### func ShouldNotAlmostEqual - -```go -func ShouldNotAlmostEqual(actual interface{}, expected ...interface{}) string -``` -ShouldNotAlmostEqual is the inverse of ShouldAlmostEqual - -#### func ShouldNotBeBetween - -```go -func ShouldNotBeBetween(actual interface{}, expected ...interface{}) string -``` -ShouldNotBeBetween receives exactly three parameters: an actual value, a lower -bound, and an upper bound. It ensures that the actual value is NOT between both -bounds. - -#### func ShouldNotBeBetweenOrEqual - -```go -func ShouldNotBeBetweenOrEqual(actual interface{}, expected ...interface{}) string -``` -ShouldNotBeBetweenOrEqual receives exactly three parameters: an actual value, a -lower bound, and an upper bound. It ensures that the actual value is nopt -between the bounds nor equal to either of them. - -#### func ShouldNotBeBlank - -```go -func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string -``` -ShouldNotBeBlank receives exactly 1 string parameter and ensures that it is -equal to "". - -#### func ShouldNotBeEmpty - -```go -func ShouldNotBeEmpty(actual interface{}, expected ...interface{}) string -``` -ShouldNotBeEmpty receives a single parameter (actual) and determines whether or -not calling len(actual) would return a value greater than zero. It obeys the -rules specified by the `len` function for determining length: -http://golang.org/pkg/builtin/#len - -#### func ShouldNotBeIn - -```go -func ShouldNotBeIn(actual interface{}, expected ...interface{}) string -``` -ShouldNotBeIn receives at least 2 parameters. The first is a proposed member of -the collection that is passed in either as the second parameter, or of the -collection that is comprised of all the remaining parameters. This assertion -ensures that the proposed member is NOT in the collection (using ShouldEqual). - -#### func ShouldNotBeNil - -```go -func ShouldNotBeNil(actual interface{}, expected ...interface{}) string -``` -ShouldNotBeNil receives a single parameter and ensures that it is not nil. - -#### func ShouldNotContain - -```go -func ShouldNotContain(actual interface{}, expected ...interface{}) string -``` -ShouldNotContain receives exactly two parameters. The first is a slice and the -second is a proposed member. Membership is determinied using ShouldEqual. - -#### func ShouldNotContainSubstring - -```go -func ShouldNotContainSubstring(actual interface{}, expected ...interface{}) string -``` -ShouldNotContainSubstring receives exactly 2 string parameters and ensures that -the first does NOT contain the second as a substring. - -#### func ShouldNotEndWith - -```go -func ShouldNotEndWith(actual interface{}, expected ...interface{}) string -``` -ShouldEndWith receives exactly 2 string parameters and ensures that the first -does not end with the second. - -#### func ShouldNotEqual - -```go -func ShouldNotEqual(actual interface{}, expected ...interface{}) string -``` -ShouldNotEqual receives exactly two parameters and does an inequality check. - -#### func ShouldNotHappenOnOrBetween - -```go -func ShouldNotHappenOnOrBetween(actual interface{}, expected ...interface{}) string -``` -ShouldNotHappenOnOrBetween receives exactly 3 time.Time arguments and asserts -that the first does NOT happen between or on the second or third. - -#### func ShouldNotHappenWithin - -```go -func ShouldNotHappenWithin(actual interface{}, expected ...interface{}) string -``` -ShouldNotHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 -arguments) and asserts that the first time.Time does NOT happen within or on the -duration specified relative to the other time.Time. - -#### func ShouldNotHaveSameTypeAs - -```go -func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string -``` -ShouldNotHaveSameTypeAs receives exactly two parameters and compares their -underlying types for inequality. - -#### func ShouldNotImplement - -```go -func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string -``` -ShouldNotImplement receives exactly two parameters and ensures that the first -does NOT implement the interface type of the second. - -#### func ShouldNotPanic - -```go -func ShouldNotPanic(actual interface{}, expected ...interface{}) (message string) -``` -ShouldNotPanic receives a void, niladic function and expects to execute the -function without any panic. - -#### func ShouldNotPanicWith - -```go -func ShouldNotPanicWith(actual interface{}, expected ...interface{}) (message string) -``` -ShouldNotPanicWith receives a void, niladic function and expects to recover a -panic whose content differs from the second argument. - -#### func ShouldNotPointTo - -```go -func ShouldNotPointTo(actual interface{}, expected ...interface{}) string -``` -ShouldNotPointTo receives exactly two parameters and checks to see that they -point to different addresess. - -#### func ShouldNotResemble - -```go -func ShouldNotResemble(actual interface{}, expected ...interface{}) string -``` -ShouldNotResemble receives exactly two parameters and does an inverse deep equal -check (see reflect.DeepEqual) - -#### func ShouldNotStartWith - -```go -func ShouldNotStartWith(actual interface{}, expected ...interface{}) string -``` -ShouldNotStartWith receives exactly 2 string parameters and ensures that the -first does not start with the second. - -#### func ShouldPanic - -```go -func ShouldPanic(actual interface{}, expected ...interface{}) (message string) -``` -ShouldPanic receives a void, niladic function and expects to recover a panic. - -#### func ShouldPanicWith - -```go -func ShouldPanicWith(actual interface{}, expected ...interface{}) (message string) -``` -ShouldPanicWith receives a void, niladic function and expects to recover a panic -with the second argument as the content. - -#### func ShouldPointTo - -```go -func ShouldPointTo(actual interface{}, expected ...interface{}) string -``` -ShouldPointTo receives exactly two parameters and checks to see that they point -to the same address. - -#### func ShouldResemble - -```go -func ShouldResemble(actual interface{}, expected ...interface{}) string -``` -ShouldResemble receives exactly two parameters and does a deep equal check (see -reflect.DeepEqual) - -#### func ShouldStartWith - -```go -func ShouldStartWith(actual interface{}, expected ...interface{}) string -``` -ShouldStartWith receives exactly 2 string parameters and ensures that the first -starts with the second. - -#### type Serializer - -```go -type Serializer interface { - // contains filtered or unexported methods -} -``` diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/assertions.goconvey b/Godeps/_workspace/src/github.com/smartystreets/assertions/assertions.goconvey deleted file mode 100644 index e76cf27..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/assertions.goconvey +++ /dev/null @@ -1,3 +0,0 @@ -#ignore --timeout=1s --coverpkg=github.com/smartystreets/assertions,github.com/smartystreets/assertions/internal/oglematchers \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/collections.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/collections.go deleted file mode 100644 index 360531f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/collections.go +++ /dev/null @@ -1,140 +0,0 @@ -package assertions - -import ( - "fmt" - "reflect" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" -) - -// ShouldContain receives exactly two parameters. The first is a slice and the -// second is a proposed member. Membership is determined using ShouldEqual. -func ShouldContain(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - if matchError := oglematchers.Contains(expected[0]).Matches(actual); matchError != nil { - typeName := reflect.TypeOf(actual) - - if fmt.Sprintf("%v", matchError) == "which is not a slice or array" { - return fmt.Sprintf(shouldHaveBeenAValidCollection, typeName) - } - return fmt.Sprintf(shouldHaveContained, typeName, expected[0]) - } - return success -} - -// ShouldNotContain receives exactly two parameters. The first is a slice and the -// second is a proposed member. Membership is determinied using ShouldEqual. -func ShouldNotContain(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - typeName := reflect.TypeOf(actual) - - if matchError := oglematchers.Contains(expected[0]).Matches(actual); matchError != nil { - if fmt.Sprintf("%v", matchError) == "which is not a slice or array" { - return fmt.Sprintf(shouldHaveBeenAValidCollection, typeName) - } - return success - } - return fmt.Sprintf(shouldNotHaveContained, typeName, expected[0]) -} - -// ShouldBeIn receives at least 2 parameters. The first is a proposed member of the collection -// that is passed in either as the second parameter, or of the collection that is comprised -// of all the remaining parameters. This assertion ensures that the proposed member is in -// the collection (using ShouldEqual). -func ShouldBeIn(actual interface{}, expected ...interface{}) string { - if fail := atLeast(1, expected); fail != success { - return fail - } - - if len(expected) == 1 { - return shouldBeIn(actual, expected[0]) - } - return shouldBeIn(actual, expected) -} -func shouldBeIn(actual interface{}, expected interface{}) string { - if matchError := oglematchers.Contains(actual).Matches(expected); matchError != nil { - return fmt.Sprintf(shouldHaveBeenIn, actual, reflect.TypeOf(expected)) - } - return success -} - -// ShouldNotBeIn receives at least 2 parameters. The first is a proposed member of the collection -// that is passed in either as the second parameter, or of the collection that is comprised -// of all the remaining parameters. This assertion ensures that the proposed member is NOT in -// the collection (using ShouldEqual). -func ShouldNotBeIn(actual interface{}, expected ...interface{}) string { - if fail := atLeast(1, expected); fail != success { - return fail - } - - if len(expected) == 1 { - return shouldNotBeIn(actual, expected[0]) - } - return shouldNotBeIn(actual, expected) -} -func shouldNotBeIn(actual interface{}, expected interface{}) string { - if matchError := oglematchers.Contains(actual).Matches(expected); matchError == nil { - return fmt.Sprintf(shouldNotHaveBeenIn, actual, reflect.TypeOf(expected)) - } - return success -} - -// ShouldBeEmpty receives a single parameter (actual) and determines whether or not -// calling len(actual) would return `0`. It obeys the rules specified by the len -// function for determining length: http://golang.org/pkg/builtin/#len -func ShouldBeEmpty(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - - if actual == nil { - return success - } - - value := reflect.ValueOf(actual) - switch value.Kind() { - case reflect.Slice: - if value.Len() == 0 { - return success - } - case reflect.Chan: - if value.Len() == 0 { - return success - } - case reflect.Map: - if value.Len() == 0 { - return success - } - case reflect.String: - if value.Len() == 0 { - return success - } - case reflect.Ptr: - elem := value.Elem() - kind := elem.Kind() - if (kind == reflect.Slice || kind == reflect.Array) && elem.Len() == 0 { - return success - } - } - - return fmt.Sprintf(shouldHaveBeenEmpty, actual) -} - -// ShouldNotBeEmpty receives a single parameter (actual) and determines whether or not -// calling len(actual) would return a value greater than zero. It obeys the rules -// specified by the `len` function for determining length: http://golang.org/pkg/builtin/#len -func ShouldNotBeEmpty(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - - if empty := ShouldBeEmpty(actual, expected...); empty != success { - return success - } - return fmt.Sprintf(shouldNotHaveBeenEmpty, actual) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/collections_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/collections_test.go deleted file mode 100644 index 4ff3d8c..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/collections_test.go +++ /dev/null @@ -1,103 +0,0 @@ -package assertions - -import ( - "fmt" - "testing" - "time" -) - -func TestShouldContain(t *testing.T) { - fail(t, so([]int{}, ShouldContain), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so([]int{}, ShouldContain, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(Thing1{}, ShouldContain, 1), "You must provide a valid container (was assertions.Thing1)!") - fail(t, so(nil, ShouldContain, 1), "You must provide a valid container (was )!") - fail(t, so([]int{1}, ShouldContain, 2), "Expected the container ([]int) to contain: '2' (but it didn't)!") - - pass(t, so([]int{1}, ShouldContain, 1)) - pass(t, so([]int{1, 2, 3}, ShouldContain, 2)) -} - -func TestShouldNotContain(t *testing.T) { - fail(t, so([]int{}, ShouldNotContain), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so([]int{}, ShouldNotContain, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(Thing1{}, ShouldNotContain, 1), "You must provide a valid container (was assertions.Thing1)!") - fail(t, so(nil, ShouldNotContain, 1), "You must provide a valid container (was )!") - - fail(t, so([]int{1}, ShouldNotContain, 1), "Expected the container ([]int) NOT to contain: '1' (but it did)!") - fail(t, so([]int{1, 2, 3}, ShouldNotContain, 2), "Expected the container ([]int) NOT to contain: '2' (but it did)!") - - pass(t, so([]int{1}, ShouldNotContain, 2)) -} - -func TestShouldBeIn(t *testing.T) { - fail(t, so(4, ShouldBeIn), needNonEmptyCollection) - - container := []int{1, 2, 3, 4} - pass(t, so(4, ShouldBeIn, container)) - pass(t, so(4, ShouldBeIn, 1, 2, 3, 4)) - - fail(t, so(4, ShouldBeIn, 1, 2, 3), "Expected '4' to be in the container ([]interface {}, but it wasn't)!") - fail(t, so(4, ShouldBeIn, []int{1, 2, 3}), "Expected '4' to be in the container ([]int, but it wasn't)!") -} - -func TestShouldNotBeIn(t *testing.T) { - fail(t, so(4, ShouldNotBeIn), needNonEmptyCollection) - - container := []int{1, 2, 3, 4} - pass(t, so(42, ShouldNotBeIn, container)) - pass(t, so(42, ShouldNotBeIn, 1, 2, 3, 4)) - - fail(t, so(2, ShouldNotBeIn, 1, 2, 3), "Expected '2' NOT to be in the container ([]interface {}, but it was)!") - fail(t, so(2, ShouldNotBeIn, []int{1, 2, 3}), "Expected '2' NOT to be in the container ([]int, but it was)!") -} - -func TestShouldBeEmpty(t *testing.T) { - fail(t, so(1, ShouldBeEmpty, 2, 3), "This assertion requires exactly 0 comparison values (you provided 2).") - - pass(t, so([]int{}, ShouldBeEmpty)) // empty slice - pass(t, so([]interface{}{}, ShouldBeEmpty)) // empty slice - pass(t, so(map[string]int{}, ShouldBeEmpty)) // empty map - pass(t, so("", ShouldBeEmpty)) // empty string - pass(t, so(&[]int{}, ShouldBeEmpty)) // pointer to empty slice - pass(t, so(&[0]int{}, ShouldBeEmpty)) // pointer to empty array - pass(t, so(nil, ShouldBeEmpty)) // nil - pass(t, so(make(chan string), ShouldBeEmpty)) // empty channel - - fail(t, so([]int{1}, ShouldBeEmpty), "Expected [1] to be empty (but it wasn't)!") // non-empty slice - fail(t, so([]interface{}{1}, ShouldBeEmpty), "Expected [1] to be empty (but it wasn't)!") // non-empty slice - fail(t, so(map[string]int{"hi": 0}, ShouldBeEmpty), "Expected map[hi:0] to be empty (but it wasn't)!") // non-empty map - fail(t, so("hi", ShouldBeEmpty), "Expected hi to be empty (but it wasn't)!") // non-empty string - fail(t, so(&[]int{1}, ShouldBeEmpty), "Expected &[1] to be empty (but it wasn't)!") // pointer to non-empty slice - fail(t, so(&[1]int{1}, ShouldBeEmpty), "Expected &[1] to be empty (but it wasn't)!") // pointer to non-empty array - c := make(chan int, 1) // non-empty channel - go func() { c <- 1 }() - time.Sleep(time.Millisecond) - fail(t, so(c, ShouldBeEmpty), fmt.Sprintf("Expected %+v to be empty (but it wasn't)!", c)) -} - -func TestShouldNotBeEmpty(t *testing.T) { - fail(t, so(1, ShouldNotBeEmpty, 2, 3), "This assertion requires exactly 0 comparison values (you provided 2).") - - fail(t, so([]int{}, ShouldNotBeEmpty), "Expected [] to NOT be empty (but it was)!") // empty slice - fail(t, so([]interface{}{}, ShouldNotBeEmpty), "Expected [] to NOT be empty (but it was)!") // empty slice - fail(t, so(map[string]int{}, ShouldNotBeEmpty), "Expected map[] to NOT be empty (but it was)!") // empty map - fail(t, so("", ShouldNotBeEmpty), "Expected to NOT be empty (but it was)!") // empty string - fail(t, so(&[]int{}, ShouldNotBeEmpty), "Expected &[] to NOT be empty (but it was)!") // pointer to empty slice - fail(t, so(&[0]int{}, ShouldNotBeEmpty), "Expected &[] to NOT be empty (but it was)!") // pointer to empty array - fail(t, so(nil, ShouldNotBeEmpty), "Expected to NOT be empty (but it was)!") // nil - c := make(chan int, 0) // non-empty channel - fail(t, so(c, ShouldNotBeEmpty), fmt.Sprintf("Expected %+v to NOT be empty (but it was)!", c)) // empty channel - - pass(t, so([]int{1}, ShouldNotBeEmpty)) // non-empty slice - pass(t, so([]interface{}{1}, ShouldNotBeEmpty)) // non-empty slice - pass(t, so(map[string]int{"hi": 0}, ShouldNotBeEmpty)) // non-empty map - pass(t, so("hi", ShouldNotBeEmpty)) // non-empty string - pass(t, so(&[]int{1}, ShouldNotBeEmpty)) // pointer to non-empty slice - pass(t, so(&[1]int{1}, ShouldNotBeEmpty)) // pointer to non-empty array - c = make(chan int, 1) - go func() { c <- 1 }() - time.Sleep(time.Millisecond) - pass(t, so(c, ShouldNotBeEmpty)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/doc.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/doc.go deleted file mode 100644 index 5659f4a..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/doc.go +++ /dev/null @@ -1,63 +0,0 @@ -// Package assertions contains the implementations for all assertions which -// are referenced in goconvey's `convey` package -// (github.com/smartystreets/goconvey/convey) for use with the So(...) method. -// They can also be used in traditional Go test functions and even in -// applicaitons. -package assertions - -// By default we use a no-op serializer. The actual Serializer provides a JSON -// representation of failure results on selected assertions so the goconvey -// web UI can display a convenient diff. -var serializer Serializer = new(noopSerializer) - -// GoConveyMode provides control over JSON serialization of failures. When -// using the assertions in this package from the convey package JSON results -// are very helpful and can be rendered in a DIFF view. In that case, this function -// will be called with a true value to enable the JSON serialization. By default, -// the assertions in this package will not serializer a JSON result, making -// standalone ussage more convenient. -func GoConveyMode(yes bool) { - if yes { - serializer = newSerializer() - } else { - serializer = new(noopSerializer) - } -} - -// So is a convenience function -// for running assertions on arbitrary arguments in any context, be it for testing or even -// application logging. It allows you to perform assertion-like behavior (and get nicely -// formatted messages detailing discrepancies) but without the program blowing up or panicking. -// All that is required is to import this package and call `So` with one of the assertions -// exported by this package as the second parameter. -// The first return parameter is a boolean indicating if the assertion was true. The second -// return parameter is the well-formatted message showing why an assertion was incorrect, or -// blank if the assertion was correct. -// -// Example: -// -// if ok, message := So(x, ShouldBeGreaterThan, y); !ok { -// log.Println(message) -// } -// -func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string) { - if result := so(actual, assert, expected...); len(result) == 0 { - return true, result - } else { - return false, result - } -} - -// so is like So, except that it only returns the string message, which is blank if the -// assertion passed. Used to facilitate testing. -func so(actual interface{}, assert func(interface{}, ...interface{}) string, expected ...interface{}) string { - return assert(actual, expected...) -} - -// assertion is an alias for a function with a signature that the So() -// function can handle. Any future or custom assertions should conform to this -// method signature. The return value should be an empty string if the assertion -// passes and a well-formed failure message if not. -type assertion func(actual interface{}, expected ...interface{}) string - -//////////////////////////////////////////////////////////////////////////// diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/equality.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/equality.go deleted file mode 100644 index 58f523a..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/equality.go +++ /dev/null @@ -1,279 +0,0 @@ -package assertions - -import ( - "errors" - "fmt" - "math" - "reflect" - "strings" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" -) - -// default acceptable delta for ShouldAlmostEqual -const defaultDelta = 0.0000000001 - -// ShouldEqual receives exactly two parameters and does an equality check. -func ShouldEqual(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } - return shouldEqual(actual, expected[0]) -} -func shouldEqual(actual, expected interface{}) (message string) { - defer func() { - if r := recover(); r != nil { - message = serializer.serialize(expected, actual, fmt.Sprintf(shouldHaveBeenEqual, expected, actual)) - return - } - }() - - if matchError := oglematchers.Equals(expected).Matches(actual); matchError != nil { - message = serializer.serialize(expected, actual, fmt.Sprintf(shouldHaveBeenEqual, expected, actual)) - return - } - - return success -} - -// ShouldNotEqual receives exactly two parameters and does an inequality check. -func ShouldNotEqual(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } else if ShouldEqual(actual, expected[0]) == success { - return fmt.Sprintf(shouldNotHaveBeenEqual, actual, expected[0]) - } - return success -} - -// ShouldAlmostEqual makes sure that two parameters are close enough to being equal. -// The acceptable delta may be specified with a third argument, -// or a very small default delta will be used. -func ShouldAlmostEqual(actual interface{}, expected ...interface{}) string { - actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...) - - if err != "" { - return err - } - - if math.Abs(actualFloat-expectedFloat) <= deltaFloat { - return success - } else { - return fmt.Sprintf(shouldHaveBeenAlmostEqual, actualFloat, expectedFloat) - } -} - -// ShouldNotAlmostEqual is the inverse of ShouldAlmostEqual -func ShouldNotAlmostEqual(actual interface{}, expected ...interface{}) string { - actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...) - - if err != "" { - return err - } - - if math.Abs(actualFloat-expectedFloat) > deltaFloat { - return success - } else { - return fmt.Sprintf(shouldHaveNotBeenAlmostEqual, actualFloat, expectedFloat) - } -} - -func cleanAlmostEqualInput(actual interface{}, expected ...interface{}) (float64, float64, float64, string) { - deltaFloat := 0.0000000001 - - if len(expected) == 0 { - return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided neither)" - } else if len(expected) == 2 { - delta, err := getFloat(expected[1]) - - if err != nil { - return 0.0, 0.0, 0.0, "delta must be a numerical type" - } - - deltaFloat = delta - } else if len(expected) > 2 { - return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided more values)" - } - - actualFloat, err := getFloat(actual) - - if err != nil { - return 0.0, 0.0, 0.0, err.Error() - } - - expectedFloat, err := getFloat(expected[0]) - - if err != nil { - return 0.0, 0.0, 0.0, err.Error() - } - - return actualFloat, expectedFloat, deltaFloat, "" -} - -// returns the float value of any real number, or error if it is not a numerical type -func getFloat(num interface{}) (float64, error) { - numValue := reflect.ValueOf(num) - numKind := numValue.Kind() - - if numKind == reflect.Int || - numKind == reflect.Int8 || - numKind == reflect.Int16 || - numKind == reflect.Int32 || - numKind == reflect.Int64 { - return float64(numValue.Int()), nil - } else if numKind == reflect.Uint || - numKind == reflect.Uint8 || - numKind == reflect.Uint16 || - numKind == reflect.Uint32 || - numKind == reflect.Uint64 { - return float64(numValue.Uint()), nil - } else if numKind == reflect.Float32 || - numKind == reflect.Float64 { - return numValue.Float(), nil - } else { - return 0.0, errors.New("must be a numerical type, but was " + numKind.String()) - } -} - -// ShouldResemble receives exactly two parameters and does a deep equal check (see reflect.DeepEqual) -func ShouldResemble(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } - - if matchError := oglematchers.DeepEquals(expected[0]).Matches(actual); matchError != nil { - expectedSyntax := fmt.Sprintf("%#v", expected[0]) - actualSyntax := fmt.Sprintf("%#v", actual) - var message string - if expectedSyntax == actualSyntax { - message = fmt.Sprintf(shouldHaveResembledTypeMismatch, expected[0], actual, expected[0], actual) - } else { - message = fmt.Sprintf(shouldHaveResembled, expected[0], actual) - } - return serializer.serializeDetailed(expected[0], actual, message) - } - - return success -} - -// ShouldNotResemble receives exactly two parameters and does an inverse deep equal check (see reflect.DeepEqual) -func ShouldNotResemble(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } else if ShouldResemble(actual, expected[0]) == success { - return fmt.Sprintf(shouldNotHaveResembled, actual, expected[0]) - } - return success -} - -// ShouldPointTo receives exactly two parameters and checks to see that they point to the same address. -func ShouldPointTo(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } - return shouldPointTo(actual, expected[0]) - -} -func shouldPointTo(actual, expected interface{}) string { - actualValue := reflect.ValueOf(actual) - expectedValue := reflect.ValueOf(expected) - - if ShouldNotBeNil(actual) != success { - return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "nil") - } else if ShouldNotBeNil(expected) != success { - return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "nil") - } else if actualValue.Kind() != reflect.Ptr { - return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "not") - } else if expectedValue.Kind() != reflect.Ptr { - return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "not") - } else if ShouldEqual(actualValue.Pointer(), expectedValue.Pointer()) != success { - actualAddress := reflect.ValueOf(actual).Pointer() - expectedAddress := reflect.ValueOf(expected).Pointer() - return serializer.serialize(expectedAddress, actualAddress, fmt.Sprintf(shouldHavePointedTo, - actual, actualAddress, - expected, expectedAddress)) - } - return success -} - -// ShouldNotPointTo receives exactly two parameters and checks to see that they point to different addresess. -func ShouldNotPointTo(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } - compare := ShouldPointTo(actual, expected[0]) - if strings.HasPrefix(compare, shouldBePointers) { - return compare - } else if compare == success { - return fmt.Sprintf(shouldNotHavePointedTo, actual, expected[0], reflect.ValueOf(actual).Pointer()) - } - return success -} - -// ShouldBeNil receives a single parameter and ensures that it is nil. -func ShouldBeNil(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } else if actual == nil { - return success - } else if interfaceHasNilValue(actual) { - return success - } - return fmt.Sprintf(shouldHaveBeenNil, actual) -} -func interfaceHasNilValue(actual interface{}) bool { - value := reflect.ValueOf(actual) - kind := value.Kind() - nilable := kind == reflect.Slice || - kind == reflect.Chan || - kind == reflect.Func || - kind == reflect.Ptr || - kind == reflect.Map - - // Careful: reflect.Value.IsNil() will panic unless it's an interface, chan, map, func, slice, or ptr - // Reference: http://golang.org/pkg/reflect/#Value.IsNil - return nilable && value.IsNil() -} - -// ShouldNotBeNil receives a single parameter and ensures that it is not nil. -func ShouldNotBeNil(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } else if ShouldBeNil(actual) == success { - return fmt.Sprintf(shouldNotHaveBeenNil, actual) - } - return success -} - -// ShouldBeTrue receives a single parameter and ensures that it is true. -func ShouldBeTrue(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } else if actual != true { - return fmt.Sprintf(shouldHaveBeenTrue, actual) - } - return success -} - -// ShouldBeFalse receives a single parameter and ensures that it is false. -func ShouldBeFalse(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } else if actual != false { - return fmt.Sprintf(shouldHaveBeenFalse, actual) - } - return success -} - -// ShouldBeZeroValue receives a single parameter and ensures that it is -// the Go equivalent of the default value, or "zero" value. -func ShouldBeZeroValue(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - zeroVal := reflect.Zero(reflect.TypeOf(actual)).Interface() - if !reflect.DeepEqual(zeroVal, actual) { - return serializer.serialize(zeroVal, actual, fmt.Sprintf(shouldHaveBeenZeroValue, actual)) - } - return success -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/equality_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/equality_test.go deleted file mode 100644 index ee39397..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/equality_test.go +++ /dev/null @@ -1,267 +0,0 @@ -package assertions - -import ( - "fmt" - "reflect" - "testing" -) - -func TestShouldEqual(t *testing.T) { - serializer = newFakeSerializer() - - fail(t, so(1, ShouldEqual), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(1, ShouldEqual, 1, 2), "This assertion requires exactly 1 comparison values (you provided 2).") - fail(t, so(1, ShouldEqual, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - pass(t, so(1, ShouldEqual, 1)) - fail(t, so(1, ShouldEqual, 2), "2|1|Expected: '2' Actual: '1' (Should be equal)") - - pass(t, so(true, ShouldEqual, true)) - fail(t, so(true, ShouldEqual, false), "false|true|Expected: 'false' Actual: 'true' (Should be equal)") - - pass(t, so("hi", ShouldEqual, "hi")) - fail(t, so("hi", ShouldEqual, "bye"), "bye|hi|Expected: 'bye' Actual: 'hi' (Should be equal)") - - pass(t, so(42, ShouldEqual, uint(42))) - - fail(t, so(Thing1{"hi"}, ShouldEqual, Thing1{}), "{}|{hi}|Expected: '{}' Actual: '{hi}' (Should be equal)") - fail(t, so(Thing1{"hi"}, ShouldEqual, Thing1{"hi"}), "{hi}|{hi}|Expected: '{hi}' Actual: '{hi}' (Should be equal)") - fail(t, so(&Thing1{"hi"}, ShouldEqual, &Thing1{"hi"}), "&{hi}|&{hi}|Expected: '&{hi}' Actual: '&{hi}' (Should be equal)") - - fail(t, so(Thing1{}, ShouldEqual, Thing2{}), "{}|{}|Expected: '{}' Actual: '{}' (Should be equal)") -} - -func TestShouldNotEqual(t *testing.T) { - fail(t, so(1, ShouldNotEqual), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(1, ShouldNotEqual, 1, 2), "This assertion requires exactly 1 comparison values (you provided 2).") - fail(t, so(1, ShouldNotEqual, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - pass(t, so(1, ShouldNotEqual, 2)) - fail(t, so(1, ShouldNotEqual, 1), "Expected '1' to NOT equal '1' (but it did)!") - - pass(t, so(true, ShouldNotEqual, false)) - fail(t, so(true, ShouldNotEqual, true), "Expected 'true' to NOT equal 'true' (but it did)!") - - pass(t, so("hi", ShouldNotEqual, "bye")) - fail(t, so("hi", ShouldNotEqual, "hi"), "Expected 'hi' to NOT equal 'hi' (but it did)!") - - pass(t, so(&Thing1{"hi"}, ShouldNotEqual, &Thing1{"hi"})) - pass(t, so(Thing1{"hi"}, ShouldNotEqual, Thing1{"hi"})) - pass(t, so(Thing1{}, ShouldNotEqual, Thing1{})) - pass(t, so(Thing1{}, ShouldNotEqual, Thing2{})) -} - -func TestShouldAlmostEqual(t *testing.T) { - fail(t, so(1, ShouldAlmostEqual), "This assertion requires exactly one comparison value and an optional delta (you provided neither)") - fail(t, so(1, ShouldAlmostEqual, 1, 2, 3), "This assertion requires exactly one comparison value and an optional delta (you provided more values)") - - // with the default delta - pass(t, so(1, ShouldAlmostEqual, .99999999999999)) - pass(t, so(1.3612499999999996, ShouldAlmostEqual, 1.36125)) - pass(t, so(0.7285312499999999, ShouldAlmostEqual, 0.72853125)) - fail(t, so(1, ShouldAlmostEqual, .99), "Expected '1' to almost equal '0.99' (but it didn't)!") - - // with a different delta - pass(t, so(100.0, ShouldAlmostEqual, 110.0, 10.0)) - fail(t, so(100.0, ShouldAlmostEqual, 111.0, 10.5), "Expected '100' to almost equal '111' (but it didn't)!") - - // ints should work - pass(t, so(100, ShouldAlmostEqual, 100.0)) - fail(t, so(100, ShouldAlmostEqual, 99.0), "Expected '100' to almost equal '99' (but it didn't)!") - - // float32 should work - pass(t, so(float64(100.0), ShouldAlmostEqual, float32(100.0))) - fail(t, so(float32(100.0), ShouldAlmostEqual, 99.0, float32(0.1)), "Expected '100' to almost equal '99' (but it didn't)!") -} - -func TestShouldNotAlmostEqual(t *testing.T) { - fail(t, so(1, ShouldNotAlmostEqual), "This assertion requires exactly one comparison value and an optional delta (you provided neither)") - fail(t, so(1, ShouldNotAlmostEqual, 1, 2, 3), "This assertion requires exactly one comparison value and an optional delta (you provided more values)") - - // with the default delta - fail(t, so(1, ShouldNotAlmostEqual, .99999999999999), "Expected '1' to NOT almost equal '0.99999999999999' (but it did)!") - fail(t, so(1.3612499999999996, ShouldNotAlmostEqual, 1.36125), "Expected '1.3612499999999996' to NOT almost equal '1.36125' (but it did)!") - pass(t, so(1, ShouldNotAlmostEqual, .99)) - - // with a different delta - fail(t, so(100.0, ShouldNotAlmostEqual, 110.0, 10.0), "Expected '100' to NOT almost equal '110' (but it did)!") - pass(t, so(100.0, ShouldNotAlmostEqual, 111.0, 10.5)) - - // ints should work - fail(t, so(100, ShouldNotAlmostEqual, 100.0), "Expected '100' to NOT almost equal '100' (but it did)!") - pass(t, so(100, ShouldNotAlmostEqual, 99.0)) - - // float32 should work - fail(t, so(float64(100.0), ShouldNotAlmostEqual, float32(100.0)), "Expected '100' to NOT almost equal '100' (but it did)!") - pass(t, so(float32(100.0), ShouldNotAlmostEqual, 99.0, float32(0.1))) -} - -func TestShouldResemble(t *testing.T) { - serializer = newFakeSerializer() - - fail(t, so(Thing1{"hi"}, ShouldResemble), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(Thing1{"hi"}, ShouldResemble, Thing1{"hi"}, Thing1{"hi"}), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so(Thing1{"hi"}, ShouldResemble, Thing1{"hi"})) - fail(t, so(Thing1{"hi"}, ShouldResemble, Thing1{"bye"}), "{bye}|{hi}|Expected: 'assertions.Thing1{a:\"bye\"}' Actual: 'assertions.Thing1{a:\"hi\"}' (Should resemble)!") - - var ( - a []int - b []int = []int{} - ) - - fail(t, so(a, ShouldResemble, b), "[]|[]|Expected: '[]int{}' Actual: '[]int(nil)' (Should resemble)!") - fail(t, so(2, ShouldResemble, 1), "1|2|Expected: '1' Actual: '2' (Should resemble)!") - - fail(t, so(StringStringMapAlias{"hi": "bye"}, ShouldResemble, map[string]string{"hi": "bye"}), - "map[hi:bye]|map[hi:bye]|Expected: 'map[string]string{\"hi\":\"bye\"}' Actual: 'assertions.StringStringMapAlias{\"hi\":\"bye\"}' (Should resemble)!") - fail(t, so(StringSliceAlias{"hi", "bye"}, ShouldResemble, []string{"hi", "bye"}), - "[hi bye]|[hi bye]|Expected: '[]string{\"hi\", \"bye\"}' Actual: 'assertions.StringSliceAlias{\"hi\", \"bye\"}' (Should resemble)!") - - // some types come out looking the same when represented with "%#v" so we show type mismatch info: - fail(t, so(StringAlias("hi"), ShouldResemble, "hi"), "hi|hi|Expected: '\"hi\"' Actual: '\"hi\"' (Type mismatch: 'string' vs 'assertions.StringAlias')!") - fail(t, so(IntAlias(42), ShouldResemble, 42), "42|42|Expected: '42' Actual: '42' (Type mismatch: 'int' vs 'assertions.IntAlias')!") -} - -func TestShouldNotResemble(t *testing.T) { - fail(t, so(Thing1{"hi"}, ShouldNotResemble), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(Thing1{"hi"}, ShouldNotResemble, Thing1{"hi"}, Thing1{"hi"}), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so(Thing1{"hi"}, ShouldNotResemble, Thing1{"bye"})) - fail(t, so(Thing1{"hi"}, ShouldNotResemble, Thing1{"hi"}), - "Expected 'assertions.Thing1{a:\"hi\"}' to NOT resemble 'assertions.Thing1{a:\"hi\"}' (but it did)!") - - pass(t, so(map[string]string{"hi": "bye"}, ShouldResemble, map[string]string{"hi": "bye"})) - pass(t, so(IntAlias(42), ShouldNotResemble, 42)) - - pass(t, so(StringSliceAlias{"hi", "bye"}, ShouldNotResemble, []string{"hi", "bye"})) -} - -func TestShouldPointTo(t *testing.T) { - serializer = newFakeSerializer() - - t1 := &Thing1{} - t2 := t1 - t3 := &Thing1{} - - pointer1 := reflect.ValueOf(t1).Pointer() - pointer3 := reflect.ValueOf(t3).Pointer() - - fail(t, so(t1, ShouldPointTo), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(t1, ShouldPointTo, t2, t3), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so(t1, ShouldPointTo, t2)) - fail(t, so(t1, ShouldPointTo, t3), fmt.Sprintf( - "%v|%v|Expected '&{a:}' (address: '%v') and '&{a:}' (address: '%v') to be the same address (but their weren't)!", - pointer3, pointer1, pointer1, pointer3)) - - t4 := Thing1{} - t5 := t4 - - fail(t, so(t4, ShouldPointTo, t5), "Both arguments should be pointers (the first was not)!") - fail(t, so(&t4, ShouldPointTo, t5), "Both arguments should be pointers (the second was not)!") - fail(t, so(nil, ShouldPointTo, nil), "Both arguments should be pointers (the first was nil)!") - fail(t, so(&t4, ShouldPointTo, nil), "Both arguments should be pointers (the second was nil)!") -} - -func TestShouldNotPointTo(t *testing.T) { - t1 := &Thing1{} - t2 := t1 - t3 := &Thing1{} - - pointer1 := reflect.ValueOf(t1).Pointer() - - fail(t, so(t1, ShouldNotPointTo), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(t1, ShouldNotPointTo, t2, t3), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so(t1, ShouldNotPointTo, t3)) - fail(t, so(t1, ShouldNotPointTo, t2), fmt.Sprintf("Expected '&{a:}' and '&{a:}' to be different references (but they matched: '%v')!", pointer1)) - - t4 := Thing1{} - t5 := t4 - - fail(t, so(t4, ShouldNotPointTo, t5), "Both arguments should be pointers (the first was not)!") - fail(t, so(&t4, ShouldNotPointTo, t5), "Both arguments should be pointers (the second was not)!") - fail(t, so(nil, ShouldNotPointTo, nil), "Both arguments should be pointers (the first was nil)!") - fail(t, so(&t4, ShouldNotPointTo, nil), "Both arguments should be pointers (the second was nil)!") -} - -func TestShouldBeNil(t *testing.T) { - fail(t, so(nil, ShouldBeNil, nil, nil, nil), "This assertion requires exactly 0 comparison values (you provided 3).") - fail(t, so(nil, ShouldBeNil, nil), "This assertion requires exactly 0 comparison values (you provided 1).") - - pass(t, so(nil, ShouldBeNil)) - fail(t, so(1, ShouldBeNil), "Expected: nil Actual: '1'") - - var thing Thinger - pass(t, so(thing, ShouldBeNil)) - thing = &Thing{} - fail(t, so(thing, ShouldBeNil), "Expected: nil Actual: '&{}'") - - var thingOne *Thing1 - pass(t, so(thingOne, ShouldBeNil)) - - var nilSlice []int = nil - pass(t, so(nilSlice, ShouldBeNil)) - - var nilMap map[string]string = nil - pass(t, so(nilMap, ShouldBeNil)) - - var nilChannel chan int = nil - pass(t, so(nilChannel, ShouldBeNil)) - - var nilFunc func() = nil - pass(t, so(nilFunc, ShouldBeNil)) - - var nilInterface interface{} = nil - pass(t, so(nilInterface, ShouldBeNil)) -} - -func TestShouldNotBeNil(t *testing.T) { - fail(t, so(nil, ShouldNotBeNil, nil, nil, nil), "This assertion requires exactly 0 comparison values (you provided 3).") - fail(t, so(nil, ShouldNotBeNil, nil), "This assertion requires exactly 0 comparison values (you provided 1).") - - fail(t, so(nil, ShouldNotBeNil), "Expected '' to NOT be nil (but it was)!") - pass(t, so(1, ShouldNotBeNil)) - - var thing Thinger - fail(t, so(thing, ShouldNotBeNil), "Expected '' to NOT be nil (but it was)!") - thing = &Thing{} - pass(t, so(thing, ShouldNotBeNil)) -} - -func TestShouldBeTrue(t *testing.T) { - fail(t, so(true, ShouldBeTrue, 1, 2, 3), "This assertion requires exactly 0 comparison values (you provided 3).") - fail(t, so(true, ShouldBeTrue, 1), "This assertion requires exactly 0 comparison values (you provided 1).") - - fail(t, so(false, ShouldBeTrue), "Expected: true Actual: false") - fail(t, so(1, ShouldBeTrue), "Expected: true Actual: 1") - pass(t, so(true, ShouldBeTrue)) -} - -func TestShouldBeFalse(t *testing.T) { - fail(t, so(false, ShouldBeFalse, 1, 2, 3), "This assertion requires exactly 0 comparison values (you provided 3).") - fail(t, so(false, ShouldBeFalse, 1), "This assertion requires exactly 0 comparison values (you provided 1).") - - fail(t, so(true, ShouldBeFalse), "Expected: false Actual: true") - fail(t, so(1, ShouldBeFalse), "Expected: false Actual: 1") - pass(t, so(false, ShouldBeFalse)) -} - -func TestShouldBeZeroValue(t *testing.T) { - serializer = newFakeSerializer() - - fail(t, so(0, ShouldBeZeroValue, 1, 2, 3), "This assertion requires exactly 0 comparison values (you provided 3).") - fail(t, so(false, ShouldBeZeroValue, true), "This assertion requires exactly 0 comparison values (you provided 1).") - - fail(t, so(1, ShouldBeZeroValue), "0|1|'1' should have been the zero value") //"Expected: (zero value) Actual: 1") - fail(t, so(true, ShouldBeZeroValue), "false|true|'true' should have been the zero value") //"Expected: (zero value) Actual: true") - fail(t, so("123", ShouldBeZeroValue), "|123|'123' should have been the zero value") //"Expected: (zero value) Actual: 123") - fail(t, so(" ", ShouldBeZeroValue), "| |' ' should have been the zero value") //"Expected: (zero value) Actual: ") - fail(t, so([]string{"Nonempty"}, ShouldBeZeroValue), "[]|[Nonempty]|'[Nonempty]' should have been the zero value") //"Expected: (zero value) Actual: [Nonempty]") - fail(t, so(struct{ a string }{a: "asdf"}, ShouldBeZeroValue), "{}|{asdf}|'{a:asdf}' should have been the zero value") - pass(t, so(0, ShouldBeZeroValue)) - pass(t, so(false, ShouldBeZeroValue)) - pass(t, so("", ShouldBeZeroValue)) - pass(t, so(struct{}{}, ShouldBeZeroValue)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/filter.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/filter.go deleted file mode 100644 index ee368a9..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/filter.go +++ /dev/null @@ -1,23 +0,0 @@ -package assertions - -import "fmt" - -const ( - success = "" - needExactValues = "This assertion requires exactly %d comparison values (you provided %d)." - needNonEmptyCollection = "This assertion requires at least 1 comparison value (you provided 0)." -) - -func need(needed int, expected []interface{}) string { - if len(expected) != needed { - return fmt.Sprintf(needExactValues, needed, len(expected)) - } - return success -} - -func atLeast(minimum int, expected []interface{}) string { - if len(expected) < 1 { - return needNonEmptyCollection - } - return success -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/.gitignore b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/.gitignore deleted file mode 100644 index dd8fc74..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.6 -6.out -_obj/ -_test/ -_testmain.go diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/LICENSE b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/LICENSE deleted file mode 100644 index d645695..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/README.markdown b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/README.markdown deleted file mode 100644 index 7b2524f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/README.markdown +++ /dev/null @@ -1,56 +0,0 @@ -`oglematchers` is a package for the Go programming language containing a set of -matchers, useful in a testing or mocking framework, inspired by and mostly -compatible with [Google Test][googletest] for C++ and -[Google JS Test][google-js-test]. The package is used by the -[ogletest][ogletest] testing framework and [oglemock][oglemock] mocking -framework, which may be more directly useful to you, but can be generically used -elsewhere as well. - -A "matcher" is simply an object with a `Matches` method defining a set of golang -values matched by the matcher, and a `Description` method describing that set. -For example, here are some matchers: - -```go -// Numbers -Equals(17.13) -LessThan(19) - -// Strings -Equals("taco") -HasSubstr("burrito") -MatchesRegex("t.*o") - -// Combining matchers -AnyOf(LessThan(17), GreaterThan(19)) -``` - -There are lots more; see [here][reference] for a reference. You can also add -your own simply by implementing the `oglematchers.Matcher` interface. - - -Installation ------------- - -First, make sure you have installed Go 1.0.2 or newer. See -[here][golang-install] for instructions. - -Use the following command to install `oglematchers` and keep it up to date: - - go get -u github.com/smartystreets/assertions/internal/oglematchers - - -Documentation -------------- - -See [here][reference] for documentation hosted on GoPkgDoc. Alternatively, you -can install the package and then use `go doc`: - - go doc github.com/smartystreets/assertions/internal/oglematchers - - -[reference]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/assertions/internal/oglematchers -[golang-install]: http://golang.org/doc/install.html -[googletest]: http://code.google.com/p/googletest/ -[google-js-test]: http://code.google.com/p/google-js-test/ -[ogletest]: http://github.com/smartystreets/assertions/internal/ogletest -[oglemock]: http://github.com/smartystreets/assertions/internal/oglemock diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/all_of.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/all_of.go deleted file mode 100644 index d93a974..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/all_of.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "strings" -) - -// AllOf accepts a set of matchers S and returns a matcher that follows the -// algorithm below when considering a candidate c: -// -// 1. Return true if for every Matcher m in S, m matches c. -// -// 2. Otherwise, if there is a matcher m in S such that m returns a fatal -// error for c, return that matcher's error message. -// -// 3. Otherwise, return false with the error from some wrapped matcher. -// -// This is akin to a logical AND operation for matchers. -func AllOf(matchers ...Matcher) Matcher { - return &allOfMatcher{matchers} -} - -type allOfMatcher struct { - wrappedMatchers []Matcher -} - -func (m *allOfMatcher) Description() string { - // Special case: the empty set. - if len(m.wrappedMatchers) == 0 { - return "is anything" - } - - // Join the descriptions for the wrapped matchers. - wrappedDescs := make([]string, len(m.wrappedMatchers)) - for i, wrappedMatcher := range m.wrappedMatchers { - wrappedDescs[i] = wrappedMatcher.Description() - } - - return strings.Join(wrappedDescs, ", and ") -} - -func (m *allOfMatcher) Matches(c interface{}) (err error) { - for _, wrappedMatcher := range m.wrappedMatchers { - if wrappedErr := wrappedMatcher.Matches(c); wrappedErr != nil { - err = wrappedErr - - // If the error is fatal, return immediately with this error. - _, ok := wrappedErr.(*FatalError) - if ok { - return - } - } - } - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/all_of_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/all_of_test.go deleted file mode 100644 index 259e5a8..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/all_of_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "errors" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type allOfFakeMatcher struct { - desc string - err error -} - -func (m *allOfFakeMatcher) Matches(c interface{}) error { - return m.err -} - -func (m *allOfFakeMatcher) Description() string { - return m.desc -} - -type AllOfTest struct { -} - -func init() { RegisterTestSuite(&AllOfTest{}) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *AllOfTest) DescriptionWithEmptySet() { - m := AllOf() - ExpectEq("is anything", m.Description()) -} - -func (t *AllOfTest) DescriptionWithOneMatcher() { - m := AllOf(&allOfFakeMatcher{"taco", errors.New("")}) - ExpectEq("taco", m.Description()) -} - -func (t *AllOfTest) DescriptionWithMultipleMatchers() { - m := AllOf( - &allOfFakeMatcher{"taco", errors.New("")}, - &allOfFakeMatcher{"burrito", errors.New("")}, - &allOfFakeMatcher{"enchilada", errors.New("")}) - - ExpectEq("taco, and burrito, and enchilada", m.Description()) -} - -func (t *AllOfTest) EmptySet() { - m := AllOf() - err := m.Matches(17) - - ExpectEq(nil, err) -} - -func (t *AllOfTest) OneMatcherReturnsFatalErrorAndSomeOthersFail() { - m := AllOf( - &allOfFakeMatcher{"", errors.New("")}, - &allOfFakeMatcher{"", NewFatalError("taco")}, - &allOfFakeMatcher{"", errors.New("")}, - &allOfFakeMatcher{"", nil}) - - err := m.Matches(17) - - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("taco"))) -} - -func (t *AllOfTest) OneMatcherReturnsNonFatalAndOthersSayTrue() { - m := AllOf( - &allOfFakeMatcher{"", nil}, - &allOfFakeMatcher{"", errors.New("taco")}, - &allOfFakeMatcher{"", nil}) - - err := m.Matches(17) - - ExpectFalse(isFatal(err)) - ExpectThat(err, Error(Equals("taco"))) -} - -func (t *AllOfTest) AllMatchersSayTrue() { - m := AllOf( - &allOfFakeMatcher{"", nil}, - &allOfFakeMatcher{"", nil}, - &allOfFakeMatcher{"", nil}) - - err := m.Matches(17) - - ExpectEq(nil, err) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any.go deleted file mode 100644 index f6991ec..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -// Any returns a matcher that matches any value. -func Any() Matcher { - return &anyMatcher{} -} - -type anyMatcher struct { -} - -func (m *anyMatcher) Description() string { - return "is anything" -} - -func (m *anyMatcher) Matches(c interface{}) error { - return nil -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any_of.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any_of.go deleted file mode 100644 index 080643a..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any_of.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" - "strings" -) - -// AnyOf accepts a set of values S and returns a matcher that follows the -// algorithm below when considering a candidate c: -// -// 1. If there exists a value m in S such that m implements the Matcher -// interface and m matches c, return true. -// -// 2. Otherwise, if there exists a value v in S such that v does not implement -// the Matcher interface and the matcher Equals(v) matches c, return true. -// -// 3. Otherwise, if there is a value m in S such that m implements the Matcher -// interface and m returns a fatal error for c, return that fatal error. -// -// 4. Otherwise, return false. -// -// This is akin to a logical OR operation for matchers, with non-matchers x -// being treated as Equals(x). -func AnyOf(vals ...interface{}) Matcher { - // Get ahold of a type variable for the Matcher interface. - var dummy *Matcher - matcherType := reflect.TypeOf(dummy).Elem() - - // Create a matcher for each value, or use the value itself if it's already a - // matcher. - wrapped := make([]Matcher, len(vals)) - for i, v := range vals { - if reflect.TypeOf(v).Implements(matcherType) { - wrapped[i] = v.(Matcher) - } else { - wrapped[i] = Equals(v) - } - } - - return &anyOfMatcher{wrapped} -} - -type anyOfMatcher struct { - wrapped []Matcher -} - -func (m *anyOfMatcher) Description() string { - wrappedDescs := make([]string, len(m.wrapped)) - for i, matcher := range m.wrapped { - wrappedDescs[i] = matcher.Description() - } - - return fmt.Sprintf("or(%s)", strings.Join(wrappedDescs, ", ")) -} - -func (m *anyOfMatcher) Matches(c interface{}) (err error) { - err = errors.New("") - - // Try each matcher in turn. - for _, matcher := range m.wrapped { - wrappedErr := matcher.Matches(c) - - // Return immediately if there's a match. - if wrappedErr == nil { - err = nil - return - } - - // Note the fatal error, if any. - if _, isFatal := wrappedErr.(*FatalError); isFatal { - err = wrappedErr - } - } - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any_of_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any_of_test.go deleted file mode 100644 index 0c41062..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any_of_test.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "errors" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type fakeAnyOfMatcher struct { - desc string - err error -} - -func (m *fakeAnyOfMatcher) Matches(c interface{}) error { - return m.err -} - -func (m *fakeAnyOfMatcher) Description() string { - return m.desc -} - -type AnyOfTest struct { -} - -func init() { RegisterTestSuite(&AnyOfTest{}) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *AnyOfTest) EmptySet() { - matcher := AnyOf() - - err := matcher.Matches(0) - ExpectThat(err, Error(Equals(""))) -} - -func (t *AnyOfTest) OneTrue() { - matcher := AnyOf( - &fakeAnyOfMatcher{"", NewFatalError("foo")}, - 17, - &fakeAnyOfMatcher{"", errors.New("foo")}, - &fakeAnyOfMatcher{"", nil}, - &fakeAnyOfMatcher{"", errors.New("foo")}, - ) - - err := matcher.Matches(0) - ExpectEq(nil, err) -} - -func (t *AnyOfTest) OneEqual() { - matcher := AnyOf( - &fakeAnyOfMatcher{"", NewFatalError("foo")}, - &fakeAnyOfMatcher{"", errors.New("foo")}, - 13, - "taco", - 19, - &fakeAnyOfMatcher{"", errors.New("foo")}, - ) - - err := matcher.Matches("taco") - ExpectEq(nil, err) -} - -func (t *AnyOfTest) OneFatal() { - matcher := AnyOf( - &fakeAnyOfMatcher{"", errors.New("foo")}, - 17, - &fakeAnyOfMatcher{"", NewFatalError("taco")}, - &fakeAnyOfMatcher{"", errors.New("foo")}, - ) - - err := matcher.Matches(0) - ExpectThat(err, Error(Equals("taco"))) -} - -func (t *AnyOfTest) AllFalseAndNotEqual() { - matcher := AnyOf( - &fakeAnyOfMatcher{"", errors.New("foo")}, - 17, - &fakeAnyOfMatcher{"", errors.New("foo")}, - 19, - ) - - err := matcher.Matches(0) - ExpectThat(err, Error(Equals(""))) -} - -func (t *AnyOfTest) DescriptionForEmptySet() { - matcher := AnyOf() - ExpectEq("or()", matcher.Description()) -} - -func (t *AnyOfTest) DescriptionForNonEmptySet() { - matcher := AnyOf( - &fakeAnyOfMatcher{"taco", nil}, - "burrito", - &fakeAnyOfMatcher{"enchilada", nil}, - ) - - ExpectEq("or(taco, burrito, enchilada)", matcher.Description()) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any_test.go deleted file mode 100644 index c0cda0a..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/any_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type AnyTest struct { -} - -func init() { RegisterTestSuite(&AnyTest{}) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *AnyTest) Description() { - m := Any() - ExpectEq("is anything", m.Description()) -} - -func (t *AnyTest) Matches() { - var err error - m := Any() - - err = m.Matches(nil) - ExpectEq(nil, err) - - err = m.Matches(17) - ExpectEq(nil, err) - - err = m.Matches("taco") - ExpectEq(nil, err) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/contains.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/contains.go deleted file mode 100644 index 2f326db..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/contains.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "fmt" - "reflect" -) - -// Return a matcher that matches arrays slices with at least one element that -// matches the supplied argument. If the argument x is not itself a Matcher, -// this is equivalent to Contains(Equals(x)). -func Contains(x interface{}) Matcher { - var result containsMatcher - var ok bool - - if result.elementMatcher, ok = x.(Matcher); !ok { - result.elementMatcher = Equals(x) - } - - return &result -} - -type containsMatcher struct { - elementMatcher Matcher -} - -func (m *containsMatcher) Description() string { - return fmt.Sprintf("contains: %s", m.elementMatcher.Description()) -} - -func (m *containsMatcher) Matches(candidate interface{}) error { - // The candidate must be a slice or an array. - v := reflect.ValueOf(candidate) - if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { - return NewFatalError("which is not a slice or array") - } - - // Check each element. - for i := 0; i < v.Len(); i++ { - elem := v.Index(i) - if matchErr := m.elementMatcher.Matches(elem.Interface()); matchErr == nil { - return nil - } - } - - return fmt.Errorf("") -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/contains_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/contains_test.go deleted file mode 100644 index 92f5d0f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/contains_test.go +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type ContainsTest struct{} - -func init() { RegisterTestSuite(&ContainsTest{}) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *ContainsTest) WrongTypeCandidates() { - m := Contains("") - ExpectEq("contains: ", m.Description()) - - var err error - - // Nil candidate - err = m.Matches(nil) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("array"))) - ExpectThat(err, Error(HasSubstr("slice"))) - - // String candidate - err = m.Matches("") - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("array"))) - ExpectThat(err, Error(HasSubstr("slice"))) - - // Map candidate - err = m.Matches(make(map[string]string)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("array"))) - ExpectThat(err, Error(HasSubstr("slice"))) -} - -func (t *ContainsTest) NilArgument() { - m := Contains(nil) - ExpectEq("contains: is nil", m.Description()) - - var c interface{} - var err error - - // Empty array of pointers - c = [...]*int{} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Empty slice of pointers - c = []*int{} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Non-empty array of integers - c = [...]int{17, 0, 19} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Non-empty slice of integers - c = []int{17, 0, 19} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Non-matching array of pointers - c = [...]*int{new(int), new(int)} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Non-matching slice of pointers - c = []*int{new(int), new(int)} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Matching array of pointers - c = [...]*int{new(int), nil, new(int)} - err = m.Matches(c) - ExpectEq(nil, err) - - // Matching slice of pointers - c = []*int{new(int), nil, new(int)} - err = m.Matches(c) - ExpectEq(nil, err) - - // Non-matching slice of pointers from matching array - someArray := [...]*int{new(int), nil, new(int)} - c = someArray[0:1] - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) -} - -func (t *ContainsTest) StringArgument() { - m := Contains("taco") - ExpectEq("contains: taco", m.Description()) - - var c interface{} - var err error - - // Non-matching array of strings - c = [...]string{"burrito", "enchilada"} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Non-matching slice of strings - c = []string{"burrito", "enchilada"} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Matching array of strings - c = [...]string{"burrito", "taco", "enchilada"} - err = m.Matches(c) - ExpectEq(nil, err) - - // Matching slice of strings - c = []string{"burrito", "taco", "enchilada"} - err = m.Matches(c) - ExpectEq(nil, err) - - // Non-matching slice of strings from matching array - someArray := [...]string{"burrito", "taco", "enchilada"} - c = someArray[0:1] - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) -} - -func (t *ContainsTest) IntegerArgument() { - m := Contains(int(17)) - ExpectEq("contains: 17", m.Description()) - - var c interface{} - var err error - - // Non-matching array of integers - c = [...]int{13, 19} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Non-matching slice of integers - c = []int{13, 19} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Matching array of integers - c = [...]int{13, 17, 19} - err = m.Matches(c) - ExpectEq(nil, err) - - // Matching slice of integers - c = []int{13, 17, 19} - err = m.Matches(c) - ExpectEq(nil, err) - - // Non-matching slice of integers from matching array - someArray := [...]int{13, 17, 19} - c = someArray[0:1] - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Non-matching array of floats - c = [...]float32{13, 17.5, 19} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Non-matching slice of floats - c = []float32{13, 17.5, 19} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Matching array of floats - c = [...]float32{13, 17, 19} - err = m.Matches(c) - ExpectEq(nil, err) - - // Matching slice of floats - c = []float32{13, 17, 19} - err = m.Matches(c) - ExpectEq(nil, err) -} - -func (t *ContainsTest) MatcherArgument() { - m := Contains(HasSubstr("ac")) - ExpectEq("contains: has substring \"ac\"", m.Description()) - - var c interface{} - var err error - - // Non-matching array of strings - c = [...]string{"burrito", "enchilada"} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Non-matching slice of strings - c = []string{"burrito", "enchilada"} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Matching array of strings - c = [...]string{"burrito", "taco", "enchilada"} - err = m.Matches(c) - ExpectEq(nil, err) - - // Matching slice of strings - c = []string{"burrito", "taco", "enchilada"} - err = m.Matches(c) - ExpectEq(nil, err) - - // Non-matching slice of strings from matching array - someArray := [...]string{"burrito", "taco", "enchilada"} - c = someArray[0:1] - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go deleted file mode 100644 index 1d91bae..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "bytes" - "errors" - "fmt" - "reflect" -) - -var byteSliceType reflect.Type = reflect.TypeOf([]byte{}) - -// DeepEquals returns a matcher that matches based on 'deep equality', as -// defined by the reflect package. This matcher requires that values have -// identical types to x. -func DeepEquals(x interface{}) Matcher { - return &deepEqualsMatcher{x} -} - -type deepEqualsMatcher struct { - x interface{} -} - -func (m *deepEqualsMatcher) Description() string { - xDesc := fmt.Sprintf("%v", m.x) - xValue := reflect.ValueOf(m.x) - - // Special case: fmt.Sprintf presents nil slices as "[]", but - // reflect.DeepEqual makes a distinction between nil and empty slices. Make - // this less confusing. - if xValue.Kind() == reflect.Slice && xValue.IsNil() { - xDesc = "" - } - - return fmt.Sprintf("deep equals: %s", xDesc) -} - -func (m *deepEqualsMatcher) Matches(c interface{}) error { - // Make sure the types match. - ct := reflect.TypeOf(c) - xt := reflect.TypeOf(m.x) - - if ct != xt { - return NewFatalError(fmt.Sprintf("which is of type %v", ct)) - } - - // Special case: handle byte slices more efficiently. - cValue := reflect.ValueOf(c) - xValue := reflect.ValueOf(m.x) - - if ct == byteSliceType && !cValue.IsNil() && !xValue.IsNil() { - xBytes := m.x.([]byte) - cBytes := c.([]byte) - - if bytes.Equal(cBytes, xBytes) { - return nil - } - - return errors.New("") - } - - // Defer to the reflect package. - if reflect.DeepEqual(m.x, c) { - return nil - } - - // Special case: if the comparison failed because c is the nil slice, given - // an indication of this (since its value is printed as "[]"). - if cValue.Kind() == reflect.Slice && cValue.IsNil() { - return errors.New("which is nil") - } - - return errors.New("") -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/deep_equals_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/deep_equals_test.go deleted file mode 100644 index 0ff12a2..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/deep_equals_test.go +++ /dev/null @@ -1,345 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "bytes" - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type DeepEqualsTest struct{} - -func init() { RegisterTestSuite(&DeepEqualsTest{}) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *DeepEqualsTest) WrongTypeCandidateWithScalarValue() { - var x int = 17 - m := DeepEquals(x) - - var err error - - // Nil candidate. - err = m.Matches(nil) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr(""))) - - // Int alias candidate. - type intAlias int - err = m.Matches(intAlias(x)) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("intAlias"))) - - // String candidate. - err = m.Matches("taco") - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("string"))) - - // Byte slice candidate. - err = m.Matches([]byte{}) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("[]uint8"))) - - // Other slice candidate. - err = m.Matches([]uint16{}) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("[]uint16"))) - - // Unsigned int candidate. - err = m.Matches(uint(17)) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("uint"))) -} - -func (t *DeepEqualsTest) WrongTypeCandidateWithByteSliceValue() { - x := []byte{} - m := DeepEquals(x) - - var err error - - // Nil candidate. - err = m.Matches(nil) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr(""))) - - // String candidate. - err = m.Matches("taco") - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("string"))) - - // Slice candidate with wrong value type. - err = m.Matches([]uint16{}) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("[]uint16"))) -} - -func (t *DeepEqualsTest) WrongTypeCandidateWithOtherSliceValue() { - x := []uint16{} - m := DeepEquals(x) - - var err error - - // Nil candidate. - err = m.Matches(nil) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr(""))) - - // String candidate. - err = m.Matches("taco") - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("string"))) - - // Byte slice candidate with wrong value type. - err = m.Matches([]byte{}) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("[]uint8"))) - - // Other slice candidate with wrong value type. - err = m.Matches([]uint32{}) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("[]uint32"))) -} - -func (t *DeepEqualsTest) WrongTypeCandidateWithNilLiteralValue() { - m := DeepEquals(nil) - - var err error - - // String candidate. - err = m.Matches("taco") - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("string"))) - - // Nil byte slice candidate. - err = m.Matches([]byte(nil)) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("[]uint8"))) - - // Nil other slice candidate. - err = m.Matches([]uint16(nil)) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("type"))) - ExpectThat(err, Error(HasSubstr("[]uint16"))) -} - -func (t *DeepEqualsTest) NilLiteralValue() { - m := DeepEquals(nil) - ExpectEq("deep equals: ", m.Description()) - - var c interface{} - var err error - - // Nil literal candidate. - c = nil - err = m.Matches(c) - ExpectEq(nil, err) -} - -func (t *DeepEqualsTest) IntValue() { - m := DeepEquals(int(17)) - ExpectEq("deep equals: 17", m.Description()) - - var c interface{} - var err error - - // Matching int. - c = int(17) - err = m.Matches(c) - ExpectEq(nil, err) - - // Non-matching int. - c = int(18) - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) -} - -func (t *DeepEqualsTest) ByteSliceValue() { - x := []byte{17, 19} - m := DeepEquals(x) - ExpectEq("deep equals: [17 19]", m.Description()) - - var c []byte - var err error - - // Matching. - c = make([]byte, len(x)) - AssertEq(len(x), copy(c, x)) - - err = m.Matches(c) - ExpectEq(nil, err) - - // Nil slice. - c = []byte(nil) - err = m.Matches(c) - ExpectThat(err, Error(Equals("which is nil"))) - - // Prefix. - AssertGt(len(x), 1) - c = make([]byte, len(x)-1) - AssertEq(len(x)-1, copy(c, x)) - - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Suffix. - c = make([]byte, len(x)+1) - AssertEq(len(x), copy(c, x)) - - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) -} - -func (t *DeepEqualsTest) OtherSliceValue() { - x := []uint16{17, 19} - m := DeepEquals(x) - ExpectEq("deep equals: [17 19]", m.Description()) - - var c []uint16 - var err error - - // Matching. - c = make([]uint16, len(x)) - AssertEq(len(x), copy(c, x)) - - err = m.Matches(c) - ExpectEq(nil, err) - - // Nil slice. - c = []uint16(nil) - err = m.Matches(c) - ExpectThat(err, Error(Equals("which is nil"))) - - // Prefix. - AssertGt(len(x), 1) - c = make([]uint16, len(x)-1) - AssertEq(len(x)-1, copy(c, x)) - - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) - - // Suffix. - c = make([]uint16, len(x)+1) - AssertEq(len(x), copy(c, x)) - - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) -} - -func (t *DeepEqualsTest) NilByteSliceValue() { - x := []byte(nil) - m := DeepEquals(x) - ExpectEq("deep equals: ", m.Description()) - - var c []byte - var err error - - // Nil slice. - c = []byte(nil) - err = m.Matches(c) - ExpectEq(nil, err) - - // Non-nil slice. - c = []byte{} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) -} - -func (t *DeepEqualsTest) NilOtherSliceValue() { - x := []uint16(nil) - m := DeepEquals(x) - ExpectEq("deep equals: ", m.Description()) - - var c []uint16 - var err error - - // Nil slice. - c = []uint16(nil) - err = m.Matches(c) - ExpectEq(nil, err) - - // Non-nil slice. - c = []uint16{} - err = m.Matches(c) - ExpectThat(err, Error(Equals(""))) -} - -//////////////////////////////////////////////////////////////////////// -// Benchmarks -//////////////////////////////////////////////////////////////////////// - -func benchmarkWithSize(b *testing.B, size int) { - b.StopTimer() - buf := bytes.Repeat([]byte{0x01}, size) - bufCopy := make([]byte, size) - copy(bufCopy, buf) - - matcher := DeepEquals(buf) - b.StartTimer() - - for i := 0; i < b.N; i++ { - matcher.Matches(bufCopy) - } - - b.SetBytes(int64(size)) -} - -func BenchmarkShortByteSlice(b *testing.B) { - benchmarkWithSize(b, 256) -} - -func BenchmarkLongByteSlice(b *testing.B) { - benchmarkWithSize(b, 1<<24) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/elements_are.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/elements_are.go deleted file mode 100644 index 2941847..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/elements_are.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" - "strings" -) - -// Given a list of arguments M, ElementsAre returns a matcher that matches -// arrays and slices A where all of the following hold: -// -// * A is the same length as M. -// -// * For each i < len(A) where M[i] is a matcher, A[i] matches M[i]. -// -// * For each i < len(A) where M[i] is not a matcher, A[i] matches -// Equals(M[i]). -// -func ElementsAre(M ...interface{}) Matcher { - // Copy over matchers, or convert to Equals(x) for non-matcher x. - subMatchers := make([]Matcher, len(M)) - for i, x := range M { - if matcher, ok := x.(Matcher); ok { - subMatchers[i] = matcher - continue - } - - subMatchers[i] = Equals(x) - } - - return &elementsAreMatcher{subMatchers} -} - -type elementsAreMatcher struct { - subMatchers []Matcher -} - -func (m *elementsAreMatcher) Description() string { - subDescs := make([]string, len(m.subMatchers)) - for i, sm := range m.subMatchers { - subDescs[i] = sm.Description() - } - - return fmt.Sprintf("elements are: [%s]", strings.Join(subDescs, ", ")) -} - -func (m *elementsAreMatcher) Matches(candidates interface{}) error { - // The candidate must be a slice or an array. - v := reflect.ValueOf(candidates) - if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { - return NewFatalError("which is not a slice or array") - } - - // The length must be correct. - if v.Len() != len(m.subMatchers) { - return errors.New(fmt.Sprintf("which is of length %d", v.Len())) - } - - // Check each element. - for i, subMatcher := range m.subMatchers { - c := v.Index(i) - if matchErr := subMatcher.Matches(c.Interface()); matchErr != nil { - // Return an errors indicating which element doesn't match. If the - // matcher error was fatal, make this one fatal too. - err := errors.New(fmt.Sprintf("whose element %d doesn't match", i)) - if _, isFatal := matchErr.(*FatalError); isFatal { - err = NewFatalError(err.Error()) - } - - return err - } - } - - return nil -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/elements_are_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/elements_are_test.go deleted file mode 100644 index 8dd2c64..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/elements_are_test.go +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type ElementsAreTest struct { -} - -func init() { RegisterTestSuite(&ElementsAreTest{}) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *ElementsAreTest) EmptySet() { - m := ElementsAre() - ExpectEq("elements are: []", m.Description()) - - var c []interface{} - var err error - - // No candidates. - c = []interface{}{} - err = m.Matches(c) - ExpectEq(nil, err) - - // One candidate. - c = []interface{}{17} - err = m.Matches(c) - ExpectThat(err, Error(HasSubstr("length 1"))) -} - -func (t *ElementsAreTest) OneMatcher() { - m := ElementsAre(LessThan(17)) - ExpectEq("elements are: [less than 17]", m.Description()) - - var c []interface{} - var err error - - // No candidates. - c = []interface{}{} - err = m.Matches(c) - ExpectThat(err, Error(HasSubstr("length 0"))) - - // Matching candidate. - c = []interface{}{16} - err = m.Matches(c) - ExpectEq(nil, err) - - // Non-matching candidate. - c = []interface{}{19} - err = m.Matches(c) - ExpectNe(nil, err) - - // Two candidates. - c = []interface{}{17, 19} - err = m.Matches(c) - ExpectThat(err, Error(HasSubstr("length 2"))) -} - -func (t *ElementsAreTest) OneValue() { - m := ElementsAre(17) - ExpectEq("elements are: [17]", m.Description()) - - var c []interface{} - var err error - - // No candidates. - c = []interface{}{} - err = m.Matches(c) - ExpectThat(err, Error(HasSubstr("length 0"))) - - // Matching int. - c = []interface{}{int(17)} - err = m.Matches(c) - ExpectEq(nil, err) - - // Matching float. - c = []interface{}{float32(17)} - err = m.Matches(c) - ExpectEq(nil, err) - - // Non-matching candidate. - c = []interface{}{19} - err = m.Matches(c) - ExpectNe(nil, err) - - // Two candidates. - c = []interface{}{17, 19} - err = m.Matches(c) - ExpectThat(err, Error(HasSubstr("length 2"))) -} - -func (t *ElementsAreTest) MultipleElements() { - m := ElementsAre("taco", LessThan(17)) - ExpectEq("elements are: [taco, less than 17]", m.Description()) - - var c []interface{} - var err error - - // One candidate. - c = []interface{}{17} - err = m.Matches(c) - ExpectThat(err, Error(HasSubstr("length 1"))) - - // Both matching. - c = []interface{}{"taco", 16} - err = m.Matches(c) - ExpectEq(nil, err) - - // First non-matching. - c = []interface{}{"burrito", 16} - err = m.Matches(c) - ExpectThat(err, Error(Equals("whose element 0 doesn't match"))) - - // Second non-matching. - c = []interface{}{"taco", 17} - err = m.Matches(c) - ExpectThat(err, Error(Equals("whose element 1 doesn't match"))) - - // Three candidates. - c = []interface{}{"taco", 17, 19} - err = m.Matches(c) - ExpectThat(err, Error(HasSubstr("length 3"))) -} - -func (t *ElementsAreTest) ArrayCandidates() { - m := ElementsAre("taco", LessThan(17)) - - var err error - - // One candidate. - err = m.Matches([1]interface{}{"taco"}) - ExpectThat(err, Error(HasSubstr("length 1"))) - - // Both matching. - err = m.Matches([2]interface{}{"taco", 16}) - ExpectEq(nil, err) - - // First non-matching. - err = m.Matches([2]interface{}{"burrito", 16}) - ExpectThat(err, Error(Equals("whose element 0 doesn't match"))) -} - -func (t *ElementsAreTest) WrongTypeCandidate() { - m := ElementsAre("taco") - - var err error - - // String candidate. - err = m.Matches("taco") - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("array"))) - ExpectThat(err, Error(HasSubstr("slice"))) - - // Map candidate. - err = m.Matches(map[string]string{}) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("array"))) - ExpectThat(err, Error(HasSubstr("slice"))) - - // Nil candidate. - err = m.Matches(nil) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("array"))) - ExpectThat(err, Error(HasSubstr("slice"))) -} - -func (t *ElementsAreTest) PropagatesFatality() { - m := ElementsAre(LessThan(17)) - ExpectEq("elements are: [less than 17]", m.Description()) - - var c []interface{} - var err error - - // Non-fatal error. - c = []interface{}{19} - err = m.Matches(c) - AssertNe(nil, err) - ExpectFalse(isFatal(err)) - - // Fatal error. - c = []interface{}{"taco"} - err = m.Matches(c) - AssertNe(nil, err) - ExpectTrue(isFatal(err)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/equals.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/equals.go deleted file mode 100644 index 164059e..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/equals.go +++ /dev/null @@ -1,529 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "math" - "reflect" -) - -// Equals(x) returns a matcher that matches values v such that v and x are -// equivalent. This includes the case when the comparison v == x using Go's -// built-in comparison operator is legal, but for convenience the following -// rules also apply: -// -// * Type checking is done based on underlying types rather than actual -// types, so that e.g. two aliases for string can be compared: -// -// type stringAlias1 string -// type stringAlias2 string -// -// a := "taco" -// b := stringAlias1("taco") -// c := stringAlias2("taco") -// -// ExpectTrue(a == b) // Legal, passes -// ExpectTrue(b == c) // Illegal, doesn't compile -// -// ExpectThat(a, Equals(b)) // Passes -// ExpectThat(b, Equals(c)) // Passes -// -// * Values of numeric type are treated as if they were abstract numbers, and -// compared accordingly. Therefore Equals(17) will match int(17), -// int16(17), uint(17), float32(17), complex64(17), and so on. -// -// If you want a stricter matcher that contains no such cleverness, see -// IdenticalTo instead. -func Equals(x interface{}) Matcher { - v := reflect.ValueOf(x) - - // The == operator is not defined for array or struct types. - if v.Kind() == reflect.Array || v.Kind() == reflect.Struct { - panic(fmt.Sprintf("oglematchers.Equals: unsupported kind %v", v.Kind())) - } - - // The == operator is not defined for non-nil slices. - if v.Kind() == reflect.Slice && v.Pointer() != uintptr(0) { - panic(fmt.Sprintf("oglematchers.Equals: non-nil slice")) - } - - return &equalsMatcher{v} -} - -type equalsMatcher struct { - expectedValue reflect.Value -} - -//////////////////////////////////////////////////////////////////////// -// Numeric types -//////////////////////////////////////////////////////////////////////// - -func isSignedInteger(v reflect.Value) bool { - k := v.Kind() - return k >= reflect.Int && k <= reflect.Int64 -} - -func isUnsignedInteger(v reflect.Value) bool { - k := v.Kind() - return k >= reflect.Uint && k <= reflect.Uint64 -} - -func isInteger(v reflect.Value) bool { - return isSignedInteger(v) || isUnsignedInteger(v) -} - -func isFloat(v reflect.Value) bool { - k := v.Kind() - return k == reflect.Float32 || k == reflect.Float64 -} - -func isComplex(v reflect.Value) bool { - k := v.Kind() - return k == reflect.Complex64 || k == reflect.Complex128 -} - -func checkAgainstInt64(e int64, c reflect.Value) (err error) { - err = errors.New("") - - switch { - case isSignedInteger(c): - if c.Int() == e { - err = nil - } - - case isUnsignedInteger(c): - u := c.Uint() - if u <= math.MaxInt64 && int64(u) == e { - err = nil - } - - // Turn around the various floating point types so that the checkAgainst* - // functions for them can deal with precision issues. - case isFloat(c), isComplex(c): - return Equals(c.Interface()).Matches(e) - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstUint64(e uint64, c reflect.Value) (err error) { - err = errors.New("") - - switch { - case isSignedInteger(c): - i := c.Int() - if i >= 0 && uint64(i) == e { - err = nil - } - - case isUnsignedInteger(c): - if c.Uint() == e { - err = nil - } - - // Turn around the various floating point types so that the checkAgainst* - // functions for them can deal with precision issues. - case isFloat(c), isComplex(c): - return Equals(c.Interface()).Matches(e) - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstFloat32(e float32, c reflect.Value) (err error) { - err = errors.New("") - - switch { - case isSignedInteger(c): - if float32(c.Int()) == e { - err = nil - } - - case isUnsignedInteger(c): - if float32(c.Uint()) == e { - err = nil - } - - case isFloat(c): - // Compare using float32 to avoid a false sense of precision; otherwise - // e.g. Equals(float32(0.1)) won't match float32(0.1). - if float32(c.Float()) == e { - err = nil - } - - case isComplex(c): - comp := c.Complex() - rl := real(comp) - im := imag(comp) - - // Compare using float32 to avoid a false sense of precision; otherwise - // e.g. Equals(float32(0.1)) won't match (0.1 + 0i). - if im == 0 && float32(rl) == e { - err = nil - } - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstFloat64(e float64, c reflect.Value) (err error) { - err = errors.New("") - - ck := c.Kind() - - switch { - case isSignedInteger(c): - if float64(c.Int()) == e { - err = nil - } - - case isUnsignedInteger(c): - if float64(c.Uint()) == e { - err = nil - } - - // If the actual value is lower precision, turn the comparison around so we - // apply the low-precision rules. Otherwise, e.g. Equals(0.1) may not match - // float32(0.1). - case ck == reflect.Float32 || ck == reflect.Complex64: - return Equals(c.Interface()).Matches(e) - - // Otherwise, compare with double precision. - case isFloat(c): - if c.Float() == e { - err = nil - } - - case isComplex(c): - comp := c.Complex() - rl := real(comp) - im := imag(comp) - - if im == 0 && rl == e { - err = nil - } - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstComplex64(e complex64, c reflect.Value) (err error) { - err = errors.New("") - realPart := real(e) - imaginaryPart := imag(e) - - switch { - case isInteger(c) || isFloat(c): - // If we have no imaginary part, then we should just compare against the - // real part. Otherwise, we can't be equal. - if imaginaryPart != 0 { - return - } - - return checkAgainstFloat32(realPart, c) - - case isComplex(c): - // Compare using complex64 to avoid a false sense of precision; otherwise - // e.g. Equals(0.1 + 0i) won't match float32(0.1). - if complex64(c.Complex()) == e { - err = nil - } - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstComplex128(e complex128, c reflect.Value) (err error) { - err = errors.New("") - realPart := real(e) - imaginaryPart := imag(e) - - switch { - case isInteger(c) || isFloat(c): - // If we have no imaginary part, then we should just compare against the - // real part. Otherwise, we can't be equal. - if imaginaryPart != 0 { - return - } - - return checkAgainstFloat64(realPart, c) - - case isComplex(c): - if c.Complex() == e { - err = nil - } - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -//////////////////////////////////////////////////////////////////////// -// Other types -//////////////////////////////////////////////////////////////////////// - -func checkAgainstBool(e bool, c reflect.Value) (err error) { - if c.Kind() != reflect.Bool { - err = NewFatalError("which is not a bool") - return - } - - err = errors.New("") - if c.Bool() == e { - err = nil - } - return -} - -func checkAgainstUintptr(e uintptr, c reflect.Value) (err error) { - if c.Kind() != reflect.Uintptr { - err = NewFatalError("which is not a uintptr") - return - } - - err = errors.New("") - if uintptr(c.Uint()) == e { - err = nil - } - return -} - -func checkAgainstChan(e reflect.Value, c reflect.Value) (err error) { - // Create a description of e's type, e.g. "chan int". - typeStr := fmt.Sprintf("%s %s", e.Type().ChanDir(), e.Type().Elem()) - - // Make sure c is a chan of the correct type. - if c.Kind() != reflect.Chan || - c.Type().ChanDir() != e.Type().ChanDir() || - c.Type().Elem() != e.Type().Elem() { - err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr)) - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstFunc(e reflect.Value, c reflect.Value) (err error) { - // Make sure c is a function. - if c.Kind() != reflect.Func { - err = NewFatalError("which is not a function") - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstMap(e reflect.Value, c reflect.Value) (err error) { - // Make sure c is a map. - if c.Kind() != reflect.Map { - err = NewFatalError("which is not a map") - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstPtr(e reflect.Value, c reflect.Value) (err error) { - // Create a description of e's type, e.g. "*int". - typeStr := fmt.Sprintf("*%v", e.Type().Elem()) - - // Make sure c is a pointer of the correct type. - if c.Kind() != reflect.Ptr || - c.Type().Elem() != e.Type().Elem() { - err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr)) - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstSlice(e reflect.Value, c reflect.Value) (err error) { - // Create a description of e's type, e.g. "[]int". - typeStr := fmt.Sprintf("[]%v", e.Type().Elem()) - - // Make sure c is a slice of the correct type. - if c.Kind() != reflect.Slice || - c.Type().Elem() != e.Type().Elem() { - err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr)) - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstString(e reflect.Value, c reflect.Value) (err error) { - // Make sure c is a string. - if c.Kind() != reflect.String { - err = NewFatalError("which is not a string") - return - } - - err = errors.New("") - if c.String() == e.String() { - err = nil - } - return -} - -func checkAgainstUnsafePointer(e reflect.Value, c reflect.Value) (err error) { - // Make sure c is a pointer. - if c.Kind() != reflect.UnsafePointer { - err = NewFatalError("which is not a unsafe.Pointer") - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkForNil(c reflect.Value) (err error) { - err = errors.New("") - - // Make sure it is legal to call IsNil. - switch c.Kind() { - case reflect.Invalid: - case reflect.Chan: - case reflect.Func: - case reflect.Interface: - case reflect.Map: - case reflect.Ptr: - case reflect.Slice: - - default: - err = NewFatalError("which cannot be compared to nil") - return - } - - // Ask whether the value is nil. Handle a nil literal (kind Invalid) - // specially, since it's not legal to call IsNil there. - if c.Kind() == reflect.Invalid || c.IsNil() { - err = nil - } - return -} - -//////////////////////////////////////////////////////////////////////// -// Public implementation -//////////////////////////////////////////////////////////////////////// - -func (m *equalsMatcher) Matches(candidate interface{}) error { - e := m.expectedValue - c := reflect.ValueOf(candidate) - ek := e.Kind() - - switch { - case ek == reflect.Bool: - return checkAgainstBool(e.Bool(), c) - - case isSignedInteger(e): - return checkAgainstInt64(e.Int(), c) - - case isUnsignedInteger(e): - return checkAgainstUint64(e.Uint(), c) - - case ek == reflect.Uintptr: - return checkAgainstUintptr(uintptr(e.Uint()), c) - - case ek == reflect.Float32: - return checkAgainstFloat32(float32(e.Float()), c) - - case ek == reflect.Float64: - return checkAgainstFloat64(e.Float(), c) - - case ek == reflect.Complex64: - return checkAgainstComplex64(complex64(e.Complex()), c) - - case ek == reflect.Complex128: - return checkAgainstComplex128(complex128(e.Complex()), c) - - case ek == reflect.Chan: - return checkAgainstChan(e, c) - - case ek == reflect.Func: - return checkAgainstFunc(e, c) - - case ek == reflect.Map: - return checkAgainstMap(e, c) - - case ek == reflect.Ptr: - return checkAgainstPtr(e, c) - - case ek == reflect.Slice: - return checkAgainstSlice(e, c) - - case ek == reflect.String: - return checkAgainstString(e, c) - - case ek == reflect.UnsafePointer: - return checkAgainstUnsafePointer(e, c) - - case ek == reflect.Invalid: - return checkForNil(c) - } - - panic(fmt.Sprintf("equalsMatcher.Matches: unexpected kind: %v", ek)) -} - -func (m *equalsMatcher) Description() string { - // Special case: handle nil. - if !m.expectedValue.IsValid() { - return "is nil" - } - - return fmt.Sprintf("%v", m.expectedValue.Interface()) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/equals_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/equals_test.go deleted file mode 100644 index 7898d42..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/equals_test.go +++ /dev/null @@ -1,3786 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "math" - "unsafe" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -var someInt int = -17 - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type EqualsTest struct { -} - -func init() { RegisterTestSuite(&EqualsTest{}) } - -type equalsTestCase struct { - candidate interface{} - expectedResult bool - shouldBeFatal bool - expectedError string -} - -func (t *EqualsTest) checkTestCases(matcher Matcher, cases []equalsTestCase) { - for i, c := range cases { - err := matcher.Matches(c.candidate) - ExpectEq(c.expectedResult, (err == nil), "Result for case %d: %v", i, c) - - if err == nil { - continue - } - - _, isFatal := err.(*FatalError) - ExpectEq(c.shouldBeFatal, isFatal, "Fatality for case %d: %v", i, c) - - ExpectThat(err, Error(Equals(c.expectedError)), "Case %d: %v", i, c) - } -} - -//////////////////////////////////////////////////////////////////////// -// nil -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) EqualsNil() { - matcher := Equals(nil) - ExpectEq("is nil", matcher.Description()) - - cases := []equalsTestCase{ - // Legal types - equalsTestCase{nil, true, false, ""}, - equalsTestCase{chan int(nil), true, false, ""}, - equalsTestCase{(func())(nil), true, false, ""}, - equalsTestCase{interface{}(nil), true, false, ""}, - equalsTestCase{map[int]int(nil), true, false, ""}, - equalsTestCase{(*int)(nil), true, false, ""}, - equalsTestCase{[]int(nil), true, false, ""}, - - equalsTestCase{make(chan int), false, false, ""}, - equalsTestCase{func() {}, false, false, ""}, - equalsTestCase{map[int]int{}, false, false, ""}, - equalsTestCase{&someInt, false, false, ""}, - equalsTestCase{[]int{}, false, false, ""}, - - // Illegal types - equalsTestCase{17, false, true, "which cannot be compared to nil"}, - equalsTestCase{int8(17), false, true, "which cannot be compared to nil"}, - equalsTestCase{uintptr(17), false, true, "which cannot be compared to nil"}, - equalsTestCase{[...]int{}, false, true, "which cannot be compared to nil"}, - equalsTestCase{"taco", false, true, "which cannot be compared to nil"}, - equalsTestCase{equalsTestCase{}, false, true, "which cannot be compared to nil"}, - equalsTestCase{unsafe.Pointer(&someInt), false, true, "which cannot be compared to nil"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Integer literals -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeIntegerLiteral() { - // -2^30 - matcher := Equals(-1073741824) - ExpectEq("-1073741824", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of -1073741824. - equalsTestCase{-1073741824, true, false, ""}, - equalsTestCase{-1073741824.0, true, false, ""}, - equalsTestCase{-1073741824 + 0i, true, false, ""}, - equalsTestCase{int(-1073741824), true, false, ""}, - equalsTestCase{int32(-1073741824), true, false, ""}, - equalsTestCase{int64(-1073741824), true, false, ""}, - equalsTestCase{float32(-1073741824), true, false, ""}, - equalsTestCase{float64(-1073741824), true, false, ""}, - equalsTestCase{complex64(-1073741824), true, false, ""}, - equalsTestCase{complex128(-1073741824), true, false, ""}, - equalsTestCase{interface{}(int(-1073741824)), true, false, ""}, - - // Values that would be -1073741824 in two's complement. - equalsTestCase{uint((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint32((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint64((1 << 64) - 1073741824), false, false, ""}, - - // Non-equal values of signed integer type. - equalsTestCase{int(-1073741823), false, false, ""}, - equalsTestCase{int32(-1073741823), false, false, ""}, - equalsTestCase{int64(-1073741823), false, false, ""}, - - // Non-equal values of other numeric types. - equalsTestCase{float64(-1073741824.1), false, false, ""}, - equalsTestCase{float64(-1073741823.9), false, false, ""}, - equalsTestCase{complex128(-1073741823), false, false, ""}, - equalsTestCase{complex128(-1073741824 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveIntegerLiteral() { - // 2^30 - matcher := Equals(1073741824) - ExpectEq("1073741824", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 1073741824. - equalsTestCase{1073741824, true, false, ""}, - equalsTestCase{1073741824.0, true, false, ""}, - equalsTestCase{1073741824 + 0i, true, false, ""}, - equalsTestCase{int(1073741824), true, false, ""}, - equalsTestCase{uint(1073741824), true, false, ""}, - equalsTestCase{int32(1073741824), true, false, ""}, - equalsTestCase{int64(1073741824), true, false, ""}, - equalsTestCase{uint32(1073741824), true, false, ""}, - equalsTestCase{uint64(1073741824), true, false, ""}, - equalsTestCase{float32(1073741824), true, false, ""}, - equalsTestCase{float64(1073741824), true, false, ""}, - equalsTestCase{complex64(1073741824), true, false, ""}, - equalsTestCase{complex128(1073741824), true, false, ""}, - equalsTestCase{interface{}(int(1073741824)), true, false, ""}, - equalsTestCase{interface{}(uint(1073741824)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(1073741823), false, false, ""}, - equalsTestCase{int32(1073741823), false, false, ""}, - equalsTestCase{int64(1073741823), false, false, ""}, - equalsTestCase{float64(1073741824.1), false, false, ""}, - equalsTestCase{float64(1073741823.9), false, false, ""}, - equalsTestCase{complex128(1073741823), false, false, ""}, - equalsTestCase{complex128(1073741824 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Floating point literals -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeIntegralFloatingPointLiteral() { - // -2^30 - matcher := Equals(-1073741824.0) - ExpectEq("-1.073741824e+09", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of -1073741824. - equalsTestCase{-1073741824, true, false, ""}, - equalsTestCase{-1073741824.0, true, false, ""}, - equalsTestCase{-1073741824 + 0i, true, false, ""}, - equalsTestCase{int(-1073741824), true, false, ""}, - equalsTestCase{int32(-1073741824), true, false, ""}, - equalsTestCase{int64(-1073741824), true, false, ""}, - equalsTestCase{float32(-1073741824), true, false, ""}, - equalsTestCase{float64(-1073741824), true, false, ""}, - equalsTestCase{complex64(-1073741824), true, false, ""}, - equalsTestCase{complex128(-1073741824), true, false, ""}, - equalsTestCase{interface{}(int(-1073741824)), true, false, ""}, - equalsTestCase{interface{}(float64(-1073741824)), true, false, ""}, - - // Values that would be -1073741824 in two's complement. - equalsTestCase{uint((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint32((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint64((1 << 64) - 1073741824), false, false, ""}, - - // Non-equal values of signed integer type. - equalsTestCase{int(-1073741823), false, false, ""}, - equalsTestCase{int32(-1073741823), false, false, ""}, - equalsTestCase{int64(-1073741823), false, false, ""}, - - // Non-equal values of other numeric types. - equalsTestCase{float64(-1073741824.1), false, false, ""}, - equalsTestCase{float64(-1073741823.9), false, false, ""}, - equalsTestCase{complex128(-1073741823), false, false, ""}, - equalsTestCase{complex128(-1073741824 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveIntegralFloatingPointLiteral() { - // 2^30 - matcher := Equals(1073741824.0) - ExpectEq("1.073741824e+09", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 1073741824. - equalsTestCase{1073741824, true, false, ""}, - equalsTestCase{1073741824.0, true, false, ""}, - equalsTestCase{1073741824 + 0i, true, false, ""}, - equalsTestCase{int(1073741824), true, false, ""}, - equalsTestCase{int32(1073741824), true, false, ""}, - equalsTestCase{int64(1073741824), true, false, ""}, - equalsTestCase{uint(1073741824), true, false, ""}, - equalsTestCase{uint32(1073741824), true, false, ""}, - equalsTestCase{uint64(1073741824), true, false, ""}, - equalsTestCase{float32(1073741824), true, false, ""}, - equalsTestCase{float64(1073741824), true, false, ""}, - equalsTestCase{complex64(1073741824), true, false, ""}, - equalsTestCase{complex128(1073741824), true, false, ""}, - equalsTestCase{interface{}(int(1073741824)), true, false, ""}, - equalsTestCase{interface{}(float64(1073741824)), true, false, ""}, - - // Values that would be 1073741824 in two's complement. - equalsTestCase{uint((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint32((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint64((1 << 64) - 1073741824), false, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(1073741823), false, false, ""}, - equalsTestCase{int32(1073741823), false, false, ""}, - equalsTestCase{int64(1073741823), false, false, ""}, - equalsTestCase{uint(1073741823), false, false, ""}, - equalsTestCase{uint32(1073741823), false, false, ""}, - equalsTestCase{uint64(1073741823), false, false, ""}, - equalsTestCase{float64(1073741824.1), false, false, ""}, - equalsTestCase{float64(1073741823.9), false, false, ""}, - equalsTestCase{complex128(1073741823), false, false, ""}, - equalsTestCase{complex128(1073741824 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NonIntegralFloatingPointLiteral() { - matcher := Equals(17.1) - ExpectEq("17.1", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 17.1. - equalsTestCase{17.1, true, false, ""}, - equalsTestCase{17.1, true, false, ""}, - equalsTestCase{17.1 + 0i, true, false, ""}, - equalsTestCase{float32(17.1), true, false, ""}, - equalsTestCase{float64(17.1), true, false, ""}, - equalsTestCase{complex64(17.1), true, false, ""}, - equalsTestCase{complex128(17.1), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{17, false, false, ""}, - equalsTestCase{17.2, false, false, ""}, - equalsTestCase{18, false, false, ""}, - equalsTestCase{int(17), false, false, ""}, - equalsTestCase{int(18), false, false, ""}, - equalsTestCase{int32(17), false, false, ""}, - equalsTestCase{int64(17), false, false, ""}, - equalsTestCase{uint(17), false, false, ""}, - equalsTestCase{uint32(17), false, false, ""}, - equalsTestCase{uint64(17), false, false, ""}, - equalsTestCase{complex128(17.1 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// bool -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) False() { - matcher := Equals(false) - ExpectEq("false", matcher.Description()) - - cases := []equalsTestCase{ - // bools - equalsTestCase{false, true, false, ""}, - equalsTestCase{bool(false), true, false, ""}, - - equalsTestCase{true, false, false, ""}, - equalsTestCase{bool(true), false, false, ""}, - - // Other types. - equalsTestCase{int(0), false, true, "which is not a bool"}, - equalsTestCase{int8(0), false, true, "which is not a bool"}, - equalsTestCase{int16(0), false, true, "which is not a bool"}, - equalsTestCase{int32(0), false, true, "which is not a bool"}, - equalsTestCase{int64(0), false, true, "which is not a bool"}, - equalsTestCase{uint(0), false, true, "which is not a bool"}, - equalsTestCase{uint8(0), false, true, "which is not a bool"}, - equalsTestCase{uint16(0), false, true, "which is not a bool"}, - equalsTestCase{uint32(0), false, true, "which is not a bool"}, - equalsTestCase{uint64(0), false, true, "which is not a bool"}, - equalsTestCase{uintptr(0), false, true, "which is not a bool"}, - equalsTestCase{[...]int{}, false, true, "which is not a bool"}, - equalsTestCase{make(chan int), false, true, "which is not a bool"}, - equalsTestCase{func() {}, false, true, "which is not a bool"}, - equalsTestCase{map[int]int{}, false, true, "which is not a bool"}, - equalsTestCase{&someInt, false, true, "which is not a bool"}, - equalsTestCase{[]int{}, false, true, "which is not a bool"}, - equalsTestCase{"taco", false, true, "which is not a bool"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a bool"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) True() { - matcher := Equals(true) - ExpectEq("true", matcher.Description()) - - cases := []equalsTestCase{ - // bools - equalsTestCase{true, true, false, ""}, - equalsTestCase{bool(true), true, false, ""}, - - equalsTestCase{false, false, false, ""}, - equalsTestCase{bool(false), false, false, ""}, - - // Other types. - equalsTestCase{int(1), false, true, "which is not a bool"}, - equalsTestCase{int8(1), false, true, "which is not a bool"}, - equalsTestCase{int16(1), false, true, "which is not a bool"}, - equalsTestCase{int32(1), false, true, "which is not a bool"}, - equalsTestCase{int64(1), false, true, "which is not a bool"}, - equalsTestCase{uint(1), false, true, "which is not a bool"}, - equalsTestCase{uint8(1), false, true, "which is not a bool"}, - equalsTestCase{uint16(1), false, true, "which is not a bool"}, - equalsTestCase{uint32(1), false, true, "which is not a bool"}, - equalsTestCase{uint64(1), false, true, "which is not a bool"}, - equalsTestCase{uintptr(1), false, true, "which is not a bool"}, - equalsTestCase{[...]int{}, false, true, "which is not a bool"}, - equalsTestCase{make(chan int), false, true, "which is not a bool"}, - equalsTestCase{func() {}, false, true, "which is not a bool"}, - equalsTestCase{map[int]int{}, false, true, "which is not a bool"}, - equalsTestCase{&someInt, false, true, "which is not a bool"}, - equalsTestCase{[]int{}, false, true, "which is not a bool"}, - equalsTestCase{"taco", false, true, "which is not a bool"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a bool"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// int -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeInt() { - // -2^30 - matcher := Equals(int(-1073741824)) - ExpectEq("-1073741824", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of -1073741824. - equalsTestCase{-1073741824, true, false, ""}, - equalsTestCase{-1073741824.0, true, false, ""}, - equalsTestCase{-1073741824 + 0i, true, false, ""}, - equalsTestCase{int(-1073741824), true, false, ""}, - equalsTestCase{int32(-1073741824), true, false, ""}, - equalsTestCase{int64(-1073741824), true, false, ""}, - equalsTestCase{float32(-1073741824), true, false, ""}, - equalsTestCase{float64(-1073741824), true, false, ""}, - equalsTestCase{complex64(-1073741824), true, false, ""}, - equalsTestCase{complex128(-1073741824), true, false, ""}, - equalsTestCase{interface{}(int(-1073741824)), true, false, ""}, - - // Values that would be -1073741824 in two's complement. - equalsTestCase{uint((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint32((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint64((1 << 64) - 1073741824), false, false, ""}, - - // Non-equal values of signed integer type. - equalsTestCase{int(-1073741823), false, false, ""}, - equalsTestCase{int32(-1073741823), false, false, ""}, - equalsTestCase{int64(-1073741823), false, false, ""}, - - // Non-equal values of other numeric types. - equalsTestCase{float64(-1073741824.1), false, false, ""}, - equalsTestCase{float64(-1073741823.9), false, false, ""}, - equalsTestCase{complex128(-1073741823), false, false, ""}, - equalsTestCase{complex128(-1073741824 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveInt() { - // 2^30 - matcher := Equals(int(1073741824)) - ExpectEq("1073741824", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 1073741824. - equalsTestCase{1073741824, true, false, ""}, - equalsTestCase{1073741824.0, true, false, ""}, - equalsTestCase{1073741824 + 0i, true, false, ""}, - equalsTestCase{int(1073741824), true, false, ""}, - equalsTestCase{uint(1073741824), true, false, ""}, - equalsTestCase{int32(1073741824), true, false, ""}, - equalsTestCase{int64(1073741824), true, false, ""}, - equalsTestCase{uint32(1073741824), true, false, ""}, - equalsTestCase{uint64(1073741824), true, false, ""}, - equalsTestCase{float32(1073741824), true, false, ""}, - equalsTestCase{float64(1073741824), true, false, ""}, - equalsTestCase{complex64(1073741824), true, false, ""}, - equalsTestCase{complex128(1073741824), true, false, ""}, - equalsTestCase{interface{}(int(1073741824)), true, false, ""}, - equalsTestCase{interface{}(uint(1073741824)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(1073741823), false, false, ""}, - equalsTestCase{int32(1073741823), false, false, ""}, - equalsTestCase{int64(1073741823), false, false, ""}, - equalsTestCase{float64(1073741824.1), false, false, ""}, - equalsTestCase{float64(1073741823.9), false, false, ""}, - equalsTestCase{complex128(1073741823), false, false, ""}, - equalsTestCase{complex128(1073741824 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// int8 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeInt8() { - matcher := Equals(int8(-17)) - ExpectEq("-17", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of -17. - equalsTestCase{-17, true, false, ""}, - equalsTestCase{-17.0, true, false, ""}, - equalsTestCase{-17 + 0i, true, false, ""}, - equalsTestCase{int(-17), true, false, ""}, - equalsTestCase{int8(-17), true, false, ""}, - equalsTestCase{int16(-17), true, false, ""}, - equalsTestCase{int32(-17), true, false, ""}, - equalsTestCase{int64(-17), true, false, ""}, - equalsTestCase{float32(-17), true, false, ""}, - equalsTestCase{float64(-17), true, false, ""}, - equalsTestCase{complex64(-17), true, false, ""}, - equalsTestCase{complex128(-17), true, false, ""}, - equalsTestCase{interface{}(int(-17)), true, false, ""}, - - // Values that would be -17 in two's complement. - equalsTestCase{uint((1 << 32) - 17), false, false, ""}, - equalsTestCase{uint8((1 << 8) - 17), false, false, ""}, - equalsTestCase{uint16((1 << 16) - 17), false, false, ""}, - equalsTestCase{uint32((1 << 32) - 17), false, false, ""}, - equalsTestCase{uint64((1 << 64) - 17), false, false, ""}, - - // Non-equal values of signed integer type. - equalsTestCase{int(-16), false, false, ""}, - equalsTestCase{int8(-16), false, false, ""}, - equalsTestCase{int16(-16), false, false, ""}, - equalsTestCase{int32(-16), false, false, ""}, - equalsTestCase{int64(-16), false, false, ""}, - - // Non-equal values of other numeric types. - equalsTestCase{float32(-17.1), false, false, ""}, - equalsTestCase{float32(-16.9), false, false, ""}, - equalsTestCase{complex64(-16), false, false, ""}, - equalsTestCase{complex64(-17 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr((1 << 32) - 17), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{-17}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{-17}, false, true, "which is not numeric"}, - equalsTestCase{"-17", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) ZeroInt8() { - matcher := Equals(int8(0)) - ExpectEq("0", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 0. - equalsTestCase{0, true, false, ""}, - equalsTestCase{0.0, true, false, ""}, - equalsTestCase{0 + 0i, true, false, ""}, - equalsTestCase{int(0), true, false, ""}, - equalsTestCase{int8(0), true, false, ""}, - equalsTestCase{int16(0), true, false, ""}, - equalsTestCase{int32(0), true, false, ""}, - equalsTestCase{int64(0), true, false, ""}, - equalsTestCase{float32(0), true, false, ""}, - equalsTestCase{float64(0), true, false, ""}, - equalsTestCase{complex64(0), true, false, ""}, - equalsTestCase{complex128(0), true, false, ""}, - equalsTestCase{interface{}(int(0)), true, false, ""}, - equalsTestCase{uint(0), true, false, ""}, - equalsTestCase{uint8(0), true, false, ""}, - equalsTestCase{uint16(0), true, false, ""}, - equalsTestCase{uint32(0), true, false, ""}, - equalsTestCase{uint64(0), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(1), false, false, ""}, - equalsTestCase{int8(1), false, false, ""}, - equalsTestCase{int16(1), false, false, ""}, - equalsTestCase{int32(1), false, false, ""}, - equalsTestCase{int64(1), false, false, ""}, - equalsTestCase{float32(-0.1), false, false, ""}, - equalsTestCase{float32(0.1), false, false, ""}, - equalsTestCase{complex64(1), false, false, ""}, - equalsTestCase{complex64(0 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{0}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{0}, false, true, "which is not numeric"}, - equalsTestCase{"0", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveInt8() { - matcher := Equals(int8(17)) - ExpectEq("17", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 17. - equalsTestCase{17, true, false, ""}, - equalsTestCase{17.0, true, false, ""}, - equalsTestCase{17 + 0i, true, false, ""}, - equalsTestCase{int(17), true, false, ""}, - equalsTestCase{int8(17), true, false, ""}, - equalsTestCase{int16(17), true, false, ""}, - equalsTestCase{int32(17), true, false, ""}, - equalsTestCase{int64(17), true, false, ""}, - equalsTestCase{float32(17), true, false, ""}, - equalsTestCase{float64(17), true, false, ""}, - equalsTestCase{complex64(17), true, false, ""}, - equalsTestCase{complex128(17), true, false, ""}, - equalsTestCase{interface{}(int(17)), true, false, ""}, - equalsTestCase{uint(17), true, false, ""}, - equalsTestCase{uint8(17), true, false, ""}, - equalsTestCase{uint16(17), true, false, ""}, - equalsTestCase{uint32(17), true, false, ""}, - equalsTestCase{uint64(17), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(16), false, false, ""}, - equalsTestCase{int8(16), false, false, ""}, - equalsTestCase{int16(16), false, false, ""}, - equalsTestCase{int32(16), false, false, ""}, - equalsTestCase{int64(16), false, false, ""}, - equalsTestCase{float32(16.9), false, false, ""}, - equalsTestCase{float32(17.1), false, false, ""}, - equalsTestCase{complex64(16), false, false, ""}, - equalsTestCase{complex64(17 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(17), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{17}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{17}, false, true, "which is not numeric"}, - equalsTestCase{"17", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// int16 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeInt16() { - matcher := Equals(int16(-32766)) - ExpectEq("-32766", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of -32766. - equalsTestCase{-32766, true, false, ""}, - equalsTestCase{-32766.0, true, false, ""}, - equalsTestCase{-32766 + 0i, true, false, ""}, - equalsTestCase{int(-32766), true, false, ""}, - equalsTestCase{int16(-32766), true, false, ""}, - equalsTestCase{int32(-32766), true, false, ""}, - equalsTestCase{int64(-32766), true, false, ""}, - equalsTestCase{float32(-32766), true, false, ""}, - equalsTestCase{float64(-32766), true, false, ""}, - equalsTestCase{complex64(-32766), true, false, ""}, - equalsTestCase{complex128(-32766), true, false, ""}, - equalsTestCase{interface{}(int(-32766)), true, false, ""}, - - // Values that would be -32766 in two's complement. - equalsTestCase{uint((1 << 32) - 32766), false, false, ""}, - equalsTestCase{uint16((1 << 16) - 32766), false, false, ""}, - equalsTestCase{uint32((1 << 32) - 32766), false, false, ""}, - equalsTestCase{uint64((1 << 64) - 32766), false, false, ""}, - - // Non-equal values of signed integer type. - equalsTestCase{int(-16), false, false, ""}, - equalsTestCase{int8(-16), false, false, ""}, - equalsTestCase{int16(-16), false, false, ""}, - equalsTestCase{int32(-16), false, false, ""}, - equalsTestCase{int64(-16), false, false, ""}, - - // Non-equal values of other numeric types. - equalsTestCase{float32(-32766.1), false, false, ""}, - equalsTestCase{float32(-32765.9), false, false, ""}, - equalsTestCase{complex64(-32766.1), false, false, ""}, - equalsTestCase{complex64(-32766 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr((1 << 32) - 32766), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{-32766}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{-32766}, false, true, "which is not numeric"}, - equalsTestCase{"-32766", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) ZeroInt16() { - matcher := Equals(int16(0)) - ExpectEq("0", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 0. - equalsTestCase{0, true, false, ""}, - equalsTestCase{0.0, true, false, ""}, - equalsTestCase{0 + 0i, true, false, ""}, - equalsTestCase{int(0), true, false, ""}, - equalsTestCase{int8(0), true, false, ""}, - equalsTestCase{int16(0), true, false, ""}, - equalsTestCase{int32(0), true, false, ""}, - equalsTestCase{int64(0), true, false, ""}, - equalsTestCase{float32(0), true, false, ""}, - equalsTestCase{float64(0), true, false, ""}, - equalsTestCase{complex64(0), true, false, ""}, - equalsTestCase{complex128(0), true, false, ""}, - equalsTestCase{interface{}(int(0)), true, false, ""}, - equalsTestCase{uint(0), true, false, ""}, - equalsTestCase{uint8(0), true, false, ""}, - equalsTestCase{uint16(0), true, false, ""}, - equalsTestCase{uint32(0), true, false, ""}, - equalsTestCase{uint64(0), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(1), false, false, ""}, - equalsTestCase{int8(1), false, false, ""}, - equalsTestCase{int16(1), false, false, ""}, - equalsTestCase{int32(1), false, false, ""}, - equalsTestCase{int64(1), false, false, ""}, - equalsTestCase{float32(-0.1), false, false, ""}, - equalsTestCase{float32(0.1), false, false, ""}, - equalsTestCase{complex64(1), false, false, ""}, - equalsTestCase{complex64(0 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{0}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{0}, false, true, "which is not numeric"}, - equalsTestCase{"0", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveInt16() { - matcher := Equals(int16(32765)) - ExpectEq("32765", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 32765. - equalsTestCase{32765, true, false, ""}, - equalsTestCase{32765.0, true, false, ""}, - equalsTestCase{32765 + 0i, true, false, ""}, - equalsTestCase{int(32765), true, false, ""}, - equalsTestCase{int16(32765), true, false, ""}, - equalsTestCase{int32(32765), true, false, ""}, - equalsTestCase{int64(32765), true, false, ""}, - equalsTestCase{float32(32765), true, false, ""}, - equalsTestCase{float64(32765), true, false, ""}, - equalsTestCase{complex64(32765), true, false, ""}, - equalsTestCase{complex128(32765), true, false, ""}, - equalsTestCase{interface{}(int(32765)), true, false, ""}, - equalsTestCase{uint(32765), true, false, ""}, - equalsTestCase{uint16(32765), true, false, ""}, - equalsTestCase{uint32(32765), true, false, ""}, - equalsTestCase{uint64(32765), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(32764), false, false, ""}, - equalsTestCase{int16(32764), false, false, ""}, - equalsTestCase{int32(32764), false, false, ""}, - equalsTestCase{int64(32764), false, false, ""}, - equalsTestCase{float32(32764.9), false, false, ""}, - equalsTestCase{float32(32765.1), false, false, ""}, - equalsTestCase{complex64(32765.9), false, false, ""}, - equalsTestCase{complex64(32765 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(32765), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{32765}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{32765}, false, true, "which is not numeric"}, - equalsTestCase{"32765", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// int32 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeInt32() { - // -2^30 - matcher := Equals(int32(-1073741824)) - ExpectEq("-1073741824", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of -1073741824. - equalsTestCase{-1073741824, true, false, ""}, - equalsTestCase{-1073741824.0, true, false, ""}, - equalsTestCase{-1073741824 + 0i, true, false, ""}, - equalsTestCase{int(-1073741824), true, false, ""}, - equalsTestCase{int32(-1073741824), true, false, ""}, - equalsTestCase{int64(-1073741824), true, false, ""}, - equalsTestCase{float32(-1073741824), true, false, ""}, - equalsTestCase{float64(-1073741824), true, false, ""}, - equalsTestCase{complex64(-1073741824), true, false, ""}, - equalsTestCase{complex128(-1073741824), true, false, ""}, - equalsTestCase{interface{}(int(-1073741824)), true, false, ""}, - - // Values that would be -1073741824 in two's complement. - equalsTestCase{uint((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint32((1 << 32) - 1073741824), false, false, ""}, - equalsTestCase{uint64((1 << 64) - 1073741824), false, false, ""}, - - // Non-equal values of signed integer type. - equalsTestCase{int(-1073741823), false, false, ""}, - equalsTestCase{int32(-1073741823), false, false, ""}, - equalsTestCase{int64(-1073741823), false, false, ""}, - - // Non-equal values of other numeric types. - equalsTestCase{float64(-1073741824.1), false, false, ""}, - equalsTestCase{float64(-1073741823.9), false, false, ""}, - equalsTestCase{complex128(-1073741823), false, false, ""}, - equalsTestCase{complex128(-1073741824 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveInt32() { - // 2^30 - matcher := Equals(int32(1073741824)) - ExpectEq("1073741824", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 1073741824. - equalsTestCase{1073741824, true, false, ""}, - equalsTestCase{1073741824.0, true, false, ""}, - equalsTestCase{1073741824 + 0i, true, false, ""}, - equalsTestCase{int(1073741824), true, false, ""}, - equalsTestCase{uint(1073741824), true, false, ""}, - equalsTestCase{int32(1073741824), true, false, ""}, - equalsTestCase{int64(1073741824), true, false, ""}, - equalsTestCase{uint32(1073741824), true, false, ""}, - equalsTestCase{uint64(1073741824), true, false, ""}, - equalsTestCase{float32(1073741824), true, false, ""}, - equalsTestCase{float64(1073741824), true, false, ""}, - equalsTestCase{complex64(1073741824), true, false, ""}, - equalsTestCase{complex128(1073741824), true, false, ""}, - equalsTestCase{interface{}(int(1073741824)), true, false, ""}, - equalsTestCase{interface{}(uint(1073741824)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(1073741823), false, false, ""}, - equalsTestCase{int32(1073741823), false, false, ""}, - equalsTestCase{int64(1073741823), false, false, ""}, - equalsTestCase{float64(1073741824.1), false, false, ""}, - equalsTestCase{float64(1073741823.9), false, false, ""}, - equalsTestCase{complex128(1073741823), false, false, ""}, - equalsTestCase{complex128(1073741824 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// int64 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeInt64() { - // -2^40 - matcher := Equals(int64(-1099511627776)) - ExpectEq("-1099511627776", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of -1099511627776. - equalsTestCase{-1099511627776.0, true, false, ""}, - equalsTestCase{-1099511627776 + 0i, true, false, ""}, - equalsTestCase{int64(-1099511627776), true, false, ""}, - equalsTestCase{float32(-1099511627776), true, false, ""}, - equalsTestCase{float64(-1099511627776), true, false, ""}, - equalsTestCase{complex64(-1099511627776), true, false, ""}, - equalsTestCase{complex128(-1099511627776), true, false, ""}, - equalsTestCase{interface{}(int64(-1099511627776)), true, false, ""}, - - // Values that would be -1099511627776 in two's complement. - equalsTestCase{uint64((1 << 64) - 1099511627776), false, false, ""}, - - // Non-equal values of signed integer type. - equalsTestCase{int64(-1099511627775), false, false, ""}, - - // Non-equal values of other numeric types. - equalsTestCase{float64(-1099511627776.1), false, false, ""}, - equalsTestCase{float64(-1099511627775.9), false, false, ""}, - equalsTestCase{complex128(-1099511627775), false, false, ""}, - equalsTestCase{complex128(-1099511627776 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveInt64() { - // 2^40 - matcher := Equals(int64(1099511627776)) - ExpectEq("1099511627776", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 1099511627776. - equalsTestCase{1099511627776.0, true, false, ""}, - equalsTestCase{1099511627776 + 0i, true, false, ""}, - equalsTestCase{int64(1099511627776), true, false, ""}, - equalsTestCase{uint64(1099511627776), true, false, ""}, - equalsTestCase{float32(1099511627776), true, false, ""}, - equalsTestCase{float64(1099511627776), true, false, ""}, - equalsTestCase{complex64(1099511627776), true, false, ""}, - equalsTestCase{complex128(1099511627776), true, false, ""}, - equalsTestCase{interface{}(int64(1099511627776)), true, false, ""}, - equalsTestCase{interface{}(uint64(1099511627776)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(1099511627775), false, false, ""}, - equalsTestCase{uint64(1099511627775), false, false, ""}, - equalsTestCase{float64(1099511627776.1), false, false, ""}, - equalsTestCase{float64(1099511627775.9), false, false, ""}, - equalsTestCase{complex128(1099511627775), false, false, ""}, - equalsTestCase{complex128(1099511627776 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Int64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := Equals(int64(kTwoTo25 + 1)) - ExpectEq("33554433", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{int64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 2), false, false, ""}, - - equalsTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - - // Single-precision floating point. - equalsTestCase{float32(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{float32(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{complex64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{complex64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 3), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{float64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 2), false, false, ""}, - - equalsTestCase{complex128(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 2), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Int64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := Equals(int64(kTwoTo54 + 1)) - ExpectEq("18014398509481985", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo54 + 0), false, false, ""}, - equalsTestCase{int64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 2), false, false, ""}, - - equalsTestCase{uint64(kTwoTo54 + 0), false, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 2), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{float64(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 3), false, false, ""}, - - equalsTestCase{complex128(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{complex128(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// uint -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) SmallUint() { - const kExpected = 17 - matcher := Equals(uint(kExpected)) - ExpectEq("17", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{17, true, false, ""}, - equalsTestCase{17.0, true, false, ""}, - equalsTestCase{17 + 0i, true, false, ""}, - equalsTestCase{int(kExpected), true, false, ""}, - equalsTestCase{int8(kExpected), true, false, ""}, - equalsTestCase{int16(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint(kExpected), true, false, ""}, - equalsTestCase{uint8(kExpected), true, false, ""}, - equalsTestCase{uint16(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric types. - equalsTestCase{kExpected + 1, false, false, ""}, - equalsTestCase{int(kExpected + 1), false, false, ""}, - equalsTestCase{int8(kExpected + 1), false, false, ""}, - equalsTestCase{int16(kExpected + 1), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint(kExpected + 1), false, false, ""}, - equalsTestCase{uint8(kExpected + 1), false, false, ""}, - equalsTestCase{uint16(kExpected + 1), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected + 1), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex64(kExpected + 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 1), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargeUint() { - const kExpected = (1 << 16) + 17 - matcher := Equals(uint(kExpected)) - ExpectEq("65553", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{65553, true, false, ""}, - equalsTestCase{65553.0, true, false, ""}, - equalsTestCase{65553 + 0i, true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric types. - equalsTestCase{int16(17), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint16(17), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected + 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 1), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) UintNotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := Equals(uint(kTwoTo25 + 1)) - ExpectEq("33554433", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{int64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 2), false, false, ""}, - - equalsTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - - // Single-precision floating point. - equalsTestCase{float32(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{float32(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{complex64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{complex64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 3), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{float64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 2), false, false, ""}, - - equalsTestCase{complex128(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 2), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// uint8 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) SmallUint8() { - const kExpected = 17 - matcher := Equals(uint8(kExpected)) - ExpectEq("17", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{17, true, false, ""}, - equalsTestCase{17.0, true, false, ""}, - equalsTestCase{17 + 0i, true, false, ""}, - equalsTestCase{int(kExpected), true, false, ""}, - equalsTestCase{int8(kExpected), true, false, ""}, - equalsTestCase{int16(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint(kExpected), true, false, ""}, - equalsTestCase{uint8(kExpected), true, false, ""}, - equalsTestCase{uint16(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric types. - equalsTestCase{kExpected + 1, false, false, ""}, - equalsTestCase{int(kExpected + 1), false, false, ""}, - equalsTestCase{int8(kExpected + 1), false, false, ""}, - equalsTestCase{int16(kExpected + 1), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint(kExpected + 1), false, false, ""}, - equalsTestCase{uint8(kExpected + 1), false, false, ""}, - equalsTestCase{uint16(kExpected + 1), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected + 1), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex64(kExpected + 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 1), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// uint16 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) SmallUint16() { - const kExpected = 17 - matcher := Equals(uint16(kExpected)) - ExpectEq("17", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{17, true, false, ""}, - equalsTestCase{17.0, true, false, ""}, - equalsTestCase{17 + 0i, true, false, ""}, - equalsTestCase{int(kExpected), true, false, ""}, - equalsTestCase{int8(kExpected), true, false, ""}, - equalsTestCase{int16(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint(kExpected), true, false, ""}, - equalsTestCase{uint8(kExpected), true, false, ""}, - equalsTestCase{uint16(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric types. - equalsTestCase{kExpected + 1, false, false, ""}, - equalsTestCase{int(kExpected + 1), false, false, ""}, - equalsTestCase{int8(kExpected + 1), false, false, ""}, - equalsTestCase{int16(kExpected + 1), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint(kExpected + 1), false, false, ""}, - equalsTestCase{uint8(kExpected + 1), false, false, ""}, - equalsTestCase{uint16(kExpected + 1), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected + 1), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex64(kExpected + 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 1), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargeUint16() { - const kExpected = (1 << 8) + 17 - matcher := Equals(uint16(kExpected)) - ExpectEq("273", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{273, true, false, ""}, - equalsTestCase{273.0, true, false, ""}, - equalsTestCase{273 + 0i, true, false, ""}, - equalsTestCase{int16(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint16(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric types. - equalsTestCase{int8(17), false, false, ""}, - equalsTestCase{int16(kExpected + 1), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint8(17), false, false, ""}, - equalsTestCase{uint16(kExpected + 1), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected + 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 1), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// uint32 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) SmallUint32() { - const kExpected = 17 - matcher := Equals(uint32(kExpected)) - ExpectEq("17", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{17, true, false, ""}, - equalsTestCase{17.0, true, false, ""}, - equalsTestCase{17 + 0i, true, false, ""}, - equalsTestCase{int(kExpected), true, false, ""}, - equalsTestCase{int8(kExpected), true, false, ""}, - equalsTestCase{int16(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint(kExpected), true, false, ""}, - equalsTestCase{uint8(kExpected), true, false, ""}, - equalsTestCase{uint16(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric types. - equalsTestCase{kExpected + 1, false, false, ""}, - equalsTestCase{int(kExpected + 1), false, false, ""}, - equalsTestCase{int8(kExpected + 1), false, false, ""}, - equalsTestCase{int16(kExpected + 1), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint(kExpected + 1), false, false, ""}, - equalsTestCase{uint8(kExpected + 1), false, false, ""}, - equalsTestCase{uint16(kExpected + 1), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected + 1), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex64(kExpected + 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 1), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargeUint32() { - const kExpected = (1 << 16) + 17 - matcher := Equals(uint32(kExpected)) - ExpectEq("65553", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{65553, true, false, ""}, - equalsTestCase{65553.0, true, false, ""}, - equalsTestCase{65553 + 0i, true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric types. - equalsTestCase{int16(17), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint16(17), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected + 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 1), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Uint32NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := Equals(uint32(kTwoTo25 + 1)) - ExpectEq("33554433", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{int64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 2), false, false, ""}, - - equalsTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - - // Single-precision floating point. - equalsTestCase{float32(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{float32(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{complex64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{complex64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 3), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{float64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 2), false, false, ""}, - - equalsTestCase{complex128(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 2), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// uint64 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) SmallUint64() { - const kExpected = 17 - matcher := Equals(uint64(kExpected)) - ExpectEq("17", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{17, true, false, ""}, - equalsTestCase{17.0, true, false, ""}, - equalsTestCase{17 + 0i, true, false, ""}, - equalsTestCase{int(kExpected), true, false, ""}, - equalsTestCase{int8(kExpected), true, false, ""}, - equalsTestCase{int16(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint(kExpected), true, false, ""}, - equalsTestCase{uint8(kExpected), true, false, ""}, - equalsTestCase{uint16(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric types. - equalsTestCase{kExpected + 1, false, false, ""}, - equalsTestCase{int(kExpected + 1), false, false, ""}, - equalsTestCase{int8(kExpected + 1), false, false, ""}, - equalsTestCase{int16(kExpected + 1), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint(kExpected + 1), false, false, ""}, - equalsTestCase{uint8(kExpected + 1), false, false, ""}, - equalsTestCase{uint16(kExpected + 1), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected + 1), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex64(kExpected + 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 1), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargeUint64() { - const kExpected = (1 << 32) + 17 - matcher := Equals(uint64(kExpected)) - ExpectEq("4294967313", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{4294967313.0, true, false, ""}, - equalsTestCase{4294967313 + 0i, true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric types. - equalsTestCase{int(17), false, false, ""}, - equalsTestCase{int32(17), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint(17), false, false, ""}, - equalsTestCase{uint32(17), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected + 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 1), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Uint64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := Equals(uint64(kTwoTo25 + 1)) - ExpectEq("33554433", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{int64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 2), false, false, ""}, - - equalsTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - - // Single-precision floating point. - equalsTestCase{float32(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{float32(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{complex64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{complex64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 3), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{float64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 2), false, false, ""}, - - equalsTestCase{complex128(kTwoTo25 + 0), false, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 2), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Uint64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := Equals(uint64(kTwoTo54 + 1)) - ExpectEq("18014398509481985", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo54 + 0), false, false, ""}, - equalsTestCase{int64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 2), false, false, ""}, - - equalsTestCase{uint64(kTwoTo54 + 0), false, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 2), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{float64(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 3), false, false, ""}, - - equalsTestCase{complex128(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{complex128(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// uintptr -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NilUintptr() { - var ptr1 uintptr - var ptr2 uintptr - - matcher := Equals(ptr1) - ExpectEq("0", matcher.Description()) - - cases := []equalsTestCase{ - // uintptrs - equalsTestCase{ptr1, true, false, ""}, - equalsTestCase{ptr2, true, false, ""}, - equalsTestCase{uintptr(0), true, false, ""}, - equalsTestCase{uintptr(17), false, false, ""}, - - // Other types. - equalsTestCase{0, false, true, "which is not a uintptr"}, - equalsTestCase{bool(false), false, true, "which is not a uintptr"}, - equalsTestCase{int(0), false, true, "which is not a uintptr"}, - equalsTestCase{int8(0), false, true, "which is not a uintptr"}, - equalsTestCase{int16(0), false, true, "which is not a uintptr"}, - equalsTestCase{int32(0), false, true, "which is not a uintptr"}, - equalsTestCase{int64(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint8(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint16(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint32(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint64(0), false, true, "which is not a uintptr"}, - equalsTestCase{true, false, true, "which is not a uintptr"}, - equalsTestCase{[...]int{}, false, true, "which is not a uintptr"}, - equalsTestCase{make(chan int), false, true, "which is not a uintptr"}, - equalsTestCase{func() {}, false, true, "which is not a uintptr"}, - equalsTestCase{map[int]int{}, false, true, "which is not a uintptr"}, - equalsTestCase{&someInt, false, true, "which is not a uintptr"}, - equalsTestCase{[]int{}, false, true, "which is not a uintptr"}, - equalsTestCase{"taco", false, true, "which is not a uintptr"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a uintptr"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NonNilUintptr() { - matcher := Equals(uintptr(17)) - ExpectEq("17", matcher.Description()) - - cases := []equalsTestCase{ - // uintptrs - equalsTestCase{uintptr(17), true, false, ""}, - equalsTestCase{uintptr(16), false, false, ""}, - equalsTestCase{uintptr(0), false, false, ""}, - - // Other types. - equalsTestCase{0, false, true, "which is not a uintptr"}, - equalsTestCase{bool(false), false, true, "which is not a uintptr"}, - equalsTestCase{int(0), false, true, "which is not a uintptr"}, - equalsTestCase{int8(0), false, true, "which is not a uintptr"}, - equalsTestCase{int16(0), false, true, "which is not a uintptr"}, - equalsTestCase{int32(0), false, true, "which is not a uintptr"}, - equalsTestCase{int64(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint8(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint16(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint32(0), false, true, "which is not a uintptr"}, - equalsTestCase{uint64(0), false, true, "which is not a uintptr"}, - equalsTestCase{true, false, true, "which is not a uintptr"}, - equalsTestCase{[...]int{}, false, true, "which is not a uintptr"}, - equalsTestCase{make(chan int), false, true, "which is not a uintptr"}, - equalsTestCase{func() {}, false, true, "which is not a uintptr"}, - equalsTestCase{map[int]int{}, false, true, "which is not a uintptr"}, - equalsTestCase{&someInt, false, true, "which is not a uintptr"}, - equalsTestCase{[]int{}, false, true, "which is not a uintptr"}, - equalsTestCase{"taco", false, true, "which is not a uintptr"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a uintptr"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// float32 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeIntegralFloat32() { - matcher := Equals(float32(-32769)) - ExpectEq("-32769", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of -32769. - equalsTestCase{-32769.0, true, false, ""}, - equalsTestCase{-32769 + 0i, true, false, ""}, - equalsTestCase{int32(-32769), true, false, ""}, - equalsTestCase{int64(-32769), true, false, ""}, - equalsTestCase{float32(-32769), true, false, ""}, - equalsTestCase{float64(-32769), true, false, ""}, - equalsTestCase{complex64(-32769), true, false, ""}, - equalsTestCase{complex128(-32769), true, false, ""}, - equalsTestCase{interface{}(float32(-32769)), true, false, ""}, - equalsTestCase{interface{}(int64(-32769)), true, false, ""}, - - // Values that would be -32769 in two's complement. - equalsTestCase{uint64((1 << 64) - 32769), false, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(-32770), false, false, ""}, - equalsTestCase{float32(-32769.1), false, false, ""}, - equalsTestCase{float32(-32768.9), false, false, ""}, - equalsTestCase{float64(-32769.1), false, false, ""}, - equalsTestCase{float64(-32768.9), false, false, ""}, - equalsTestCase{complex128(-32768), false, false, ""}, - equalsTestCase{complex128(-32769 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NegativeNonIntegralFloat32() { - matcher := Equals(float32(-32769.1)) - ExpectEq("-32769.1", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of -32769.1. - equalsTestCase{-32769.1, true, false, ""}, - equalsTestCase{-32769.1 + 0i, true, false, ""}, - equalsTestCase{float32(-32769.1), true, false, ""}, - equalsTestCase{float64(-32769.1), true, false, ""}, - equalsTestCase{complex64(-32769.1), true, false, ""}, - equalsTestCase{complex128(-32769.1), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int32(-32769), false, false, ""}, - equalsTestCase{int32(-32770), false, false, ""}, - equalsTestCase{int64(-32769), false, false, ""}, - equalsTestCase{int64(-32770), false, false, ""}, - equalsTestCase{float32(-32769.2), false, false, ""}, - equalsTestCase{float32(-32769.0), false, false, ""}, - equalsTestCase{float64(-32769.2), false, false, ""}, - equalsTestCase{complex128(-32769.1 + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargeNegativeFloat32() { - const kExpected = -1 * (1 << 65) - matcher := Equals(float32(kExpected)) - ExpectEq("-3.689349e+19", matcher.Description()) - - floatExpected := float32(kExpected) - castedInt := int64(floatExpected) - - cases := []equalsTestCase{ - // Equal values of numeric type. - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{castedInt, false, false, ""}, - equalsTestCase{int64(0), false, false, ""}, - equalsTestCase{int64(math.MinInt64), false, false, ""}, - equalsTestCase{int64(math.MaxInt64), false, false, ""}, - equalsTestCase{float32(kExpected / 2), false, false, ""}, - equalsTestCase{float64(kExpected / 2), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) ZeroFloat32() { - matcher := Equals(float32(0)) - ExpectEq("0", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of zero. - equalsTestCase{0.0, true, false, ""}, - equalsTestCase{0 + 0i, true, false, ""}, - equalsTestCase{int(0), true, false, ""}, - equalsTestCase{int8(0), true, false, ""}, - equalsTestCase{int16(0), true, false, ""}, - equalsTestCase{int32(0), true, false, ""}, - equalsTestCase{int64(0), true, false, ""}, - equalsTestCase{uint(0), true, false, ""}, - equalsTestCase{uint8(0), true, false, ""}, - equalsTestCase{uint16(0), true, false, ""}, - equalsTestCase{uint32(0), true, false, ""}, - equalsTestCase{uint64(0), true, false, ""}, - equalsTestCase{float32(0), true, false, ""}, - equalsTestCase{float64(0), true, false, ""}, - equalsTestCase{complex64(0), true, false, ""}, - equalsTestCase{complex128(0), true, false, ""}, - equalsTestCase{interface{}(float32(0)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(1), false, false, ""}, - equalsTestCase{int64(-1), false, false, ""}, - equalsTestCase{float32(1), false, false, ""}, - equalsTestCase{float32(-1), false, false, ""}, - equalsTestCase{complex128(0 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveIntegralFloat32() { - matcher := Equals(float32(32769)) - ExpectEq("32769", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 32769. - equalsTestCase{32769.0, true, false, ""}, - equalsTestCase{32769 + 0i, true, false, ""}, - equalsTestCase{int(32769), true, false, ""}, - equalsTestCase{int32(32769), true, false, ""}, - equalsTestCase{int64(32769), true, false, ""}, - equalsTestCase{uint(32769), true, false, ""}, - equalsTestCase{uint32(32769), true, false, ""}, - equalsTestCase{uint64(32769), true, false, ""}, - equalsTestCase{float32(32769), true, false, ""}, - equalsTestCase{float64(32769), true, false, ""}, - equalsTestCase{complex64(32769), true, false, ""}, - equalsTestCase{complex128(32769), true, false, ""}, - equalsTestCase{interface{}(float32(32769)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(32770), false, false, ""}, - equalsTestCase{uint64(32770), false, false, ""}, - equalsTestCase{float32(32769.1), false, false, ""}, - equalsTestCase{float32(32768.9), false, false, ""}, - equalsTestCase{float64(32769.1), false, false, ""}, - equalsTestCase{float64(32768.9), false, false, ""}, - equalsTestCase{complex128(32768), false, false, ""}, - equalsTestCase{complex128(32769 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveNonIntegralFloat32() { - matcher := Equals(float32(32769.1)) - ExpectEq("32769.1", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 32769.1. - equalsTestCase{32769.1, true, false, ""}, - equalsTestCase{32769.1 + 0i, true, false, ""}, - equalsTestCase{float32(32769.1), true, false, ""}, - equalsTestCase{float64(32769.1), true, false, ""}, - equalsTestCase{complex64(32769.1), true, false, ""}, - equalsTestCase{complex128(32769.1), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int32(32769), false, false, ""}, - equalsTestCase{int32(32770), false, false, ""}, - equalsTestCase{uint64(32769), false, false, ""}, - equalsTestCase{uint64(32770), false, false, ""}, - equalsTestCase{float32(32769.2), false, false, ""}, - equalsTestCase{float32(32769.0), false, false, ""}, - equalsTestCase{float64(32769.2), false, false, ""}, - equalsTestCase{complex128(32769.1 + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargePositiveFloat32() { - const kExpected = 1 << 65 - matcher := Equals(float32(kExpected)) - ExpectEq("3.689349e+19", matcher.Description()) - - floatExpected := float32(kExpected) - castedInt := uint64(floatExpected) - - cases := []equalsTestCase{ - // Equal values of numeric type. - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{castedInt, false, false, ""}, - equalsTestCase{int64(0), false, false, ""}, - equalsTestCase{int64(math.MinInt64), false, false, ""}, - equalsTestCase{int64(math.MaxInt64), false, false, ""}, - equalsTestCase{uint64(0), false, false, ""}, - equalsTestCase{uint64(math.MaxUint64), false, false, ""}, - equalsTestCase{float32(kExpected / 2), false, false, ""}, - equalsTestCase{float64(kExpected / 2), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Float32AboveExactIntegerRange() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := Equals(float32(kTwoTo25 + 1)) - ExpectEq("3.3554432e+07", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{int64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{uint64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{uint64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 3), false, false, ""}, - - // Single-precision floating point. - equalsTestCase{float32(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{float32(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{complex64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{complex64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 3), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{float64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{complex128(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{complex128(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// float64 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeIntegralFloat64() { - const kExpected = -(1 << 50) - matcher := Equals(float64(kExpected)) - ExpectEq("-1.125899906842624e+15", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{-1125899906842624.0, true, false, ""}, - equalsTestCase{-1125899906842624.0 + 0i, true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - equalsTestCase{interface{}(float64(kExpected)), true, false, ""}, - - // Values that would be kExpected in two's complement. - equalsTestCase{uint64((1 << 64) + kExpected), false, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected - (1 << 30)), false, false, ""}, - equalsTestCase{float32(kExpected + (1 << 30)), false, false, ""}, - equalsTestCase{float64(kExpected - 0.5), false, false, ""}, - equalsTestCase{float64(kExpected + 0.5), false, false, ""}, - equalsTestCase{complex128(kExpected - 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NegativeNonIntegralFloat64() { - const kTwoTo50 = 1 << 50 - const kExpected = -kTwoTo50 - 0.25 - - matcher := Equals(float64(kExpected)) - ExpectEq("-1.1258999068426242e+15", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{kExpected, true, false, ""}, - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(-kTwoTo50), false, false, ""}, - equalsTestCase{int64(-kTwoTo50 - 1), false, false, ""}, - equalsTestCase{float32(kExpected - (1 << 30)), false, false, ""}, - equalsTestCase{float64(kExpected - 0.25), false, false, ""}, - equalsTestCase{float64(kExpected + 0.25), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargeNegativeFloat64() { - const kExpected = -1 * (1 << 65) - matcher := Equals(float64(kExpected)) - ExpectEq("-3.6893488147419103e+19", matcher.Description()) - - floatExpected := float64(kExpected) - castedInt := int64(floatExpected) - - cases := []equalsTestCase{ - // Equal values of numeric type. - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{castedInt, false, false, ""}, - equalsTestCase{int64(0), false, false, ""}, - equalsTestCase{int64(math.MinInt64), false, false, ""}, - equalsTestCase{int64(math.MaxInt64), false, false, ""}, - equalsTestCase{float32(kExpected / 2), false, false, ""}, - equalsTestCase{float64(kExpected / 2), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) ZeroFloat64() { - matcher := Equals(float64(0)) - ExpectEq("0", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of zero. - equalsTestCase{0.0, true, false, ""}, - equalsTestCase{0 + 0i, true, false, ""}, - equalsTestCase{int(0), true, false, ""}, - equalsTestCase{int8(0), true, false, ""}, - equalsTestCase{int16(0), true, false, ""}, - equalsTestCase{int32(0), true, false, ""}, - equalsTestCase{int64(0), true, false, ""}, - equalsTestCase{uint(0), true, false, ""}, - equalsTestCase{uint8(0), true, false, ""}, - equalsTestCase{uint16(0), true, false, ""}, - equalsTestCase{uint32(0), true, false, ""}, - equalsTestCase{uint64(0), true, false, ""}, - equalsTestCase{float32(0), true, false, ""}, - equalsTestCase{float64(0), true, false, ""}, - equalsTestCase{complex64(0), true, false, ""}, - equalsTestCase{complex128(0), true, false, ""}, - equalsTestCase{interface{}(float32(0)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(1), false, false, ""}, - equalsTestCase{int64(-1), false, false, ""}, - equalsTestCase{float32(1), false, false, ""}, - equalsTestCase{float32(-1), false, false, ""}, - equalsTestCase{complex128(0 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveIntegralFloat64() { - const kExpected = 1 << 50 - matcher := Equals(float64(kExpected)) - ExpectEq("1.125899906842624e+15", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 32769. - equalsTestCase{1125899906842624.0, true, false, ""}, - equalsTestCase{1125899906842624.0 + 0i, true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - equalsTestCase{interface{}(float64(kExpected)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected - (1 << 30)), false, false, ""}, - equalsTestCase{float32(kExpected + (1 << 30)), false, false, ""}, - equalsTestCase{float64(kExpected - 0.5), false, false, ""}, - equalsTestCase{float64(kExpected + 0.5), false, false, ""}, - equalsTestCase{complex128(kExpected - 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveNonIntegralFloat64() { - const kTwoTo50 = 1 << 50 - const kExpected = kTwoTo50 + 0.25 - matcher := Equals(float64(kExpected)) - ExpectEq("1.1258999068426242e+15", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{kExpected, true, false, ""}, - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(kTwoTo50), false, false, ""}, - equalsTestCase{int64(kTwoTo50 - 1), false, false, ""}, - equalsTestCase{float64(kExpected - 0.25), false, false, ""}, - equalsTestCase{float64(kExpected + 0.25), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargePositiveFloat64() { - const kExpected = 1 << 65 - matcher := Equals(float64(kExpected)) - ExpectEq("3.6893488147419103e+19", matcher.Description()) - - floatExpected := float64(kExpected) - castedInt := uint64(floatExpected) - - cases := []equalsTestCase{ - // Equal values of numeric type. - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{castedInt, false, false, ""}, - equalsTestCase{int64(0), false, false, ""}, - equalsTestCase{int64(math.MinInt64), false, false, ""}, - equalsTestCase{int64(math.MaxInt64), false, false, ""}, - equalsTestCase{uint64(0), false, false, ""}, - equalsTestCase{uint64(math.MaxUint64), false, false, ""}, - equalsTestCase{float32(kExpected / 2), false, false, ""}, - equalsTestCase{float64(kExpected / 2), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Float64AboveExactIntegerRange() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := Equals(float64(kTwoTo54 + 1)) - ExpectEq("1.8014398509481984e+16", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{int64(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 3), false, false, ""}, - - equalsTestCase{uint64(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{uint64(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 3), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{float64(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 3), false, false, ""}, - - equalsTestCase{complex128(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{complex128(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// complex64 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeIntegralComplex64() { - const kExpected = -32769 - matcher := Equals(complex64(kExpected)) - ExpectEq("(-32769+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{-32769.0, true, false, ""}, - equalsTestCase{-32769.0 + 0i, true, false, ""}, - equalsTestCase{int(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - equalsTestCase{interface{}(float64(kExpected)), true, false, ""}, - - // Values that would be kExpected in two's complement. - equalsTestCase{uint32((1 << 32) + kExpected), false, false, ""}, - equalsTestCase{uint64((1 << 64) + kExpected), false, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected - (1 << 30)), false, false, ""}, - equalsTestCase{float32(kExpected + (1 << 30)), false, false, ""}, - equalsTestCase{float64(kExpected - 0.5), false, false, ""}, - equalsTestCase{float64(kExpected + 0.5), false, false, ""}, - equalsTestCase{complex64(kExpected - 1), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected - 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NegativeNonIntegralComplex64() { - const kTwoTo20 = 1 << 20 - const kExpected = -kTwoTo20 - 0.25 - - matcher := Equals(complex64(kExpected)) - ExpectEq("(-1.0485762e+06+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{kExpected, true, false, ""}, - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(-kTwoTo20), false, false, ""}, - equalsTestCase{int(-kTwoTo20 - 1), false, false, ""}, - equalsTestCase{int32(-kTwoTo20), false, false, ""}, - equalsTestCase{int32(-kTwoTo20 - 1), false, false, ""}, - equalsTestCase{int64(-kTwoTo20), false, false, ""}, - equalsTestCase{int64(-kTwoTo20 - 1), false, false, ""}, - equalsTestCase{float32(kExpected - (1 << 30)), false, false, ""}, - equalsTestCase{float64(kExpected - 0.25), false, false, ""}, - equalsTestCase{float64(kExpected + 0.25), false, false, ""}, - equalsTestCase{complex64(kExpected - 0.75), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected - 0.75), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargeNegativeComplex64() { - const kExpected = -1 * (1 << 65) - matcher := Equals(complex64(kExpected)) - ExpectEq("(-3.689349e+19+0i)", matcher.Description()) - - floatExpected := float64(kExpected) - castedInt := int64(floatExpected) - - cases := []equalsTestCase{ - // Equal values of numeric type. - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{castedInt, false, false, ""}, - equalsTestCase{int64(0), false, false, ""}, - equalsTestCase{int64(math.MinInt64), false, false, ""}, - equalsTestCase{int64(math.MaxInt64), false, false, ""}, - equalsTestCase{float32(kExpected / 2), false, false, ""}, - equalsTestCase{float64(kExpected / 2), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) ZeroComplex64() { - matcher := Equals(complex64(0)) - ExpectEq("(0+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of zero. - equalsTestCase{0.0, true, false, ""}, - equalsTestCase{0 + 0i, true, false, ""}, - equalsTestCase{int(0), true, false, ""}, - equalsTestCase{int8(0), true, false, ""}, - equalsTestCase{int16(0), true, false, ""}, - equalsTestCase{int32(0), true, false, ""}, - equalsTestCase{int64(0), true, false, ""}, - equalsTestCase{uint(0), true, false, ""}, - equalsTestCase{uint8(0), true, false, ""}, - equalsTestCase{uint16(0), true, false, ""}, - equalsTestCase{uint32(0), true, false, ""}, - equalsTestCase{uint64(0), true, false, ""}, - equalsTestCase{float32(0), true, false, ""}, - equalsTestCase{float64(0), true, false, ""}, - equalsTestCase{complex64(0), true, false, ""}, - equalsTestCase{complex128(0), true, false, ""}, - equalsTestCase{interface{}(float32(0)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(1), false, false, ""}, - equalsTestCase{int64(-1), false, false, ""}, - equalsTestCase{float32(1), false, false, ""}, - equalsTestCase{float32(-1), false, false, ""}, - equalsTestCase{float64(1), false, false, ""}, - equalsTestCase{float64(-1), false, false, ""}, - equalsTestCase{complex64(0 + 2i), false, false, ""}, - equalsTestCase{complex128(0 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveIntegralComplex64() { - const kExpected = 1 << 20 - matcher := Equals(complex64(kExpected)) - ExpectEq("(1.048576e+06+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 32769. - equalsTestCase{1048576.0, true, false, ""}, - equalsTestCase{1048576.0 + 0i, true, false, ""}, - equalsTestCase{int(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - equalsTestCase{interface{}(float64(kExpected)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(kExpected + 1), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint(kExpected + 1), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected - (1 << 30)), false, false, ""}, - equalsTestCase{float32(kExpected + (1 << 30)), false, false, ""}, - equalsTestCase{float64(kExpected - 0.5), false, false, ""}, - equalsTestCase{float64(kExpected + 0.5), false, false, ""}, - equalsTestCase{complex128(kExpected - 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveNonIntegralComplex64() { - const kTwoTo20 = 1 << 20 - const kExpected = kTwoTo20 + 0.25 - matcher := Equals(complex64(kExpected)) - ExpectEq("(1.0485762e+06+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{kExpected, true, false, ""}, - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(kTwoTo20), false, false, ""}, - equalsTestCase{int64(kTwoTo20 - 1), false, false, ""}, - equalsTestCase{uint64(kTwoTo20), false, false, ""}, - equalsTestCase{uint64(kTwoTo20 - 1), false, false, ""}, - equalsTestCase{float32(kExpected - 1), false, false, ""}, - equalsTestCase{float32(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected - 0.25), false, false, ""}, - equalsTestCase{float64(kExpected + 0.25), false, false, ""}, - equalsTestCase{complex64(kExpected - 1), false, false, ""}, - equalsTestCase{complex64(kExpected - 1i), false, false, ""}, - equalsTestCase{complex128(kExpected - 1), false, false, ""}, - equalsTestCase{complex128(kExpected - 1i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargePositiveComplex64() { - const kExpected = 1 << 65 - matcher := Equals(complex64(kExpected)) - ExpectEq("(3.689349e+19+0i)", matcher.Description()) - - floatExpected := float64(kExpected) - castedInt := uint64(floatExpected) - - cases := []equalsTestCase{ - // Equal values of numeric type. - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{castedInt, false, false, ""}, - equalsTestCase{int64(0), false, false, ""}, - equalsTestCase{int64(math.MinInt64), false, false, ""}, - equalsTestCase{int64(math.MaxInt64), false, false, ""}, - equalsTestCase{uint64(0), false, false, ""}, - equalsTestCase{uint64(math.MaxUint64), false, false, ""}, - equalsTestCase{float32(kExpected / 2), false, false, ""}, - equalsTestCase{float64(kExpected / 2), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Complex64AboveExactIntegerRange() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := Equals(complex64(kTwoTo25 + 1)) - ExpectEq("(3.3554432e+07+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{int64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{int64(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{uint64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{uint64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{uint64(kTwoTo25 + 3), false, false, ""}, - - // Single-precision floating point. - equalsTestCase{float32(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{float32(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{complex64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{complex64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{complex64(kTwoTo25 + 3), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{float64(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{float64(kTwoTo25 + 3), false, false, ""}, - - equalsTestCase{complex128(kTwoTo25 - 2), false, false, ""}, - equalsTestCase{complex128(kTwoTo25 - 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 0), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 2), true, false, ""}, - equalsTestCase{complex128(kTwoTo25 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Complex64WithNonZeroImaginaryPart() { - const kRealPart = 17 - const kImagPart = 0.25i - const kExpected = kRealPart + kImagPart - matcher := Equals(complex64(kExpected)) - ExpectEq("(17+0.25i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{kExpected, true, false, ""}, - equalsTestCase{kRealPart + kImagPart, true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(kRealPart), false, false, ""}, - equalsTestCase{int8(kRealPart), false, false, ""}, - equalsTestCase{int16(kRealPart), false, false, ""}, - equalsTestCase{int32(kRealPart), false, false, ""}, - equalsTestCase{int64(kRealPart), false, false, ""}, - equalsTestCase{uint(kRealPart), false, false, ""}, - equalsTestCase{uint8(kRealPart), false, false, ""}, - equalsTestCase{uint16(kRealPart), false, false, ""}, - equalsTestCase{uint32(kRealPart), false, false, ""}, - equalsTestCase{uint64(kRealPart), false, false, ""}, - equalsTestCase{float32(kRealPart), false, false, ""}, - equalsTestCase{float64(kRealPart), false, false, ""}, - equalsTestCase{complex64(kRealPart), false, false, ""}, - equalsTestCase{complex64(kRealPart + kImagPart + 0.5), false, false, ""}, - equalsTestCase{complex64(kRealPart + kImagPart + 0.5i), false, false, ""}, - equalsTestCase{complex128(kRealPart), false, false, ""}, - equalsTestCase{complex128(kRealPart + kImagPart + 0.5), false, false, ""}, - equalsTestCase{complex128(kRealPart + kImagPart + 0.5i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// complex128 -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NegativeIntegralComplex128() { - const kExpected = -32769 - matcher := Equals(complex128(kExpected)) - ExpectEq("(-32769+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{-32769.0, true, false, ""}, - equalsTestCase{-32769.0 + 0i, true, false, ""}, - equalsTestCase{int(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - equalsTestCase{interface{}(float64(kExpected)), true, false, ""}, - - // Values that would be kExpected in two's complement. - equalsTestCase{uint32((1 << 32) + kExpected), false, false, ""}, - equalsTestCase{uint64((1 << 64) + kExpected), false, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected - (1 << 30)), false, false, ""}, - equalsTestCase{float32(kExpected + (1 << 30)), false, false, ""}, - equalsTestCase{float64(kExpected - 0.5), false, false, ""}, - equalsTestCase{float64(kExpected + 0.5), false, false, ""}, - equalsTestCase{complex64(kExpected - 1), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected - 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NegativeNonIntegralComplex128() { - const kTwoTo20 = 1 << 20 - const kExpected = -kTwoTo20 - 0.25 - - matcher := Equals(complex128(kExpected)) - ExpectEq("(-1.04857625e+06+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{kExpected, true, false, ""}, - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(-kTwoTo20), false, false, ""}, - equalsTestCase{int(-kTwoTo20 - 1), false, false, ""}, - equalsTestCase{int32(-kTwoTo20), false, false, ""}, - equalsTestCase{int32(-kTwoTo20 - 1), false, false, ""}, - equalsTestCase{int64(-kTwoTo20), false, false, ""}, - equalsTestCase{int64(-kTwoTo20 - 1), false, false, ""}, - equalsTestCase{float32(kExpected - (1 << 30)), false, false, ""}, - equalsTestCase{float64(kExpected - 0.25), false, false, ""}, - equalsTestCase{float64(kExpected + 0.25), false, false, ""}, - equalsTestCase{complex64(kExpected - 0.75), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected - 0.75), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargeNegativeComplex128() { - const kExpected = -1 * (1 << 65) - matcher := Equals(complex128(kExpected)) - ExpectEq("(-3.6893488147419103e+19+0i)", matcher.Description()) - - floatExpected := float64(kExpected) - castedInt := int64(floatExpected) - - cases := []equalsTestCase{ - // Equal values of numeric type. - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{castedInt, false, false, ""}, - equalsTestCase{int64(0), false, false, ""}, - equalsTestCase{int64(math.MinInt64), false, false, ""}, - equalsTestCase{int64(math.MaxInt64), false, false, ""}, - equalsTestCase{float32(kExpected / 2), false, false, ""}, - equalsTestCase{float64(kExpected / 2), false, false, ""}, - equalsTestCase{complex64(kExpected + 2i), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) ZeroComplex128() { - matcher := Equals(complex128(0)) - ExpectEq("(0+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of zero. - equalsTestCase{0.0, true, false, ""}, - equalsTestCase{0 + 0i, true, false, ""}, - equalsTestCase{int(0), true, false, ""}, - equalsTestCase{int8(0), true, false, ""}, - equalsTestCase{int16(0), true, false, ""}, - equalsTestCase{int32(0), true, false, ""}, - equalsTestCase{int64(0), true, false, ""}, - equalsTestCase{uint(0), true, false, ""}, - equalsTestCase{uint8(0), true, false, ""}, - equalsTestCase{uint16(0), true, false, ""}, - equalsTestCase{uint32(0), true, false, ""}, - equalsTestCase{uint64(0), true, false, ""}, - equalsTestCase{float32(0), true, false, ""}, - equalsTestCase{float64(0), true, false, ""}, - equalsTestCase{complex64(0), true, false, ""}, - equalsTestCase{complex128(0), true, false, ""}, - equalsTestCase{interface{}(float32(0)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(1), false, false, ""}, - equalsTestCase{int64(-1), false, false, ""}, - equalsTestCase{float32(1), false, false, ""}, - equalsTestCase{float32(-1), false, false, ""}, - equalsTestCase{float64(1), false, false, ""}, - equalsTestCase{float64(-1), false, false, ""}, - equalsTestCase{complex64(0 + 2i), false, false, ""}, - equalsTestCase{complex128(0 + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveIntegralComplex128() { - const kExpected = 1 << 20 - matcher := Equals(complex128(kExpected)) - ExpectEq("(1.048576e+06+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of 32769. - equalsTestCase{1048576.0, true, false, ""}, - equalsTestCase{1048576.0 + 0i, true, false, ""}, - equalsTestCase{int(kExpected), true, false, ""}, - equalsTestCase{int32(kExpected), true, false, ""}, - equalsTestCase{int64(kExpected), true, false, ""}, - equalsTestCase{uint(kExpected), true, false, ""}, - equalsTestCase{uint32(kExpected), true, false, ""}, - equalsTestCase{uint64(kExpected), true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - equalsTestCase{interface{}(float64(kExpected)), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(kExpected + 1), false, false, ""}, - equalsTestCase{int32(kExpected + 1), false, false, ""}, - equalsTestCase{int64(kExpected + 1), false, false, ""}, - equalsTestCase{uint(kExpected + 1), false, false, ""}, - equalsTestCase{uint32(kExpected + 1), false, false, ""}, - equalsTestCase{uint64(kExpected + 1), false, false, ""}, - equalsTestCase{float32(kExpected - (1 << 30)), false, false, ""}, - equalsTestCase{float32(kExpected + (1 << 30)), false, false, ""}, - equalsTestCase{float64(kExpected - 0.5), false, false, ""}, - equalsTestCase{float64(kExpected + 0.5), false, false, ""}, - equalsTestCase{complex128(kExpected - 1), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - - // Non-numeric types. - equalsTestCase{uintptr(0), false, true, "which is not numeric"}, - equalsTestCase{true, false, true, "which is not numeric"}, - equalsTestCase{[...]int{}, false, true, "which is not numeric"}, - equalsTestCase{make(chan int), false, true, "which is not numeric"}, - equalsTestCase{func() {}, false, true, "which is not numeric"}, - equalsTestCase{map[int]int{}, false, true, "which is not numeric"}, - equalsTestCase{&someInt, false, true, "which is not numeric"}, - equalsTestCase{[]int{}, false, true, "which is not numeric"}, - equalsTestCase{"taco", false, true, "which is not numeric"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not numeric"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) PositiveNonIntegralComplex128() { - const kTwoTo20 = 1 << 20 - const kExpected = kTwoTo20 + 0.25 - matcher := Equals(complex128(kExpected)) - ExpectEq("(1.04857625e+06+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{kExpected, true, false, ""}, - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int64(kTwoTo20), false, false, ""}, - equalsTestCase{int64(kTwoTo20 - 1), false, false, ""}, - equalsTestCase{uint64(kTwoTo20), false, false, ""}, - equalsTestCase{uint64(kTwoTo20 - 1), false, false, ""}, - equalsTestCase{float32(kExpected - 1), false, false, ""}, - equalsTestCase{float32(kExpected + 1), false, false, ""}, - equalsTestCase{float64(kExpected - 0.25), false, false, ""}, - equalsTestCase{float64(kExpected + 0.25), false, false, ""}, - equalsTestCase{complex64(kExpected - 1), false, false, ""}, - equalsTestCase{complex64(kExpected - 1i), false, false, ""}, - equalsTestCase{complex128(kExpected - 1), false, false, ""}, - equalsTestCase{complex128(kExpected - 1i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) LargePositiveComplex128() { - const kExpected = 1 << 65 - matcher := Equals(complex128(kExpected)) - ExpectEq("(3.6893488147419103e+19+0i)", matcher.Description()) - - floatExpected := float64(kExpected) - castedInt := uint64(floatExpected) - - cases := []equalsTestCase{ - // Equal values of numeric type. - equalsTestCase{kExpected + 0i, true, false, ""}, - equalsTestCase{float32(kExpected), true, false, ""}, - equalsTestCase{float64(kExpected), true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{castedInt, false, false, ""}, - equalsTestCase{int64(0), false, false, ""}, - equalsTestCase{int64(math.MinInt64), false, false, ""}, - equalsTestCase{int64(math.MaxInt64), false, false, ""}, - equalsTestCase{uint64(0), false, false, ""}, - equalsTestCase{uint64(math.MaxUint64), false, false, ""}, - equalsTestCase{float32(kExpected / 2), false, false, ""}, - equalsTestCase{float64(kExpected / 2), false, false, ""}, - equalsTestCase{complex128(kExpected + 2i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Complex128AboveExactIntegerRange() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := Equals(complex128(kTwoTo54 + 1)) - ExpectEq("(1.8014398509481984e+16+0i)", matcher.Description()) - - cases := []equalsTestCase{ - // Integers. - equalsTestCase{int64(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{int64(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{int64(kTwoTo54 + 3), false, false, ""}, - - equalsTestCase{uint64(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{uint64(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{uint64(kTwoTo54 + 3), false, false, ""}, - - // Double-precision floating point. - equalsTestCase{float64(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{float64(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{float64(kTwoTo54 + 3), false, false, ""}, - - equalsTestCase{complex128(kTwoTo54 - 2), false, false, ""}, - equalsTestCase{complex128(kTwoTo54 - 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 0), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 1), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 2), true, false, ""}, - equalsTestCase{complex128(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) Complex128WithNonZeroImaginaryPart() { - const kRealPart = 17 - const kImagPart = 0.25i - const kExpected = kRealPart + kImagPart - matcher := Equals(complex128(kExpected)) - ExpectEq("(17+0.25i)", matcher.Description()) - - cases := []equalsTestCase{ - // Various types of the expected value. - equalsTestCase{kExpected, true, false, ""}, - equalsTestCase{kRealPart + kImagPart, true, false, ""}, - equalsTestCase{complex64(kExpected), true, false, ""}, - equalsTestCase{complex128(kExpected), true, false, ""}, - - // Non-equal values of numeric type. - equalsTestCase{int(kRealPart), false, false, ""}, - equalsTestCase{int8(kRealPart), false, false, ""}, - equalsTestCase{int16(kRealPart), false, false, ""}, - equalsTestCase{int32(kRealPart), false, false, ""}, - equalsTestCase{int64(kRealPart), false, false, ""}, - equalsTestCase{uint(kRealPart), false, false, ""}, - equalsTestCase{uint8(kRealPart), false, false, ""}, - equalsTestCase{uint16(kRealPart), false, false, ""}, - equalsTestCase{uint32(kRealPart), false, false, ""}, - equalsTestCase{uint64(kRealPart), false, false, ""}, - equalsTestCase{float32(kRealPart), false, false, ""}, - equalsTestCase{float64(kRealPart), false, false, ""}, - equalsTestCase{complex64(kRealPart), false, false, ""}, - equalsTestCase{complex64(kRealPart + kImagPart + 0.5), false, false, ""}, - equalsTestCase{complex64(kRealPart + kImagPart + 0.5i), false, false, ""}, - equalsTestCase{complex128(kRealPart), false, false, ""}, - equalsTestCase{complex128(kRealPart + kImagPart + 0.5), false, false, ""}, - equalsTestCase{complex128(kRealPart + kImagPart + 0.5i), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// array -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) Array() { - var someArray [3]int - f := func() { Equals(someArray) } - ExpectThat(f, Panics(HasSubstr("unsupported kind array"))) -} - -//////////////////////////////////////////////////////////////////////// -// chan -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NilChan() { - var nilChan1 chan int - var nilChan2 chan int - var nilChan3 chan uint - var nonNilChan1 chan int = make(chan int) - var nonNilChan2 chan uint = make(chan uint) - - matcher := Equals(nilChan1) - ExpectEq("", matcher.Description()) - - cases := []equalsTestCase{ - // int channels - equalsTestCase{nilChan1, true, false, ""}, - equalsTestCase{nilChan2, true, false, ""}, - equalsTestCase{nonNilChan1, false, false, ""}, - - // uint channels - equalsTestCase{nilChan3, false, true, "which is not a chan int"}, - equalsTestCase{nonNilChan2, false, true, "which is not a chan int"}, - - // Other types. - equalsTestCase{0, false, true, "which is not a chan int"}, - equalsTestCase{bool(false), false, true, "which is not a chan int"}, - equalsTestCase{int(0), false, true, "which is not a chan int"}, - equalsTestCase{int8(0), false, true, "which is not a chan int"}, - equalsTestCase{int16(0), false, true, "which is not a chan int"}, - equalsTestCase{int32(0), false, true, "which is not a chan int"}, - equalsTestCase{int64(0), false, true, "which is not a chan int"}, - equalsTestCase{uint(0), false, true, "which is not a chan int"}, - equalsTestCase{uint8(0), false, true, "which is not a chan int"}, - equalsTestCase{uint16(0), false, true, "which is not a chan int"}, - equalsTestCase{uint32(0), false, true, "which is not a chan int"}, - equalsTestCase{uint64(0), false, true, "which is not a chan int"}, - equalsTestCase{true, false, true, "which is not a chan int"}, - equalsTestCase{[...]int{}, false, true, "which is not a chan int"}, - equalsTestCase{func() {}, false, true, "which is not a chan int"}, - equalsTestCase{map[int]int{}, false, true, "which is not a chan int"}, - equalsTestCase{&someInt, false, true, "which is not a chan int"}, - equalsTestCase{[]int{}, false, true, "which is not a chan int"}, - equalsTestCase{"taco", false, true, "which is not a chan int"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a chan int"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NonNilChan() { - var nilChan1 chan int - var nilChan2 chan uint - var nonNilChan1 chan int = make(chan int) - var nonNilChan2 chan int = make(chan int) - var nonNilChan3 chan uint = make(chan uint) - - matcher := Equals(nonNilChan1) - ExpectEq(fmt.Sprintf("%v", nonNilChan1), matcher.Description()) - - cases := []equalsTestCase{ - // int channels - equalsTestCase{nonNilChan1, true, false, ""}, - equalsTestCase{nonNilChan2, false, false, ""}, - equalsTestCase{nilChan1, false, false, ""}, - - // uint channels - equalsTestCase{nilChan2, false, true, "which is not a chan int"}, - equalsTestCase{nonNilChan3, false, true, "which is not a chan int"}, - - // Other types. - equalsTestCase{0, false, true, "which is not a chan int"}, - equalsTestCase{bool(false), false, true, "which is not a chan int"}, - equalsTestCase{int(0), false, true, "which is not a chan int"}, - equalsTestCase{int8(0), false, true, "which is not a chan int"}, - equalsTestCase{int16(0), false, true, "which is not a chan int"}, - equalsTestCase{int32(0), false, true, "which is not a chan int"}, - equalsTestCase{int64(0), false, true, "which is not a chan int"}, - equalsTestCase{uint(0), false, true, "which is not a chan int"}, - equalsTestCase{uint8(0), false, true, "which is not a chan int"}, - equalsTestCase{uint16(0), false, true, "which is not a chan int"}, - equalsTestCase{uint32(0), false, true, "which is not a chan int"}, - equalsTestCase{uint64(0), false, true, "which is not a chan int"}, - equalsTestCase{true, false, true, "which is not a chan int"}, - equalsTestCase{[...]int{}, false, true, "which is not a chan int"}, - equalsTestCase{func() {}, false, true, "which is not a chan int"}, - equalsTestCase{map[int]int{}, false, true, "which is not a chan int"}, - equalsTestCase{&someInt, false, true, "which is not a chan int"}, - equalsTestCase{[]int{}, false, true, "which is not a chan int"}, - equalsTestCase{"taco", false, true, "which is not a chan int"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a chan int"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) ChanDirection() { - var chan1 chan<- int - var chan2 <-chan int - var chan3 chan int - - matcher := Equals(chan1) - ExpectEq(fmt.Sprintf("%v", chan1), matcher.Description()) - - cases := []equalsTestCase{ - equalsTestCase{chan1, true, false, ""}, - equalsTestCase{chan2, false, true, "which is not a chan<- int"}, - equalsTestCase{chan3, false, true, "which is not a chan<- int"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// func -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) Functions() { - func1 := func() {} - func2 := func() {} - func3 := func(x int) {} - - matcher := Equals(func1) - ExpectEq(fmt.Sprintf("%v", func1), matcher.Description()) - - cases := []equalsTestCase{ - // Functions. - equalsTestCase{func1, true, false, ""}, - equalsTestCase{func2, false, false, ""}, - equalsTestCase{func3, false, false, ""}, - - // Other types. - equalsTestCase{0, false, true, "which is not a function"}, - equalsTestCase{bool(false), false, true, "which is not a function"}, - equalsTestCase{int(0), false, true, "which is not a function"}, - equalsTestCase{int8(0), false, true, "which is not a function"}, - equalsTestCase{int16(0), false, true, "which is not a function"}, - equalsTestCase{int32(0), false, true, "which is not a function"}, - equalsTestCase{int64(0), false, true, "which is not a function"}, - equalsTestCase{uint(0), false, true, "which is not a function"}, - equalsTestCase{uint8(0), false, true, "which is not a function"}, - equalsTestCase{uint16(0), false, true, "which is not a function"}, - equalsTestCase{uint32(0), false, true, "which is not a function"}, - equalsTestCase{uint64(0), false, true, "which is not a function"}, - equalsTestCase{true, false, true, "which is not a function"}, - equalsTestCase{[...]int{}, false, true, "which is not a function"}, - equalsTestCase{map[int]int{}, false, true, "which is not a function"}, - equalsTestCase{&someInt, false, true, "which is not a function"}, - equalsTestCase{[]int{}, false, true, "which is not a function"}, - equalsTestCase{"taco", false, true, "which is not a function"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a function"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// map -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NilMap() { - var nilMap1 map[int]int - var nilMap2 map[int]int - var nilMap3 map[int]uint - var nonNilMap1 map[int]int = make(map[int]int) - var nonNilMap2 map[int]uint = make(map[int]uint) - - matcher := Equals(nilMap1) - ExpectEq("map[]", matcher.Description()) - - cases := []equalsTestCase{ - // Correct type. - equalsTestCase{nilMap1, true, false, ""}, - equalsTestCase{nilMap2, true, false, ""}, - equalsTestCase{nilMap3, true, false, ""}, - equalsTestCase{nonNilMap1, false, false, ""}, - equalsTestCase{nonNilMap2, false, false, ""}, - - // Other types. - equalsTestCase{0, false, true, "which is not a map"}, - equalsTestCase{bool(false), false, true, "which is not a map"}, - equalsTestCase{int(0), false, true, "which is not a map"}, - equalsTestCase{int8(0), false, true, "which is not a map"}, - equalsTestCase{int16(0), false, true, "which is not a map"}, - equalsTestCase{int32(0), false, true, "which is not a map"}, - equalsTestCase{int64(0), false, true, "which is not a map"}, - equalsTestCase{uint(0), false, true, "which is not a map"}, - equalsTestCase{uint8(0), false, true, "which is not a map"}, - equalsTestCase{uint16(0), false, true, "which is not a map"}, - equalsTestCase{uint32(0), false, true, "which is not a map"}, - equalsTestCase{uint64(0), false, true, "which is not a map"}, - equalsTestCase{true, false, true, "which is not a map"}, - equalsTestCase{[...]int{}, false, true, "which is not a map"}, - equalsTestCase{func() {}, false, true, "which is not a map"}, - equalsTestCase{&someInt, false, true, "which is not a map"}, - equalsTestCase{[]int{}, false, true, "which is not a map"}, - equalsTestCase{"taco", false, true, "which is not a map"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a map"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NonNilMap() { - var nilMap1 map[int]int - var nilMap2 map[int]uint - var nonNilMap1 map[int]int = make(map[int]int) - var nonNilMap2 map[int]int = make(map[int]int) - var nonNilMap3 map[int]uint = make(map[int]uint) - - matcher := Equals(nonNilMap1) - ExpectEq("map[]", matcher.Description()) - - cases := []equalsTestCase{ - // Correct type. - equalsTestCase{nonNilMap1, true, false, ""}, - equalsTestCase{nonNilMap2, false, false, ""}, - equalsTestCase{nonNilMap3, false, false, ""}, - equalsTestCase{nilMap1, false, false, ""}, - equalsTestCase{nilMap2, false, false, ""}, - - // Other types. - equalsTestCase{0, false, true, "which is not a map"}, - equalsTestCase{bool(false), false, true, "which is not a map"}, - equalsTestCase{int(0), false, true, "which is not a map"}, - equalsTestCase{int8(0), false, true, "which is not a map"}, - equalsTestCase{int16(0), false, true, "which is not a map"}, - equalsTestCase{int32(0), false, true, "which is not a map"}, - equalsTestCase{int64(0), false, true, "which is not a map"}, - equalsTestCase{uint(0), false, true, "which is not a map"}, - equalsTestCase{uint8(0), false, true, "which is not a map"}, - equalsTestCase{uint16(0), false, true, "which is not a map"}, - equalsTestCase{uint32(0), false, true, "which is not a map"}, - equalsTestCase{uint64(0), false, true, "which is not a map"}, - equalsTestCase{true, false, true, "which is not a map"}, - equalsTestCase{[...]int{}, false, true, "which is not a map"}, - equalsTestCase{func() {}, false, true, "which is not a map"}, - equalsTestCase{&someInt, false, true, "which is not a map"}, - equalsTestCase{[]int{}, false, true, "which is not a map"}, - equalsTestCase{"taco", false, true, "which is not a map"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a map"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Pointers -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NilPointer() { - var someInt int = 17 - var someUint uint = 17 - - var nilInt1 *int - var nilInt2 *int - var nilUint *uint - var nonNilInt *int = &someInt - var nonNilUint *uint = &someUint - - matcher := Equals(nilInt1) - ExpectEq("", matcher.Description()) - - cases := []equalsTestCase{ - // Correct type. - equalsTestCase{nilInt1, true, false, ""}, - equalsTestCase{nilInt2, true, false, ""}, - equalsTestCase{nonNilInt, false, false, ""}, - - // Incorrect type. - equalsTestCase{nilUint, false, true, "which is not a *int"}, - equalsTestCase{nonNilUint, false, true, "which is not a *int"}, - - // Other types. - equalsTestCase{0, false, true, "which is not a *int"}, - equalsTestCase{bool(false), false, true, "which is not a *int"}, - equalsTestCase{int(0), false, true, "which is not a *int"}, - equalsTestCase{int8(0), false, true, "which is not a *int"}, - equalsTestCase{int16(0), false, true, "which is not a *int"}, - equalsTestCase{int32(0), false, true, "which is not a *int"}, - equalsTestCase{int64(0), false, true, "which is not a *int"}, - equalsTestCase{uint(0), false, true, "which is not a *int"}, - equalsTestCase{uint8(0), false, true, "which is not a *int"}, - equalsTestCase{uint16(0), false, true, "which is not a *int"}, - equalsTestCase{uint32(0), false, true, "which is not a *int"}, - equalsTestCase{uint64(0), false, true, "which is not a *int"}, - equalsTestCase{true, false, true, "which is not a *int"}, - equalsTestCase{[...]int{}, false, true, "which is not a *int"}, - equalsTestCase{func() {}, false, true, "which is not a *int"}, - equalsTestCase{map[int]int{}, false, true, "which is not a *int"}, - equalsTestCase{[]int{}, false, true, "which is not a *int"}, - equalsTestCase{"taco", false, true, "which is not a *int"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a *int"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NonNilPointer() { - var someInt int = 17 - var someOtherInt int = 17 - var someUint uint = 17 - - var nilInt *int - var nilUint *uint - var nonNilInt1 *int = &someInt - var nonNilInt2 *int = &someOtherInt - var nonNilUint *uint = &someUint - - matcher := Equals(nonNilInt1) - ExpectEq(fmt.Sprintf("%v", nonNilInt1), matcher.Description()) - - cases := []equalsTestCase{ - // Correct type. - equalsTestCase{nonNilInt1, true, false, ""}, - equalsTestCase{nonNilInt2, false, false, ""}, - equalsTestCase{nilInt, false, false, ""}, - - // Incorrect type. - equalsTestCase{nilUint, false, true, "which is not a *int"}, - equalsTestCase{nonNilUint, false, true, "which is not a *int"}, - - // Other types. - equalsTestCase{0, false, true, "which is not a *int"}, - equalsTestCase{bool(false), false, true, "which is not a *int"}, - equalsTestCase{int(0), false, true, "which is not a *int"}, - equalsTestCase{int8(0), false, true, "which is not a *int"}, - equalsTestCase{int16(0), false, true, "which is not a *int"}, - equalsTestCase{int32(0), false, true, "which is not a *int"}, - equalsTestCase{int64(0), false, true, "which is not a *int"}, - equalsTestCase{uint(0), false, true, "which is not a *int"}, - equalsTestCase{uint8(0), false, true, "which is not a *int"}, - equalsTestCase{uint16(0), false, true, "which is not a *int"}, - equalsTestCase{uint32(0), false, true, "which is not a *int"}, - equalsTestCase{uint64(0), false, true, "which is not a *int"}, - equalsTestCase{true, false, true, "which is not a *int"}, - equalsTestCase{[...]int{}, false, true, "which is not a *int"}, - equalsTestCase{func() {}, false, true, "which is not a *int"}, - equalsTestCase{map[int]int{}, false, true, "which is not a *int"}, - equalsTestCase{[]int{}, false, true, "which is not a *int"}, - equalsTestCase{"taco", false, true, "which is not a *int"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a *int"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Slices -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NilSlice() { - var nilInt1 []int - var nilInt2 []int - var nilUint []uint - - var nonNilInt []int = make([]int, 0) - var nonNilUint []uint = make([]uint, 0) - - matcher := Equals(nilInt1) - ExpectEq("[]", matcher.Description()) - - cases := []equalsTestCase{ - // Correct type. - equalsTestCase{nilInt1, true, false, ""}, - equalsTestCase{nilInt2, true, false, ""}, - equalsTestCase{nonNilInt, false, false, ""}, - - // Incorrect type. - equalsTestCase{nilUint, false, true, "which is not a []int"}, - equalsTestCase{nonNilUint, false, true, "which is not a []int"}, - - // Other types. - equalsTestCase{0, false, true, "which is not a []int"}, - equalsTestCase{bool(false), false, true, "which is not a []int"}, - equalsTestCase{int(0), false, true, "which is not a []int"}, - equalsTestCase{int8(0), false, true, "which is not a []int"}, - equalsTestCase{int16(0), false, true, "which is not a []int"}, - equalsTestCase{int32(0), false, true, "which is not a []int"}, - equalsTestCase{int64(0), false, true, "which is not a []int"}, - equalsTestCase{uint(0), false, true, "which is not a []int"}, - equalsTestCase{uint8(0), false, true, "which is not a []int"}, - equalsTestCase{uint16(0), false, true, "which is not a []int"}, - equalsTestCase{uint32(0), false, true, "which is not a []int"}, - equalsTestCase{uint64(0), false, true, "which is not a []int"}, - equalsTestCase{true, false, true, "which is not a []int"}, - equalsTestCase{[...]int{}, false, true, "which is not a []int"}, - equalsTestCase{func() {}, false, true, "which is not a []int"}, - equalsTestCase{map[int]int{}, false, true, "which is not a []int"}, - equalsTestCase{"taco", false, true, "which is not a []int"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a []int"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NonNilSlice() { - nonNil := make([]int, 0) - f := func() { Equals(nonNil) } - ExpectThat(f, Panics(HasSubstr("non-nil slice"))) -} - -//////////////////////////////////////////////////////////////////////// -// string -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) String() { - partial := "taco" - expected := fmt.Sprintf("%s%d", partial, 1) - - matcher := Equals(expected) - ExpectEq("taco1", matcher.Description()) - - type stringAlias string - - cases := []equalsTestCase{ - // Correct types. - equalsTestCase{"taco1", true, false, ""}, - equalsTestCase{"taco" + "1", true, false, ""}, - equalsTestCase{expected, true, false, ""}, - equalsTestCase{stringAlias("taco1"), true, false, ""}, - - equalsTestCase{"", false, false, ""}, - equalsTestCase{"taco", false, false, ""}, - equalsTestCase{"taco1\x00", false, false, ""}, - equalsTestCase{"taco2", false, false, ""}, - equalsTestCase{stringAlias("taco2"), false, false, ""}, - - // Other types. - equalsTestCase{0, false, true, "which is not a string"}, - equalsTestCase{bool(false), false, true, "which is not a string"}, - equalsTestCase{int(0), false, true, "which is not a string"}, - equalsTestCase{int8(0), false, true, "which is not a string"}, - equalsTestCase{int16(0), false, true, "which is not a string"}, - equalsTestCase{int32(0), false, true, "which is not a string"}, - equalsTestCase{int64(0), false, true, "which is not a string"}, - equalsTestCase{uint(0), false, true, "which is not a string"}, - equalsTestCase{uint8(0), false, true, "which is not a string"}, - equalsTestCase{uint16(0), false, true, "which is not a string"}, - equalsTestCase{uint32(0), false, true, "which is not a string"}, - equalsTestCase{uint64(0), false, true, "which is not a string"}, - equalsTestCase{true, false, true, "which is not a string"}, - equalsTestCase{[...]int{}, false, true, "which is not a string"}, - equalsTestCase{func() {}, false, true, "which is not a string"}, - equalsTestCase{map[int]int{}, false, true, "which is not a string"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a string"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) StringAlias() { - type stringAlias string - - matcher := Equals(stringAlias("taco")) - ExpectEq("taco", matcher.Description()) - - cases := []equalsTestCase{ - // Correct types. - equalsTestCase{stringAlias("taco"), true, false, ""}, - equalsTestCase{"taco", true, false, ""}, - - equalsTestCase{"burrito", false, false, ""}, - equalsTestCase{stringAlias("burrito"), false, false, ""}, - - // Other types. - equalsTestCase{0, false, true, "which is not a string"}, - equalsTestCase{bool(false), false, true, "which is not a string"}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// struct -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) Struct() { - type someStruct struct{ foo uint } - f := func() { Equals(someStruct{17}) } - ExpectThat(f, Panics(HasSubstr("unsupported kind struct"))) -} - -//////////////////////////////////////////////////////////////////////// -// unsafe.Pointer -//////////////////////////////////////////////////////////////////////// - -func (t *EqualsTest) NilUnsafePointer() { - someInt := int(17) - - var nilPtr1 unsafe.Pointer - var nilPtr2 unsafe.Pointer - var nonNilPtr unsafe.Pointer = unsafe.Pointer(&someInt) - - matcher := Equals(nilPtr1) - ExpectEq("", matcher.Description()) - - cases := []equalsTestCase{ - // Correct type. - equalsTestCase{nilPtr1, true, false, ""}, - equalsTestCase{nilPtr2, true, false, ""}, - equalsTestCase{nonNilPtr, false, false, ""}, - - // Other types. - equalsTestCase{0, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{bool(false), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int8(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int16(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int32(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int64(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint8(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint16(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint32(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint64(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uintptr(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{true, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{[...]int{}, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{make(chan int), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{func() {}, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{map[int]int{}, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{&someInt, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{[]int{}, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{"taco", false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a unsafe.Pointer"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *EqualsTest) NonNilUnsafePointer() { - someInt := int(17) - someOtherInt := int(17) - - var nilPtr unsafe.Pointer - var nonNilPtr1 unsafe.Pointer = unsafe.Pointer(&someInt) - var nonNilPtr2 unsafe.Pointer = unsafe.Pointer(&someOtherInt) - - matcher := Equals(nonNilPtr1) - ExpectEq(fmt.Sprintf("%v", nonNilPtr1), matcher.Description()) - - cases := []equalsTestCase{ - // Correct type. - equalsTestCase{nonNilPtr1, true, false, ""}, - equalsTestCase{nonNilPtr2, false, false, ""}, - equalsTestCase{nilPtr, false, false, ""}, - - // Other types. - equalsTestCase{0, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{bool(false), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int8(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int16(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int32(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{int64(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint8(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint16(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint32(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uint64(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{uintptr(0), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{true, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{[...]int{}, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{make(chan int), false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{func() {}, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{map[int]int{}, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{&someInt, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{[]int{}, false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{"taco", false, true, "which is not a unsafe.Pointer"}, - equalsTestCase{equalsTestCase{}, false, true, "which is not a unsafe.Pointer"}, - } - - t.checkTestCases(matcher, cases) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/error.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/error.go deleted file mode 100644 index 8a078e3..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/error.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -// Error returns a matcher that matches non-nil values implementing the -// built-in error interface for whom the return value of Error() matches the -// supplied matcher. -// -// For example: -// -// err := errors.New("taco burrito") -// -// Error(Equals("taco burrito")) // matches err -// Error(HasSubstr("taco")) // matches err -// Error(HasSubstr("enchilada")) // doesn't match err -// -func Error(m Matcher) Matcher { - return &errorMatcher{m} -} - -type errorMatcher struct { - wrappedMatcher Matcher -} - -func (m *errorMatcher) Description() string { - return "error " + m.wrappedMatcher.Description() -} - -func (m *errorMatcher) Matches(c interface{}) error { - // Make sure that c is an error. - e, ok := c.(error) - if !ok { - return NewFatalError("which is not an error") - } - - // Pass on the error text to the wrapped matcher. - return m.wrappedMatcher.Matches(e.Error()) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/error_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/error_test.go deleted file mode 100644 index 1ff1999..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/error_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "errors" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type ErrorTest struct { - matcherCalled bool - suppliedCandidate interface{} - wrappedError error - - matcher Matcher -} - -func init() { RegisterTestSuite(&ErrorTest{}) } - -func (t *ErrorTest) SetUp(i *TestInfo) { - wrapped := &fakeMatcher{ - func(c interface{}) error { - t.matcherCalled = true - t.suppliedCandidate = c - return t.wrappedError - }, - "is foo", - } - - t.matcher = Error(wrapped) -} - -func isFatal(err error) bool { - _, isFatal := err.(*FatalError) - return isFatal -} - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *ErrorTest) Description() { - ExpectThat(t.matcher.Description(), Equals("error is foo")) -} - -func (t *ErrorTest) CandidateIsNil() { - err := t.matcher.Matches(nil) - - ExpectThat(t.matcherCalled, Equals(false)) - ExpectThat(err.Error(), Equals("which is not an error")) - ExpectTrue(isFatal(err)) -} - -func (t *ErrorTest) CandidateIsString() { - err := t.matcher.Matches("taco") - - ExpectThat(t.matcherCalled, Equals(false)) - ExpectThat(err.Error(), Equals("which is not an error")) - ExpectTrue(isFatal(err)) -} - -func (t *ErrorTest) CallsWrappedMatcher() { - candidate := errors.New("taco") - t.matcher.Matches(candidate) - - ExpectThat(t.matcherCalled, Equals(true)) - ExpectThat(t.suppliedCandidate, Equals("taco")) -} - -func (t *ErrorTest) ReturnsWrappedMatcherResult() { - t.wrappedError = errors.New("burrito") - err := t.matcher.Matches(errors.New("")) - ExpectThat(err, Equals(t.wrappedError)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go deleted file mode 100644 index 4b9d103..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "fmt" - "reflect" -) - -// GreaterOrEqual returns a matcher that matches integer, floating point, or -// strings values v such that v >= x. Comparison is not defined between numeric -// and string types, but is defined between all integer and floating point -// types. -// -// x must itself be an integer, floating point, or string type; otherwise, -// GreaterOrEqual will panic. -func GreaterOrEqual(x interface{}) Matcher { - desc := fmt.Sprintf("greater than or equal to %v", x) - - // Special case: make it clear that strings are strings. - if reflect.TypeOf(x).Kind() == reflect.String { - desc = fmt.Sprintf("greater than or equal to \"%s\"", x) - } - - return transformDescription(Not(LessThan(x)), desc) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal_test.go deleted file mode 100644 index 6f4700f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal_test.go +++ /dev/null @@ -1,1060 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "math" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type GreaterOrEqualTest struct { -} - -func init() { RegisterTestSuite(&GreaterOrEqualTest{}) } - -type geTestCase struct { - candidate interface{} - expectedResult bool - shouldBeFatal bool - expectedError string -} - -func (t *GreaterOrEqualTest) checkTestCases(matcher Matcher, cases []geTestCase) { - for i, c := range cases { - err := matcher.Matches(c.candidate) - - ExpectThat( - (err == nil), - Equals(c.expectedResult), - "Case %d (candidate %v)", - i, - c.candidate) - - if err == nil { - continue - } - - _, isFatal := err.(*FatalError) - ExpectEq( - c.shouldBeFatal, - isFatal, - "Case %d (candidate %v)", - i, - c.candidate) - - ExpectThat( - err, - Error(Equals(c.expectedError)), - "Case %d (candidate %v)", - i, - c.candidate) - } -} - -//////////////////////////////////////////////////////////////////////// -// Integer literals -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterOrEqualTest) IntegerCandidateBadTypes() { - matcher := GreaterOrEqual(int(-150)) - - cases := []geTestCase{ - geTestCase{true, false, true, "which is not comparable"}, - geTestCase{uintptr(17), false, true, "which is not comparable"}, - geTestCase{complex64(-151), false, true, "which is not comparable"}, - geTestCase{complex128(-151), false, true, "which is not comparable"}, - geTestCase{[...]int{-151}, false, true, "which is not comparable"}, - geTestCase{make(chan int), false, true, "which is not comparable"}, - geTestCase{func() {}, false, true, "which is not comparable"}, - geTestCase{map[int]int{}, false, true, "which is not comparable"}, - geTestCase{&geTestCase{}, false, true, "which is not comparable"}, - geTestCase{make([]int, 0), false, true, "which is not comparable"}, - geTestCase{"-151", false, true, "which is not comparable"}, - geTestCase{geTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) FloatCandidateBadTypes() { - matcher := GreaterOrEqual(float32(-150)) - - cases := []geTestCase{ - geTestCase{true, false, true, "which is not comparable"}, - geTestCase{uintptr(17), false, true, "which is not comparable"}, - geTestCase{complex64(-151), false, true, "which is not comparable"}, - geTestCase{complex128(-151), false, true, "which is not comparable"}, - geTestCase{[...]int{-151}, false, true, "which is not comparable"}, - geTestCase{make(chan int), false, true, "which is not comparable"}, - geTestCase{func() {}, false, true, "which is not comparable"}, - geTestCase{map[int]int{}, false, true, "which is not comparable"}, - geTestCase{&geTestCase{}, false, true, "which is not comparable"}, - geTestCase{make([]int, 0), false, true, "which is not comparable"}, - geTestCase{"-151", false, true, "which is not comparable"}, - geTestCase{geTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) StringCandidateBadTypes() { - matcher := GreaterOrEqual("17") - - cases := []geTestCase{ - geTestCase{true, false, true, "which is not comparable"}, - geTestCase{int(0), false, true, "which is not comparable"}, - geTestCase{int8(0), false, true, "which is not comparable"}, - geTestCase{int16(0), false, true, "which is not comparable"}, - geTestCase{int32(0), false, true, "which is not comparable"}, - geTestCase{int64(0), false, true, "which is not comparable"}, - geTestCase{uint(0), false, true, "which is not comparable"}, - geTestCase{uint8(0), false, true, "which is not comparable"}, - geTestCase{uint16(0), false, true, "which is not comparable"}, - geTestCase{uint32(0), false, true, "which is not comparable"}, - geTestCase{uint64(0), false, true, "which is not comparable"}, - geTestCase{uintptr(17), false, true, "which is not comparable"}, - geTestCase{float32(0), false, true, "which is not comparable"}, - geTestCase{float64(0), false, true, "which is not comparable"}, - geTestCase{complex64(-151), false, true, "which is not comparable"}, - geTestCase{complex128(-151), false, true, "which is not comparable"}, - geTestCase{[...]int{-151}, false, true, "which is not comparable"}, - geTestCase{make(chan int), false, true, "which is not comparable"}, - geTestCase{func() {}, false, true, "which is not comparable"}, - geTestCase{map[int]int{}, false, true, "which is not comparable"}, - geTestCase{&geTestCase{}, false, true, "which is not comparable"}, - geTestCase{make([]int, 0), false, true, "which is not comparable"}, - geTestCase{geTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) BadArgument() { - panicked := false - - defer func() { - ExpectThat(panicked, Equals(true)) - }() - - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - GreaterOrEqual(complex128(0)) -} - -//////////////////////////////////////////////////////////////////////// -// Integer literals -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterOrEqualTest) NegativeIntegerLiteral() { - matcher := GreaterOrEqual(-150) - desc := matcher.Description() - expectedDesc := "greater than or equal to -150" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{-(1 << 30), false, false, ""}, - geTestCase{-151, false, false, ""}, - geTestCase{-150, true, false, ""}, - geTestCase{0, true, false, ""}, - geTestCase{17, true, false, ""}, - - geTestCase{int(-(1 << 30)), false, false, ""}, - geTestCase{int(-151), false, false, ""}, - geTestCase{int(-150), true, false, ""}, - geTestCase{int(0), true, false, ""}, - geTestCase{int(17), true, false, ""}, - - geTestCase{int8(-127), true, false, ""}, - geTestCase{int8(0), true, false, ""}, - geTestCase{int8(17), true, false, ""}, - - geTestCase{int16(-(1 << 14)), false, false, ""}, - geTestCase{int16(-151), false, false, ""}, - geTestCase{int16(-150), true, false, ""}, - geTestCase{int16(0), true, false, ""}, - geTestCase{int16(17), true, false, ""}, - - geTestCase{int32(-(1 << 30)), false, false, ""}, - geTestCase{int32(-151), false, false, ""}, - geTestCase{int32(-150), true, false, ""}, - geTestCase{int32(0), true, false, ""}, - geTestCase{int32(17), true, false, ""}, - - geTestCase{int64(-(1 << 30)), false, false, ""}, - geTestCase{int64(-151), false, false, ""}, - geTestCase{int64(-150), true, false, ""}, - geTestCase{int64(0), true, false, ""}, - geTestCase{int64(17), true, false, ""}, - - // Unsigned integers. - geTestCase{uint((1 << 32) - 151), true, false, ""}, - geTestCase{uint(0), true, false, ""}, - geTestCase{uint(17), true, false, ""}, - - geTestCase{uint8(0), true, false, ""}, - geTestCase{uint8(17), true, false, ""}, - geTestCase{uint8(253), true, false, ""}, - - geTestCase{uint16((1 << 16) - 151), true, false, ""}, - geTestCase{uint16(0), true, false, ""}, - geTestCase{uint16(17), true, false, ""}, - - geTestCase{uint32((1 << 32) - 151), true, false, ""}, - geTestCase{uint32(0), true, false, ""}, - geTestCase{uint32(17), true, false, ""}, - - geTestCase{uint64((1 << 64) - 151), true, false, ""}, - geTestCase{uint64(0), true, false, ""}, - geTestCase{uint64(17), true, false, ""}, - - // Floating point. - geTestCase{float32(-(1 << 30)), false, false, ""}, - geTestCase{float32(-151), false, false, ""}, - geTestCase{float32(-150.1), false, false, ""}, - geTestCase{float32(-150), true, false, ""}, - geTestCase{float32(-149.9), true, false, ""}, - geTestCase{float32(0), true, false, ""}, - geTestCase{float32(17), true, false, ""}, - geTestCase{float32(160), true, false, ""}, - - geTestCase{float64(-(1 << 30)), false, false, ""}, - geTestCase{float64(-151), false, false, ""}, - geTestCase{float64(-150.1), false, false, ""}, - geTestCase{float64(-150), true, false, ""}, - geTestCase{float64(-149.9), true, false, ""}, - geTestCase{float64(0), true, false, ""}, - geTestCase{float64(17), true, false, ""}, - geTestCase{float64(160), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) ZeroIntegerLiteral() { - matcher := GreaterOrEqual(0) - desc := matcher.Description() - expectedDesc := "greater than or equal to 0" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{-(1 << 30), false, false, ""}, - geTestCase{-1, false, false, ""}, - geTestCase{0, true, false, ""}, - geTestCase{1, true, false, ""}, - geTestCase{17, true, false, ""}, - geTestCase{(1 << 30), true, false, ""}, - - geTestCase{int(-(1 << 30)), false, false, ""}, - geTestCase{int(-1), false, false, ""}, - geTestCase{int(0), true, false, ""}, - geTestCase{int(1), true, false, ""}, - geTestCase{int(17), true, false, ""}, - - geTestCase{int8(-1), false, false, ""}, - geTestCase{int8(0), true, false, ""}, - geTestCase{int8(1), true, false, ""}, - - geTestCase{int16(-(1 << 14)), false, false, ""}, - geTestCase{int16(-1), false, false, ""}, - geTestCase{int16(0), true, false, ""}, - geTestCase{int16(1), true, false, ""}, - geTestCase{int16(17), true, false, ""}, - - geTestCase{int32(-(1 << 30)), false, false, ""}, - geTestCase{int32(-1), false, false, ""}, - geTestCase{int32(0), true, false, ""}, - geTestCase{int32(1), true, false, ""}, - geTestCase{int32(17), true, false, ""}, - - geTestCase{int64(-(1 << 30)), false, false, ""}, - geTestCase{int64(-1), false, false, ""}, - geTestCase{int64(0), true, false, ""}, - geTestCase{int64(1), true, false, ""}, - geTestCase{int64(17), true, false, ""}, - - // Unsigned integers. - geTestCase{uint((1 << 32) - 1), true, false, ""}, - geTestCase{uint(0), true, false, ""}, - geTestCase{uint(17), true, false, ""}, - - geTestCase{uint8(0), true, false, ""}, - geTestCase{uint8(17), true, false, ""}, - geTestCase{uint8(253), true, false, ""}, - - geTestCase{uint16((1 << 16) - 1), true, false, ""}, - geTestCase{uint16(0), true, false, ""}, - geTestCase{uint16(17), true, false, ""}, - - geTestCase{uint32((1 << 32) - 1), true, false, ""}, - geTestCase{uint32(0), true, false, ""}, - geTestCase{uint32(17), true, false, ""}, - - geTestCase{uint64((1 << 64) - 1), true, false, ""}, - geTestCase{uint64(0), true, false, ""}, - geTestCase{uint64(17), true, false, ""}, - - // Floating point. - geTestCase{float32(-(1 << 30)), false, false, ""}, - geTestCase{float32(-1), false, false, ""}, - geTestCase{float32(-0.1), false, false, ""}, - geTestCase{float32(-0.0), true, false, ""}, - geTestCase{float32(0), true, false, ""}, - geTestCase{float32(0.1), true, false, ""}, - geTestCase{float32(17), true, false, ""}, - geTestCase{float32(160), true, false, ""}, - - geTestCase{float64(-(1 << 30)), false, false, ""}, - geTestCase{float64(-1), false, false, ""}, - geTestCase{float64(-0.1), false, false, ""}, - geTestCase{float64(-0), true, false, ""}, - geTestCase{float64(0), true, false, ""}, - geTestCase{float64(17), true, false, ""}, - geTestCase{float64(160), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) PositiveIntegerLiteral() { - matcher := GreaterOrEqual(150) - desc := matcher.Description() - expectedDesc := "greater than or equal to 150" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{-1, false, false, ""}, - geTestCase{149, false, false, ""}, - geTestCase{150, true, false, ""}, - geTestCase{151, true, false, ""}, - - geTestCase{int(-1), false, false, ""}, - geTestCase{int(149), false, false, ""}, - geTestCase{int(150), true, false, ""}, - geTestCase{int(151), true, false, ""}, - - geTestCase{int8(-1), false, false, ""}, - geTestCase{int8(0), false, false, ""}, - geTestCase{int8(17), false, false, ""}, - geTestCase{int8(127), false, false, ""}, - - geTestCase{int16(-1), false, false, ""}, - geTestCase{int16(149), false, false, ""}, - geTestCase{int16(150), true, false, ""}, - geTestCase{int16(151), true, false, ""}, - - geTestCase{int32(-1), false, false, ""}, - geTestCase{int32(149), false, false, ""}, - geTestCase{int32(150), true, false, ""}, - geTestCase{int32(151), true, false, ""}, - - geTestCase{int64(-1), false, false, ""}, - geTestCase{int64(149), false, false, ""}, - geTestCase{int64(150), true, false, ""}, - geTestCase{int64(151), true, false, ""}, - - // Unsigned integers. - geTestCase{uint(0), false, false, ""}, - geTestCase{uint(149), false, false, ""}, - geTestCase{uint(150), true, false, ""}, - geTestCase{uint(151), true, false, ""}, - - geTestCase{uint8(0), false, false, ""}, - geTestCase{uint8(127), false, false, ""}, - - geTestCase{uint16(0), false, false, ""}, - geTestCase{uint16(149), false, false, ""}, - geTestCase{uint16(150), true, false, ""}, - geTestCase{uint16(151), true, false, ""}, - - geTestCase{uint32(0), false, false, ""}, - geTestCase{uint32(149), false, false, ""}, - geTestCase{uint32(150), true, false, ""}, - geTestCase{uint32(151), true, false, ""}, - - geTestCase{uint64(0), false, false, ""}, - geTestCase{uint64(149), false, false, ""}, - geTestCase{uint64(150), true, false, ""}, - geTestCase{uint64(151), true, false, ""}, - - // Floating point. - geTestCase{float32(-1), false, false, ""}, - geTestCase{float32(149), false, false, ""}, - geTestCase{float32(149.9), false, false, ""}, - geTestCase{float32(150), true, false, ""}, - geTestCase{float32(150.1), true, false, ""}, - geTestCase{float32(151), true, false, ""}, - - geTestCase{float64(-1), false, false, ""}, - geTestCase{float64(149), false, false, ""}, - geTestCase{float64(149.9), false, false, ""}, - geTestCase{float64(150), true, false, ""}, - geTestCase{float64(150.1), true, false, ""}, - geTestCase{float64(151), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Float literals -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterOrEqualTest) NegativeFloatLiteral() { - matcher := GreaterOrEqual(-150.1) - desc := matcher.Description() - expectedDesc := "greater than or equal to -150.1" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{-(1 << 30), false, false, ""}, - geTestCase{-151, false, false, ""}, - geTestCase{-150, true, false, ""}, - geTestCase{0, true, false, ""}, - geTestCase{17, true, false, ""}, - - geTestCase{int(-(1 << 30)), false, false, ""}, - geTestCase{int(-151), false, false, ""}, - geTestCase{int(-150), true, false, ""}, - geTestCase{int(0), true, false, ""}, - geTestCase{int(17), true, false, ""}, - - geTestCase{int8(-127), true, false, ""}, - geTestCase{int8(0), true, false, ""}, - geTestCase{int8(17), true, false, ""}, - - geTestCase{int16(-(1 << 14)), false, false, ""}, - geTestCase{int16(-151), false, false, ""}, - geTestCase{int16(-150), true, false, ""}, - geTestCase{int16(0), true, false, ""}, - geTestCase{int16(17), true, false, ""}, - - geTestCase{int32(-(1 << 30)), false, false, ""}, - geTestCase{int32(-151), false, false, ""}, - geTestCase{int32(-150), true, false, ""}, - geTestCase{int32(0), true, false, ""}, - geTestCase{int32(17), true, false, ""}, - - geTestCase{int64(-(1 << 30)), false, false, ""}, - geTestCase{int64(-151), false, false, ""}, - geTestCase{int64(-150), true, false, ""}, - geTestCase{int64(0), true, false, ""}, - geTestCase{int64(17), true, false, ""}, - - // Unsigned integers. - geTestCase{uint((1 << 32) - 151), true, false, ""}, - geTestCase{uint(0), true, false, ""}, - geTestCase{uint(17), true, false, ""}, - - geTestCase{uint8(0), true, false, ""}, - geTestCase{uint8(17), true, false, ""}, - geTestCase{uint8(253), true, false, ""}, - - geTestCase{uint16((1 << 16) - 151), true, false, ""}, - geTestCase{uint16(0), true, false, ""}, - geTestCase{uint16(17), true, false, ""}, - - geTestCase{uint32((1 << 32) - 151), true, false, ""}, - geTestCase{uint32(0), true, false, ""}, - geTestCase{uint32(17), true, false, ""}, - - geTestCase{uint64((1 << 64) - 151), true, false, ""}, - geTestCase{uint64(0), true, false, ""}, - geTestCase{uint64(17), true, false, ""}, - - // Floating point. - geTestCase{float32(-(1 << 30)), false, false, ""}, - geTestCase{float32(-151), false, false, ""}, - geTestCase{float32(-150.2), false, false, ""}, - geTestCase{float32(-150.1), true, false, ""}, - geTestCase{float32(-150), true, false, ""}, - geTestCase{float32(0), true, false, ""}, - geTestCase{float32(17), true, false, ""}, - geTestCase{float32(160), true, false, ""}, - - geTestCase{float64(-(1 << 30)), false, false, ""}, - geTestCase{float64(-151), false, false, ""}, - geTestCase{float64(-150.2), false, false, ""}, - geTestCase{float64(-150.1), true, false, ""}, - geTestCase{float64(-150), true, false, ""}, - geTestCase{float64(0), true, false, ""}, - geTestCase{float64(17), true, false, ""}, - geTestCase{float64(160), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) PositiveFloatLiteral() { - matcher := GreaterOrEqual(149.9) - desc := matcher.Description() - expectedDesc := "greater than or equal to 149.9" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{-1, false, false, ""}, - geTestCase{149, false, false, ""}, - geTestCase{150, true, false, ""}, - geTestCase{151, true, false, ""}, - - geTestCase{int(-1), false, false, ""}, - geTestCase{int(149), false, false, ""}, - geTestCase{int(150), true, false, ""}, - geTestCase{int(151), true, false, ""}, - - geTestCase{int8(-1), false, false, ""}, - geTestCase{int8(0), false, false, ""}, - geTestCase{int8(17), false, false, ""}, - geTestCase{int8(127), false, false, ""}, - - geTestCase{int16(-1), false, false, ""}, - geTestCase{int16(149), false, false, ""}, - geTestCase{int16(150), true, false, ""}, - geTestCase{int16(151), true, false, ""}, - - geTestCase{int32(-1), false, false, ""}, - geTestCase{int32(149), false, false, ""}, - geTestCase{int32(150), true, false, ""}, - geTestCase{int32(151), true, false, ""}, - - geTestCase{int64(-1), false, false, ""}, - geTestCase{int64(149), false, false, ""}, - geTestCase{int64(150), true, false, ""}, - geTestCase{int64(151), true, false, ""}, - - // Unsigned integers. - geTestCase{uint(0), false, false, ""}, - geTestCase{uint(149), false, false, ""}, - geTestCase{uint(150), true, false, ""}, - geTestCase{uint(151), true, false, ""}, - - geTestCase{uint8(0), false, false, ""}, - geTestCase{uint8(127), false, false, ""}, - - geTestCase{uint16(0), false, false, ""}, - geTestCase{uint16(149), false, false, ""}, - geTestCase{uint16(150), true, false, ""}, - geTestCase{uint16(151), true, false, ""}, - - geTestCase{uint32(0), false, false, ""}, - geTestCase{uint32(149), false, false, ""}, - geTestCase{uint32(150), true, false, ""}, - geTestCase{uint32(151), true, false, ""}, - - geTestCase{uint64(0), false, false, ""}, - geTestCase{uint64(149), false, false, ""}, - geTestCase{uint64(150), true, false, ""}, - geTestCase{uint64(151), true, false, ""}, - - // Floating point. - geTestCase{float32(-1), false, false, ""}, - geTestCase{float32(149), false, false, ""}, - geTestCase{float32(149.8), false, false, ""}, - geTestCase{float32(149.9), true, false, ""}, - geTestCase{float32(150), true, false, ""}, - geTestCase{float32(151), true, false, ""}, - - geTestCase{float64(-1), false, false, ""}, - geTestCase{float64(149), false, false, ""}, - geTestCase{float64(149.8), false, false, ""}, - geTestCase{float64(149.9), true, false, ""}, - geTestCase{float64(150), true, false, ""}, - geTestCase{float64(151), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Subtle cases -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterOrEqualTest) Int64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := GreaterOrEqual(int64(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than or equal to 33554433" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{-1, false, false, ""}, - geTestCase{kTwoTo25 + 0, false, false, ""}, - geTestCase{kTwoTo25 + 1, true, false, ""}, - geTestCase{kTwoTo25 + 2, true, false, ""}, - - geTestCase{int(-1), false, false, ""}, - geTestCase{int(kTwoTo25 + 0), false, false, ""}, - geTestCase{int(kTwoTo25 + 1), true, false, ""}, - geTestCase{int(kTwoTo25 + 2), true, false, ""}, - - geTestCase{int8(-1), false, false, ""}, - geTestCase{int8(127), false, false, ""}, - - geTestCase{int16(-1), false, false, ""}, - geTestCase{int16(0), false, false, ""}, - geTestCase{int16(32767), false, false, ""}, - - geTestCase{int32(-1), false, false, ""}, - geTestCase{int32(kTwoTo25 + 0), false, false, ""}, - geTestCase{int32(kTwoTo25 + 1), true, false, ""}, - geTestCase{int32(kTwoTo25 + 2), true, false, ""}, - - geTestCase{int64(-1), false, false, ""}, - geTestCase{int64(kTwoTo25 + 0), false, false, ""}, - geTestCase{int64(kTwoTo25 + 1), true, false, ""}, - geTestCase{int64(kTwoTo25 + 2), true, false, ""}, - - // Unsigned integers. - geTestCase{uint(0), false, false, ""}, - geTestCase{uint(kTwoTo25 + 0), false, false, ""}, - geTestCase{uint(kTwoTo25 + 1), true, false, ""}, - geTestCase{uint(kTwoTo25 + 2), true, false, ""}, - - geTestCase{uint8(0), false, false, ""}, - geTestCase{uint8(255), false, false, ""}, - - geTestCase{uint16(0), false, false, ""}, - geTestCase{uint16(65535), false, false, ""}, - - geTestCase{uint32(0), false, false, ""}, - geTestCase{uint32(kTwoTo25 + 0), false, false, ""}, - geTestCase{uint32(kTwoTo25 + 1), true, false, ""}, - geTestCase{uint32(kTwoTo25 + 2), true, false, ""}, - - geTestCase{uint64(0), false, false, ""}, - geTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - geTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - geTestCase{uint64(kTwoTo25 + 2), true, false, ""}, - - // Floating point. - geTestCase{float32(-1), false, false, ""}, - geTestCase{float32(kTwoTo25 - 2), false, false, ""}, - geTestCase{float32(kTwoTo25 - 1), true, false, ""}, - geTestCase{float32(kTwoTo25 + 0), true, false, ""}, - geTestCase{float32(kTwoTo25 + 1), true, false, ""}, - geTestCase{float32(kTwoTo25 + 2), true, false, ""}, - geTestCase{float32(kTwoTo25 + 3), true, false, ""}, - - geTestCase{float64(-1), false, false, ""}, - geTestCase{float64(kTwoTo25 - 2), false, false, ""}, - geTestCase{float64(kTwoTo25 - 1), false, false, ""}, - geTestCase{float64(kTwoTo25 + 0), false, false, ""}, - geTestCase{float64(kTwoTo25 + 1), true, false, ""}, - geTestCase{float64(kTwoTo25 + 2), true, false, ""}, - geTestCase{float64(kTwoTo25 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) Int64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := GreaterOrEqual(int64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than or equal to 18014398509481985" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{-1, false, false, ""}, - geTestCase{1 << 30, false, false, ""}, - - geTestCase{int(-1), false, false, ""}, - geTestCase{int(math.MaxInt32), false, false, ""}, - - geTestCase{int8(-1), false, false, ""}, - geTestCase{int8(127), false, false, ""}, - - geTestCase{int16(-1), false, false, ""}, - geTestCase{int16(0), false, false, ""}, - geTestCase{int16(32767), false, false, ""}, - - geTestCase{int32(-1), false, false, ""}, - geTestCase{int32(math.MaxInt32), false, false, ""}, - - geTestCase{int64(-1), false, false, ""}, - geTestCase{int64(kTwoTo54 - 1), false, false, ""}, - geTestCase{int64(kTwoTo54 + 0), false, false, ""}, - geTestCase{int64(kTwoTo54 + 1), true, false, ""}, - geTestCase{int64(kTwoTo54 + 2), true, false, ""}, - - // Unsigned integers. - geTestCase{uint(0), false, false, ""}, - geTestCase{uint(math.MaxUint32), false, false, ""}, - - geTestCase{uint8(0), false, false, ""}, - geTestCase{uint8(255), false, false, ""}, - - geTestCase{uint16(0), false, false, ""}, - geTestCase{uint16(65535), false, false, ""}, - - geTestCase{uint32(0), false, false, ""}, - geTestCase{uint32(math.MaxUint32), false, false, ""}, - - geTestCase{uint64(0), false, false, ""}, - geTestCase{uint64(kTwoTo54 - 1), false, false, ""}, - geTestCase{uint64(kTwoTo54 + 0), false, false, ""}, - geTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - geTestCase{uint64(kTwoTo54 + 2), true, false, ""}, - - // Floating point. - geTestCase{float64(-1), false, false, ""}, - geTestCase{float64(kTwoTo54 - 2), false, false, ""}, - geTestCase{float64(kTwoTo54 - 1), true, false, ""}, - geTestCase{float64(kTwoTo54 + 0), true, false, ""}, - geTestCase{float64(kTwoTo54 + 1), true, false, ""}, - geTestCase{float64(kTwoTo54 + 2), true, false, ""}, - geTestCase{float64(kTwoTo54 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) Uint64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := GreaterOrEqual(uint64(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than or equal to 33554433" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{-1, false, false, ""}, - geTestCase{kTwoTo25 + 0, false, false, ""}, - geTestCase{kTwoTo25 + 1, true, false, ""}, - geTestCase{kTwoTo25 + 2, true, false, ""}, - - geTestCase{int(-1), false, false, ""}, - geTestCase{int(kTwoTo25 + 0), false, false, ""}, - geTestCase{int(kTwoTo25 + 1), true, false, ""}, - geTestCase{int(kTwoTo25 + 2), true, false, ""}, - - geTestCase{int8(-1), false, false, ""}, - geTestCase{int8(127), false, false, ""}, - - geTestCase{int16(-1), false, false, ""}, - geTestCase{int16(0), false, false, ""}, - geTestCase{int16(32767), false, false, ""}, - - geTestCase{int32(-1), false, false, ""}, - geTestCase{int32(kTwoTo25 + 0), false, false, ""}, - geTestCase{int32(kTwoTo25 + 1), true, false, ""}, - geTestCase{int32(kTwoTo25 + 2), true, false, ""}, - - geTestCase{int64(-1), false, false, ""}, - geTestCase{int64(kTwoTo25 + 0), false, false, ""}, - geTestCase{int64(kTwoTo25 + 1), true, false, ""}, - geTestCase{int64(kTwoTo25 + 2), true, false, ""}, - - // Unsigned integers. - geTestCase{uint(0), false, false, ""}, - geTestCase{uint(kTwoTo25 + 0), false, false, ""}, - geTestCase{uint(kTwoTo25 + 1), true, false, ""}, - geTestCase{uint(kTwoTo25 + 2), true, false, ""}, - - geTestCase{uint8(0), false, false, ""}, - geTestCase{uint8(255), false, false, ""}, - - geTestCase{uint16(0), false, false, ""}, - geTestCase{uint16(65535), false, false, ""}, - - geTestCase{uint32(0), false, false, ""}, - geTestCase{uint32(kTwoTo25 + 0), false, false, ""}, - geTestCase{uint32(kTwoTo25 + 1), true, false, ""}, - geTestCase{uint32(kTwoTo25 + 2), true, false, ""}, - - geTestCase{uint64(0), false, false, ""}, - geTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - geTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - geTestCase{uint64(kTwoTo25 + 2), true, false, ""}, - - // Floating point. - geTestCase{float32(-1), false, false, ""}, - geTestCase{float32(kTwoTo25 - 2), false, false, ""}, - geTestCase{float32(kTwoTo25 - 1), true, false, ""}, - geTestCase{float32(kTwoTo25 + 0), true, false, ""}, - geTestCase{float32(kTwoTo25 + 1), true, false, ""}, - geTestCase{float32(kTwoTo25 + 2), true, false, ""}, - geTestCase{float32(kTwoTo25 + 3), true, false, ""}, - - geTestCase{float64(-1), false, false, ""}, - geTestCase{float64(kTwoTo25 - 2), false, false, ""}, - geTestCase{float64(kTwoTo25 - 1), false, false, ""}, - geTestCase{float64(kTwoTo25 + 0), false, false, ""}, - geTestCase{float64(kTwoTo25 + 1), true, false, ""}, - geTestCase{float64(kTwoTo25 + 2), true, false, ""}, - geTestCase{float64(kTwoTo25 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) Uint64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := GreaterOrEqual(uint64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than or equal to 18014398509481985" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{-1, false, false, ""}, - geTestCase{1 << 30, false, false, ""}, - - geTestCase{int(-1), false, false, ""}, - geTestCase{int(math.MaxInt32), false, false, ""}, - - geTestCase{int8(-1), false, false, ""}, - geTestCase{int8(127), false, false, ""}, - - geTestCase{int16(-1), false, false, ""}, - geTestCase{int16(0), false, false, ""}, - geTestCase{int16(32767), false, false, ""}, - - geTestCase{int32(-1), false, false, ""}, - geTestCase{int32(math.MaxInt32), false, false, ""}, - - geTestCase{int64(-1), false, false, ""}, - geTestCase{int64(kTwoTo54 - 1), false, false, ""}, - geTestCase{int64(kTwoTo54 + 0), false, false, ""}, - geTestCase{int64(kTwoTo54 + 1), true, false, ""}, - geTestCase{int64(kTwoTo54 + 2), true, false, ""}, - - // Unsigned integers. - geTestCase{uint(0), false, false, ""}, - geTestCase{uint(math.MaxUint32), false, false, ""}, - - geTestCase{uint8(0), false, false, ""}, - geTestCase{uint8(255), false, false, ""}, - - geTestCase{uint16(0), false, false, ""}, - geTestCase{uint16(65535), false, false, ""}, - - geTestCase{uint32(0), false, false, ""}, - geTestCase{uint32(math.MaxUint32), false, false, ""}, - - geTestCase{uint64(0), false, false, ""}, - geTestCase{uint64(kTwoTo54 - 1), false, false, ""}, - geTestCase{uint64(kTwoTo54 + 0), false, false, ""}, - geTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - geTestCase{uint64(kTwoTo54 + 2), true, false, ""}, - - // Floating point. - geTestCase{float64(-1), false, false, ""}, - geTestCase{float64(kTwoTo54 - 2), false, false, ""}, - geTestCase{float64(kTwoTo54 - 1), true, false, ""}, - geTestCase{float64(kTwoTo54 + 0), true, false, ""}, - geTestCase{float64(kTwoTo54 + 1), true, false, ""}, - geTestCase{float64(kTwoTo54 + 2), true, false, ""}, - geTestCase{float64(kTwoTo54 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) Float32AboveExactIntegerRange() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := GreaterOrEqual(float32(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than or equal to 3.3554432e+07" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{int64(-1), false, false, ""}, - geTestCase{int64(kTwoTo25 - 2), false, false, ""}, - geTestCase{int64(kTwoTo25 - 1), true, false, ""}, - geTestCase{int64(kTwoTo25 + 0), true, false, ""}, - geTestCase{int64(kTwoTo25 + 1), true, false, ""}, - geTestCase{int64(kTwoTo25 + 2), true, false, ""}, - geTestCase{int64(kTwoTo25 + 3), true, false, ""}, - - // Unsigned integers. - geTestCase{uint64(0), false, false, ""}, - geTestCase{uint64(kTwoTo25 - 2), false, false, ""}, - geTestCase{uint64(kTwoTo25 - 1), true, false, ""}, - geTestCase{uint64(kTwoTo25 + 0), true, false, ""}, - geTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - geTestCase{uint64(kTwoTo25 + 2), true, false, ""}, - geTestCase{uint64(kTwoTo25 + 3), true, false, ""}, - - // Floating point. - geTestCase{float32(-1), false, false, ""}, - geTestCase{float32(kTwoTo25 - 2), false, false, ""}, - geTestCase{float32(kTwoTo25 - 1), true, false, ""}, - geTestCase{float32(kTwoTo25 + 0), true, false, ""}, - geTestCase{float32(kTwoTo25 + 1), true, false, ""}, - geTestCase{float32(kTwoTo25 + 2), true, false, ""}, - geTestCase{float32(kTwoTo25 + 3), true, false, ""}, - - geTestCase{float64(-1), false, false, ""}, - geTestCase{float64(kTwoTo25 - 2), false, false, ""}, - geTestCase{float64(kTwoTo25 - 1), true, false, ""}, - geTestCase{float64(kTwoTo25 + 0), true, false, ""}, - geTestCase{float64(kTwoTo25 + 1), true, false, ""}, - geTestCase{float64(kTwoTo25 + 2), true, false, ""}, - geTestCase{float64(kTwoTo25 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) Float64AboveExactIntegerRange() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := GreaterOrEqual(float64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than or equal to 1.8014398509481984e+16" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - // Signed integers. - geTestCase{int64(-1), false, false, ""}, - geTestCase{int64(kTwoTo54 - 2), false, false, ""}, - geTestCase{int64(kTwoTo54 - 1), true, false, ""}, - geTestCase{int64(kTwoTo54 + 0), true, false, ""}, - geTestCase{int64(kTwoTo54 + 1), true, false, ""}, - geTestCase{int64(kTwoTo54 + 2), true, false, ""}, - geTestCase{int64(kTwoTo54 + 3), true, false, ""}, - - // Unsigned integers. - geTestCase{uint64(0), false, false, ""}, - geTestCase{uint64(kTwoTo54 - 2), false, false, ""}, - geTestCase{uint64(kTwoTo54 - 1), true, false, ""}, - geTestCase{uint64(kTwoTo54 + 0), true, false, ""}, - geTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - geTestCase{uint64(kTwoTo54 + 2), true, false, ""}, - geTestCase{uint64(kTwoTo54 + 3), true, false, ""}, - - // Floating point. - geTestCase{float64(-1), false, false, ""}, - geTestCase{float64(kTwoTo54 - 2), false, false, ""}, - geTestCase{float64(kTwoTo54 - 1), true, false, ""}, - geTestCase{float64(kTwoTo54 + 0), true, false, ""}, - geTestCase{float64(kTwoTo54 + 1), true, false, ""}, - geTestCase{float64(kTwoTo54 + 2), true, false, ""}, - geTestCase{float64(kTwoTo54 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// String literals -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterOrEqualTest) EmptyString() { - matcher := GreaterOrEqual("") - desc := matcher.Description() - expectedDesc := "greater than or equal to \"\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - geTestCase{"", true, false, ""}, - geTestCase{"\x00", true, false, ""}, - geTestCase{"a", true, false, ""}, - geTestCase{"foo", true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) SingleNullByte() { - matcher := GreaterOrEqual("\x00") - desc := matcher.Description() - expectedDesc := "greater than or equal to \"\x00\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - geTestCase{"", false, false, ""}, - geTestCase{"\x00", true, false, ""}, - geTestCase{"a", true, false, ""}, - geTestCase{"foo", true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterOrEqualTest) LongerString() { - matcher := GreaterOrEqual("foo\x00") - desc := matcher.Description() - expectedDesc := "greater than or equal to \"foo\x00\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []geTestCase{ - geTestCase{"", false, false, ""}, - geTestCase{"\x00", false, false, ""}, - geTestCase{"bar", false, false, ""}, - geTestCase{"foo", false, false, ""}, - geTestCase{"foo\x00", true, false, ""}, - geTestCase{"fooa", true, false, ""}, - geTestCase{"qux", true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go deleted file mode 100644 index 3eef321..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "fmt" - "reflect" -) - -// GreaterThan returns a matcher that matches integer, floating point, or -// strings values v such that v > x. Comparison is not defined between numeric -// and string types, but is defined between all integer and floating point -// types. -// -// x must itself be an integer, floating point, or string type; otherwise, -// GreaterThan will panic. -func GreaterThan(x interface{}) Matcher { - desc := fmt.Sprintf("greater than %v", x) - - // Special case: make it clear that strings are strings. - if reflect.TypeOf(x).Kind() == reflect.String { - desc = fmt.Sprintf("greater than \"%s\"", x) - } - - return transformDescription(Not(LessOrEqual(x)), desc) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_than_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_than_test.go deleted file mode 100644 index edede07..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/greater_than_test.go +++ /dev/null @@ -1,1080 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "math" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type GreaterThanTest struct { -} - -func init() { RegisterTestSuite(&GreaterThanTest{}) } - -type gtTestCase struct { - candidate interface{} - expectedResult bool - shouldBeFatal bool - expectedError string -} - -func (t *GreaterThanTest) checkTestCases(matcher Matcher, cases []gtTestCase) { - for i, c := range cases { - err := matcher.Matches(c.candidate) - - ExpectThat( - (err == nil), - Equals(c.expectedResult), - "Case %d (candidate %v)", - i, - c.candidate) - - if err == nil { - continue - } - - _, isFatal := err.(*FatalError) - ExpectEq( - c.shouldBeFatal, - isFatal, - "Case %d (candidate %v)", - i, - c.candidate) - - ExpectThat( - err, - Error(Equals(c.expectedError)), - "Case %d (candidate %v)", - i, - c.candidate) - } -} - -//////////////////////////////////////////////////////////////////////// -// Integer literals -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterThanTest) IntegerCandidateBadTypes() { - matcher := GreaterThan(int(-150)) - - cases := []gtTestCase{ - gtTestCase{true, false, true, "which is not comparable"}, - gtTestCase{uintptr(17), false, true, "which is not comparable"}, - gtTestCase{complex64(-151), false, true, "which is not comparable"}, - gtTestCase{complex128(-151), false, true, "which is not comparable"}, - gtTestCase{[...]int{-151}, false, true, "which is not comparable"}, - gtTestCase{make(chan int), false, true, "which is not comparable"}, - gtTestCase{func() {}, false, true, "which is not comparable"}, - gtTestCase{map[int]int{}, false, true, "which is not comparable"}, - gtTestCase{>TestCase{}, false, true, "which is not comparable"}, - gtTestCase{make([]int, 0), false, true, "which is not comparable"}, - gtTestCase{"-151", false, true, "which is not comparable"}, - gtTestCase{gtTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) FloatCandidateBadTypes() { - matcher := GreaterThan(float32(-150)) - - cases := []gtTestCase{ - gtTestCase{true, false, true, "which is not comparable"}, - gtTestCase{uintptr(17), false, true, "which is not comparable"}, - gtTestCase{complex64(-151), false, true, "which is not comparable"}, - gtTestCase{complex128(-151), false, true, "which is not comparable"}, - gtTestCase{[...]int{-151}, false, true, "which is not comparable"}, - gtTestCase{make(chan int), false, true, "which is not comparable"}, - gtTestCase{func() {}, false, true, "which is not comparable"}, - gtTestCase{map[int]int{}, false, true, "which is not comparable"}, - gtTestCase{>TestCase{}, false, true, "which is not comparable"}, - gtTestCase{make([]int, 0), false, true, "which is not comparable"}, - gtTestCase{"-151", false, true, "which is not comparable"}, - gtTestCase{gtTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) StringCandidateBadTypes() { - matcher := GreaterThan("17") - - cases := []gtTestCase{ - gtTestCase{true, false, true, "which is not comparable"}, - gtTestCase{int(0), false, true, "which is not comparable"}, - gtTestCase{int8(0), false, true, "which is not comparable"}, - gtTestCase{int16(0), false, true, "which is not comparable"}, - gtTestCase{int32(0), false, true, "which is not comparable"}, - gtTestCase{int64(0), false, true, "which is not comparable"}, - gtTestCase{uint(0), false, true, "which is not comparable"}, - gtTestCase{uint8(0), false, true, "which is not comparable"}, - gtTestCase{uint16(0), false, true, "which is not comparable"}, - gtTestCase{uint32(0), false, true, "which is not comparable"}, - gtTestCase{uint64(0), false, true, "which is not comparable"}, - gtTestCase{uintptr(17), false, true, "which is not comparable"}, - gtTestCase{float32(0), false, true, "which is not comparable"}, - gtTestCase{float64(0), false, true, "which is not comparable"}, - gtTestCase{complex64(-151), false, true, "which is not comparable"}, - gtTestCase{complex128(-151), false, true, "which is not comparable"}, - gtTestCase{[...]int{-151}, false, true, "which is not comparable"}, - gtTestCase{make(chan int), false, true, "which is not comparable"}, - gtTestCase{func() {}, false, true, "which is not comparable"}, - gtTestCase{map[int]int{}, false, true, "which is not comparable"}, - gtTestCase{>TestCase{}, false, true, "which is not comparable"}, - gtTestCase{make([]int, 0), false, true, "which is not comparable"}, - gtTestCase{gtTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) BadArgument() { - panicked := false - - defer func() { - ExpectThat(panicked, Equals(true)) - }() - - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - GreaterThan(complex128(0)) -} - -//////////////////////////////////////////////////////////////////////// -// Integer literals -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterThanTest) NegativeIntegerLiteral() { - matcher := GreaterThan(-150) - desc := matcher.Description() - expectedDesc := "greater than -150" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{-(1 << 30), false, false, ""}, - gtTestCase{-151, false, false, ""}, - gtTestCase{-150, false, false, ""}, - gtTestCase{-149, true, false, ""}, - gtTestCase{0, true, false, ""}, - gtTestCase{17, true, false, ""}, - - gtTestCase{int(-(1 << 30)), false, false, ""}, - gtTestCase{int(-151), false, false, ""}, - gtTestCase{int(-150), false, false, ""}, - gtTestCase{int(-149), true, false, ""}, - gtTestCase{int(0), true, false, ""}, - gtTestCase{int(17), true, false, ""}, - - gtTestCase{int8(-127), true, false, ""}, - gtTestCase{int8(0), true, false, ""}, - gtTestCase{int8(17), true, false, ""}, - - gtTestCase{int16(-(1 << 14)), false, false, ""}, - gtTestCase{int16(-151), false, false, ""}, - gtTestCase{int16(-150), false, false, ""}, - gtTestCase{int16(-149), true, false, ""}, - gtTestCase{int16(0), true, false, ""}, - gtTestCase{int16(17), true, false, ""}, - - gtTestCase{int32(-(1 << 30)), false, false, ""}, - gtTestCase{int32(-151), false, false, ""}, - gtTestCase{int32(-150), false, false, ""}, - gtTestCase{int32(-149), true, false, ""}, - gtTestCase{int32(0), true, false, ""}, - gtTestCase{int32(17), true, false, ""}, - - gtTestCase{int64(-(1 << 30)), false, false, ""}, - gtTestCase{int64(-151), false, false, ""}, - gtTestCase{int64(-150), false, false, ""}, - gtTestCase{int64(-149), true, false, ""}, - gtTestCase{int64(0), true, false, ""}, - gtTestCase{int64(17), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint((1 << 32) - 151), true, false, ""}, - gtTestCase{uint(0), true, false, ""}, - gtTestCase{uint(17), true, false, ""}, - - gtTestCase{uint8(0), true, false, ""}, - gtTestCase{uint8(17), true, false, ""}, - gtTestCase{uint8(253), true, false, ""}, - - gtTestCase{uint16((1 << 16) - 151), true, false, ""}, - gtTestCase{uint16(0), true, false, ""}, - gtTestCase{uint16(17), true, false, ""}, - - gtTestCase{uint32((1 << 32) - 151), true, false, ""}, - gtTestCase{uint32(0), true, false, ""}, - gtTestCase{uint32(17), true, false, ""}, - - gtTestCase{uint64((1 << 64) - 151), true, false, ""}, - gtTestCase{uint64(0), true, false, ""}, - gtTestCase{uint64(17), true, false, ""}, - - // Floating point. - gtTestCase{float32(-(1 << 30)), false, false, ""}, - gtTestCase{float32(-151), false, false, ""}, - gtTestCase{float32(-150.1), false, false, ""}, - gtTestCase{float32(-150), false, false, ""}, - gtTestCase{float32(-149.9), true, false, ""}, - gtTestCase{float32(0), true, false, ""}, - gtTestCase{float32(17), true, false, ""}, - gtTestCase{float32(160), true, false, ""}, - - gtTestCase{float64(-(1 << 30)), false, false, ""}, - gtTestCase{float64(-151), false, false, ""}, - gtTestCase{float64(-150.1), false, false, ""}, - gtTestCase{float64(-150), false, false, ""}, - gtTestCase{float64(-149.9), true, false, ""}, - gtTestCase{float64(0), true, false, ""}, - gtTestCase{float64(17), true, false, ""}, - gtTestCase{float64(160), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) ZeroIntegerLiteral() { - matcher := GreaterThan(0) - desc := matcher.Description() - expectedDesc := "greater than 0" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{-(1 << 30), false, false, ""}, - gtTestCase{-1, false, false, ""}, - gtTestCase{0, false, false, ""}, - gtTestCase{1, true, false, ""}, - gtTestCase{17, true, false, ""}, - gtTestCase{(1 << 30), true, false, ""}, - - gtTestCase{int(-(1 << 30)), false, false, ""}, - gtTestCase{int(-1), false, false, ""}, - gtTestCase{int(0), false, false, ""}, - gtTestCase{int(1), true, false, ""}, - gtTestCase{int(17), true, false, ""}, - - gtTestCase{int8(-1), false, false, ""}, - gtTestCase{int8(0), false, false, ""}, - gtTestCase{int8(1), true, false, ""}, - - gtTestCase{int16(-(1 << 14)), false, false, ""}, - gtTestCase{int16(-1), false, false, ""}, - gtTestCase{int16(0), false, false, ""}, - gtTestCase{int16(1), true, false, ""}, - gtTestCase{int16(17), true, false, ""}, - - gtTestCase{int32(-(1 << 30)), false, false, ""}, - gtTestCase{int32(-1), false, false, ""}, - gtTestCase{int32(0), false, false, ""}, - gtTestCase{int32(1), true, false, ""}, - gtTestCase{int32(17), true, false, ""}, - - gtTestCase{int64(-(1 << 30)), false, false, ""}, - gtTestCase{int64(-1), false, false, ""}, - gtTestCase{int64(0), false, false, ""}, - gtTestCase{int64(1), true, false, ""}, - gtTestCase{int64(17), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint((1 << 32) - 1), true, false, ""}, - gtTestCase{uint(0), false, false, ""}, - gtTestCase{uint(1), true, false, ""}, - gtTestCase{uint(17), true, false, ""}, - - gtTestCase{uint8(0), false, false, ""}, - gtTestCase{uint8(1), true, false, ""}, - gtTestCase{uint8(17), true, false, ""}, - gtTestCase{uint8(253), true, false, ""}, - - gtTestCase{uint16((1 << 16) - 1), true, false, ""}, - gtTestCase{uint16(0), false, false, ""}, - gtTestCase{uint16(1), true, false, ""}, - gtTestCase{uint16(17), true, false, ""}, - - gtTestCase{uint32((1 << 32) - 1), true, false, ""}, - gtTestCase{uint32(0), false, false, ""}, - gtTestCase{uint32(1), true, false, ""}, - gtTestCase{uint32(17), true, false, ""}, - - gtTestCase{uint64((1 << 64) - 1), true, false, ""}, - gtTestCase{uint64(0), false, false, ""}, - gtTestCase{uint64(1), true, false, ""}, - gtTestCase{uint64(17), true, false, ""}, - - // Floating point. - gtTestCase{float32(-(1 << 30)), false, false, ""}, - gtTestCase{float32(-1), false, false, ""}, - gtTestCase{float32(-0.1), false, false, ""}, - gtTestCase{float32(-0.0), false, false, ""}, - gtTestCase{float32(0), false, false, ""}, - gtTestCase{float32(0.1), true, false, ""}, - gtTestCase{float32(17), true, false, ""}, - gtTestCase{float32(160), true, false, ""}, - - gtTestCase{float64(-(1 << 30)), false, false, ""}, - gtTestCase{float64(-1), false, false, ""}, - gtTestCase{float64(-0.1), false, false, ""}, - gtTestCase{float64(-0), false, false, ""}, - gtTestCase{float64(0), false, false, ""}, - gtTestCase{float64(0.1), true, false, ""}, - gtTestCase{float64(17), true, false, ""}, - gtTestCase{float64(160), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) PositiveIntegerLiteral() { - matcher := GreaterThan(150) - desc := matcher.Description() - expectedDesc := "greater than 150" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{-1, false, false, ""}, - gtTestCase{149, false, false, ""}, - gtTestCase{150, false, false, ""}, - gtTestCase{151, true, false, ""}, - - gtTestCase{int(-1), false, false, ""}, - gtTestCase{int(149), false, false, ""}, - gtTestCase{int(150), false, false, ""}, - gtTestCase{int(151), true, false, ""}, - - gtTestCase{int8(-1), false, false, ""}, - gtTestCase{int8(0), false, false, ""}, - gtTestCase{int8(17), false, false, ""}, - gtTestCase{int8(127), false, false, ""}, - - gtTestCase{int16(-1), false, false, ""}, - gtTestCase{int16(149), false, false, ""}, - gtTestCase{int16(150), false, false, ""}, - gtTestCase{int16(151), true, false, ""}, - - gtTestCase{int32(-1), false, false, ""}, - gtTestCase{int32(149), false, false, ""}, - gtTestCase{int32(150), false, false, ""}, - gtTestCase{int32(151), true, false, ""}, - - gtTestCase{int64(-1), false, false, ""}, - gtTestCase{int64(149), false, false, ""}, - gtTestCase{int64(150), false, false, ""}, - gtTestCase{int64(151), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint(0), false, false, ""}, - gtTestCase{uint(149), false, false, ""}, - gtTestCase{uint(150), false, false, ""}, - gtTestCase{uint(151), true, false, ""}, - - gtTestCase{uint8(0), false, false, ""}, - gtTestCase{uint8(127), false, false, ""}, - - gtTestCase{uint16(0), false, false, ""}, - gtTestCase{uint16(149), false, false, ""}, - gtTestCase{uint16(150), false, false, ""}, - gtTestCase{uint16(151), true, false, ""}, - - gtTestCase{uint32(0), false, false, ""}, - gtTestCase{uint32(149), false, false, ""}, - gtTestCase{uint32(150), false, false, ""}, - gtTestCase{uint32(151), true, false, ""}, - - gtTestCase{uint64(0), false, false, ""}, - gtTestCase{uint64(149), false, false, ""}, - gtTestCase{uint64(150), false, false, ""}, - gtTestCase{uint64(151), true, false, ""}, - - // Floating point. - gtTestCase{float32(-1), false, false, ""}, - gtTestCase{float32(149), false, false, ""}, - gtTestCase{float32(149.9), false, false, ""}, - gtTestCase{float32(150), false, false, ""}, - gtTestCase{float32(150.1), true, false, ""}, - gtTestCase{float32(151), true, false, ""}, - - gtTestCase{float64(-1), false, false, ""}, - gtTestCase{float64(149), false, false, ""}, - gtTestCase{float64(149.9), false, false, ""}, - gtTestCase{float64(150), false, false, ""}, - gtTestCase{float64(150.1), true, false, ""}, - gtTestCase{float64(151), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Float literals -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterThanTest) NegativeFloatLiteral() { - matcher := GreaterThan(-150.1) - desc := matcher.Description() - expectedDesc := "greater than -150.1" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{-(1 << 30), false, false, ""}, - gtTestCase{-151, false, false, ""}, - gtTestCase{-150.1, false, false, ""}, - gtTestCase{-150, true, false, ""}, - gtTestCase{-149, true, false, ""}, - gtTestCase{0, true, false, ""}, - gtTestCase{17, true, false, ""}, - - gtTestCase{int(-(1 << 30)), false, false, ""}, - gtTestCase{int(-151), false, false, ""}, - gtTestCase{int(-150), true, false, ""}, - gtTestCase{int(-149), true, false, ""}, - gtTestCase{int(0), true, false, ""}, - gtTestCase{int(17), true, false, ""}, - - gtTestCase{int8(-127), true, false, ""}, - gtTestCase{int8(0), true, false, ""}, - gtTestCase{int8(17), true, false, ""}, - - gtTestCase{int16(-(1 << 14)), false, false, ""}, - gtTestCase{int16(-151), false, false, ""}, - gtTestCase{int16(-150), true, false, ""}, - gtTestCase{int16(-149), true, false, ""}, - gtTestCase{int16(0), true, false, ""}, - gtTestCase{int16(17), true, false, ""}, - - gtTestCase{int32(-(1 << 30)), false, false, ""}, - gtTestCase{int32(-151), false, false, ""}, - gtTestCase{int32(-150), true, false, ""}, - gtTestCase{int32(-149), true, false, ""}, - gtTestCase{int32(0), true, false, ""}, - gtTestCase{int32(17), true, false, ""}, - - gtTestCase{int64(-(1 << 30)), false, false, ""}, - gtTestCase{int64(-151), false, false, ""}, - gtTestCase{int64(-150), true, false, ""}, - gtTestCase{int64(-149), true, false, ""}, - gtTestCase{int64(0), true, false, ""}, - gtTestCase{int64(17), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint((1 << 32) - 151), true, false, ""}, - gtTestCase{uint(0), true, false, ""}, - gtTestCase{uint(17), true, false, ""}, - - gtTestCase{uint8(0), true, false, ""}, - gtTestCase{uint8(17), true, false, ""}, - gtTestCase{uint8(253), true, false, ""}, - - gtTestCase{uint16((1 << 16) - 151), true, false, ""}, - gtTestCase{uint16(0), true, false, ""}, - gtTestCase{uint16(17), true, false, ""}, - - gtTestCase{uint32((1 << 32) - 151), true, false, ""}, - gtTestCase{uint32(0), true, false, ""}, - gtTestCase{uint32(17), true, false, ""}, - - gtTestCase{uint64((1 << 64) - 151), true, false, ""}, - gtTestCase{uint64(0), true, false, ""}, - gtTestCase{uint64(17), true, false, ""}, - - // Floating point. - gtTestCase{float32(-(1 << 30)), false, false, ""}, - gtTestCase{float32(-151), false, false, ""}, - gtTestCase{float32(-150.2), false, false, ""}, - gtTestCase{float32(-150.1), false, false, ""}, - gtTestCase{float32(-150), true, false, ""}, - gtTestCase{float32(0), true, false, ""}, - gtTestCase{float32(17), true, false, ""}, - gtTestCase{float32(160), true, false, ""}, - - gtTestCase{float64(-(1 << 30)), false, false, ""}, - gtTestCase{float64(-151), false, false, ""}, - gtTestCase{float64(-150.2), false, false, ""}, - gtTestCase{float64(-150.1), false, false, ""}, - gtTestCase{float64(-150), true, false, ""}, - gtTestCase{float64(0), true, false, ""}, - gtTestCase{float64(17), true, false, ""}, - gtTestCase{float64(160), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) PositiveFloatLiteral() { - matcher := GreaterThan(149.9) - desc := matcher.Description() - expectedDesc := "greater than 149.9" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{-1, false, false, ""}, - gtTestCase{149, false, false, ""}, - gtTestCase{149.9, false, false, ""}, - gtTestCase{150, true, false, ""}, - gtTestCase{151, true, false, ""}, - - gtTestCase{int(-1), false, false, ""}, - gtTestCase{int(149), false, false, ""}, - gtTestCase{int(150), true, false, ""}, - gtTestCase{int(151), true, false, ""}, - - gtTestCase{int8(-1), false, false, ""}, - gtTestCase{int8(0), false, false, ""}, - gtTestCase{int8(17), false, false, ""}, - gtTestCase{int8(127), false, false, ""}, - - gtTestCase{int16(-1), false, false, ""}, - gtTestCase{int16(149), false, false, ""}, - gtTestCase{int16(150), true, false, ""}, - gtTestCase{int16(151), true, false, ""}, - - gtTestCase{int32(-1), false, false, ""}, - gtTestCase{int32(149), false, false, ""}, - gtTestCase{int32(150), true, false, ""}, - gtTestCase{int32(151), true, false, ""}, - - gtTestCase{int64(-1), false, false, ""}, - gtTestCase{int64(149), false, false, ""}, - gtTestCase{int64(150), true, false, ""}, - gtTestCase{int64(151), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint(0), false, false, ""}, - gtTestCase{uint(149), false, false, ""}, - gtTestCase{uint(150), true, false, ""}, - gtTestCase{uint(151), true, false, ""}, - - gtTestCase{uint8(0), false, false, ""}, - gtTestCase{uint8(127), false, false, ""}, - - gtTestCase{uint16(0), false, false, ""}, - gtTestCase{uint16(149), false, false, ""}, - gtTestCase{uint16(150), true, false, ""}, - gtTestCase{uint16(151), true, false, ""}, - - gtTestCase{uint32(0), false, false, ""}, - gtTestCase{uint32(149), false, false, ""}, - gtTestCase{uint32(150), true, false, ""}, - gtTestCase{uint32(151), true, false, ""}, - - gtTestCase{uint64(0), false, false, ""}, - gtTestCase{uint64(149), false, false, ""}, - gtTestCase{uint64(150), true, false, ""}, - gtTestCase{uint64(151), true, false, ""}, - - // Floating point. - gtTestCase{float32(-1), false, false, ""}, - gtTestCase{float32(149), false, false, ""}, - gtTestCase{float32(149.8), false, false, ""}, - gtTestCase{float32(149.9), false, false, ""}, - gtTestCase{float32(150), true, false, ""}, - gtTestCase{float32(151), true, false, ""}, - - gtTestCase{float64(-1), false, false, ""}, - gtTestCase{float64(149), false, false, ""}, - gtTestCase{float64(149.8), false, false, ""}, - gtTestCase{float64(149.9), false, false, ""}, - gtTestCase{float64(150), true, false, ""}, - gtTestCase{float64(151), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Subtle cases -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterThanTest) Int64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := GreaterThan(int64(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than 33554433" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{-1, false, false, ""}, - gtTestCase{kTwoTo25 + 0, false, false, ""}, - gtTestCase{kTwoTo25 + 1, false, false, ""}, - gtTestCase{kTwoTo25 + 2, true, false, ""}, - - gtTestCase{int(-1), false, false, ""}, - gtTestCase{int(kTwoTo25 + 0), false, false, ""}, - gtTestCase{int(kTwoTo25 + 1), false, false, ""}, - gtTestCase{int(kTwoTo25 + 2), true, false, ""}, - - gtTestCase{int8(-1), false, false, ""}, - gtTestCase{int8(127), false, false, ""}, - - gtTestCase{int16(-1), false, false, ""}, - gtTestCase{int16(0), false, false, ""}, - gtTestCase{int16(32767), false, false, ""}, - - gtTestCase{int32(-1), false, false, ""}, - gtTestCase{int32(kTwoTo25 + 0), false, false, ""}, - gtTestCase{int32(kTwoTo25 + 1), false, false, ""}, - gtTestCase{int32(kTwoTo25 + 2), true, false, ""}, - - gtTestCase{int64(-1), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 0), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 1), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 2), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint(0), false, false, ""}, - gtTestCase{uint(kTwoTo25 + 0), false, false, ""}, - gtTestCase{uint(kTwoTo25 + 1), false, false, ""}, - gtTestCase{uint(kTwoTo25 + 2), true, false, ""}, - - gtTestCase{uint8(0), false, false, ""}, - gtTestCase{uint8(255), false, false, ""}, - - gtTestCase{uint16(0), false, false, ""}, - gtTestCase{uint16(65535), false, false, ""}, - - gtTestCase{uint32(0), false, false, ""}, - gtTestCase{uint32(kTwoTo25 + 0), false, false, ""}, - gtTestCase{uint32(kTwoTo25 + 1), false, false, ""}, - gtTestCase{uint32(kTwoTo25 + 2), true, false, ""}, - - gtTestCase{uint64(0), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 1), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 2), true, false, ""}, - - // Floating point. - gtTestCase{float32(-1), false, false, ""}, - gtTestCase{float32(kTwoTo25 - 2), false, false, ""}, - gtTestCase{float32(kTwoTo25 - 1), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 0), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 1), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 2), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 3), true, false, ""}, - - gtTestCase{float64(-1), false, false, ""}, - gtTestCase{float64(kTwoTo25 - 2), false, false, ""}, - gtTestCase{float64(kTwoTo25 - 1), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 0), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 1), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 2), true, false, ""}, - gtTestCase{float64(kTwoTo25 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) Int64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := GreaterThan(int64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than 18014398509481985" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{-1, false, false, ""}, - gtTestCase{1 << 30, false, false, ""}, - - gtTestCase{int(-1), false, false, ""}, - gtTestCase{int(math.MaxInt32), false, false, ""}, - - gtTestCase{int8(-1), false, false, ""}, - gtTestCase{int8(127), false, false, ""}, - - gtTestCase{int16(-1), false, false, ""}, - gtTestCase{int16(0), false, false, ""}, - gtTestCase{int16(32767), false, false, ""}, - - gtTestCase{int32(-1), false, false, ""}, - gtTestCase{int32(math.MaxInt32), false, false, ""}, - - gtTestCase{int64(-1), false, false, ""}, - gtTestCase{int64(kTwoTo54 - 1), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 0), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 1), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 2), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint(0), false, false, ""}, - gtTestCase{uint(math.MaxUint32), false, false, ""}, - - gtTestCase{uint8(0), false, false, ""}, - gtTestCase{uint8(255), false, false, ""}, - - gtTestCase{uint16(0), false, false, ""}, - gtTestCase{uint16(65535), false, false, ""}, - - gtTestCase{uint32(0), false, false, ""}, - gtTestCase{uint32(math.MaxUint32), false, false, ""}, - - gtTestCase{uint64(0), false, false, ""}, - gtTestCase{uint64(kTwoTo54 - 1), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 0), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 1), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 2), true, false, ""}, - - // Floating point. - gtTestCase{float64(-1), false, false, ""}, - gtTestCase{float64(kTwoTo54 - 2), false, false, ""}, - gtTestCase{float64(kTwoTo54 - 1), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 0), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 1), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 2), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) Uint64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := GreaterThan(uint64(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than 33554433" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{-1, false, false, ""}, - gtTestCase{kTwoTo25 + 0, false, false, ""}, - gtTestCase{kTwoTo25 + 1, false, false, ""}, - gtTestCase{kTwoTo25 + 2, true, false, ""}, - - gtTestCase{int(-1), false, false, ""}, - gtTestCase{int(kTwoTo25 + 0), false, false, ""}, - gtTestCase{int(kTwoTo25 + 1), false, false, ""}, - gtTestCase{int(kTwoTo25 + 2), true, false, ""}, - - gtTestCase{int8(-1), false, false, ""}, - gtTestCase{int8(127), false, false, ""}, - - gtTestCase{int16(-1), false, false, ""}, - gtTestCase{int16(0), false, false, ""}, - gtTestCase{int16(32767), false, false, ""}, - - gtTestCase{int32(-1), false, false, ""}, - gtTestCase{int32(kTwoTo25 + 0), false, false, ""}, - gtTestCase{int32(kTwoTo25 + 1), false, false, ""}, - gtTestCase{int32(kTwoTo25 + 2), true, false, ""}, - - gtTestCase{int64(-1), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 0), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 1), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 2), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint(0), false, false, ""}, - gtTestCase{uint(kTwoTo25 + 0), false, false, ""}, - gtTestCase{uint(kTwoTo25 + 1), false, false, ""}, - gtTestCase{uint(kTwoTo25 + 2), true, false, ""}, - - gtTestCase{uint8(0), false, false, ""}, - gtTestCase{uint8(255), false, false, ""}, - - gtTestCase{uint16(0), false, false, ""}, - gtTestCase{uint16(65535), false, false, ""}, - - gtTestCase{uint32(0), false, false, ""}, - gtTestCase{uint32(kTwoTo25 + 0), false, false, ""}, - gtTestCase{uint32(kTwoTo25 + 1), false, false, ""}, - gtTestCase{uint32(kTwoTo25 + 2), true, false, ""}, - - gtTestCase{uint64(0), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 1), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 2), true, false, ""}, - - // Floating point. - gtTestCase{float32(-1), false, false, ""}, - gtTestCase{float32(kTwoTo25 - 2), false, false, ""}, - gtTestCase{float32(kTwoTo25 - 1), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 0), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 1), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 2), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 3), true, false, ""}, - - gtTestCase{float64(-1), false, false, ""}, - gtTestCase{float64(kTwoTo25 - 2), false, false, ""}, - gtTestCase{float64(kTwoTo25 - 1), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 0), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 1), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 2), true, false, ""}, - gtTestCase{float64(kTwoTo25 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) Uint64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := GreaterThan(uint64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than 18014398509481985" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{-1, false, false, ""}, - gtTestCase{1 << 30, false, false, ""}, - - gtTestCase{int(-1), false, false, ""}, - gtTestCase{int(math.MaxInt32), false, false, ""}, - - gtTestCase{int8(-1), false, false, ""}, - gtTestCase{int8(127), false, false, ""}, - - gtTestCase{int16(-1), false, false, ""}, - gtTestCase{int16(0), false, false, ""}, - gtTestCase{int16(32767), false, false, ""}, - - gtTestCase{int32(-1), false, false, ""}, - gtTestCase{int32(math.MaxInt32), false, false, ""}, - - gtTestCase{int64(-1), false, false, ""}, - gtTestCase{int64(kTwoTo54 - 1), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 0), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 1), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 2), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint(0), false, false, ""}, - gtTestCase{uint(math.MaxUint32), false, false, ""}, - - gtTestCase{uint8(0), false, false, ""}, - gtTestCase{uint8(255), false, false, ""}, - - gtTestCase{uint16(0), false, false, ""}, - gtTestCase{uint16(65535), false, false, ""}, - - gtTestCase{uint32(0), false, false, ""}, - gtTestCase{uint32(math.MaxUint32), false, false, ""}, - - gtTestCase{uint64(0), false, false, ""}, - gtTestCase{uint64(kTwoTo54 - 1), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 0), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 1), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 2), true, false, ""}, - - // Floating point. - gtTestCase{float64(-1), false, false, ""}, - gtTestCase{float64(kTwoTo54 - 2), false, false, ""}, - gtTestCase{float64(kTwoTo54 - 1), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 0), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 1), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 2), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) Float32AboveExactIntegerRange() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := GreaterThan(float32(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than 3.3554432e+07" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{int64(-1), false, false, ""}, - gtTestCase{int64(kTwoTo25 - 2), false, false, ""}, - gtTestCase{int64(kTwoTo25 - 1), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 0), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 1), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 2), false, false, ""}, - gtTestCase{int64(kTwoTo25 + 3), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint64(0), false, false, ""}, - gtTestCase{uint64(kTwoTo25 - 2), false, false, ""}, - gtTestCase{uint64(kTwoTo25 - 1), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 1), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - gtTestCase{uint64(kTwoTo25 + 3), true, false, ""}, - - // Floating point. - gtTestCase{float32(-1), false, false, ""}, - gtTestCase{float32(kTwoTo25 - 2), false, false, ""}, - gtTestCase{float32(kTwoTo25 - 1), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 0), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 1), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 2), false, false, ""}, - gtTestCase{float32(kTwoTo25 + 3), true, false, ""}, - - gtTestCase{float64(-1), false, false, ""}, - gtTestCase{float64(kTwoTo25 - 2), false, false, ""}, - gtTestCase{float64(kTwoTo25 - 1), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 0), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 1), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 2), false, false, ""}, - gtTestCase{float64(kTwoTo25 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) Float64AboveExactIntegerRange() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := GreaterThan(float64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "greater than 1.8014398509481984e+16" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - // Signed integers. - gtTestCase{int64(-1), false, false, ""}, - gtTestCase{int64(kTwoTo54 - 2), false, false, ""}, - gtTestCase{int64(kTwoTo54 - 1), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 0), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 1), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 2), false, false, ""}, - gtTestCase{int64(kTwoTo54 + 3), true, false, ""}, - - // Unsigned integers. - gtTestCase{uint64(0), false, false, ""}, - gtTestCase{uint64(kTwoTo54 - 2), false, false, ""}, - gtTestCase{uint64(kTwoTo54 - 1), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 0), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 1), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 2), false, false, ""}, - gtTestCase{uint64(kTwoTo54 + 3), true, false, ""}, - - // Floating point. - gtTestCase{float64(-1), false, false, ""}, - gtTestCase{float64(kTwoTo54 - 2), false, false, ""}, - gtTestCase{float64(kTwoTo54 - 1), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 0), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 1), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 2), false, false, ""}, - gtTestCase{float64(kTwoTo54 + 3), true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// String literals -//////////////////////////////////////////////////////////////////////// - -func (t *GreaterThanTest) EmptyString() { - matcher := GreaterThan("") - desc := matcher.Description() - expectedDesc := "greater than \"\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - gtTestCase{"", false, false, ""}, - gtTestCase{"\x00", true, false, ""}, - gtTestCase{"a", true, false, ""}, - gtTestCase{"foo", true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) SingleNullByte() { - matcher := GreaterThan("\x00") - desc := matcher.Description() - expectedDesc := "greater than \"\x00\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - gtTestCase{"", false, false, ""}, - gtTestCase{"\x00", false, false, ""}, - gtTestCase{"\x00\x00", true, false, ""}, - gtTestCase{"a", true, false, ""}, - gtTestCase{"foo", true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *GreaterThanTest) LongerString() { - matcher := GreaterThan("foo\x00") - desc := matcher.Description() - expectedDesc := "greater than \"foo\x00\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []gtTestCase{ - gtTestCase{"", false, false, ""}, - gtTestCase{"\x00", false, false, ""}, - gtTestCase{"bar", false, false, ""}, - gtTestCase{"foo", false, false, ""}, - gtTestCase{"foo\x00", false, false, ""}, - gtTestCase{"foo\x00\x00", true, false, ""}, - gtTestCase{"fooa", true, false, ""}, - gtTestCase{"qux", true, false, ""}, - } - - t.checkTestCases(matcher, cases) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/has_substr.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/has_substr.go deleted file mode 100644 index a32c1cf..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/has_substr.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" - "strings" -) - -// HasSubstr returns a matcher that matches strings containing s as a -// substring. -func HasSubstr(s string) Matcher { - return &hasSubstrMatcher{s} -} - -type hasSubstrMatcher struct { - needle string -} - -func (m *hasSubstrMatcher) Description() string { - return fmt.Sprintf("has substring \"%s\"", m.needle) -} - -func (m *hasSubstrMatcher) Matches(c interface{}) error { - v := reflect.ValueOf(c) - if v.Kind() != reflect.String { - return NewFatalError("which is not a string") - } - - // Perform the substring search. - haystack := v.String() - if strings.Contains(haystack, m.needle) { - return nil - } - - return errors.New("") -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/has_substr_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/has_substr_test.go deleted file mode 100644 index 5bf4f02..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/has_substr_test.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type HasSubstrTest struct { -} - -func init() { RegisterTestSuite(&HasSubstrTest{}) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *HasSubstrTest) Description() { - matcher := HasSubstr("taco") - ExpectThat(matcher.Description(), Equals("has substring \"taco\"")) -} - -func (t *HasSubstrTest) CandidateIsNil() { - matcher := HasSubstr("") - err := matcher.Matches(nil) - - ExpectThat(err, Error(Equals("which is not a string"))) - ExpectTrue(isFatal(err)) -} - -func (t *HasSubstrTest) CandidateIsInteger() { - matcher := HasSubstr("") - err := matcher.Matches(17) - - ExpectThat(err, Error(Equals("which is not a string"))) - ExpectTrue(isFatal(err)) -} - -func (t *HasSubstrTest) CandidateIsByteSlice() { - matcher := HasSubstr("") - err := matcher.Matches([]byte{17}) - - ExpectThat(err, Error(Equals("which is not a string"))) - ExpectTrue(isFatal(err)) -} - -func (t *HasSubstrTest) CandidateDoesntHaveSubstring() { - matcher := HasSubstr("taco") - err := matcher.Matches("tac") - - ExpectThat(err, Error(Equals(""))) - ExpectFalse(isFatal(err)) -} - -func (t *HasSubstrTest) CandidateEqualsArg() { - matcher := HasSubstr("taco") - err := matcher.Matches("taco") - - ExpectThat(err, Equals(nil)) -} - -func (t *HasSubstrTest) CandidateHasProperSubstring() { - matcher := HasSubstr("taco") - err := matcher.Matches("burritos and tacos") - - ExpectThat(err, Equals(nil)) -} - -func (t *HasSubstrTest) EmptyStringIsAlwaysSubString() { - matcher := HasSubstr("") - err := matcher.Matches("asdf") - - ExpectThat(err, Equals(nil)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/identical_to.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/identical_to.go deleted file mode 100644 index ae6460e..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/identical_to.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" -) - -// Is the type comparable according to the definition here? -// -// http://weekly.golang.org/doc/go_spec.html#Comparison_operators -// -func isComparable(t reflect.Type) bool { - switch t.Kind() { - case reflect.Array: - return isComparable(t.Elem()) - - case reflect.Struct: - for i := 0; i < t.NumField(); i++ { - if !isComparable(t.Field(i).Type) { - return false - } - } - - return true - - case reflect.Slice, reflect.Map, reflect.Func: - return false - } - - return true -} - -// Should the supplied type be allowed as an argument to IdenticalTo? -func isLegalForIdenticalTo(t reflect.Type) (bool, error) { - // Allow the zero type. - if t == nil { - return true, nil - } - - // Reference types are always okay; we compare pointers. - switch t.Kind() { - case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan: - return true, nil - } - - // Reject other non-comparable types. - if !isComparable(t) { - return false, errors.New(fmt.Sprintf("%v is not comparable", t)) - } - - return true, nil -} - -// IdenticalTo(x) returns a matcher that matches values v with type identical -// to x such that: -// -// 1. If v and x are of a reference type (slice, map, function, channel), then -// they are either both nil or are references to the same object. -// -// 2. Otherwise, if v and x are not of a reference type but have a valid type, -// then v == x. -// -// If v and x are both the invalid type (which results from the predeclared nil -// value, or from nil interface variables), then the matcher is satisfied. -// -// This function will panic if x is of a value type that is not comparable. For -// example, x cannot be an array of functions. -func IdenticalTo(x interface{}) Matcher { - t := reflect.TypeOf(x) - - // Reject illegal arguments. - if ok, err := isLegalForIdenticalTo(t); !ok { - panic("IdenticalTo: " + err.Error()) - } - - return &identicalToMatcher{x} -} - -type identicalToMatcher struct { - x interface{} -} - -func (m *identicalToMatcher) Description() string { - t := reflect.TypeOf(m.x) - return fmt.Sprintf("identical to <%v> %v", t, m.x) -} - -func (m *identicalToMatcher) Matches(c interface{}) error { - // Make sure the candidate's type is correct. - t := reflect.TypeOf(m.x) - if ct := reflect.TypeOf(c); t != ct { - return NewFatalError(fmt.Sprintf("which is of type %v", ct)) - } - - // Special case: two values of the invalid type are always identical. - if t == nil { - return nil - } - - // Handle reference types. - switch t.Kind() { - case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan: - xv := reflect.ValueOf(m.x) - cv := reflect.ValueOf(c) - if xv.Pointer() == cv.Pointer() { - return nil - } - - return errors.New("which is not an identical reference") - } - - // Are the values equal? - if m.x == c { - return nil - } - - return errors.New("") -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/identical_to_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/identical_to_test.go deleted file mode 100644 index 8622e52..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/identical_to_test.go +++ /dev/null @@ -1,850 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "io" - "unsafe" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type IdenticalToTest struct { -} - -func init() { RegisterTestSuite(&IdenticalToTest{}) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *IdenticalToTest) TypesNotIdentical() { - var m Matcher - var err error - - type intAlias int - - // Type alias expected value - m = IdenticalTo(intAlias(17)) - err = m.Matches(int(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int"))) - - // Type alias candidate - m = IdenticalTo(int(17)) - err = m.Matches(intAlias(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.intAlias"))) - - // int and uint - m = IdenticalTo(int(17)) - err = m.Matches(uint(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type uint"))) -} - -func (t *IdenticalToTest) PredeclaredNilIdentifier() { - var m Matcher - var err error - - // Nil literal - m = IdenticalTo(nil) - err = m.Matches(nil) - ExpectEq(nil, err) - - // Zero interface var (which is the same as above since IdenticalTo takes an - // interface{} as an arg) - var nilReader io.Reader - var nilWriter io.Writer - - m = IdenticalTo(nilReader) - err = m.Matches(nilWriter) - ExpectEq(nil, err) - - // Typed nil value. - m = IdenticalTo(nil) - err = m.Matches((chan int)(nil)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type chan int"))) - - // Non-nil value. - m = IdenticalTo(nil) - err = m.Matches("taco") - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type string"))) -} - -func (t *IdenticalToTest) Slices() { - var m Matcher - var err error - - // Nil expected value - m = IdenticalTo(([]int)(nil)) - ExpectEq("identical to <[]int> []", m.Description()) - - err = m.Matches(([]int)(nil)) - ExpectEq(nil, err) - - err = m.Matches([]int{}) - ExpectThat(err, Error(Equals("which is not an identical reference"))) - - // Non-nil expected value - o1 := make([]int, 1) - o2 := make([]int, 1) - m = IdenticalTo(o1) - ExpectEq(fmt.Sprintf("identical to <[]int> %v", o1), m.Description()) - - err = m.Matches(o1) - ExpectEq(nil, err) - - err = m.Matches(o2) - ExpectThat(err, Error(Equals("which is not an identical reference"))) -} - -func (t *IdenticalToTest) Maps() { - var m Matcher - var err error - - // Nil expected value - m = IdenticalTo((map[int]int)(nil)) - ExpectEq("identical to map[]", m.Description()) - - err = m.Matches((map[int]int)(nil)) - ExpectEq(nil, err) - - err = m.Matches(map[int]int{}) - ExpectThat(err, Error(Equals("which is not an identical reference"))) - - // Non-nil expected value - o1 := map[int]int{} - o2 := map[int]int{} - m = IdenticalTo(o1) - ExpectEq(fmt.Sprintf("identical to %v", o1), m.Description()) - - err = m.Matches(o1) - ExpectEq(nil, err) - - err = m.Matches(o2) - ExpectThat(err, Error(Equals("which is not an identical reference"))) -} - -func (t *IdenticalToTest) Functions() { - var m Matcher - var err error - - // Nil expected value - m = IdenticalTo((func())(nil)) - ExpectEq("identical to ", m.Description()) - - err = m.Matches((func())(nil)) - ExpectEq(nil, err) - - err = m.Matches(func() {}) - ExpectThat(err, Error(Equals("which is not an identical reference"))) - - // Non-nil expected value - o1 := func() {} - o2 := func() {} - m = IdenticalTo(o1) - ExpectEq(fmt.Sprintf("identical to %v", o1), m.Description()) - - err = m.Matches(o1) - ExpectEq(nil, err) - - err = m.Matches(o2) - ExpectThat(err, Error(Equals("which is not an identical reference"))) -} - -func (t *IdenticalToTest) Channels() { - var m Matcher - var err error - - // Nil expected value - m = IdenticalTo((chan int)(nil)) - ExpectEq("identical to ", m.Description()) - - err = m.Matches((chan int)(nil)) - ExpectEq(nil, err) - - err = m.Matches(make(chan int)) - ExpectThat(err, Error(Equals("which is not an identical reference"))) - - // Non-nil expected value - o1 := make(chan int) - o2 := make(chan int) - m = IdenticalTo(o1) - ExpectEq(fmt.Sprintf("identical to %v", o1), m.Description()) - - err = m.Matches(o1) - ExpectEq(nil, err) - - err = m.Matches(o2) - ExpectThat(err, Error(Equals("which is not an identical reference"))) -} - -func (t *IdenticalToTest) Bools() { - var m Matcher - var err error - - // false - m = IdenticalTo(false) - ExpectEq("identical to false", m.Description()) - - err = m.Matches(false) - ExpectEq(nil, err) - - err = m.Matches(true) - ExpectThat(err, Error(Equals(""))) - - // true - m = IdenticalTo(true) - ExpectEq("identical to true", m.Description()) - - err = m.Matches(false) - ExpectThat(err, Error(Equals(""))) - - err = m.Matches(true) - ExpectEq(nil, err) -} - -func (t *IdenticalToTest) Ints() { - var m Matcher - var err error - - m = IdenticalTo(int(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(int(17)) - ExpectEq(nil, err) - - // Type alias - type myType int - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Int8s() { - var m Matcher - var err error - - m = IdenticalTo(int8(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(int8(17)) - ExpectEq(nil, err) - - // Type alias - type myType int8 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Int16s() { - var m Matcher - var err error - - m = IdenticalTo(int16(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(int16(17)) - ExpectEq(nil, err) - - // Type alias - type myType int16 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Int32s() { - var m Matcher - var err error - - m = IdenticalTo(int32(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(int32(17)) - ExpectEq(nil, err) - - // Type alias - type myType int32 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int16(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int16"))) -} - -func (t *IdenticalToTest) Int64s() { - var m Matcher - var err error - - m = IdenticalTo(int64(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(int64(17)) - ExpectEq(nil, err) - - // Type alias - type myType int64 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Uints() { - var m Matcher - var err error - - m = IdenticalTo(uint(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(uint(17)) - ExpectEq(nil, err) - - // Type alias - type myType uint - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Uint8s() { - var m Matcher - var err error - - m = IdenticalTo(uint8(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(uint8(17)) - ExpectEq(nil, err) - - // Type alias - type myType uint8 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Uint16s() { - var m Matcher - var err error - - m = IdenticalTo(uint16(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(uint16(17)) - ExpectEq(nil, err) - - // Type alias - type myType uint16 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Uint32s() { - var m Matcher - var err error - - m = IdenticalTo(uint32(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(uint32(17)) - ExpectEq(nil, err) - - // Type alias - type myType uint32 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Uint64s() { - var m Matcher - var err error - - m = IdenticalTo(uint64(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(uint64(17)) - ExpectEq(nil, err) - - // Type alias - type myType uint64 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Uintptrs() { - var m Matcher - var err error - - m = IdenticalTo(uintptr(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(uintptr(17)) - ExpectEq(nil, err) - - // Type alias - type myType uintptr - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Float32s() { - var m Matcher - var err error - - m = IdenticalTo(float32(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(float32(17)) - ExpectEq(nil, err) - - // Type alias - type myType float32 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Float64s() { - var m Matcher - var err error - - m = IdenticalTo(float64(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(float64(17)) - ExpectEq(nil, err) - - // Type alias - type myType float64 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Complex64s() { - var m Matcher - var err error - - m = IdenticalTo(complex64(17)) - ExpectEq("identical to (17+0i)", m.Description()) - - // Identical value - err = m.Matches(complex64(17)) - ExpectEq(nil, err) - - // Type alias - type myType complex64 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) Complex128s() { - var m Matcher - var err error - - m = IdenticalTo(complex128(17)) - ExpectEq("identical to (17+0i)", m.Description()) - - // Identical value - err = m.Matches(complex128(17)) - ExpectEq(nil, err) - - // Type alias - type myType complex128 - err = m.Matches(myType(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) EmptyComparableArrays() { - var m Matcher - var err error - - m = IdenticalTo([0]int{}) - ExpectEq("identical to <[0]int> []", m.Description()) - - // Identical value - err = m.Matches([0]int{}) - ExpectEq(nil, err) - - // Length too long - err = m.Matches([1]int{17}) - ExpectThat(err, Error(Equals("which is of type [1]int"))) - - // Element type alias - type myType int - err = m.Matches([0]myType{}) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type [0]oglematchers_test.myType"))) - - // Completely wrong element type - err = m.Matches([0]int32{}) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type [0]int32"))) -} - -func (t *IdenticalToTest) NonEmptyComparableArrays() { - var m Matcher - var err error - - m = IdenticalTo([2]int{17, 19}) - ExpectEq("identical to <[2]int> [17 19]", m.Description()) - - // Identical value - err = m.Matches([2]int{17, 19}) - ExpectEq(nil, err) - - // Length too short - err = m.Matches([1]int{17}) - ExpectThat(err, Error(Equals("which is of type [1]int"))) - - // Length too long - err = m.Matches([3]int{17, 19, 23}) - ExpectThat(err, Error(Equals("which is of type [3]int"))) - - // First element different - err = m.Matches([2]int{13, 19}) - ExpectThat(err, Error(Equals(""))) - - // Second element different - err = m.Matches([2]int{17, 23}) - ExpectThat(err, Error(Equals(""))) - - // Element type alias - type myType int - err = m.Matches([2]myType{17, 19}) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type [2]oglematchers_test.myType"))) - - // Completely wrong element type - err = m.Matches([2]int32{17, 19}) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type [2]int32"))) -} - -func (t *IdenticalToTest) NonEmptyArraysOfComparableArrays() { - var m Matcher - var err error - - x := [2][2]int{ - [2]int{17, 19}, - [2]int{23, 29}, - } - m = IdenticalTo(x) - ExpectEq("identical to <[2][2]int> [[17 19] [23 29]]", m.Description()) - - // Identical value - err = m.Matches([2][2]int{[2]int{17, 19}, [2]int{23, 29}}) - ExpectEq(nil, err) - - // Outer length too short - err = m.Matches([1][2]int{[2]int{17, 19}}) - ExpectThat(err, Error(Equals("which is of type [1][2]int"))) - - // Inner length too short - err = m.Matches([2][1]int{[1]int{17}, [1]int{23}}) - ExpectThat(err, Error(Equals("which is of type [2][1]int"))) - - // First element different - err = m.Matches([2][2]int{[2]int{13, 19}, [2]int{23, 29}}) - ExpectThat(err, Error(Equals(""))) - - // Element type alias - type myType int - err = m.Matches([2][2]myType{[2]myType{17, 19}, [2]myType{23, 29}}) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type [2][2]oglematchers_test.myType"))) -} - -func (t *IdenticalToTest) NonComparableArrays() { - x := [0]func(){} - f := func() { IdenticalTo(x) } - ExpectThat(f, Panics(HasSubstr("is not comparable"))) -} - -func (t *IdenticalToTest) ArraysOfNonComparableArrays() { - x := [0][0]func(){} - f := func() { IdenticalTo(x) } - ExpectThat(f, Panics(HasSubstr("is not comparable"))) -} - -func (t *IdenticalToTest) Strings() { - var m Matcher - var err error - - m = IdenticalTo("taco") - ExpectEq("identical to taco", m.Description()) - - // Identical value - err = m.Matches("ta" + "co") - ExpectEq(nil, err) - - // Type alias - type myType string - err = m.Matches(myType("taco")) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) ComparableStructs() { - var m Matcher - var err error - - type subStruct struct { - i int - } - - type myStruct struct { - u uint - s subStruct - } - - x := myStruct{17, subStruct{19}} - m = IdenticalTo(x) - ExpectEq("identical to {17 {19}}", m.Description()) - - // Identical value - err = m.Matches(myStruct{17, subStruct{19}}) - ExpectEq(nil, err) - - // Wrong outer field - err = m.Matches(myStruct{13, subStruct{19}}) - ExpectThat(err, Error(Equals(""))) - - // Wrong inner field - err = m.Matches(myStruct{17, subStruct{23}}) - ExpectThat(err, Error(Equals(""))) - - // Type alias - type myType myStruct - err = m.Matches(myType{17, subStruct{19}}) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) NonComparableStructs() { - type subStruct struct { - s []int - } - - type myStruct struct { - u uint - s subStruct - } - - x := myStruct{17, subStruct{[]int{19}}} - f := func() { IdenticalTo(x) } - ExpectThat(f, Panics(AllOf(HasSubstr("IdenticalTo"), HasSubstr("comparable")))) -} - -func (t *IdenticalToTest) NilUnsafePointer() { - var m Matcher - var err error - - x := unsafe.Pointer(nil) - m = IdenticalTo(x) - ExpectEq(fmt.Sprintf("identical to %v", x), m.Description()) - - // Identical value - err = m.Matches(unsafe.Pointer(nil)) - ExpectEq(nil, err) - - // Wrong value - j := 17 - err = m.Matches(unsafe.Pointer(&j)) - ExpectThat(err, Error(Equals(""))) - - // Type alias - type myType unsafe.Pointer - err = m.Matches(myType(unsafe.Pointer(nil))) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) NonNilUnsafePointer() { - var m Matcher - var err error - - i := 17 - x := unsafe.Pointer(&i) - m = IdenticalTo(x) - ExpectEq(fmt.Sprintf("identical to %v", x), m.Description()) - - // Identical value - err = m.Matches(unsafe.Pointer(&i)) - ExpectEq(nil, err) - - // Nil value - err = m.Matches(unsafe.Pointer(nil)) - ExpectThat(err, Error(Equals(""))) - - // Wrong value - j := 17 - err = m.Matches(unsafe.Pointer(&j)) - ExpectThat(err, Error(Equals(""))) - - // Type alias - type myType unsafe.Pointer - err = m.Matches(myType(unsafe.Pointer(&i))) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} - -func (t *IdenticalToTest) IntAlias() { - var m Matcher - var err error - - type intAlias int - - m = IdenticalTo(intAlias(17)) - ExpectEq("identical to 17", m.Description()) - - // Identical value - err = m.Matches(intAlias(17)) - ExpectEq(nil, err) - - // Int - err = m.Matches(int(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int"))) - - // Completely wrong type - err = m.Matches(int32(17)) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("which is of type int32"))) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go deleted file mode 100644 index 8402cde..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "fmt" - "reflect" -) - -// LessOrEqual returns a matcher that matches integer, floating point, or -// strings values v such that v <= x. Comparison is not defined between numeric -// and string types, but is defined between all integer and floating point -// types. -// -// x must itself be an integer, floating point, or string type; otherwise, -// LessOrEqual will panic. -func LessOrEqual(x interface{}) Matcher { - desc := fmt.Sprintf("less than or equal to %v", x) - - // Special case: make it clear that strings are strings. - if reflect.TypeOf(x).Kind() == reflect.String { - desc = fmt.Sprintf("less than or equal to \"%s\"", x) - } - - // Put LessThan last so that its error messages will be used in the event of - // failure. - return transformDescription(AnyOf(Equals(x), LessThan(x)), desc) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal_test.go deleted file mode 100644 index ab87a5e..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal_test.go +++ /dev/null @@ -1,1080 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "math" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type LessOrEqualTest struct { -} - -func init() { RegisterTestSuite(&LessOrEqualTest{}) } - -type leTestCase struct { - candidate interface{} - expectedResult bool - shouldBeFatal bool - expectedError string -} - -func (t *LessOrEqualTest) checkTestCases(matcher Matcher, cases []leTestCase) { - for i, c := range cases { - err := matcher.Matches(c.candidate) - - ExpectThat( - (err == nil), - Equals(c.expectedResult), - "Case %d (candidate %v)", - i, - c.candidate) - - if err == nil { - continue - } - - _, isFatal := err.(*FatalError) - ExpectEq( - c.shouldBeFatal, - isFatal, - "Case %d (candidate %v)", - i, - c.candidate) - - ExpectThat( - err, - Error(Equals(c.expectedError)), - "Case %d (candidate %v)", - i, - c.candidate) - } -} - -//////////////////////////////////////////////////////////////////////// -// Integer literals -//////////////////////////////////////////////////////////////////////// - -func (t *LessOrEqualTest) IntegerCandidateBadTypes() { - matcher := LessOrEqual(int(-150)) - - cases := []leTestCase{ - leTestCase{true, false, true, "which is not comparable"}, - leTestCase{uintptr(17), false, true, "which is not comparable"}, - leTestCase{complex64(-151), false, true, "which is not comparable"}, - leTestCase{complex128(-151), false, true, "which is not comparable"}, - leTestCase{[...]int{-151}, false, true, "which is not comparable"}, - leTestCase{make(chan int), false, true, "which is not comparable"}, - leTestCase{func() {}, false, true, "which is not comparable"}, - leTestCase{map[int]int{}, false, true, "which is not comparable"}, - leTestCase{&leTestCase{}, false, true, "which is not comparable"}, - leTestCase{make([]int, 0), false, true, "which is not comparable"}, - leTestCase{"-151", false, true, "which is not comparable"}, - leTestCase{leTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) FloatCandidateBadTypes() { - matcher := LessOrEqual(float32(-150)) - - cases := []leTestCase{ - leTestCase{true, false, true, "which is not comparable"}, - leTestCase{uintptr(17), false, true, "which is not comparable"}, - leTestCase{complex64(-151), false, true, "which is not comparable"}, - leTestCase{complex128(-151), false, true, "which is not comparable"}, - leTestCase{[...]int{-151}, false, true, "which is not comparable"}, - leTestCase{make(chan int), false, true, "which is not comparable"}, - leTestCase{func() {}, false, true, "which is not comparable"}, - leTestCase{map[int]int{}, false, true, "which is not comparable"}, - leTestCase{&leTestCase{}, false, true, "which is not comparable"}, - leTestCase{make([]int, 0), false, true, "which is not comparable"}, - leTestCase{"-151", false, true, "which is not comparable"}, - leTestCase{leTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) StringCandidateBadTypes() { - matcher := LessOrEqual("17") - - cases := []leTestCase{ - leTestCase{true, false, true, "which is not comparable"}, - leTestCase{int(0), false, true, "which is not comparable"}, - leTestCase{int8(0), false, true, "which is not comparable"}, - leTestCase{int16(0), false, true, "which is not comparable"}, - leTestCase{int32(0), false, true, "which is not comparable"}, - leTestCase{int64(0), false, true, "which is not comparable"}, - leTestCase{uint(0), false, true, "which is not comparable"}, - leTestCase{uint8(0), false, true, "which is not comparable"}, - leTestCase{uint16(0), false, true, "which is not comparable"}, - leTestCase{uint32(0), false, true, "which is not comparable"}, - leTestCase{uint64(0), false, true, "which is not comparable"}, - leTestCase{uintptr(17), false, true, "which is not comparable"}, - leTestCase{float32(0), false, true, "which is not comparable"}, - leTestCase{float64(0), false, true, "which is not comparable"}, - leTestCase{complex64(-151), false, true, "which is not comparable"}, - leTestCase{complex128(-151), false, true, "which is not comparable"}, - leTestCase{[...]int{-151}, false, true, "which is not comparable"}, - leTestCase{make(chan int), false, true, "which is not comparable"}, - leTestCase{func() {}, false, true, "which is not comparable"}, - leTestCase{map[int]int{}, false, true, "which is not comparable"}, - leTestCase{&leTestCase{}, false, true, "which is not comparable"}, - leTestCase{make([]int, 0), false, true, "which is not comparable"}, - leTestCase{leTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) BadArgument() { - panicked := false - - defer func() { - ExpectThat(panicked, Equals(true)) - }() - - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - LessOrEqual(complex128(0)) -} - -//////////////////////////////////////////////////////////////////////// -// Integer literals -//////////////////////////////////////////////////////////////////////// - -func (t *LessOrEqualTest) NegativeIntegerLiteral() { - matcher := LessOrEqual(-150) - desc := matcher.Description() - expectedDesc := "less than or equal to -150" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{-(1 << 30), true, false, ""}, - leTestCase{-151, true, false, ""}, - leTestCase{-150, true, false, ""}, - leTestCase{-149, false, false, ""}, - leTestCase{0, false, false, ""}, - leTestCase{17, false, false, ""}, - - leTestCase{int(-(1 << 30)), true, false, ""}, - leTestCase{int(-151), true, false, ""}, - leTestCase{int(-150), true, false, ""}, - leTestCase{int(-149), false, false, ""}, - leTestCase{int(0), false, false, ""}, - leTestCase{int(17), false, false, ""}, - - leTestCase{int8(-127), false, false, ""}, - leTestCase{int8(0), false, false, ""}, - leTestCase{int8(17), false, false, ""}, - - leTestCase{int16(-(1 << 14)), true, false, ""}, - leTestCase{int16(-151), true, false, ""}, - leTestCase{int16(-150), true, false, ""}, - leTestCase{int16(-149), false, false, ""}, - leTestCase{int16(0), false, false, ""}, - leTestCase{int16(17), false, false, ""}, - - leTestCase{int32(-(1 << 30)), true, false, ""}, - leTestCase{int32(-151), true, false, ""}, - leTestCase{int32(-150), true, false, ""}, - leTestCase{int32(-149), false, false, ""}, - leTestCase{int32(0), false, false, ""}, - leTestCase{int32(17), false, false, ""}, - - leTestCase{int64(-(1 << 30)), true, false, ""}, - leTestCase{int64(-151), true, false, ""}, - leTestCase{int64(-150), true, false, ""}, - leTestCase{int64(-149), false, false, ""}, - leTestCase{int64(0), false, false, ""}, - leTestCase{int64(17), false, false, ""}, - - // Unsigned integers. - leTestCase{uint((1 << 32) - 151), false, false, ""}, - leTestCase{uint(0), false, false, ""}, - leTestCase{uint(17), false, false, ""}, - - leTestCase{uint8(0), false, false, ""}, - leTestCase{uint8(17), false, false, ""}, - leTestCase{uint8(253), false, false, ""}, - - leTestCase{uint16((1 << 16) - 151), false, false, ""}, - leTestCase{uint16(0), false, false, ""}, - leTestCase{uint16(17), false, false, ""}, - - leTestCase{uint32((1 << 32) - 151), false, false, ""}, - leTestCase{uint32(0), false, false, ""}, - leTestCase{uint32(17), false, false, ""}, - - leTestCase{uint64((1 << 64) - 151), false, false, ""}, - leTestCase{uint64(0), false, false, ""}, - leTestCase{uint64(17), false, false, ""}, - - // Floating point. - leTestCase{float32(-(1 << 30)), true, false, ""}, - leTestCase{float32(-151), true, false, ""}, - leTestCase{float32(-150.1), true, false, ""}, - leTestCase{float32(-150), true, false, ""}, - leTestCase{float32(-149.9), false, false, ""}, - leTestCase{float32(0), false, false, ""}, - leTestCase{float32(17), false, false, ""}, - leTestCase{float32(160), false, false, ""}, - - leTestCase{float64(-(1 << 30)), true, false, ""}, - leTestCase{float64(-151), true, false, ""}, - leTestCase{float64(-150.1), true, false, ""}, - leTestCase{float64(-150), true, false, ""}, - leTestCase{float64(-149.9), false, false, ""}, - leTestCase{float64(0), false, false, ""}, - leTestCase{float64(17), false, false, ""}, - leTestCase{float64(160), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) ZeroIntegerLiteral() { - matcher := LessOrEqual(0) - desc := matcher.Description() - expectedDesc := "less than or equal to 0" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{-(1 << 30), true, false, ""}, - leTestCase{-1, true, false, ""}, - leTestCase{0, true, false, ""}, - leTestCase{1, false, false, ""}, - leTestCase{17, false, false, ""}, - leTestCase{(1 << 30), false, false, ""}, - - leTestCase{int(-(1 << 30)), true, false, ""}, - leTestCase{int(-1), true, false, ""}, - leTestCase{int(0), true, false, ""}, - leTestCase{int(1), false, false, ""}, - leTestCase{int(17), false, false, ""}, - - leTestCase{int8(-1), true, false, ""}, - leTestCase{int8(0), true, false, ""}, - leTestCase{int8(1), false, false, ""}, - - leTestCase{int16(-(1 << 14)), true, false, ""}, - leTestCase{int16(-1), true, false, ""}, - leTestCase{int16(0), true, false, ""}, - leTestCase{int16(1), false, false, ""}, - leTestCase{int16(17), false, false, ""}, - - leTestCase{int32(-(1 << 30)), true, false, ""}, - leTestCase{int32(-1), true, false, ""}, - leTestCase{int32(0), true, false, ""}, - leTestCase{int32(1), false, false, ""}, - leTestCase{int32(17), false, false, ""}, - - leTestCase{int64(-(1 << 30)), true, false, ""}, - leTestCase{int64(-1), true, false, ""}, - leTestCase{int64(0), true, false, ""}, - leTestCase{int64(1), false, false, ""}, - leTestCase{int64(17), false, false, ""}, - - // Unsigned integers. - leTestCase{uint((1 << 32) - 1), false, false, ""}, - leTestCase{uint(0), true, false, ""}, - leTestCase{uint(1), false, false, ""}, - leTestCase{uint(17), false, false, ""}, - - leTestCase{uint8(0), true, false, ""}, - leTestCase{uint8(1), false, false, ""}, - leTestCase{uint8(17), false, false, ""}, - leTestCase{uint8(253), false, false, ""}, - - leTestCase{uint16((1 << 16) - 1), false, false, ""}, - leTestCase{uint16(0), true, false, ""}, - leTestCase{uint16(1), false, false, ""}, - leTestCase{uint16(17), false, false, ""}, - - leTestCase{uint32((1 << 32) - 1), false, false, ""}, - leTestCase{uint32(0), true, false, ""}, - leTestCase{uint32(1), false, false, ""}, - leTestCase{uint32(17), false, false, ""}, - - leTestCase{uint64((1 << 64) - 1), false, false, ""}, - leTestCase{uint64(0), true, false, ""}, - leTestCase{uint64(1), false, false, ""}, - leTestCase{uint64(17), false, false, ""}, - - // Floating point. - leTestCase{float32(-(1 << 30)), true, false, ""}, - leTestCase{float32(-1), true, false, ""}, - leTestCase{float32(-0.1), true, false, ""}, - leTestCase{float32(-0.0), true, false, ""}, - leTestCase{float32(0), true, false, ""}, - leTestCase{float32(0.1), false, false, ""}, - leTestCase{float32(17), false, false, ""}, - leTestCase{float32(160), false, false, ""}, - - leTestCase{float64(-(1 << 30)), true, false, ""}, - leTestCase{float64(-1), true, false, ""}, - leTestCase{float64(-0.1), true, false, ""}, - leTestCase{float64(-0), true, false, ""}, - leTestCase{float64(0), true, false, ""}, - leTestCase{float64(0.1), false, false, ""}, - leTestCase{float64(17), false, false, ""}, - leTestCase{float64(160), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) PositiveIntegerLiteral() { - matcher := LessOrEqual(150) - desc := matcher.Description() - expectedDesc := "less than or equal to 150" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{-1, true, false, ""}, - leTestCase{149, true, false, ""}, - leTestCase{150, true, false, ""}, - leTestCase{151, false, false, ""}, - - leTestCase{int(-1), true, false, ""}, - leTestCase{int(149), true, false, ""}, - leTestCase{int(150), true, false, ""}, - leTestCase{int(151), false, false, ""}, - - leTestCase{int8(-1), true, false, ""}, - leTestCase{int8(0), true, false, ""}, - leTestCase{int8(17), true, false, ""}, - leTestCase{int8(127), true, false, ""}, - - leTestCase{int16(-1), true, false, ""}, - leTestCase{int16(149), true, false, ""}, - leTestCase{int16(150), true, false, ""}, - leTestCase{int16(151), false, false, ""}, - - leTestCase{int32(-1), true, false, ""}, - leTestCase{int32(149), true, false, ""}, - leTestCase{int32(150), true, false, ""}, - leTestCase{int32(151), false, false, ""}, - - leTestCase{int64(-1), true, false, ""}, - leTestCase{int64(149), true, false, ""}, - leTestCase{int64(150), true, false, ""}, - leTestCase{int64(151), false, false, ""}, - - // Unsigned integers. - leTestCase{uint(0), true, false, ""}, - leTestCase{uint(149), true, false, ""}, - leTestCase{uint(150), true, false, ""}, - leTestCase{uint(151), false, false, ""}, - - leTestCase{uint8(0), true, false, ""}, - leTestCase{uint8(127), true, false, ""}, - - leTestCase{uint16(0), true, false, ""}, - leTestCase{uint16(149), true, false, ""}, - leTestCase{uint16(150), true, false, ""}, - leTestCase{uint16(151), false, false, ""}, - - leTestCase{uint32(0), true, false, ""}, - leTestCase{uint32(149), true, false, ""}, - leTestCase{uint32(150), true, false, ""}, - leTestCase{uint32(151), false, false, ""}, - - leTestCase{uint64(0), true, false, ""}, - leTestCase{uint64(149), true, false, ""}, - leTestCase{uint64(150), true, false, ""}, - leTestCase{uint64(151), false, false, ""}, - - // Floating point. - leTestCase{float32(-1), true, false, ""}, - leTestCase{float32(149), true, false, ""}, - leTestCase{float32(149.9), true, false, ""}, - leTestCase{float32(150), true, false, ""}, - leTestCase{float32(150.1), false, false, ""}, - leTestCase{float32(151), false, false, ""}, - - leTestCase{float64(-1), true, false, ""}, - leTestCase{float64(149), true, false, ""}, - leTestCase{float64(149.9), true, false, ""}, - leTestCase{float64(150), true, false, ""}, - leTestCase{float64(150.1), false, false, ""}, - leTestCase{float64(151), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Float literals -//////////////////////////////////////////////////////////////////////// - -func (t *LessOrEqualTest) NegativeFloatLiteral() { - matcher := LessOrEqual(-150.1) - desc := matcher.Description() - expectedDesc := "less than or equal to -150.1" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{-(1 << 30), true, false, ""}, - leTestCase{-151, true, false, ""}, - leTestCase{-150.1, true, false, ""}, - leTestCase{-150, false, false, ""}, - leTestCase{-149, false, false, ""}, - leTestCase{0, false, false, ""}, - leTestCase{17, false, false, ""}, - - leTestCase{int(-(1 << 30)), true, false, ""}, - leTestCase{int(-151), true, false, ""}, - leTestCase{int(-150), false, false, ""}, - leTestCase{int(-149), false, false, ""}, - leTestCase{int(0), false, false, ""}, - leTestCase{int(17), false, false, ""}, - - leTestCase{int8(-127), false, false, ""}, - leTestCase{int8(0), false, false, ""}, - leTestCase{int8(17), false, false, ""}, - - leTestCase{int16(-(1 << 14)), true, false, ""}, - leTestCase{int16(-151), true, false, ""}, - leTestCase{int16(-150), false, false, ""}, - leTestCase{int16(-149), false, false, ""}, - leTestCase{int16(0), false, false, ""}, - leTestCase{int16(17), false, false, ""}, - - leTestCase{int32(-(1 << 30)), true, false, ""}, - leTestCase{int32(-151), true, false, ""}, - leTestCase{int32(-150), false, false, ""}, - leTestCase{int32(-149), false, false, ""}, - leTestCase{int32(0), false, false, ""}, - leTestCase{int32(17), false, false, ""}, - - leTestCase{int64(-(1 << 30)), true, false, ""}, - leTestCase{int64(-151), true, false, ""}, - leTestCase{int64(-150), false, false, ""}, - leTestCase{int64(-149), false, false, ""}, - leTestCase{int64(0), false, false, ""}, - leTestCase{int64(17), false, false, ""}, - - // Unsigned integers. - leTestCase{uint((1 << 32) - 151), false, false, ""}, - leTestCase{uint(0), false, false, ""}, - leTestCase{uint(17), false, false, ""}, - - leTestCase{uint8(0), false, false, ""}, - leTestCase{uint8(17), false, false, ""}, - leTestCase{uint8(253), false, false, ""}, - - leTestCase{uint16((1 << 16) - 151), false, false, ""}, - leTestCase{uint16(0), false, false, ""}, - leTestCase{uint16(17), false, false, ""}, - - leTestCase{uint32((1 << 32) - 151), false, false, ""}, - leTestCase{uint32(0), false, false, ""}, - leTestCase{uint32(17), false, false, ""}, - - leTestCase{uint64((1 << 64) - 151), false, false, ""}, - leTestCase{uint64(0), false, false, ""}, - leTestCase{uint64(17), false, false, ""}, - - // Floating point. - leTestCase{float32(-(1 << 30)), true, false, ""}, - leTestCase{float32(-151), true, false, ""}, - leTestCase{float32(-150.2), true, false, ""}, - leTestCase{float32(-150.1), true, false, ""}, - leTestCase{float32(-150), false, false, ""}, - leTestCase{float32(0), false, false, ""}, - leTestCase{float32(17), false, false, ""}, - leTestCase{float32(160), false, false, ""}, - - leTestCase{float64(-(1 << 30)), true, false, ""}, - leTestCase{float64(-151), true, false, ""}, - leTestCase{float64(-150.2), true, false, ""}, - leTestCase{float64(-150.1), true, false, ""}, - leTestCase{float64(-150), false, false, ""}, - leTestCase{float64(0), false, false, ""}, - leTestCase{float64(17), false, false, ""}, - leTestCase{float64(160), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) PositiveFloatLiteral() { - matcher := LessOrEqual(149.9) - desc := matcher.Description() - expectedDesc := "less than or equal to 149.9" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{-1, true, false, ""}, - leTestCase{149, true, false, ""}, - leTestCase{149.9, true, false, ""}, - leTestCase{150, false, false, ""}, - leTestCase{151, false, false, ""}, - - leTestCase{int(-1), true, false, ""}, - leTestCase{int(149), true, false, ""}, - leTestCase{int(150), false, false, ""}, - leTestCase{int(151), false, false, ""}, - - leTestCase{int8(-1), true, false, ""}, - leTestCase{int8(0), true, false, ""}, - leTestCase{int8(17), true, false, ""}, - leTestCase{int8(127), true, false, ""}, - - leTestCase{int16(-1), true, false, ""}, - leTestCase{int16(149), true, false, ""}, - leTestCase{int16(150), false, false, ""}, - leTestCase{int16(151), false, false, ""}, - - leTestCase{int32(-1), true, false, ""}, - leTestCase{int32(149), true, false, ""}, - leTestCase{int32(150), false, false, ""}, - leTestCase{int32(151), false, false, ""}, - - leTestCase{int64(-1), true, false, ""}, - leTestCase{int64(149), true, false, ""}, - leTestCase{int64(150), false, false, ""}, - leTestCase{int64(151), false, false, ""}, - - // Unsigned integers. - leTestCase{uint(0), true, false, ""}, - leTestCase{uint(149), true, false, ""}, - leTestCase{uint(150), false, false, ""}, - leTestCase{uint(151), false, false, ""}, - - leTestCase{uint8(0), true, false, ""}, - leTestCase{uint8(127), true, false, ""}, - - leTestCase{uint16(0), true, false, ""}, - leTestCase{uint16(149), true, false, ""}, - leTestCase{uint16(150), false, false, ""}, - leTestCase{uint16(151), false, false, ""}, - - leTestCase{uint32(0), true, false, ""}, - leTestCase{uint32(149), true, false, ""}, - leTestCase{uint32(150), false, false, ""}, - leTestCase{uint32(151), false, false, ""}, - - leTestCase{uint64(0), true, false, ""}, - leTestCase{uint64(149), true, false, ""}, - leTestCase{uint64(150), false, false, ""}, - leTestCase{uint64(151), false, false, ""}, - - // Floating point. - leTestCase{float32(-1), true, false, ""}, - leTestCase{float32(149), true, false, ""}, - leTestCase{float32(149.8), true, false, ""}, - leTestCase{float32(149.9), true, false, ""}, - leTestCase{float32(150), false, false, ""}, - leTestCase{float32(151), false, false, ""}, - - leTestCase{float64(-1), true, false, ""}, - leTestCase{float64(149), true, false, ""}, - leTestCase{float64(149.8), true, false, ""}, - leTestCase{float64(149.9), true, false, ""}, - leTestCase{float64(150), false, false, ""}, - leTestCase{float64(151), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Subtle cases -//////////////////////////////////////////////////////////////////////// - -func (t *LessOrEqualTest) Int64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := LessOrEqual(int64(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "less than or equal to 33554433" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{-1, true, false, ""}, - leTestCase{kTwoTo25 + 0, true, false, ""}, - leTestCase{kTwoTo25 + 1, true, false, ""}, - leTestCase{kTwoTo25 + 2, false, false, ""}, - - leTestCase{int(-1), true, false, ""}, - leTestCase{int(kTwoTo25 + 0), true, false, ""}, - leTestCase{int(kTwoTo25 + 1), true, false, ""}, - leTestCase{int(kTwoTo25 + 2), false, false, ""}, - - leTestCase{int8(-1), true, false, ""}, - leTestCase{int8(127), true, false, ""}, - - leTestCase{int16(-1), true, false, ""}, - leTestCase{int16(0), true, false, ""}, - leTestCase{int16(32767), true, false, ""}, - - leTestCase{int32(-1), true, false, ""}, - leTestCase{int32(kTwoTo25 + 0), true, false, ""}, - leTestCase{int32(kTwoTo25 + 1), true, false, ""}, - leTestCase{int32(kTwoTo25 + 2), false, false, ""}, - - leTestCase{int64(-1), true, false, ""}, - leTestCase{int64(kTwoTo25 + 0), true, false, ""}, - leTestCase{int64(kTwoTo25 + 1), true, false, ""}, - leTestCase{int64(kTwoTo25 + 2), false, false, ""}, - - // Unsigned integers. - leTestCase{uint(0), true, false, ""}, - leTestCase{uint(kTwoTo25 + 0), true, false, ""}, - leTestCase{uint(kTwoTo25 + 1), true, false, ""}, - leTestCase{uint(kTwoTo25 + 2), false, false, ""}, - - leTestCase{uint8(0), true, false, ""}, - leTestCase{uint8(255), true, false, ""}, - - leTestCase{uint16(0), true, false, ""}, - leTestCase{uint16(65535), true, false, ""}, - - leTestCase{uint32(0), true, false, ""}, - leTestCase{uint32(kTwoTo25 + 0), true, false, ""}, - leTestCase{uint32(kTwoTo25 + 1), true, false, ""}, - leTestCase{uint32(kTwoTo25 + 2), false, false, ""}, - - leTestCase{uint64(0), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 0), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - - // Floating point. - leTestCase{float32(-1), true, false, ""}, - leTestCase{float32(kTwoTo25 - 2), true, false, ""}, - leTestCase{float32(kTwoTo25 - 1), true, false, ""}, - leTestCase{float32(kTwoTo25 + 0), true, false, ""}, - leTestCase{float32(kTwoTo25 + 1), true, false, ""}, - leTestCase{float32(kTwoTo25 + 2), true, false, ""}, - leTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - leTestCase{float64(-1), true, false, ""}, - leTestCase{float64(kTwoTo25 - 2), true, false, ""}, - leTestCase{float64(kTwoTo25 - 1), true, false, ""}, - leTestCase{float64(kTwoTo25 + 0), true, false, ""}, - leTestCase{float64(kTwoTo25 + 1), true, false, ""}, - leTestCase{float64(kTwoTo25 + 2), false, false, ""}, - leTestCase{float64(kTwoTo25 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) Int64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := LessOrEqual(int64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "less than or equal to 18014398509481985" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{-1, true, false, ""}, - leTestCase{1 << 30, true, false, ""}, - - leTestCase{int(-1), true, false, ""}, - leTestCase{int(math.MaxInt32), true, false, ""}, - - leTestCase{int8(-1), true, false, ""}, - leTestCase{int8(127), true, false, ""}, - - leTestCase{int16(-1), true, false, ""}, - leTestCase{int16(0), true, false, ""}, - leTestCase{int16(32767), true, false, ""}, - - leTestCase{int32(-1), true, false, ""}, - leTestCase{int32(math.MaxInt32), true, false, ""}, - - leTestCase{int64(-1), true, false, ""}, - leTestCase{int64(kTwoTo54 - 1), true, false, ""}, - leTestCase{int64(kTwoTo54 + 0), true, false, ""}, - leTestCase{int64(kTwoTo54 + 1), true, false, ""}, - leTestCase{int64(kTwoTo54 + 2), false, false, ""}, - - // Unsigned integers. - leTestCase{uint(0), true, false, ""}, - leTestCase{uint(math.MaxUint32), true, false, ""}, - - leTestCase{uint8(0), true, false, ""}, - leTestCase{uint8(255), true, false, ""}, - - leTestCase{uint16(0), true, false, ""}, - leTestCase{uint16(65535), true, false, ""}, - - leTestCase{uint32(0), true, false, ""}, - leTestCase{uint32(math.MaxUint32), true, false, ""}, - - leTestCase{uint64(0), true, false, ""}, - leTestCase{uint64(kTwoTo54 - 1), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 0), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 2), false, false, ""}, - - // Floating point. - leTestCase{float64(-1), true, false, ""}, - leTestCase{float64(kTwoTo54 - 2), true, false, ""}, - leTestCase{float64(kTwoTo54 - 1), true, false, ""}, - leTestCase{float64(kTwoTo54 + 0), true, false, ""}, - leTestCase{float64(kTwoTo54 + 1), true, false, ""}, - leTestCase{float64(kTwoTo54 + 2), true, false, ""}, - leTestCase{float64(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) Uint64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := LessOrEqual(uint64(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "less than or equal to 33554433" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{-1, true, false, ""}, - leTestCase{kTwoTo25 + 0, true, false, ""}, - leTestCase{kTwoTo25 + 1, true, false, ""}, - leTestCase{kTwoTo25 + 2, false, false, ""}, - - leTestCase{int(-1), true, false, ""}, - leTestCase{int(kTwoTo25 + 0), true, false, ""}, - leTestCase{int(kTwoTo25 + 1), true, false, ""}, - leTestCase{int(kTwoTo25 + 2), false, false, ""}, - - leTestCase{int8(-1), true, false, ""}, - leTestCase{int8(127), true, false, ""}, - - leTestCase{int16(-1), true, false, ""}, - leTestCase{int16(0), true, false, ""}, - leTestCase{int16(32767), true, false, ""}, - - leTestCase{int32(-1), true, false, ""}, - leTestCase{int32(kTwoTo25 + 0), true, false, ""}, - leTestCase{int32(kTwoTo25 + 1), true, false, ""}, - leTestCase{int32(kTwoTo25 + 2), false, false, ""}, - - leTestCase{int64(-1), true, false, ""}, - leTestCase{int64(kTwoTo25 + 0), true, false, ""}, - leTestCase{int64(kTwoTo25 + 1), true, false, ""}, - leTestCase{int64(kTwoTo25 + 2), false, false, ""}, - - // Unsigned integers. - leTestCase{uint(0), true, false, ""}, - leTestCase{uint(kTwoTo25 + 0), true, false, ""}, - leTestCase{uint(kTwoTo25 + 1), true, false, ""}, - leTestCase{uint(kTwoTo25 + 2), false, false, ""}, - - leTestCase{uint8(0), true, false, ""}, - leTestCase{uint8(255), true, false, ""}, - - leTestCase{uint16(0), true, false, ""}, - leTestCase{uint16(65535), true, false, ""}, - - leTestCase{uint32(0), true, false, ""}, - leTestCase{uint32(kTwoTo25 + 0), true, false, ""}, - leTestCase{uint32(kTwoTo25 + 1), true, false, ""}, - leTestCase{uint32(kTwoTo25 + 2), false, false, ""}, - - leTestCase{uint64(0), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 0), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - - // Floating point. - leTestCase{float32(-1), true, false, ""}, - leTestCase{float32(kTwoTo25 - 2), true, false, ""}, - leTestCase{float32(kTwoTo25 - 1), true, false, ""}, - leTestCase{float32(kTwoTo25 + 0), true, false, ""}, - leTestCase{float32(kTwoTo25 + 1), true, false, ""}, - leTestCase{float32(kTwoTo25 + 2), true, false, ""}, - leTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - leTestCase{float64(-1), true, false, ""}, - leTestCase{float64(kTwoTo25 - 2), true, false, ""}, - leTestCase{float64(kTwoTo25 - 1), true, false, ""}, - leTestCase{float64(kTwoTo25 + 0), true, false, ""}, - leTestCase{float64(kTwoTo25 + 1), true, false, ""}, - leTestCase{float64(kTwoTo25 + 2), false, false, ""}, - leTestCase{float64(kTwoTo25 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) Uint64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := LessOrEqual(uint64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "less than or equal to 18014398509481985" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{-1, true, false, ""}, - leTestCase{1 << 30, true, false, ""}, - - leTestCase{int(-1), true, false, ""}, - leTestCase{int(math.MaxInt32), true, false, ""}, - - leTestCase{int8(-1), true, false, ""}, - leTestCase{int8(127), true, false, ""}, - - leTestCase{int16(-1), true, false, ""}, - leTestCase{int16(0), true, false, ""}, - leTestCase{int16(32767), true, false, ""}, - - leTestCase{int32(-1), true, false, ""}, - leTestCase{int32(math.MaxInt32), true, false, ""}, - - leTestCase{int64(-1), true, false, ""}, - leTestCase{int64(kTwoTo54 - 1), true, false, ""}, - leTestCase{int64(kTwoTo54 + 0), true, false, ""}, - leTestCase{int64(kTwoTo54 + 1), true, false, ""}, - leTestCase{int64(kTwoTo54 + 2), false, false, ""}, - - // Unsigned integers. - leTestCase{uint(0), true, false, ""}, - leTestCase{uint(math.MaxUint32), true, false, ""}, - - leTestCase{uint8(0), true, false, ""}, - leTestCase{uint8(255), true, false, ""}, - - leTestCase{uint16(0), true, false, ""}, - leTestCase{uint16(65535), true, false, ""}, - - leTestCase{uint32(0), true, false, ""}, - leTestCase{uint32(math.MaxUint32), true, false, ""}, - - leTestCase{uint64(0), true, false, ""}, - leTestCase{uint64(kTwoTo54 - 1), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 0), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 2), false, false, ""}, - - // Floating point. - leTestCase{float64(-1), true, false, ""}, - leTestCase{float64(kTwoTo54 - 2), true, false, ""}, - leTestCase{float64(kTwoTo54 - 1), true, false, ""}, - leTestCase{float64(kTwoTo54 + 0), true, false, ""}, - leTestCase{float64(kTwoTo54 + 1), true, false, ""}, - leTestCase{float64(kTwoTo54 + 2), true, false, ""}, - leTestCase{float64(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) Float32AboveExactIntegerRange() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := LessOrEqual(float32(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "less than or equal to 3.3554432e+07" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{int64(-1), true, false, ""}, - leTestCase{int64(kTwoTo25 - 2), true, false, ""}, - leTestCase{int64(kTwoTo25 - 1), true, false, ""}, - leTestCase{int64(kTwoTo25 + 0), true, false, ""}, - leTestCase{int64(kTwoTo25 + 1), true, false, ""}, - leTestCase{int64(kTwoTo25 + 2), true, false, ""}, - leTestCase{int64(kTwoTo25 + 3), false, false, ""}, - - // Unsigned integers. - leTestCase{uint64(0), true, false, ""}, - leTestCase{uint64(kTwoTo25 - 2), true, false, ""}, - leTestCase{uint64(kTwoTo25 - 1), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 0), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 1), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 2), true, false, ""}, - leTestCase{uint64(kTwoTo25 + 3), false, false, ""}, - - // Floating point. - leTestCase{float32(-1), true, false, ""}, - leTestCase{float32(kTwoTo25 - 2), true, false, ""}, - leTestCase{float32(kTwoTo25 - 1), true, false, ""}, - leTestCase{float32(kTwoTo25 + 0), true, false, ""}, - leTestCase{float32(kTwoTo25 + 1), true, false, ""}, - leTestCase{float32(kTwoTo25 + 2), true, false, ""}, - leTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - leTestCase{float64(-1), true, false, ""}, - leTestCase{float64(kTwoTo25 - 2), true, false, ""}, - leTestCase{float64(kTwoTo25 - 1), true, false, ""}, - leTestCase{float64(kTwoTo25 + 0), true, false, ""}, - leTestCase{float64(kTwoTo25 + 1), true, false, ""}, - leTestCase{float64(kTwoTo25 + 2), true, false, ""}, - leTestCase{float64(kTwoTo25 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) Float64AboveExactIntegerRange() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := LessOrEqual(float64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "less than or equal to 1.8014398509481984e+16" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - // Signed integers. - leTestCase{int64(-1), true, false, ""}, - leTestCase{int64(kTwoTo54 - 2), true, false, ""}, - leTestCase{int64(kTwoTo54 - 1), true, false, ""}, - leTestCase{int64(kTwoTo54 + 0), true, false, ""}, - leTestCase{int64(kTwoTo54 + 1), true, false, ""}, - leTestCase{int64(kTwoTo54 + 2), true, false, ""}, - leTestCase{int64(kTwoTo54 + 3), false, false, ""}, - - // Unsigned integers. - leTestCase{uint64(0), true, false, ""}, - leTestCase{uint64(kTwoTo54 - 2), true, false, ""}, - leTestCase{uint64(kTwoTo54 - 1), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 0), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 1), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 2), true, false, ""}, - leTestCase{uint64(kTwoTo54 + 3), false, false, ""}, - - // Floating point. - leTestCase{float64(-1), true, false, ""}, - leTestCase{float64(kTwoTo54 - 2), true, false, ""}, - leTestCase{float64(kTwoTo54 - 1), true, false, ""}, - leTestCase{float64(kTwoTo54 + 0), true, false, ""}, - leTestCase{float64(kTwoTo54 + 1), true, false, ""}, - leTestCase{float64(kTwoTo54 + 2), true, false, ""}, - leTestCase{float64(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// String literals -//////////////////////////////////////////////////////////////////////// - -func (t *LessOrEqualTest) EmptyString() { - matcher := LessOrEqual("") - desc := matcher.Description() - expectedDesc := "less than or equal to \"\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - leTestCase{"", true, false, ""}, - leTestCase{"\x00", false, false, ""}, - leTestCase{"a", false, false, ""}, - leTestCase{"foo", false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) SingleNullByte() { - matcher := LessOrEqual("\x00") - desc := matcher.Description() - expectedDesc := "less than or equal to \"\x00\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - leTestCase{"", true, false, ""}, - leTestCase{"\x00", true, false, ""}, - leTestCase{"\x00\x00", false, false, ""}, - leTestCase{"a", false, false, ""}, - leTestCase{"foo", false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessOrEqualTest) LongerString() { - matcher := LessOrEqual("foo\x00") - desc := matcher.Description() - expectedDesc := "less than or equal to \"foo\x00\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []leTestCase{ - leTestCase{"", true, false, ""}, - leTestCase{"\x00", true, false, ""}, - leTestCase{"bar", true, false, ""}, - leTestCase{"foo", true, false, ""}, - leTestCase{"foo\x00", true, false, ""}, - leTestCase{"foo\x00\x00", false, false, ""}, - leTestCase{"fooa", false, false, ""}, - leTestCase{"qux", false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_than.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_than.go deleted file mode 100644 index 8258e45..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_than.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "math" - "reflect" -) - -// LessThan returns a matcher that matches integer, floating point, or strings -// values v such that v < x. Comparison is not defined between numeric and -// string types, but is defined between all integer and floating point types. -// -// x must itself be an integer, floating point, or string type; otherwise, -// LessThan will panic. -func LessThan(x interface{}) Matcher { - v := reflect.ValueOf(x) - kind := v.Kind() - - switch { - case isInteger(v): - case isFloat(v): - case kind == reflect.String: - - default: - panic(fmt.Sprintf("LessThan: unexpected kind %v", kind)) - } - - return &lessThanMatcher{v} -} - -type lessThanMatcher struct { - limit reflect.Value -} - -func (m *lessThanMatcher) Description() string { - // Special case: make it clear that strings are strings. - if m.limit.Kind() == reflect.String { - return fmt.Sprintf("less than \"%s\"", m.limit.String()) - } - - return fmt.Sprintf("less than %v", m.limit.Interface()) -} - -func compareIntegers(v1, v2 reflect.Value) (err error) { - err = errors.New("") - - switch { - case isSignedInteger(v1) && isSignedInteger(v2): - if v1.Int() < v2.Int() { - err = nil - } - return - - case isSignedInteger(v1) && isUnsignedInteger(v2): - if v1.Int() < 0 || uint64(v1.Int()) < v2.Uint() { - err = nil - } - return - - case isUnsignedInteger(v1) && isSignedInteger(v2): - if v1.Uint() <= math.MaxInt64 && int64(v1.Uint()) < v2.Int() { - err = nil - } - return - - case isUnsignedInteger(v1) && isUnsignedInteger(v2): - if v1.Uint() < v2.Uint() { - err = nil - } - return - } - - panic(fmt.Sprintf("compareIntegers: %v %v", v1, v2)) -} - -func getFloat(v reflect.Value) float64 { - switch { - case isSignedInteger(v): - return float64(v.Int()) - - case isUnsignedInteger(v): - return float64(v.Uint()) - - case isFloat(v): - return v.Float() - } - - panic(fmt.Sprintf("getFloat: %v", v)) -} - -func (m *lessThanMatcher) Matches(c interface{}) (err error) { - v1 := reflect.ValueOf(c) - v2 := m.limit - - err = errors.New("") - - // Handle strings as a special case. - if v1.Kind() == reflect.String && v2.Kind() == reflect.String { - if v1.String() < v2.String() { - err = nil - } - return - } - - // If we get here, we require that we are dealing with integers or floats. - v1Legal := isInteger(v1) || isFloat(v1) - v2Legal := isInteger(v2) || isFloat(v2) - if !v1Legal || !v2Legal { - err = NewFatalError("which is not comparable") - return - } - - // Handle the various comparison cases. - switch { - // Both integers - case isInteger(v1) && isInteger(v2): - return compareIntegers(v1, v2) - - // At least one float32 - case v1.Kind() == reflect.Float32 || v2.Kind() == reflect.Float32: - if float32(getFloat(v1)) < float32(getFloat(v2)) { - err = nil - } - return - - // At least one float64 - case v1.Kind() == reflect.Float64 || v2.Kind() == reflect.Float64: - if getFloat(v1) < getFloat(v2) { - err = nil - } - return - } - - // We shouldn't get here. - panic(fmt.Sprintf("lessThanMatcher.Matches: Shouldn't get here: %v %v", v1, v2)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_than_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_than_test.go deleted file mode 100644 index f87d0a8..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/less_than_test.go +++ /dev/null @@ -1,1060 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "math" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type LessThanTest struct { -} - -func init() { RegisterTestSuite(&LessThanTest{}) } - -type ltTestCase struct { - candidate interface{} - expectedResult bool - shouldBeFatal bool - expectedError string -} - -func (t *LessThanTest) checkTestCases(matcher Matcher, cases []ltTestCase) { - for i, c := range cases { - err := matcher.Matches(c.candidate) - - ExpectThat( - (err == nil), - Equals(c.expectedResult), - "Case %d (candidate %v)", - i, - c.candidate) - - if err == nil { - continue - } - - _, isFatal := err.(*FatalError) - ExpectEq( - c.shouldBeFatal, - isFatal, - "Case %d (candidate %v)", - i, - c.candidate) - - ExpectThat( - err, - Error(Equals(c.expectedError)), - "Case %d (candidate %v)", - i, - c.candidate) - } -} - -//////////////////////////////////////////////////////////////////////// -// Integer literals -//////////////////////////////////////////////////////////////////////// - -func (t *LessThanTest) IntegerCandidateBadTypes() { - matcher := LessThan(int(-150)) - - cases := []ltTestCase{ - ltTestCase{true, false, true, "which is not comparable"}, - ltTestCase{uintptr(17), false, true, "which is not comparable"}, - ltTestCase{complex64(-151), false, true, "which is not comparable"}, - ltTestCase{complex128(-151), false, true, "which is not comparable"}, - ltTestCase{[...]int{-151}, false, true, "which is not comparable"}, - ltTestCase{make(chan int), false, true, "which is not comparable"}, - ltTestCase{func() {}, false, true, "which is not comparable"}, - ltTestCase{map[int]int{}, false, true, "which is not comparable"}, - ltTestCase{<TestCase{}, false, true, "which is not comparable"}, - ltTestCase{make([]int, 0), false, true, "which is not comparable"}, - ltTestCase{"-151", false, true, "which is not comparable"}, - ltTestCase{ltTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) FloatCandidateBadTypes() { - matcher := LessThan(float32(-150)) - - cases := []ltTestCase{ - ltTestCase{true, false, true, "which is not comparable"}, - ltTestCase{uintptr(17), false, true, "which is not comparable"}, - ltTestCase{complex64(-151), false, true, "which is not comparable"}, - ltTestCase{complex128(-151), false, true, "which is not comparable"}, - ltTestCase{[...]int{-151}, false, true, "which is not comparable"}, - ltTestCase{make(chan int), false, true, "which is not comparable"}, - ltTestCase{func() {}, false, true, "which is not comparable"}, - ltTestCase{map[int]int{}, false, true, "which is not comparable"}, - ltTestCase{<TestCase{}, false, true, "which is not comparable"}, - ltTestCase{make([]int, 0), false, true, "which is not comparable"}, - ltTestCase{"-151", false, true, "which is not comparable"}, - ltTestCase{ltTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) StringCandidateBadTypes() { - matcher := LessThan("17") - - cases := []ltTestCase{ - ltTestCase{true, false, true, "which is not comparable"}, - ltTestCase{int(0), false, true, "which is not comparable"}, - ltTestCase{int8(0), false, true, "which is not comparable"}, - ltTestCase{int16(0), false, true, "which is not comparable"}, - ltTestCase{int32(0), false, true, "which is not comparable"}, - ltTestCase{int64(0), false, true, "which is not comparable"}, - ltTestCase{uint(0), false, true, "which is not comparable"}, - ltTestCase{uint8(0), false, true, "which is not comparable"}, - ltTestCase{uint16(0), false, true, "which is not comparable"}, - ltTestCase{uint32(0), false, true, "which is not comparable"}, - ltTestCase{uint64(0), false, true, "which is not comparable"}, - ltTestCase{uintptr(17), false, true, "which is not comparable"}, - ltTestCase{float32(0), false, true, "which is not comparable"}, - ltTestCase{float64(0), false, true, "which is not comparable"}, - ltTestCase{complex64(-151), false, true, "which is not comparable"}, - ltTestCase{complex128(-151), false, true, "which is not comparable"}, - ltTestCase{[...]int{-151}, false, true, "which is not comparable"}, - ltTestCase{make(chan int), false, true, "which is not comparable"}, - ltTestCase{func() {}, false, true, "which is not comparable"}, - ltTestCase{map[int]int{}, false, true, "which is not comparable"}, - ltTestCase{<TestCase{}, false, true, "which is not comparable"}, - ltTestCase{make([]int, 0), false, true, "which is not comparable"}, - ltTestCase{ltTestCase{}, false, true, "which is not comparable"}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) BadArgument() { - panicked := false - - defer func() { - ExpectThat(panicked, Equals(true)) - }() - - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - LessThan(complex128(0)) -} - -//////////////////////////////////////////////////////////////////////// -// Integer literals -//////////////////////////////////////////////////////////////////////// - -func (t *LessThanTest) NegativeIntegerLiteral() { - matcher := LessThan(-150) - desc := matcher.Description() - expectedDesc := "less than -150" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{-(1 << 30), true, false, ""}, - ltTestCase{-151, true, false, ""}, - ltTestCase{-150, false, false, ""}, - ltTestCase{0, false, false, ""}, - ltTestCase{17, false, false, ""}, - - ltTestCase{int(-(1 << 30)), true, false, ""}, - ltTestCase{int(-151), true, false, ""}, - ltTestCase{int(-150), false, false, ""}, - ltTestCase{int(0), false, false, ""}, - ltTestCase{int(17), false, false, ""}, - - ltTestCase{int8(-127), false, false, ""}, - ltTestCase{int8(0), false, false, ""}, - ltTestCase{int8(17), false, false, ""}, - - ltTestCase{int16(-(1 << 14)), true, false, ""}, - ltTestCase{int16(-151), true, false, ""}, - ltTestCase{int16(-150), false, false, ""}, - ltTestCase{int16(0), false, false, ""}, - ltTestCase{int16(17), false, false, ""}, - - ltTestCase{int32(-(1 << 30)), true, false, ""}, - ltTestCase{int32(-151), true, false, ""}, - ltTestCase{int32(-150), false, false, ""}, - ltTestCase{int32(0), false, false, ""}, - ltTestCase{int32(17), false, false, ""}, - - ltTestCase{int64(-(1 << 30)), true, false, ""}, - ltTestCase{int64(-151), true, false, ""}, - ltTestCase{int64(-150), false, false, ""}, - ltTestCase{int64(0), false, false, ""}, - ltTestCase{int64(17), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint((1 << 32) - 151), false, false, ""}, - ltTestCase{uint(0), false, false, ""}, - ltTestCase{uint(17), false, false, ""}, - - ltTestCase{uint8(0), false, false, ""}, - ltTestCase{uint8(17), false, false, ""}, - ltTestCase{uint8(253), false, false, ""}, - - ltTestCase{uint16((1 << 16) - 151), false, false, ""}, - ltTestCase{uint16(0), false, false, ""}, - ltTestCase{uint16(17), false, false, ""}, - - ltTestCase{uint32((1 << 32) - 151), false, false, ""}, - ltTestCase{uint32(0), false, false, ""}, - ltTestCase{uint32(17), false, false, ""}, - - ltTestCase{uint64((1 << 64) - 151), false, false, ""}, - ltTestCase{uint64(0), false, false, ""}, - ltTestCase{uint64(17), false, false, ""}, - - // Floating point. - ltTestCase{float32(-(1 << 30)), true, false, ""}, - ltTestCase{float32(-151), true, false, ""}, - ltTestCase{float32(-150.1), true, false, ""}, - ltTestCase{float32(-150), false, false, ""}, - ltTestCase{float32(-149.9), false, false, ""}, - ltTestCase{float32(0), false, false, ""}, - ltTestCase{float32(17), false, false, ""}, - ltTestCase{float32(160), false, false, ""}, - - ltTestCase{float64(-(1 << 30)), true, false, ""}, - ltTestCase{float64(-151), true, false, ""}, - ltTestCase{float64(-150.1), true, false, ""}, - ltTestCase{float64(-150), false, false, ""}, - ltTestCase{float64(-149.9), false, false, ""}, - ltTestCase{float64(0), false, false, ""}, - ltTestCase{float64(17), false, false, ""}, - ltTestCase{float64(160), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) ZeroIntegerLiteral() { - matcher := LessThan(0) - desc := matcher.Description() - expectedDesc := "less than 0" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{-(1 << 30), true, false, ""}, - ltTestCase{-1, true, false, ""}, - ltTestCase{0, false, false, ""}, - ltTestCase{1, false, false, ""}, - ltTestCase{17, false, false, ""}, - ltTestCase{(1 << 30), false, false, ""}, - - ltTestCase{int(-(1 << 30)), true, false, ""}, - ltTestCase{int(-1), true, false, ""}, - ltTestCase{int(0), false, false, ""}, - ltTestCase{int(1), false, false, ""}, - ltTestCase{int(17), false, false, ""}, - - ltTestCase{int8(-1), true, false, ""}, - ltTestCase{int8(0), false, false, ""}, - ltTestCase{int8(1), false, false, ""}, - - ltTestCase{int16(-(1 << 14)), true, false, ""}, - ltTestCase{int16(-1), true, false, ""}, - ltTestCase{int16(0), false, false, ""}, - ltTestCase{int16(1), false, false, ""}, - ltTestCase{int16(17), false, false, ""}, - - ltTestCase{int32(-(1 << 30)), true, false, ""}, - ltTestCase{int32(-1), true, false, ""}, - ltTestCase{int32(0), false, false, ""}, - ltTestCase{int32(1), false, false, ""}, - ltTestCase{int32(17), false, false, ""}, - - ltTestCase{int64(-(1 << 30)), true, false, ""}, - ltTestCase{int64(-1), true, false, ""}, - ltTestCase{int64(0), false, false, ""}, - ltTestCase{int64(1), false, false, ""}, - ltTestCase{int64(17), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint((1 << 32) - 1), false, false, ""}, - ltTestCase{uint(0), false, false, ""}, - ltTestCase{uint(17), false, false, ""}, - - ltTestCase{uint8(0), false, false, ""}, - ltTestCase{uint8(17), false, false, ""}, - ltTestCase{uint8(253), false, false, ""}, - - ltTestCase{uint16((1 << 16) - 1), false, false, ""}, - ltTestCase{uint16(0), false, false, ""}, - ltTestCase{uint16(17), false, false, ""}, - - ltTestCase{uint32((1 << 32) - 1), false, false, ""}, - ltTestCase{uint32(0), false, false, ""}, - ltTestCase{uint32(17), false, false, ""}, - - ltTestCase{uint64((1 << 64) - 1), false, false, ""}, - ltTestCase{uint64(0), false, false, ""}, - ltTestCase{uint64(17), false, false, ""}, - - // Floating point. - ltTestCase{float32(-(1 << 30)), true, false, ""}, - ltTestCase{float32(-1), true, false, ""}, - ltTestCase{float32(-0.1), true, false, ""}, - ltTestCase{float32(-0.0), false, false, ""}, - ltTestCase{float32(0), false, false, ""}, - ltTestCase{float32(0.1), false, false, ""}, - ltTestCase{float32(17), false, false, ""}, - ltTestCase{float32(160), false, false, ""}, - - ltTestCase{float64(-(1 << 30)), true, false, ""}, - ltTestCase{float64(-1), true, false, ""}, - ltTestCase{float64(-0.1), true, false, ""}, - ltTestCase{float64(-0), false, false, ""}, - ltTestCase{float64(0), false, false, ""}, - ltTestCase{float64(17), false, false, ""}, - ltTestCase{float64(160), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) PositiveIntegerLiteral() { - matcher := LessThan(150) - desc := matcher.Description() - expectedDesc := "less than 150" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{-1, true, false, ""}, - ltTestCase{149, true, false, ""}, - ltTestCase{150, false, false, ""}, - ltTestCase{151, false, false, ""}, - - ltTestCase{int(-1), true, false, ""}, - ltTestCase{int(149), true, false, ""}, - ltTestCase{int(150), false, false, ""}, - ltTestCase{int(151), false, false, ""}, - - ltTestCase{int8(-1), true, false, ""}, - ltTestCase{int8(0), true, false, ""}, - ltTestCase{int8(17), true, false, ""}, - ltTestCase{int8(127), true, false, ""}, - - ltTestCase{int16(-1), true, false, ""}, - ltTestCase{int16(149), true, false, ""}, - ltTestCase{int16(150), false, false, ""}, - ltTestCase{int16(151), false, false, ""}, - - ltTestCase{int32(-1), true, false, ""}, - ltTestCase{int32(149), true, false, ""}, - ltTestCase{int32(150), false, false, ""}, - ltTestCase{int32(151), false, false, ""}, - - ltTestCase{int64(-1), true, false, ""}, - ltTestCase{int64(149), true, false, ""}, - ltTestCase{int64(150), false, false, ""}, - ltTestCase{int64(151), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint(0), true, false, ""}, - ltTestCase{uint(149), true, false, ""}, - ltTestCase{uint(150), false, false, ""}, - ltTestCase{uint(151), false, false, ""}, - - ltTestCase{uint8(0), true, false, ""}, - ltTestCase{uint8(127), true, false, ""}, - - ltTestCase{uint16(0), true, false, ""}, - ltTestCase{uint16(149), true, false, ""}, - ltTestCase{uint16(150), false, false, ""}, - ltTestCase{uint16(151), false, false, ""}, - - ltTestCase{uint32(0), true, false, ""}, - ltTestCase{uint32(149), true, false, ""}, - ltTestCase{uint32(150), false, false, ""}, - ltTestCase{uint32(151), false, false, ""}, - - ltTestCase{uint64(0), true, false, ""}, - ltTestCase{uint64(149), true, false, ""}, - ltTestCase{uint64(150), false, false, ""}, - ltTestCase{uint64(151), false, false, ""}, - - // Floating point. - ltTestCase{float32(-1), true, false, ""}, - ltTestCase{float32(149), true, false, ""}, - ltTestCase{float32(149.9), true, false, ""}, - ltTestCase{float32(150), false, false, ""}, - ltTestCase{float32(150.1), false, false, ""}, - ltTestCase{float32(151), false, false, ""}, - - ltTestCase{float64(-1), true, false, ""}, - ltTestCase{float64(149), true, false, ""}, - ltTestCase{float64(149.9), true, false, ""}, - ltTestCase{float64(150), false, false, ""}, - ltTestCase{float64(150.1), false, false, ""}, - ltTestCase{float64(151), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Float literals -//////////////////////////////////////////////////////////////////////// - -func (t *LessThanTest) NegativeFloatLiteral() { - matcher := LessThan(-150.1) - desc := matcher.Description() - expectedDesc := "less than -150.1" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{-(1 << 30), true, false, ""}, - ltTestCase{-151, true, false, ""}, - ltTestCase{-150, false, false, ""}, - ltTestCase{0, false, false, ""}, - ltTestCase{17, false, false, ""}, - - ltTestCase{int(-(1 << 30)), true, false, ""}, - ltTestCase{int(-151), true, false, ""}, - ltTestCase{int(-150), false, false, ""}, - ltTestCase{int(0), false, false, ""}, - ltTestCase{int(17), false, false, ""}, - - ltTestCase{int8(-127), false, false, ""}, - ltTestCase{int8(0), false, false, ""}, - ltTestCase{int8(17), false, false, ""}, - - ltTestCase{int16(-(1 << 14)), true, false, ""}, - ltTestCase{int16(-151), true, false, ""}, - ltTestCase{int16(-150), false, false, ""}, - ltTestCase{int16(0), false, false, ""}, - ltTestCase{int16(17), false, false, ""}, - - ltTestCase{int32(-(1 << 30)), true, false, ""}, - ltTestCase{int32(-151), true, false, ""}, - ltTestCase{int32(-150), false, false, ""}, - ltTestCase{int32(0), false, false, ""}, - ltTestCase{int32(17), false, false, ""}, - - ltTestCase{int64(-(1 << 30)), true, false, ""}, - ltTestCase{int64(-151), true, false, ""}, - ltTestCase{int64(-150), false, false, ""}, - ltTestCase{int64(0), false, false, ""}, - ltTestCase{int64(17), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint((1 << 32) - 151), false, false, ""}, - ltTestCase{uint(0), false, false, ""}, - ltTestCase{uint(17), false, false, ""}, - - ltTestCase{uint8(0), false, false, ""}, - ltTestCase{uint8(17), false, false, ""}, - ltTestCase{uint8(253), false, false, ""}, - - ltTestCase{uint16((1 << 16) - 151), false, false, ""}, - ltTestCase{uint16(0), false, false, ""}, - ltTestCase{uint16(17), false, false, ""}, - - ltTestCase{uint32((1 << 32) - 151), false, false, ""}, - ltTestCase{uint32(0), false, false, ""}, - ltTestCase{uint32(17), false, false, ""}, - - ltTestCase{uint64((1 << 64) - 151), false, false, ""}, - ltTestCase{uint64(0), false, false, ""}, - ltTestCase{uint64(17), false, false, ""}, - - // Floating point. - ltTestCase{float32(-(1 << 30)), true, false, ""}, - ltTestCase{float32(-151), true, false, ""}, - ltTestCase{float32(-150.2), true, false, ""}, - ltTestCase{float32(-150.1), false, false, ""}, - ltTestCase{float32(-150), false, false, ""}, - ltTestCase{float32(0), false, false, ""}, - ltTestCase{float32(17), false, false, ""}, - ltTestCase{float32(160), false, false, ""}, - - ltTestCase{float64(-(1 << 30)), true, false, ""}, - ltTestCase{float64(-151), true, false, ""}, - ltTestCase{float64(-150.2), true, false, ""}, - ltTestCase{float64(-150.1), false, false, ""}, - ltTestCase{float64(-150), false, false, ""}, - ltTestCase{float64(0), false, false, ""}, - ltTestCase{float64(17), false, false, ""}, - ltTestCase{float64(160), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) PositiveFloatLiteral() { - matcher := LessThan(149.9) - desc := matcher.Description() - expectedDesc := "less than 149.9" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{-1, true, false, ""}, - ltTestCase{149, true, false, ""}, - ltTestCase{150, false, false, ""}, - ltTestCase{151, false, false, ""}, - - ltTestCase{int(-1), true, false, ""}, - ltTestCase{int(149), true, false, ""}, - ltTestCase{int(150), false, false, ""}, - ltTestCase{int(151), false, false, ""}, - - ltTestCase{int8(-1), true, false, ""}, - ltTestCase{int8(0), true, false, ""}, - ltTestCase{int8(17), true, false, ""}, - ltTestCase{int8(127), true, false, ""}, - - ltTestCase{int16(-1), true, false, ""}, - ltTestCase{int16(149), true, false, ""}, - ltTestCase{int16(150), false, false, ""}, - ltTestCase{int16(151), false, false, ""}, - - ltTestCase{int32(-1), true, false, ""}, - ltTestCase{int32(149), true, false, ""}, - ltTestCase{int32(150), false, false, ""}, - ltTestCase{int32(151), false, false, ""}, - - ltTestCase{int64(-1), true, false, ""}, - ltTestCase{int64(149), true, false, ""}, - ltTestCase{int64(150), false, false, ""}, - ltTestCase{int64(151), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint(0), true, false, ""}, - ltTestCase{uint(149), true, false, ""}, - ltTestCase{uint(150), false, false, ""}, - ltTestCase{uint(151), false, false, ""}, - - ltTestCase{uint8(0), true, false, ""}, - ltTestCase{uint8(127), true, false, ""}, - - ltTestCase{uint16(0), true, false, ""}, - ltTestCase{uint16(149), true, false, ""}, - ltTestCase{uint16(150), false, false, ""}, - ltTestCase{uint16(151), false, false, ""}, - - ltTestCase{uint32(0), true, false, ""}, - ltTestCase{uint32(149), true, false, ""}, - ltTestCase{uint32(150), false, false, ""}, - ltTestCase{uint32(151), false, false, ""}, - - ltTestCase{uint64(0), true, false, ""}, - ltTestCase{uint64(149), true, false, ""}, - ltTestCase{uint64(150), false, false, ""}, - ltTestCase{uint64(151), false, false, ""}, - - // Floating point. - ltTestCase{float32(-1), true, false, ""}, - ltTestCase{float32(149), true, false, ""}, - ltTestCase{float32(149.8), true, false, ""}, - ltTestCase{float32(149.9), false, false, ""}, - ltTestCase{float32(150), false, false, ""}, - ltTestCase{float32(151), false, false, ""}, - - ltTestCase{float64(-1), true, false, ""}, - ltTestCase{float64(149), true, false, ""}, - ltTestCase{float64(149.8), true, false, ""}, - ltTestCase{float64(149.9), false, false, ""}, - ltTestCase{float64(150), false, false, ""}, - ltTestCase{float64(151), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// Subtle cases -//////////////////////////////////////////////////////////////////////// - -func (t *LessThanTest) Int64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := LessThan(int64(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "less than 33554433" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{-1, true, false, ""}, - ltTestCase{kTwoTo25 + 0, true, false, ""}, - ltTestCase{kTwoTo25 + 1, false, false, ""}, - ltTestCase{kTwoTo25 + 2, false, false, ""}, - - ltTestCase{int(-1), true, false, ""}, - ltTestCase{int(kTwoTo25 + 0), true, false, ""}, - ltTestCase{int(kTwoTo25 + 1), false, false, ""}, - ltTestCase{int(kTwoTo25 + 2), false, false, ""}, - - ltTestCase{int8(-1), true, false, ""}, - ltTestCase{int8(127), true, false, ""}, - - ltTestCase{int16(-1), true, false, ""}, - ltTestCase{int16(0), true, false, ""}, - ltTestCase{int16(32767), true, false, ""}, - - ltTestCase{int32(-1), true, false, ""}, - ltTestCase{int32(kTwoTo25 + 0), true, false, ""}, - ltTestCase{int32(kTwoTo25 + 1), false, false, ""}, - ltTestCase{int32(kTwoTo25 + 2), false, false, ""}, - - ltTestCase{int64(-1), true, false, ""}, - ltTestCase{int64(kTwoTo25 + 0), true, false, ""}, - ltTestCase{int64(kTwoTo25 + 1), false, false, ""}, - ltTestCase{int64(kTwoTo25 + 2), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint(0), true, false, ""}, - ltTestCase{uint(kTwoTo25 + 0), true, false, ""}, - ltTestCase{uint(kTwoTo25 + 1), false, false, ""}, - ltTestCase{uint(kTwoTo25 + 2), false, false, ""}, - - ltTestCase{uint8(0), true, false, ""}, - ltTestCase{uint8(255), true, false, ""}, - - ltTestCase{uint16(0), true, false, ""}, - ltTestCase{uint16(65535), true, false, ""}, - - ltTestCase{uint32(0), true, false, ""}, - ltTestCase{uint32(kTwoTo25 + 0), true, false, ""}, - ltTestCase{uint32(kTwoTo25 + 1), false, false, ""}, - ltTestCase{uint32(kTwoTo25 + 2), false, false, ""}, - - ltTestCase{uint64(0), true, false, ""}, - ltTestCase{uint64(kTwoTo25 + 0), true, false, ""}, - ltTestCase{uint64(kTwoTo25 + 1), false, false, ""}, - ltTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - - // Floating point. - ltTestCase{float32(-1), true, false, ""}, - ltTestCase{float32(kTwoTo25 - 2), true, false, ""}, - ltTestCase{float32(kTwoTo25 - 1), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 0), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 1), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 2), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - ltTestCase{float64(-1), true, false, ""}, - ltTestCase{float64(kTwoTo25 - 2), true, false, ""}, - ltTestCase{float64(kTwoTo25 - 1), true, false, ""}, - ltTestCase{float64(kTwoTo25 + 0), true, false, ""}, - ltTestCase{float64(kTwoTo25 + 1), false, false, ""}, - ltTestCase{float64(kTwoTo25 + 2), false, false, ""}, - ltTestCase{float64(kTwoTo25 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) Int64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := LessThan(int64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "less than 18014398509481985" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{-1, true, false, ""}, - ltTestCase{1 << 30, true, false, ""}, - - ltTestCase{int(-1), true, false, ""}, - ltTestCase{int(math.MaxInt32), true, false, ""}, - - ltTestCase{int8(-1), true, false, ""}, - ltTestCase{int8(127), true, false, ""}, - - ltTestCase{int16(-1), true, false, ""}, - ltTestCase{int16(0), true, false, ""}, - ltTestCase{int16(32767), true, false, ""}, - - ltTestCase{int32(-1), true, false, ""}, - ltTestCase{int32(math.MaxInt32), true, false, ""}, - - ltTestCase{int64(-1), true, false, ""}, - ltTestCase{int64(kTwoTo54 - 1), true, false, ""}, - ltTestCase{int64(kTwoTo54 + 0), true, false, ""}, - ltTestCase{int64(kTwoTo54 + 1), false, false, ""}, - ltTestCase{int64(kTwoTo54 + 2), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint(0), true, false, ""}, - ltTestCase{uint(math.MaxUint32), true, false, ""}, - - ltTestCase{uint8(0), true, false, ""}, - ltTestCase{uint8(255), true, false, ""}, - - ltTestCase{uint16(0), true, false, ""}, - ltTestCase{uint16(65535), true, false, ""}, - - ltTestCase{uint32(0), true, false, ""}, - ltTestCase{uint32(math.MaxUint32), true, false, ""}, - - ltTestCase{uint64(0), true, false, ""}, - ltTestCase{uint64(kTwoTo54 - 1), true, false, ""}, - ltTestCase{uint64(kTwoTo54 + 0), true, false, ""}, - ltTestCase{uint64(kTwoTo54 + 1), false, false, ""}, - ltTestCase{uint64(kTwoTo54 + 2), false, false, ""}, - - // Floating point. - ltTestCase{float64(-1), true, false, ""}, - ltTestCase{float64(kTwoTo54 - 2), true, false, ""}, - ltTestCase{float64(kTwoTo54 - 1), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 0), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 1), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 2), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) Uint64NotExactlyRepresentableBySinglePrecision() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := LessThan(uint64(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "less than 33554433" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{-1, true, false, ""}, - ltTestCase{kTwoTo25 + 0, true, false, ""}, - ltTestCase{kTwoTo25 + 1, false, false, ""}, - ltTestCase{kTwoTo25 + 2, false, false, ""}, - - ltTestCase{int(-1), true, false, ""}, - ltTestCase{int(kTwoTo25 + 0), true, false, ""}, - ltTestCase{int(kTwoTo25 + 1), false, false, ""}, - ltTestCase{int(kTwoTo25 + 2), false, false, ""}, - - ltTestCase{int8(-1), true, false, ""}, - ltTestCase{int8(127), true, false, ""}, - - ltTestCase{int16(-1), true, false, ""}, - ltTestCase{int16(0), true, false, ""}, - ltTestCase{int16(32767), true, false, ""}, - - ltTestCase{int32(-1), true, false, ""}, - ltTestCase{int32(kTwoTo25 + 0), true, false, ""}, - ltTestCase{int32(kTwoTo25 + 1), false, false, ""}, - ltTestCase{int32(kTwoTo25 + 2), false, false, ""}, - - ltTestCase{int64(-1), true, false, ""}, - ltTestCase{int64(kTwoTo25 + 0), true, false, ""}, - ltTestCase{int64(kTwoTo25 + 1), false, false, ""}, - ltTestCase{int64(kTwoTo25 + 2), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint(0), true, false, ""}, - ltTestCase{uint(kTwoTo25 + 0), true, false, ""}, - ltTestCase{uint(kTwoTo25 + 1), false, false, ""}, - ltTestCase{uint(kTwoTo25 + 2), false, false, ""}, - - ltTestCase{uint8(0), true, false, ""}, - ltTestCase{uint8(255), true, false, ""}, - - ltTestCase{uint16(0), true, false, ""}, - ltTestCase{uint16(65535), true, false, ""}, - - ltTestCase{uint32(0), true, false, ""}, - ltTestCase{uint32(kTwoTo25 + 0), true, false, ""}, - ltTestCase{uint32(kTwoTo25 + 1), false, false, ""}, - ltTestCase{uint32(kTwoTo25 + 2), false, false, ""}, - - ltTestCase{uint64(0), true, false, ""}, - ltTestCase{uint64(kTwoTo25 + 0), true, false, ""}, - ltTestCase{uint64(kTwoTo25 + 1), false, false, ""}, - ltTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - - // Floating point. - ltTestCase{float32(-1), true, false, ""}, - ltTestCase{float32(kTwoTo25 - 2), true, false, ""}, - ltTestCase{float32(kTwoTo25 - 1), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 0), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 1), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 2), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - ltTestCase{float64(-1), true, false, ""}, - ltTestCase{float64(kTwoTo25 - 2), true, false, ""}, - ltTestCase{float64(kTwoTo25 - 1), true, false, ""}, - ltTestCase{float64(kTwoTo25 + 0), true, false, ""}, - ltTestCase{float64(kTwoTo25 + 1), false, false, ""}, - ltTestCase{float64(kTwoTo25 + 2), false, false, ""}, - ltTestCase{float64(kTwoTo25 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) Uint64NotExactlyRepresentableByDoublePrecision() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := LessThan(uint64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "less than 18014398509481985" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{-1, true, false, ""}, - ltTestCase{1 << 30, true, false, ""}, - - ltTestCase{int(-1), true, false, ""}, - ltTestCase{int(math.MaxInt32), true, false, ""}, - - ltTestCase{int8(-1), true, false, ""}, - ltTestCase{int8(127), true, false, ""}, - - ltTestCase{int16(-1), true, false, ""}, - ltTestCase{int16(0), true, false, ""}, - ltTestCase{int16(32767), true, false, ""}, - - ltTestCase{int32(-1), true, false, ""}, - ltTestCase{int32(math.MaxInt32), true, false, ""}, - - ltTestCase{int64(-1), true, false, ""}, - ltTestCase{int64(kTwoTo54 - 1), true, false, ""}, - ltTestCase{int64(kTwoTo54 + 0), true, false, ""}, - ltTestCase{int64(kTwoTo54 + 1), false, false, ""}, - ltTestCase{int64(kTwoTo54 + 2), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint(0), true, false, ""}, - ltTestCase{uint(math.MaxUint32), true, false, ""}, - - ltTestCase{uint8(0), true, false, ""}, - ltTestCase{uint8(255), true, false, ""}, - - ltTestCase{uint16(0), true, false, ""}, - ltTestCase{uint16(65535), true, false, ""}, - - ltTestCase{uint32(0), true, false, ""}, - ltTestCase{uint32(math.MaxUint32), true, false, ""}, - - ltTestCase{uint64(0), true, false, ""}, - ltTestCase{uint64(kTwoTo54 - 1), true, false, ""}, - ltTestCase{uint64(kTwoTo54 + 0), true, false, ""}, - ltTestCase{uint64(kTwoTo54 + 1), false, false, ""}, - ltTestCase{uint64(kTwoTo54 + 2), false, false, ""}, - - // Floating point. - ltTestCase{float64(-1), true, false, ""}, - ltTestCase{float64(kTwoTo54 - 2), true, false, ""}, - ltTestCase{float64(kTwoTo54 - 1), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 0), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 1), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 2), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) Float32AboveExactIntegerRange() { - // Single-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo25 = 1 << 25 - matcher := LessThan(float32(kTwoTo25 + 1)) - - desc := matcher.Description() - expectedDesc := "less than 3.3554432e+07" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{int64(-1), true, false, ""}, - ltTestCase{int64(kTwoTo25 - 2), true, false, ""}, - ltTestCase{int64(kTwoTo25 - 1), false, false, ""}, - ltTestCase{int64(kTwoTo25 + 0), false, false, ""}, - ltTestCase{int64(kTwoTo25 + 1), false, false, ""}, - ltTestCase{int64(kTwoTo25 + 2), false, false, ""}, - ltTestCase{int64(kTwoTo25 + 3), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint64(0), true, false, ""}, - ltTestCase{uint64(kTwoTo25 - 2), true, false, ""}, - ltTestCase{uint64(kTwoTo25 - 1), false, false, ""}, - ltTestCase{uint64(kTwoTo25 + 0), false, false, ""}, - ltTestCase{uint64(kTwoTo25 + 1), false, false, ""}, - ltTestCase{uint64(kTwoTo25 + 2), false, false, ""}, - ltTestCase{uint64(kTwoTo25 + 3), false, false, ""}, - - // Floating point. - ltTestCase{float32(-1), true, false, ""}, - ltTestCase{float32(kTwoTo25 - 2), true, false, ""}, - ltTestCase{float32(kTwoTo25 - 1), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 0), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 1), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 2), false, false, ""}, - ltTestCase{float32(kTwoTo25 + 3), false, false, ""}, - - ltTestCase{float64(-1), true, false, ""}, - ltTestCase{float64(kTwoTo25 - 2), true, false, ""}, - ltTestCase{float64(kTwoTo25 - 1), false, false, ""}, - ltTestCase{float64(kTwoTo25 + 0), false, false, ""}, - ltTestCase{float64(kTwoTo25 + 1), false, false, ""}, - ltTestCase{float64(kTwoTo25 + 2), false, false, ""}, - ltTestCase{float64(kTwoTo25 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) Float64AboveExactIntegerRange() { - // Double-precision floats don't have enough bits to represent the integers - // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value - // and should be treated as equivalent when floats are in the mix. - const kTwoTo54 = 1 << 54 - matcher := LessThan(float64(kTwoTo54 + 1)) - - desc := matcher.Description() - expectedDesc := "less than 1.8014398509481984e+16" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - // Signed integers. - ltTestCase{int64(-1), true, false, ""}, - ltTestCase{int64(kTwoTo54 - 2), true, false, ""}, - ltTestCase{int64(kTwoTo54 - 1), false, false, ""}, - ltTestCase{int64(kTwoTo54 + 0), false, false, ""}, - ltTestCase{int64(kTwoTo54 + 1), false, false, ""}, - ltTestCase{int64(kTwoTo54 + 2), false, false, ""}, - ltTestCase{int64(kTwoTo54 + 3), false, false, ""}, - - // Unsigned integers. - ltTestCase{uint64(0), true, false, ""}, - ltTestCase{uint64(kTwoTo54 - 2), true, false, ""}, - ltTestCase{uint64(kTwoTo54 - 1), false, false, ""}, - ltTestCase{uint64(kTwoTo54 + 0), false, false, ""}, - ltTestCase{uint64(kTwoTo54 + 1), false, false, ""}, - ltTestCase{uint64(kTwoTo54 + 2), false, false, ""}, - ltTestCase{uint64(kTwoTo54 + 3), false, false, ""}, - - // Floating point. - ltTestCase{float64(-1), true, false, ""}, - ltTestCase{float64(kTwoTo54 - 2), true, false, ""}, - ltTestCase{float64(kTwoTo54 - 1), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 0), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 1), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 2), false, false, ""}, - ltTestCase{float64(kTwoTo54 + 3), false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -//////////////////////////////////////////////////////////////////////// -// String literals -//////////////////////////////////////////////////////////////////////// - -func (t *LessThanTest) EmptyString() { - matcher := LessThan("") - desc := matcher.Description() - expectedDesc := "less than \"\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - ltTestCase{"", false, false, ""}, - ltTestCase{"\x00", false, false, ""}, - ltTestCase{"a", false, false, ""}, - ltTestCase{"foo", false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) SingleNullByte() { - matcher := LessThan("\x00") - desc := matcher.Description() - expectedDesc := "less than \"\x00\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - ltTestCase{"", true, false, ""}, - ltTestCase{"\x00", false, false, ""}, - ltTestCase{"a", false, false, ""}, - ltTestCase{"foo", false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} - -func (t *LessThanTest) LongerString() { - matcher := LessThan("foo\x00") - desc := matcher.Description() - expectedDesc := "less than \"foo\x00\"" - - ExpectThat(desc, Equals(expectedDesc)) - - cases := []ltTestCase{ - ltTestCase{"", true, false, ""}, - ltTestCase{"\x00", true, false, ""}, - ltTestCase{"bar", true, false, ""}, - ltTestCase{"foo", true, false, ""}, - ltTestCase{"foo\x00", false, false, ""}, - ltTestCase{"fooa", false, false, ""}, - ltTestCase{"qux", false, false, ""}, - } - - t.checkTestCases(matcher, cases) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/matcher.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/matcher.go deleted file mode 100644 index 3e007ab..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/matcher.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package oglematchers provides a set of matchers useful in a testing or -// mocking framework. These matchers are inspired by and mostly compatible with -// Google Test for C++ and Google JS Test. -// -// This package is used by github.com/smartystreets/assertions/internal/ogletest and -// github.com/smartystreets/assertions/internal/oglemock, which may be more directly useful if you're not -// writing your own testing package or defining your own matchers. -package oglematchers - -// A Matcher is some predicate implicitly defining a set of values that it -// matches. For example, GreaterThan(17) matches all numeric values greater -// than 17, and HasSubstr("taco") matches all strings with the substring -// "taco". -type Matcher interface { - // Check whether the supplied value belongs to the the set defined by the - // matcher. Return a non-nil error if and only if it does not. - // - // The error describes why the value doesn't match. The error text is a - // relative clause that is suitable for being placed after the value. For - // example, a predicate that matches strings with a particular substring may, - // when presented with a numerical value, return the following error text: - // - // "which is not a string" - // - // Then the failure message may look like: - // - // Expected: has substring "taco" - // Actual: 17, which is not a string - // - // If the error is self-apparent based on the description of the matcher, the - // error text may be empty (but the error still non-nil). For example: - // - // Expected: 17 - // Actual: 19 - // - // If you are implementing a new matcher, see also the documentation on - // FatalError. - Matches(candidate interface{}) error - - // Description returns a string describing the property that values matching - // this matcher have, as a verb phrase where the subject is the value. For - // example, "is greather than 17" or "has substring "taco"". - Description() string -} - -// FatalError is an implementation of the error interface that may be returned -// from matchers, indicating the error should be propagated. Returning a -// *FatalError indicates that the matcher doesn't process values of the -// supplied type, or otherwise doesn't know how to handle the value. -// -// For example, if GreaterThan(17) returned false for the value "taco" without -// a fatal error, then Not(GreaterThan(17)) would return true. This is -// technically correct, but is surprising and may mask failures where the wrong -// sort of matcher is accidentally used. Instead, GreaterThan(17) can return a -// fatal error, which will be propagated by Not(). -type FatalError struct { - errorText string -} - -// NewFatalError creates a FatalError struct with the supplied error text. -func NewFatalError(s string) *FatalError { - return &FatalError{s} -} - -func (e *FatalError) Error() string { - return e.errorText -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp.go deleted file mode 100644 index b7439a9..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" - "regexp" -) - -// MatchesRegexp returns a matcher that matches strings and byte slices whose -// contents match the supplide regular expression. The semantics are those of -// regexp.Match. In particular, that means the match is not implicitly anchored -// to the ends of the string: MatchesRegexp("bar") will match "foo bar baz". -func MatchesRegexp(pattern string) Matcher { - re, err := regexp.Compile(pattern) - if err != nil { - panic("MatchesRegexp: " + err.Error()) - } - - return &matchesRegexpMatcher{re} -} - -type matchesRegexpMatcher struct { - re *regexp.Regexp -} - -func (m *matchesRegexpMatcher) Description() string { - return fmt.Sprintf("matches regexp \"%s\"", m.re.String()) -} - -func (m *matchesRegexpMatcher) Matches(c interface{}) (err error) { - v := reflect.ValueOf(c) - isString := v.Kind() == reflect.String - isByteSlice := v.Kind() == reflect.Slice && v.Elem().Kind() == reflect.Uint8 - - err = errors.New("") - - switch { - case isString: - if m.re.MatchString(v.String()) { - err = nil - } - - case isByteSlice: - if m.re.Match(v.Bytes()) { - err = nil - } - - default: - err = NewFatalError("which is not a string or []byte") - } - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp_test.go deleted file mode 100644 index bd61dc0..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp_test.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type MatchesRegexpTest struct { -} - -func init() { RegisterTestSuite(&MatchesRegexpTest{}) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *MatchesRegexpTest) Description() { - m := MatchesRegexp("foo.*bar") - ExpectEq("matches regexp \"foo.*bar\"", m.Description()) -} - -func (t *MatchesRegexpTest) InvalidRegexp() { - ExpectThat( - func() { MatchesRegexp("(foo") }, - Panics(HasSubstr("missing closing )"))) -} - -func (t *MatchesRegexpTest) CandidateIsNil() { - m := MatchesRegexp("") - err := m.Matches(nil) - - ExpectThat(err, Error(Equals("which is not a string or []byte"))) - ExpectTrue(isFatal(err)) -} - -func (t *MatchesRegexpTest) CandidateIsInteger() { - m := MatchesRegexp("") - err := m.Matches(17) - - ExpectThat(err, Error(Equals("which is not a string or []byte"))) - ExpectTrue(isFatal(err)) -} - -func (t *MatchesRegexpTest) NonMatchingCandidates() { - m := MatchesRegexp("fo[op]\\s+x") - var err error - - err = m.Matches("fon x") - ExpectThat(err, Error(Equals(""))) - ExpectFalse(isFatal(err)) - - err = m.Matches("fopx") - ExpectThat(err, Error(Equals(""))) - ExpectFalse(isFatal(err)) - - err = m.Matches("fop ") - ExpectThat(err, Error(Equals(""))) - ExpectFalse(isFatal(err)) -} - -func (t *MatchesRegexpTest) MatchingCandidates() { - m := MatchesRegexp("fo[op]\\s+x") - var err error - - err = m.Matches("foo x") - ExpectEq(nil, err) - - err = m.Matches("fop x") - ExpectEq(nil, err) - - err = m.Matches("blah blah foo x blah blah") - ExpectEq(nil, err) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/not.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/not.go deleted file mode 100644 index 623789f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/not.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" -) - -// Not returns a matcher that inverts the set of values matched by the wrapped -// matcher. It does not transform the result for values for which the wrapped -// matcher returns a fatal error. -func Not(m Matcher) Matcher { - return ¬Matcher{m} -} - -type notMatcher struct { - wrapped Matcher -} - -func (m *notMatcher) Matches(c interface{}) (err error) { - err = m.wrapped.Matches(c) - - // Did the wrapped matcher say yes? - if err == nil { - return errors.New("") - } - - // Did the wrapped matcher return a fatal error? - if _, isFatal := err.(*FatalError); isFatal { - return err - } - - // The wrapped matcher returned a non-fatal error. - return nil -} - -func (m *notMatcher) Description() string { - return fmt.Sprintf("not(%s)", m.wrapped.Description()) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/not_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/not_test.go deleted file mode 100644 index 0b8d80d..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/not_test.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "errors" - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type fakeMatcher struct { - matchFunc func(interface{}) error - description string -} - -func (m *fakeMatcher) Matches(c interface{}) error { - return m.matchFunc(c) -} - -func (m *fakeMatcher) Description() string { - return m.description -} - -type NotTest struct { -} - -func init() { RegisterTestSuite(&NotTest{}) } -func TestOgletest(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *NotTest) CallsWrapped() { - var suppliedCandidate interface{} - matchFunc := func(c interface{}) error { - suppliedCandidate = c - return nil - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Not(wrapped) - - matcher.Matches(17) - ExpectThat(suppliedCandidate, Equals(17)) -} - -func (t *NotTest) WrappedReturnsTrue() { - matchFunc := func(c interface{}) error { - return nil - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Not(wrapped) - - err := matcher.Matches(0) - ExpectThat(err, Error(Equals(""))) -} - -func (t *NotTest) WrappedReturnsNonFatalError() { - matchFunc := func(c interface{}) error { - return errors.New("taco") - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Not(wrapped) - - err := matcher.Matches(0) - ExpectEq(nil, err) -} - -func (t *NotTest) WrappedReturnsFatalError() { - matchFunc := func(c interface{}) error { - return NewFatalError("taco") - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Not(wrapped) - - err := matcher.Matches(0) - ExpectThat(err, Error(Equals("taco"))) -} - -func (t *NotTest) Description() { - wrapped := &fakeMatcher{nil, "taco"} - matcher := Not(wrapped) - - ExpectEq("not(taco)", matcher.Description()) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/oglematchers.goconvey b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/oglematchers.goconvey deleted file mode 100644 index 7998285..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/oglematchers.goconvey +++ /dev/null @@ -1,2 +0,0 @@ -#ignore --timeout=1s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/panics.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/panics.go deleted file mode 100644 index d2cfc97..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/panics.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" -) - -// Panics matches zero-arg functions which, when invoked, panic with an error -// that matches the supplied matcher. -// -// NOTE(jacobsa): This matcher cannot detect the case where the function panics -// using panic(nil), by design of the language. See here for more info: -// -// http://goo.gl/9aIQL -// -func Panics(m Matcher) Matcher { - return &panicsMatcher{m} -} - -type panicsMatcher struct { - wrappedMatcher Matcher -} - -func (m *panicsMatcher) Description() string { - return "panics with: " + m.wrappedMatcher.Description() -} - -func (m *panicsMatcher) Matches(c interface{}) (err error) { - // Make sure c is a zero-arg function. - v := reflect.ValueOf(c) - if v.Kind() != reflect.Func || v.Type().NumIn() != 0 { - err = NewFatalError("which is not a zero-arg function") - return - } - - // Call the function and check its panic error. - defer func() { - if e := recover(); e != nil { - err = m.wrappedMatcher.Matches(e) - - // Set a clearer error message if the matcher said no. - if err != nil { - wrappedClause := "" - if err.Error() != "" { - wrappedClause = ", " + err.Error() - } - - err = errors.New(fmt.Sprintf("which panicked with: %v%s", e, wrappedClause)) - } - } - }() - - v.Call([]reflect.Value{}) - - // If we get here, the function didn't panic. - err = errors.New("which didn't panic") - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/panics_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/panics_test.go deleted file mode 100644 index 26f463d..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/panics_test.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "errors" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type PanicsTest struct { - matcherCalled bool - suppliedCandidate interface{} - wrappedError error - - matcher Matcher -} - -func init() { RegisterTestSuite(&PanicsTest{}) } - -func (t *PanicsTest) SetUp(i *TestInfo) { - wrapped := &fakeMatcher{ - func(c interface{}) error { - t.matcherCalled = true - t.suppliedCandidate = c - return t.wrappedError - }, - "foo", - } - - t.matcher = Panics(wrapped) -} - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *PanicsTest) Description() { - ExpectThat(t.matcher.Description(), Equals("panics with: foo")) -} - -func (t *PanicsTest) CandidateIsNil() { - err := t.matcher.Matches(nil) - - ExpectThat(err, Error(Equals("which is not a zero-arg function"))) - ExpectTrue(isFatal(err)) -} - -func (t *PanicsTest) CandidateIsString() { - err := t.matcher.Matches("taco") - - ExpectThat(err, Error(Equals("which is not a zero-arg function"))) - ExpectTrue(isFatal(err)) -} - -func (t *PanicsTest) CandidateTakesArgs() { - err := t.matcher.Matches(func(i int) string { return "" }) - - ExpectThat(err, Error(Equals("which is not a zero-arg function"))) - ExpectTrue(isFatal(err)) -} - -func (t *PanicsTest) CallsFunction() { - callCount := 0 - t.matcher.Matches(func() string { - callCount++ - return "" - }) - - ExpectThat(callCount, Equals(1)) -} - -func (t *PanicsTest) FunctionDoesntPanic() { - err := t.matcher.Matches(func() {}) - - ExpectThat(err, Error(Equals("which didn't panic"))) - ExpectFalse(isFatal(err)) -} - -func (t *PanicsTest) CallsWrappedMatcher() { - expectedErr := 17 - t.wrappedError = errors.New("") - t.matcher.Matches(func() { panic(expectedErr) }) - - ExpectThat(t.suppliedCandidate, Equals(expectedErr)) -} - -func (t *PanicsTest) WrappedReturnsTrue() { - err := t.matcher.Matches(func() { panic("") }) - - ExpectEq(nil, err) -} - -func (t *PanicsTest) WrappedReturnsFatalErrorWithoutText() { - t.wrappedError = NewFatalError("") - err := t.matcher.Matches(func() { panic(17) }) - - ExpectThat(err, Error(Equals("which panicked with: 17"))) - ExpectFalse(isFatal(err)) -} - -func (t *PanicsTest) WrappedReturnsFatalErrorWithText() { - t.wrappedError = NewFatalError("which blah") - err := t.matcher.Matches(func() { panic(17) }) - - ExpectThat(err, Error(Equals("which panicked with: 17, which blah"))) - ExpectFalse(isFatal(err)) -} - -func (t *PanicsTest) WrappedReturnsNonFatalErrorWithoutText() { - t.wrappedError = errors.New("") - err := t.matcher.Matches(func() { panic(17) }) - - ExpectThat(err, Error(Equals("which panicked with: 17"))) - ExpectFalse(isFatal(err)) -} - -func (t *PanicsTest) WrappedReturnsNonFatalErrorWithText() { - t.wrappedError = errors.New("which blah") - err := t.matcher.Matches(func() { panic(17) }) - - ExpectThat(err, Error(Equals("which panicked with: 17, which blah"))) - ExpectFalse(isFatal(err)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/pointee.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/pointee.go deleted file mode 100644 index c5383f2..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/pointee.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" -) - -// Return a matcher that matches non-nil pointers whose pointee matches the -// wrapped matcher. -func Pointee(m Matcher) Matcher { - return &pointeeMatcher{m} -} - -type pointeeMatcher struct { - wrapped Matcher -} - -func (m *pointeeMatcher) Matches(c interface{}) (err error) { - // Make sure the candidate is of the appropriate type. - cv := reflect.ValueOf(c) - if !cv.IsValid() || cv.Kind() != reflect.Ptr { - return NewFatalError("which is not a pointer") - } - - // Make sure the candidate is non-nil. - if cv.IsNil() { - return NewFatalError("") - } - - // Defer to the wrapped matcher. Fix up empty errors so that failure messages - // are more helpful than just printing a pointer for "Actual". - pointee := cv.Elem().Interface() - err = m.wrapped.Matches(pointee) - if err != nil && err.Error() == "" { - s := fmt.Sprintf("whose pointee is %v", pointee) - - if _, ok := err.(*FatalError); ok { - err = NewFatalError(s) - } else { - err = errors.New(s) - } - } - - return err -} - -func (m *pointeeMatcher) Description() string { - return fmt.Sprintf("pointee(%s)", m.wrapped.Description()) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/pointee_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/pointee_test.go deleted file mode 100644 index fe61aca..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/pointee_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "errors" - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type PointeeTest struct{} - -func init() { RegisterTestSuite(&PointeeTest{}) } - -func TestPointee(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *PointeeTest) Description() { - wrapped := &fakeMatcher{nil, "taco"} - matcher := Pointee(wrapped) - - ExpectEq("pointee(taco)", matcher.Description()) -} - -func (t *PointeeTest) CandidateIsNotAPointer() { - matcher := Pointee(HasSubstr("")) - err := matcher.Matches([]byte{}) - - ExpectThat(err, Error(Equals("which is not a pointer"))) - ExpectTrue(isFatal(err)) -} - -func (t *PointeeTest) CandidateIsANilLiteral() { - matcher := Pointee(HasSubstr("")) - err := matcher.Matches(nil) - - ExpectThat(err, Error(Equals("which is not a pointer"))) - ExpectTrue(isFatal(err)) -} - -func (t *PointeeTest) CandidateIsANilPointer() { - matcher := Pointee(HasSubstr("")) - err := matcher.Matches((*int)(nil)) - - ExpectThat(err, Error(Equals(""))) - ExpectTrue(isFatal(err)) -} - -func (t *PointeeTest) CallsWrapped() { - var suppliedCandidate interface{} - matchFunc := func(c interface{}) error { - suppliedCandidate = c - return nil - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Pointee(wrapped) - - someSlice := []byte{} - matcher.Matches(&someSlice) - ExpectThat(suppliedCandidate, IdenticalTo(someSlice)) -} - -func (t *PointeeTest) WrappedReturnsOkay() { - matchFunc := func(c interface{}) error { - return nil - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Pointee(wrapped) - - err := matcher.Matches(new(int)) - ExpectEq(nil, err) -} - -func (t *PointeeTest) WrappedReturnsNonFatalNonEmptyError() { - matchFunc := func(c interface{}) error { - return errors.New("taco") - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Pointee(wrapped) - - i := 17 - err := matcher.Matches(&i) - ExpectFalse(isFatal(err)) - ExpectThat(err, Error(Equals("taco"))) -} - -func (t *PointeeTest) WrappedReturnsNonFatalEmptyError() { - matchFunc := func(c interface{}) error { - return errors.New("") - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Pointee(wrapped) - - i := 17 - err := matcher.Matches(&i) - ExpectFalse(isFatal(err)) - ExpectThat(err, Error(HasSubstr("whose pointee"))) - ExpectThat(err, Error(HasSubstr("17"))) -} - -func (t *PointeeTest) WrappedReturnsFatalNonEmptyError() { - matchFunc := func(c interface{}) error { - return NewFatalError("taco") - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Pointee(wrapped) - - i := 17 - err := matcher.Matches(&i) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(Equals("taco"))) -} - -func (t *PointeeTest) WrappedReturnsFatalEmptyError() { - matchFunc := func(c interface{}) error { - return NewFatalError("") - } - - wrapped := &fakeMatcher{matchFunc, ""} - matcher := Pointee(wrapped) - - i := 17 - err := matcher.Matches(&i) - ExpectTrue(isFatal(err)) - ExpectThat(err, Error(HasSubstr("whose pointee"))) - ExpectThat(err, Error(HasSubstr("17"))) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go deleted file mode 100644 index f79d0c0..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -// transformDescription returns a matcher that is equivalent to the supplied -// one, except that it has the supplied description instead of the one attached -// to the existing matcher. -func transformDescription(m Matcher, newDesc string) Matcher { - return &transformDescriptionMatcher{newDesc, m} -} - -type transformDescriptionMatcher struct { - desc string - wrappedMatcher Matcher -} - -func (m *transformDescriptionMatcher) Description() string { - return m.desc -} - -func (m *transformDescriptionMatcher) Matches(c interface{}) error { - return m.wrappedMatcher.Matches(c) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/.gitignore b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/.gitignore deleted file mode 100644 index dd8fc74..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.6 -6.out -_obj/ -_test/ -_testmain.go diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/LICENSE b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/LICENSE deleted file mode 100644 index d645695..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/README.markdown b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/README.markdown deleted file mode 100644 index 4744f8a..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/README.markdown +++ /dev/null @@ -1,101 +0,0 @@ -`oglemock` is a mocking framework for the Go programming language with the -following features: - - * An extensive and extensible set of matchers for expressing call - expectations (provided by the [oglematchers][] package). - - * Clean, readable output that tells you exactly what you need to know. - - * Style and semantics similar to [Google Mock][googlemock] and - [Google JS Test][google-js-test]. - - * Seamless integration with the [ogletest][] unit testing framework. - -It can be integrated into any testing framework (including Go's `testing` -package), but out of the box support is built in to [ogletest][] and that is the -easiest place to use it. - - -Installation ------------- - -First, make sure you have installed Go 1.0.2 or newer. See -[here][golang-install] for instructions. - -Use the following command to install `oglemock` and its dependencies, and to -keep them up to date: - - go get -u github.com/smartystreets/assertions/internal/oglemock - go get -u github.com/smartystreets/assertions/internal/oglemock/createmock - -Those commands will install the `oglemock` package itself, along with the -`createmock` tool that is used to auto-generate mock types. - - -Generating and using mock types -------------------------------- - -Automatically generating a mock implementation of an interface is easy. If you -want to mock interfaces `Bar` and `Baz` from package `foo`, simply run the -following: - - createmock foo Bar Baz - -That will print source code that can be saved to a file and used in your tests. -For example, to create a `mock_io` package containing mock implementations of -`io.Reader` and `io.Writer`: - - mkdir mock_io - createmock io Reader Writer > mock_io/mock_io.go - -The new package will be named `mock_io`, and contain types called `MockReader` -and `MockWriter`, which implement `io.Reader` and `io.Writer` respectively. - -For each generated mock type, there is a corresponding function for creating an -instance of that type given a `Controller` object (see below). For example, to -create a mock reader: - -```go -someController := [...] // See next section. -someReader := mock_io.NewMockReader(someController, "Mock file reader") -``` - -The snippet above creates a mock `io.Reader` that reports failures to -`someController`. The reader can subsequently have expectations set up and be -passed to your code under test that uses an `io.Reader`. - - -Getting ahold of a controller ------------------------------ - -[oglemock.Controller][controller-ref] is used to create mock objects, and to set -up and verify expectations for them. You can create one by calling -`NewController` with an `ErrorReporter`, which is the basic type used to -interface between `oglemock` and the testing framework within which it is being -used. - -If you are using [ogletest][] you don't need to worry about any of this, since -the `TestInfo` struct provided to your test's `SetUp` function already contains -a working `Controller` that you can use to create mock object, and you can use -the built-in `ExpectCall` function for setting expectations. (See the -[ogletest documentation][ogletest-docs] for more info.) Otherwise, you will need -to implement the simple [ErrorReporter interface][reporter-ref] for your test -environment. - - -Documentation -------------- - -For thorough documentation, including information on how to set up expectations, -see [here][oglemock-docs]. - - -[controller-ref]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/assertions/internal/oglemock#Controller -[reporter-ref]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/assertions/internal/oglemock#ErrorReporter -[golang-install]: http://golang.org/doc/install.html -[google-js-test]: http://code.google.com/p/google-js-test/ -[googlemock]: http://code.google.com/p/googlemock/ -[oglematchers]: https://github.com/smartystreets/assertions/internal/oglematchers -[oglemock-docs]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/assertions/internal/oglemock -[ogletest]: https://github.com/smartystreets/assertions/internal/oglematchers -[ogletest-docs]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/assertions/internal/ogletest diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/action.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/action.go deleted file mode 100644 index 9fd40d8..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/action.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "reflect" -) - -// Action represents an action to be taken in response to a call to a mock -// method. -type Action interface { - // Set the signature of the function with which this action is being used. - // This must be called before Invoke is called. - SetSignature(signature reflect.Type) error - - // Invoke runs the specified action, given the arguments to the mock method. - // It returns zero or more values that may be treated as the return values of - // the method. If the action doesn't return any values, it may return the nil - // slice. - // - // You must call SetSignature before calling Invoke. - Invoke(methodArgs []interface{}) []interface{} -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/controller.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/controller.go deleted file mode 100644 index 93a1d62..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/controller.go +++ /dev/null @@ -1,480 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "errors" - "fmt" - "log" - "math" - "reflect" - "sync" -) - -// PartialExpecation is a function that should be called exactly once with -// expected arguments or matchers in order to set up an expected method call. -// See Controller.ExpectMethodCall below. It returns an expectation that can be -// further modified (e.g. by calling WillOnce). -// -// If the arguments are of the wrong type, the function reports a fatal error -// and returns nil. -type PartialExpecation func(...interface{}) Expectation - -// Controller represents an object that implements the central logic of -// oglemock: recording and verifying expectations, responding to mock method -// calls, and so on. -type Controller interface { - // ExpectCall expresses an expectation that the method of the given name - // should be called on the supplied mock object. It returns a function that - // should be called with the expected arguments, matchers for the arguments, - // or a mix of both. - // - // fileName and lineNumber should indicate the line on which the expectation - // was made, if known. - // - // For example: - // - // mockWriter := [...] - // controller.ExpectCall(mockWriter, "Write", "foo.go", 17)(ElementsAre(0x1)) - // .WillOnce(Return(1, nil)) - // - // If the mock object doesn't have a method of the supplied name, the - // function reports a fatal error and returns nil. - ExpectCall( - o MockObject, - methodName string, - fileName string, - lineNumber int) PartialExpecation - - // Finish causes the controller to check for any unsatisfied expectations, - // and report them as errors if they exist. - // - // The controller may panic if any of its methods (including this one) are - // called after Finish is called. - Finish() - - // HandleMethodCall looks for a registered expectation matching the call of - // the given method on mock object o, invokes the appropriate action (if - // any), and returns the values returned by that action (if any). - // - // If the action returns nothing, the controller returns zero values. If - // there is no matching expectation, the controller reports an error and - // returns zero values. - // - // If the mock object doesn't have a method of the supplied name, the - // arguments are of the wrong type, or the action returns the wrong types, - // the function reports a fatal error. - // - // HandleMethodCall is exported for the sake of mock implementations, and - // should not be used directly. - HandleMethodCall( - o MockObject, - methodName string, - fileName string, - lineNumber int, - args []interface{}) []interface{} -} - -// methodMap represents a map from method name to set of expectations for that -// method. -type methodMap map[string][]*InternalExpectation - -// objectMap represents a map from mock object ID to a methodMap for that object. -type objectMap map[uintptr]methodMap - -// NewController sets up a fresh controller, without any expectations set, and -// configures the controller to use the supplied error reporter. -func NewController(reporter ErrorReporter) Controller { - return &controllerImpl{reporter, sync.RWMutex{}, objectMap{}} -} - -type controllerImpl struct { - reporter ErrorReporter - - mutex sync.RWMutex - expectationsByObject objectMap // Protected by mutex -} - -// Return the list of registered expectations for the named method of the -// supplied object, or an empty slice if none have been registered. When this -// method returns, it is guaranteed that c.expectationsByObject has an entry -// for the object. -// -// c.mutex must be held for reading. -func (c *controllerImpl) getExpectationsLocked( - o MockObject, - methodName string) []*InternalExpectation { - id := o.Oglemock_Id() - - // Look up the mock object. - expectationsByMethod, ok := c.expectationsByObject[id] - if !ok { - expectationsByMethod = methodMap{} - c.expectationsByObject[id] = expectationsByMethod - } - - result, ok := expectationsByMethod[methodName] - if !ok { - return []*InternalExpectation{} - } - - return result -} - -// Add an expectation to the list registered for the named method of the -// supplied mock object. -// -// c.mutex must be held for writing. -func (c *controllerImpl) addExpectationLocked( - o MockObject, - methodName string, - exp *InternalExpectation) { - // Get the existing list. - existing := c.getExpectationsLocked(o, methodName) - - // Store a modified list. - id := o.Oglemock_Id() - c.expectationsByObject[id][methodName] = append(existing, exp) -} - -func (c *controllerImpl) ExpectCall( - o MockObject, - methodName string, - fileName string, - lineNumber int) PartialExpecation { - // Find the signature for the requested method. - ov := reflect.ValueOf(o) - method := ov.MethodByName(methodName) - if method.Kind() == reflect.Invalid { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New("Unknown method: "+methodName)) - return nil - } - - partialAlreadyCalled := false // Protected by c.mutex - return func(args ...interface{}) Expectation { - c.mutex.Lock() - defer c.mutex.Unlock() - - // This function should only be called once. - if partialAlreadyCalled { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New("Partial expectation called more than once.")) - return nil - } - - partialAlreadyCalled = true - - // Make sure that the number of args is legal. Keep in mind that the - // method's type has an extra receiver arg. - if len(args) != method.Type().NumIn() { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New( - fmt.Sprintf( - "Expectation for %s given wrong number of arguments: "+ - "expected %d, got %d.", - methodName, - method.Type().NumIn(), - len(args)))) - return nil - } - - // Create an expectation and insert it into the controller's map. - exp := InternalNewExpectation( - c.reporter, - method.Type(), - args, - fileName, - lineNumber) - - c.addExpectationLocked(o, methodName, exp) - - // Return the expectation to the user. - return exp - } -} - -func (c *controllerImpl) Finish() { - c.mutex.Lock() - defer c.mutex.Unlock() - - // Check whether the minimum cardinality for each registered expectation has - // been satisfied. - for _, expectationsByMethod := range c.expectationsByObject { - for methodName, expectations := range expectationsByMethod { - for _, exp := range expectations { - exp.mutex.Lock() - defer exp.mutex.Unlock() - - minCardinality, _ := computeCardinalityLocked(exp) - if exp.NumMatches < minCardinality { - c.reporter.ReportError( - exp.FileName, - exp.LineNumber, - errors.New( - fmt.Sprintf( - "Unsatisfied expectation; expected %s to be called "+ - "at least %d times; called %d times.", - methodName, - minCardinality, - exp.NumMatches))) - } - } - } - } -} - -// expectationMatches checks the matchers for the expectation against the -// supplied arguments. -func expectationMatches(exp *InternalExpectation, args []interface{}) bool { - matchers := exp.ArgMatchers - if len(args) != len(matchers) { - panic("expectationMatches: len(args)") - } - - // Check each matcher. - for i, matcher := range matchers { - if err := matcher.Matches(args[i]); err != nil { - return false - } - } - - return true -} - -// Return the expectation that matches the supplied arguments. If there is more -// than one such expectation, the one furthest along in the list for the method -// is returned. If there is no such expectation, nil is returned. -// -// c.mutex must be held for reading. -func (c *controllerImpl) chooseExpectationLocked( - o MockObject, - methodName string, - args []interface{}) *InternalExpectation { - // Do we have any expectations for this method? - expectations := c.getExpectationsLocked(o, methodName) - if len(expectations) == 0 { - return nil - } - - for i := len(expectations) - 1; i >= 0; i-- { - if expectationMatches(expectations[i], args) { - return expectations[i] - } - } - - return nil -} - -// makeZeroReturnValues creates a []interface{} containing appropriate zero -// values for returning from the supplied method type. -func makeZeroReturnValues(signature reflect.Type) []interface{} { - result := make([]interface{}, signature.NumOut()) - - for i, _ := range result { - outType := signature.Out(i) - zeroVal := reflect.Zero(outType) - result[i] = zeroVal.Interface() - } - - return result -} - -// computeCardinality decides on the [min, max] range of the number of expected -// matches for the supplied expectations, according to the rules documented in -// expectation.go. -// -// exp.mutex must be held for reading. -func computeCardinalityLocked(exp *InternalExpectation) (min, max uint) { - // Explicit cardinality. - if exp.ExpectedNumMatches >= 0 { - min = uint(exp.ExpectedNumMatches) - max = min - return - } - - // Implicit count based on one-time actions. - if len(exp.OneTimeActions) != 0 { - min = uint(len(exp.OneTimeActions)) - max = min - - // If there is a fallback action, this is only a lower bound. - if exp.FallbackAction != nil { - max = math.MaxUint32 - } - - return - } - - // Implicit lack of restriction based on a fallback action being configured. - if exp.FallbackAction != nil { - min = 0 - max = math.MaxUint32 - return - } - - // Implicit cardinality of one. - min = 1 - max = 1 - return -} - -// chooseAction returns the action that should be invoked for the i'th match to -// the supplied expectation (counting from zero). If the implicit "return zero -// values" action should be used, it returns nil. -// -// exp.mutex must be held for reading. -func chooseActionLocked(i uint, exp *InternalExpectation) Action { - // Exhaust one-time actions first. - if i < uint(len(exp.OneTimeActions)) { - return exp.OneTimeActions[i] - } - - // Fallback action (or nil if none is configured). - return exp.FallbackAction -} - -// Find an action for the method call, updating expectation match state in the -// process. Return either an action that should be invoked or a set of zero -// values to return immediately. -// -// This is split out from HandleMethodCall in order to more easily avoid -// invoking the action with locks held. -func (c *controllerImpl) chooseActionAndUpdateExpectations( - o MockObject, - methodName string, - fileName string, - lineNumber int, - args []interface{}, -) (action Action, zeroVals []interface{}) { - c.mutex.Lock() - defer c.mutex.Unlock() - - // Find the signature for the requested method. - ov := reflect.ValueOf(o) - method := ov.MethodByName(methodName) - if method.Kind() == reflect.Invalid { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New("Unknown method: "+methodName), - ) - - // Should never get here in real code. - log.Println("ReportFatalError unexpectedly returned.") - return - } - - // HACK(jacobsa): Make sure we got the correct number of arguments. This will - // need to be refined when issue #5 (variadic methods) is handled. - if len(args) != method.Type().NumIn() { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New( - fmt.Sprintf( - "Wrong number of arguments: expected %d; got %d", - method.Type().NumIn(), - len(args), - ), - ), - ) - - // Should never get here in real code. - log.Println("ReportFatalError unexpectedly returned.") - return - } - - // Find an expectation matching this call. - expectation := c.chooseExpectationLocked(o, methodName, args) - if expectation == nil { - c.reporter.ReportError( - fileName, - lineNumber, - errors.New( - fmt.Sprintf("Unexpected call to %s with args: %v", methodName, args), - ), - ) - - zeroVals = makeZeroReturnValues(method.Type()) - return - } - - expectation.mutex.Lock() - defer expectation.mutex.Unlock() - - // Increase the number of matches recorded, and check whether we're over the - // number expected. - expectation.NumMatches++ - _, maxCardinality := computeCardinalityLocked(expectation) - if expectation.NumMatches > maxCardinality { - c.reporter.ReportError( - expectation.FileName, - expectation.LineNumber, - errors.New( - fmt.Sprintf( - "Unexpected call to %s: "+ - "expected to be called at most %d times; called %d times.", - methodName, - maxCardinality, - expectation.NumMatches, - ), - ), - ) - - zeroVals = makeZeroReturnValues(method.Type()) - return - } - - // Choose an action to invoke. If there is none, just return zero values. - action = chooseActionLocked(expectation.NumMatches-1, expectation) - if action == nil { - zeroVals = makeZeroReturnValues(method.Type()) - return - } - - // Let the action take over. - return -} - -func (c *controllerImpl) HandleMethodCall( - o MockObject, - methodName string, - fileName string, - lineNumber int, - args []interface{}, -) []interface{} { - // Figure out whether to invoke an action or return zero values. - action, zeroVals := c.chooseActionAndUpdateExpectations( - o, - methodName, - fileName, - lineNumber, - args, - ) - - if action != nil { - return action.Invoke(args) - } - - return zeroVals -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/createmock.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/createmock.go deleted file mode 100644 index 4c233b6..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/createmock.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// createmock is used to generate source code for mock versions of interfaces -// from installed packages. -package main - -import ( - "errors" - "flag" - "fmt" - "go/build" - "io/ioutil" - "log" - "os" - "os/exec" - "path" - "regexp" - "text/template" - - // Ensure that the generate package, which is used by the generated code, is - // installed by goinstall. - _ "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate" -) - -// A template for generated code that is used to print the result. -const tmplStr = ` -{{$inputPkg := .InputPkg}} -{{$outputPkg := .OutputPkg}} - -package main - -import ( - {{range $identifier, $import := .Imports}} - {{$identifier}} "{{$import}}" - {{end}} -) - -func getTypeForPtr(ptr interface{}) reflect.Type { - return reflect.TypeOf(ptr).Elem() -} - -func main() { - // Reduce noise in logging output. - log.SetFlags(0) - - interfaces := []reflect.Type{ - {{range $typeName := .TypeNames}} - getTypeForPtr((*{{base $inputPkg}}.{{$typeName}})(nil)), - {{end}} - } - - err := generate.GenerateMockSource(os.Stdout, "{{$outputPkg}}", interfaces) - if err != nil { - log.Fatalf("Error generating mock source: %v", err) - } -} -` - -// A map from import identifier to package to use that identifier for, -// containing elements for each import needed by the generated code. -type importMap map[string]string - -type tmplArg struct { - InputPkg string - OutputPkg string - - // Imports needed by the generated code. - Imports importMap - - // Types to be mocked, relative to their package's name. - TypeNames []string -} - -var unknownPackageRegexp = regexp.MustCompile( - `tool\.go:\d+:\d+: cannot find package "([^"]+)"`) - -var undefinedInterfaceRegexp = regexp.MustCompile(`tool\.go:\d+: undefined: [\pL_0-9]+\.([\pL_0-9]+)`) - -// Does the 'go build' output indicate that a package wasn't found? If so, -// return the name of the package. -func findUnknownPackage(output []byte) *string { - if match := unknownPackageRegexp.FindSubmatch(output); match != nil { - res := string(match[1]) - return &res - } - - return nil -} - -// Does the 'go build' output indicate that an interface wasn't found? If so, -// return the name of the interface. -func findUndefinedInterface(output []byte) *string { - if match := undefinedInterfaceRegexp.FindSubmatch(output); match != nil { - res := string(match[1]) - return &res - } - - return nil -} - -// Split out from main so that deferred calls are executed even in the event of -// an error. -func run() error { - // Reduce noise in logging output. - log.SetFlags(0) - - // Check the command-line arguments. - flag.Parse() - - cmdLineArgs := flag.Args() - if len(cmdLineArgs) < 2 { - return errors.New("Usage: createmock [package] [interface ...]") - } - - // Create a temporary directory inside of $GOPATH to hold generated code. - buildPkg, err := build.Import("github.com/smartystreets/assertions/internal/oglemock", "", build.FindOnly) - if err != nil { - return errors.New(fmt.Sprintf("Couldn't find oglemock in $GOPATH: %v", err)) - } - - tmpDir, err := ioutil.TempDir(buildPkg.SrcRoot, "tmp-createmock-") - if err != nil { - return errors.New(fmt.Sprintf("Creating temp dir: %v", err)) - } - - defer os.RemoveAll(tmpDir) - - // Create a file to hold generated code. - codeFile, err := os.Create(path.Join(tmpDir, "tool.go")) - if err != nil { - return errors.New(fmt.Sprintf("Couldn't create a file to hold code: %v", err)) - } - - // Create an appropriate path for the built binary. - binaryPath := path.Join(tmpDir, "tool") - - // Create an appropriate template argument. - var arg tmplArg - arg.InputPkg = cmdLineArgs[0] - arg.OutputPkg = "mock_" + path.Base(arg.InputPkg) - arg.TypeNames = cmdLineArgs[1:] - - arg.Imports = make(importMap) - arg.Imports[path.Base(arg.InputPkg)] = arg.InputPkg - arg.Imports["generate"] = "github.com/smartystreets/assertions/internal/oglemock/generate" - arg.Imports["log"] = "log" - arg.Imports["os"] = "os" - arg.Imports["reflect"] = "reflect" - - // Execute the template to generate code that will itself generate the mock - // code. Write the code to the temp file. - tmpl := template.Must( - template.New("code").Funcs( - template.FuncMap{ - "base": path.Base, - }).Parse(tmplStr)) - if err := tmpl.Execute(codeFile, arg); err != nil { - return errors.New(fmt.Sprintf("Error executing template: %v", err)) - } - - codeFile.Close() - - // Attempt to build the code. - cmd := exec.Command("go", "build", "-o", binaryPath) - cmd.Dir = tmpDir - buildOutput, err := cmd.CombinedOutput() - - if err != nil { - // Did the compilation fail due to the user-specified package not being found? - if pkg := findUnknownPackage(buildOutput); pkg != nil && *pkg == arg.InputPkg { - return errors.New(fmt.Sprintf("Unknown package: %s", *pkg)) - } - - // Did the compilation fail due to an unknown interface? - if in := findUndefinedInterface(buildOutput); in != nil { - return errors.New(fmt.Sprintf("Unknown interface: %s", *in)) - } - - // Otherwise return a generic error. - return errors.New(fmt.Sprintf( - "%s\n\nError building generated code:\n\n"+ - " %v\n\nPlease report this oglemock bug.", - buildOutput, - err)) - } - - // Run the binary. - cmd = exec.Command(binaryPath) - binaryOutput, err := cmd.CombinedOutput() - - if err != nil { - return errors.New(fmt.Sprintf( - "%s\n\nError running generated code:\n\n"+ - " %v\n\n Please report this oglemock bug.", - binaryOutput, - err)) - } - - // Copy its output. - _, err = os.Stdout.Write(binaryOutput) - if err != nil { - return errors.New(fmt.Sprintf("Error copying binary output: %v", err)) - } - - return nil -} - -func main() { - if err := run(); err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_interfaces b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_interfaces deleted file mode 100644 index b70535f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_interfaces +++ /dev/null @@ -1 +0,0 @@ -Usage: createmock [package] [interface ...] diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_package b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_package deleted file mode 100644 index b70535f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_package +++ /dev/null @@ -1 +0,0 @@ -Usage: createmock [package] [interface ...] diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_interface b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_interface deleted file mode 100644 index c32950a..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_interface +++ /dev/null @@ -1 +0,0 @@ -Unknown interface: Frobnicator diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_package b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_package deleted file mode 100644 index d07e915..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_package +++ /dev/null @@ -1 +0,0 @@ -Unknown package: foo/bar diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/error_reporter.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/error_reporter.go deleted file mode 100644 index 0c3a65e..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/error_reporter.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -// ErrorReporter is an interface that wraps methods for reporting errors that -// should cause test failures. -type ErrorReporter interface { - // Report that some failure (e.g. an unsatisfied expectation) occurred. If - // known, fileName and lineNumber should contain information about where it - // occurred. The test may continue if the test framework supports it. - ReportError(fileName string, lineNumber int, err error) - - // Like ReportError, but the test should be halted immediately. It is assumed - // that this method does not return. - ReportFatalError(fileName string, lineNumber int, err error) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/expectation.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/expectation.go deleted file mode 100644 index d18bfb8..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/expectation.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -// Expectation is an expectation for zero or more calls to a mock method with -// particular arguments or sets of arguments. -type Expectation interface { - // Times expresses that a matching method call should happen exactly N times. - // Times must not be called more than once, and must not be called after - // WillOnce or WillRepeatedly. - // - // The full rules for the cardinality of an expectation are as follows: - // - // 1. If an explicit cardinality is set with Times(N), then anything other - // than exactly N matching calls will cause a test failure. - // - // 2. Otherwise, if there are any one-time actions set up, then it is - // expected there will be at least that many matching calls. If there is - // not also a fallback action, then it is expected that there will be - // exactly that many. - // - // 3. Otherwise, if there is a fallback action configured, any number of - // matching calls (including zero) is allowed. - // - // 4. Otherwise, the implicit cardinality is one. - // - Times(n uint) Expectation - - // WillOnce configures a "one-time action". WillOnce can be called zero or - // more times, but must be called after any call to Times and before any call - // to WillRepeatedly. - // - // When matching method calls are made on the mock object, one-time actions - // are invoked one per matching call in the order that they were set up until - // they are exhausted. Afterward the fallback action, if any, will be used. - WillOnce(a Action) Expectation - - // WillRepeatedly configures a "fallback action". WillRepeatedly can be - // called zero or one times, and must not be called before Times or WillOnce. - // - // Once all one-time actions are exhausted (see above), the fallback action - // will be invoked for any further method calls. If WillRepeatedly is not - // called, the fallback action is implicitly an action that returns zero - // values for the method's return values. - WillRepeatedly(a Action) Expectation -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/generate.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/generate.go deleted file mode 100644 index 387367e..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/generate.go +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package generate implements code generation for mock classes. This is an -// implementation detail of the createmock command, which you probably want to -// use directly instead. -package generate - -import ( - "bytes" - "errors" - "go/ast" - "go/parser" - "go/printer" - "go/token" - "io" - "reflect" - "regexp" - "text/template" -) - -const tmplStr = ` -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package {{.Pkg}} - -import ( - {{range $identifier, $import := .Imports}}{{$identifier}} "{{$import}}" - {{end}} -) - -{{range .Interfaces}} - {{$interfaceName := printf "Mock%s" .Name}} - {{$structName := printf "mock%s" .Name}} - - type {{$interfaceName}} interface { - {{getTypeString .}} - oglemock.MockObject - } - - type {{$structName}} struct { - controller oglemock.Controller - description string - } - - func New{{printf "Mock%s" .Name}}( - c oglemock.Controller, - desc string) {{$interfaceName}} { - return &{{$structName}}{ - controller: c, - description: desc, - } - } - - func (m *{{$structName}}) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) - } - - func (m *{{$structName}}) Oglemock_Description() string { - return m.description - } - - {{range getMethods .}} - {{$funcType := .Type}} - {{$inputTypes := getInputs $funcType}} - {{$outputTypes := getOutputs $funcType}} - - func (m *{{$structName}}) {{.Name}}({{range $i, $type := $inputTypes}}p{{$i}} {{getInputTypeString $i $funcType}}, {{end}}) ({{range $i, $type := $outputTypes}}o{{$i}} {{getTypeString $type}}, {{end}}) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "{{.Name}}", - file, - line, - []interface{}{ {{range $i, $type := $inputTypes}}p{{$i}}, {{end}} }) - - if len(retVals) != {{len $outputTypes}} { - panic(fmt.Sprintf("{{$structName}}.{{.Name}}: invalid return values: %v", retVals)) - } - - {{range $i, $type := $outputTypes}} - // o{{$i}} {{getTypeString $type}} - if retVals[{{$i}}] != nil { - o{{$i}} = retVals[{{$i}}].({{getTypeString $type}}) - } - {{end}} - - return - } - {{end}} -{{end}} -` - -type tmplArg struct { - // The package of the generated code. - Pkg string - - // Imports needed by the interfaces. - Imports importMap - - // The set of interfaces to mock. - Interfaces []reflect.Type -} - -var tmpl *template.Template - -func init() { - extraFuncs := make(template.FuncMap) - extraFuncs["getMethods"] = getMethods - extraFuncs["getInputs"] = getInputs - extraFuncs["getOutputs"] = getOutputs - extraFuncs["getInputTypeString"] = getInputTypeString - extraFuncs["getTypeString"] = getTypeString - - tmpl = template.New("code") - tmpl.Funcs(extraFuncs) - tmpl.Parse(tmplStr) -} - -func getInputTypeString(i int, ft reflect.Type) string { - numInputs := ft.NumIn() - if i == numInputs-1 && ft.IsVariadic() { - return "..." + getTypeString(ft.In(i).Elem()) - } - - return getTypeString(ft.In(i)) -} - -func getTypeString(t reflect.Type) string { - return t.String() -} - -func getMethods(it reflect.Type) []reflect.Method { - numMethods := it.NumMethod() - methods := make([]reflect.Method, numMethods) - - for i := 0; i < numMethods; i++ { - methods[i] = it.Method(i) - } - - return methods -} - -func getInputs(ft reflect.Type) []reflect.Type { - numIn := ft.NumIn() - inputs := make([]reflect.Type, numIn) - - for i := 0; i < numIn; i++ { - inputs[i] = ft.In(i) - } - - return inputs -} - -func getOutputs(ft reflect.Type) []reflect.Type { - numOut := ft.NumOut() - outputs := make([]reflect.Type, numOut) - - for i := 0; i < numOut; i++ { - outputs[i] = ft.Out(i) - } - - return outputs -} - -// A map from import identifier to package to use that identifier for, -// containing elements for each import needed by a set of mocked interfaces. -type importMap map[string]string - -var typePackageIdentifierRegexp = regexp.MustCompile(`^([\pL_0-9]+)\.[\pL_0-9]+$`) - -// Add an import for the supplied type, without recursing. -func addImportForType(imports importMap, t reflect.Type) { - // If there is no package path, this is a built-in type and we don't need an - // import. - pkgPath := t.PkgPath() - if pkgPath == "" { - return - } - - // Work around a bug in Go: - // - // http://code.google.com/p/go/issues/detail?id=2660 - // - var errorPtr *error - if t == reflect.TypeOf(errorPtr).Elem() { - return - } - - // Use the identifier that's part of the type's string representation as the - // import identifier. This means that we'll do the right thing for package - // "foo/bar" with declaration "package baz". - match := typePackageIdentifierRegexp.FindStringSubmatch(t.String()) - if match == nil { - return - } - - imports[match[1]] = pkgPath -} - -// Add all necessary imports for the type, recursing as appropriate. -func addImportsForType(imports importMap, t reflect.Type) { - // Add any import needed for the type itself. - addImportForType(imports, t) - - // Handle special cases where recursion is needed. - switch t.Kind() { - case reflect.Array, reflect.Chan, reflect.Ptr, reflect.Slice: - addImportsForType(imports, t.Elem()) - - case reflect.Func: - // Input parameters. - for i := 0; i < t.NumIn(); i++ { - addImportsForType(imports, t.In(i)) - } - - // Return values. - for i := 0; i < t.NumOut(); i++ { - addImportsForType(imports, t.Out(i)) - } - - case reflect.Map: - addImportsForType(imports, t.Key()) - addImportsForType(imports, t.Elem()) - } -} - -// Add imports for each of the methods of the interface, but not the interface -// itself. -func addImportsForInterfaceMethods(imports importMap, it reflect.Type) { - // Handle each method. - for i := 0; i < it.NumMethod(); i++ { - m := it.Method(i) - addImportsForType(imports, m.Type) - } -} - -// Given a set of interfaces, return a map from import identifier to package to -// use that identifier for, containing elements for each import needed by the -// mock versions of those interfaces. -func getImports(interfaces []reflect.Type) importMap { - imports := make(importMap) - for _, it := range interfaces { - addImportForType(imports, it) - addImportsForInterfaceMethods(imports, it) - } - - // Make sure there are imports for other types used by the generated code - // itself. - imports["fmt"] = "fmt" - imports["oglemock"] = "github.com/smartystreets/assertions/internal/oglemock" - imports["runtime"] = "runtime" - imports["unsafe"] = "unsafe" - - return imports -} - -// Given a set of interfaces to mock, write out source code for a package named -// `pkg` that contains mock implementations of those interfaces. -func GenerateMockSource(w io.Writer, pkg string, interfaces []reflect.Type) error { - // Sanity-check arguments. - if pkg == "" { - return errors.New("Package name must be non-empty.") - } - - if len(interfaces) == 0 { - return errors.New("List of interfaces must be non-empty.") - } - - // Make sure each type is indeed an interface. - for _, it := range interfaces { - if it.Kind() != reflect.Interface { - return errors.New("Invalid type: " + it.String()) - } - } - - // Create an appropriate template arg, then execute the template. Write the - // raw output into a buffer. - var arg tmplArg - arg.Pkg = pkg - arg.Imports = getImports(interfaces) - arg.Interfaces = interfaces - - buf := new(bytes.Buffer) - if err := tmpl.Execute(buf, arg); err != nil { - return err - } - - // Parse the output. - fset := token.NewFileSet() - astFile, err := parser.ParseFile(fset, pkg+".go", buf, parser.ParseComments) - if err != nil { - return errors.New("Error parsing generated code: " + err.Error()) - } - - // Sort the import lines in the AST in the same way that gofmt does. - ast.SortImports(fset, astFile) - - // Pretty-print the AST, using the same options that gofmt does by default. - cfg := &printer.Config{ - Mode: printer.UseSpaces | printer.TabIndent, - Tabwidth: 8, - } - - if err = cfg.Fprint(w, fset, astFile); err != nil { - return errors.New("Error pretty printing: " + err.Error()) - } - - return nil -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/complicated_pkg/complicated_pkg.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/complicated_pkg/complicated_pkg.go deleted file mode 100644 index bf1fa6d..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/complicated_pkg/complicated_pkg.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package complicated_pkg contains an interface with lots of interesting -// cases, for use in integration testing. -package complicated_pkg - -import ( - "image" - "io" - "net" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg" -) - -type Byte uint8 - -type ComplicatedThing interface { - Channels(a chan chan<- <-chan net.Conn) chan int - Pointers(a *int, b *net.Conn, c **io.Reader) (*int, error) - Functions(a func(int, image.Image) int) func(string, int) net.Conn - Maps(a map[string]*int) (map[int]*string, error) - Arrays(a [3]string) ([3]int, error) - Slices(a []string) ([]int, error) - NamedScalarType(a Byte) ([]Byte, error) - EmptyInterface(a interface{}) (interface{}, error) - RenamedPackage(a tony.SomeUint8Alias) - Variadic(a int, b ...net.Conn) int -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.complicated_pkg.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.complicated_pkg.go deleted file mode 100644 index a8c4d25..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.complicated_pkg.go +++ /dev/null @@ -1,312 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package some_pkg - -import ( - fmt "fmt" - image "image" - io "io" - net "net" - runtime "runtime" - unsafe "unsafe" - - oglemock "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock" - complicated_pkg "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/complicated_pkg" - tony "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg" -) - -type MockComplicatedThing interface { - complicated_pkg.ComplicatedThing - oglemock.MockObject -} - -type mockComplicatedThing struct { - controller oglemock.Controller - description string -} - -func NewMockComplicatedThing( - c oglemock.Controller, - desc string) MockComplicatedThing { - return &mockComplicatedThing{ - controller: c, - description: desc, - } -} - -func (m *mockComplicatedThing) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockComplicatedThing) Oglemock_Description() string { - return m.description -} - -func (m *mockComplicatedThing) Arrays(p0 [3]string) (o0 [3]int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Arrays", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.Arrays: invalid return values: %v", retVals)) - } - - // o0 [3]int - if retVals[0] != nil { - o0 = retVals[0].([3]int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) Channels(p0 chan chan<- <-chan net.Conn) (o0 chan int) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Channels", - file, - line, - []interface{}{p0}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockComplicatedThing.Channels: invalid return values: %v", retVals)) - } - - // o0 chan int - if retVals[0] != nil { - o0 = retVals[0].(chan int) - } - - return -} - -func (m *mockComplicatedThing) EmptyInterface(p0 interface{}) (o0 interface{}, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "EmptyInterface", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.EmptyInterface: invalid return values: %v", retVals)) - } - - // o0 interface {} - if retVals[0] != nil { - o0 = retVals[0].(interface{}) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) Functions(p0 func(int, image.Image) int) (o0 func(string, int) net.Conn) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Functions", - file, - line, - []interface{}{p0}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockComplicatedThing.Functions: invalid return values: %v", retVals)) - } - - // o0 func(string, int) net.Conn - if retVals[0] != nil { - o0 = retVals[0].(func(string, int) net.Conn) - } - - return -} - -func (m *mockComplicatedThing) Maps(p0 map[string]*int) (o0 map[int]*string, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Maps", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.Maps: invalid return values: %v", retVals)) - } - - // o0 map[int]*string - if retVals[0] != nil { - o0 = retVals[0].(map[int]*string) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) NamedScalarType(p0 complicated_pkg.Byte) (o0 []complicated_pkg.Byte, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "NamedScalarType", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.NamedScalarType: invalid return values: %v", retVals)) - } - - // o0 []complicated_pkg.Byte - if retVals[0] != nil { - o0 = retVals[0].([]complicated_pkg.Byte) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) Pointers(p0 *int, p1 *net.Conn, p2 **io.Reader) (o0 *int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Pointers", - file, - line, - []interface{}{p0, p1, p2}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.Pointers: invalid return values: %v", retVals)) - } - - // o0 *int - if retVals[0] != nil { - o0 = retVals[0].(*int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) RenamedPackage(p0 tony.SomeUint8Alias) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "RenamedPackage", - file, - line, - []interface{}{p0}) - - if len(retVals) != 0 { - panic(fmt.Sprintf("mockComplicatedThing.RenamedPackage: invalid return values: %v", retVals)) - } - - return -} - -func (m *mockComplicatedThing) Slices(p0 []string) (o0 []int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Slices", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.Slices: invalid return values: %v", retVals)) - } - - // o0 []int - if retVals[0] != nil { - o0 = retVals[0].([]int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) Variadic(p0 int, p1 ...net.Conn) (o0 int) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Variadic", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockComplicatedThing.Variadic: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.image.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.image.go deleted file mode 100644 index b06b4fe..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.image.go +++ /dev/null @@ -1,239 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package some_pkg - -import ( - fmt "fmt" - image "image" - color "image/color" - runtime "runtime" - unsafe "unsafe" - - oglemock "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock" -) - -type MockImage interface { - image.Image - oglemock.MockObject -} - -type mockImage struct { - controller oglemock.Controller - description string -} - -func NewMockImage( - c oglemock.Controller, - desc string) MockImage { - return &mockImage{ - controller: c, - description: desc, - } -} - -func (m *mockImage) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockImage) Oglemock_Description() string { - return m.description -} - -func (m *mockImage) At(p0 int, p1 int) (o0 color.Color) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "At", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.At: invalid return values: %v", retVals)) - } - - // o0 color.Color - if retVals[0] != nil { - o0 = retVals[0].(color.Color) - } - - return -} - -func (m *mockImage) Bounds() (o0 image.Rectangle) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Bounds", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.Bounds: invalid return values: %v", retVals)) - } - - // o0 image.Rectangle - if retVals[0] != nil { - o0 = retVals[0].(image.Rectangle) - } - - return -} - -func (m *mockImage) ColorModel() (o0 color.Model) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "ColorModel", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.ColorModel: invalid return values: %v", retVals)) - } - - // o0 color.Model - if retVals[0] != nil { - o0 = retVals[0].(color.Model) - } - - return -} - -type MockPalettedImage interface { - image.PalettedImage - oglemock.MockObject -} - -type mockPalettedImage struct { - controller oglemock.Controller - description string -} - -func NewMockPalettedImage( - c oglemock.Controller, - desc string) MockPalettedImage { - return &mockPalettedImage{ - controller: c, - description: desc, - } -} - -func (m *mockPalettedImage) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockPalettedImage) Oglemock_Description() string { - return m.description -} - -func (m *mockPalettedImage) At(p0 int, p1 int) (o0 color.Color) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "At", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockPalettedImage.At: invalid return values: %v", retVals)) - } - - // o0 color.Color - if retVals[0] != nil { - o0 = retVals[0].(color.Color) - } - - return -} - -func (m *mockPalettedImage) Bounds() (o0 image.Rectangle) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Bounds", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockPalettedImage.Bounds: invalid return values: %v", retVals)) - } - - // o0 image.Rectangle - if retVals[0] != nil { - o0 = retVals[0].(image.Rectangle) - } - - return -} - -func (m *mockPalettedImage) ColorIndexAt(p0 int, p1 int) (o0 uint8) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "ColorIndexAt", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockPalettedImage.ColorIndexAt: invalid return values: %v", retVals)) - } - - // o0 uint8 - if retVals[0] != nil { - o0 = retVals[0].(uint8) - } - - return -} - -func (m *mockPalettedImage) ColorModel() (o0 color.Model) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "ColorModel", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockPalettedImage.ColorModel: invalid return values: %v", retVals)) - } - - // o0 color.Model - if retVals[0] != nil { - o0 = retVals[0].(color.Model) - } - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.io_reader_writer.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.io_reader_writer.go deleted file mode 100644 index b9e3d25..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.io_reader_writer.go +++ /dev/null @@ -1,128 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package some_pkg - -import ( - fmt "fmt" - io "io" - runtime "runtime" - unsafe "unsafe" - - oglemock "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock" -) - -type MockReader interface { - io.Reader - oglemock.MockObject -} - -type mockReader struct { - controller oglemock.Controller - description string -} - -func NewMockReader( - c oglemock.Controller, - desc string) MockReader { - return &mockReader{ - controller: c, - description: desc, - } -} - -func (m *mockReader) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockReader) Oglemock_Description() string { - return m.description -} - -func (m *mockReader) Read(p0 []uint8) (o0 int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Read", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockReader.Read: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -type MockWriter interface { - io.Writer - oglemock.MockObject -} - -type mockWriter struct { - controller oglemock.Controller - description string -} - -func NewMockWriter( - c oglemock.Controller, - desc string) MockWriter { - return &mockWriter{ - controller: c, - description: desc, - } -} - -func (m *mockWriter) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockWriter) Oglemock_Description() string { - return m.description -} - -func (m *mockWriter) Write(p0 []uint8) (o0 int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Write", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockWriter.Write: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.renamed_pkg.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.renamed_pkg.go deleted file mode 100644 index 6c15871..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.renamed_pkg.go +++ /dev/null @@ -1,67 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package some_pkg - -import ( - fmt "fmt" - runtime "runtime" - unsafe "unsafe" - - oglemock "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock" - tony "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg" -) - -type MockSomeInterface interface { - tony.SomeInterface - oglemock.MockObject -} - -type mockSomeInterface struct { - controller oglemock.Controller - description string -} - -func NewMockSomeInterface( - c oglemock.Controller, - desc string) MockSomeInterface { - return &mockSomeInterface{ - controller: c, - description: desc, - } -} - -func (m *mockSomeInterface) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockSomeInterface) Oglemock_Description() string { - return m.description -} - -func (m *mockSomeInterface) DoFoo(p0 int) (o0 int) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "DoFoo", - file, - line, - []interface{}{p0}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockSomeInterface.DoFoo: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg/renamed_pkg.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg/renamed_pkg.go deleted file mode 100644 index 1461cd6..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg/renamed_pkg.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// A package that calls itself something different than its package path would -// have you believe. -package tony - -type SomeUint8Alias uint8 - -type SomeInterface interface { - DoFoo(a int) int -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/internal_expectation.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/internal_expectation.go deleted file mode 100644 index ec4b546..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/internal_expectation.go +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "errors" - "fmt" - "reflect" - "sync" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" -) - -// InternalExpectation is exported for purposes of testing only. You should not -// touch it. -// -// InternalExpectation represents an expectation for zero or more calls to a -// mock method, and a set of actions to be taken when those calls are received. -type InternalExpectation struct { - // The signature of the method to which this expectation is bound, for - // checking action types. - methodSignature reflect.Type - - // An error reporter to use for reporting errors in the way that expectations - // are set. - errorReporter ErrorReporter - - // A mutex protecting mutable fields of the struct. - mutex sync.Mutex - - // Matchers that the arguments to the mock method must satisfy in order to - // match this expectation. - ArgMatchers []oglematchers.Matcher - - // The name of the file in which this expectation was expressed. - FileName string - - // The line number at which this expectation was expressed. - LineNumber int - - // The number of times this expectation should be matched, as explicitly - // listed by the user. If there was no explicit number expressed, this is -1. - ExpectedNumMatches int - - // Actions to be taken for the first N calls, one per call in order, where N - // is the length of this slice. - OneTimeActions []Action - - // An action to be taken when the one-time actions have expired, or nil if - // there is no such action. - FallbackAction Action - - // The number of times this expectation has been matched so far. - NumMatches uint -} - -// InternalNewExpectation is exported for purposes of testing only. You should -// not touch it. -func InternalNewExpectation( - reporter ErrorReporter, - methodSignature reflect.Type, - args []interface{}, - fileName string, - lineNumber int) *InternalExpectation { - result := &InternalExpectation{} - - // Store fields that can be stored directly. - result.methodSignature = methodSignature - result.errorReporter = reporter - result.FileName = fileName - result.LineNumber = lineNumber - - // Set up defaults. - result.ExpectedNumMatches = -1 - result.OneTimeActions = make([]Action, 0) - - // Set up the ArgMatchers slice, using Equals(x) for each x that is not a - // matcher itself. - result.ArgMatchers = make([]oglematchers.Matcher, len(args)) - for i, x := range args { - if matcher, ok := x.(oglematchers.Matcher); ok { - result.ArgMatchers[i] = matcher - } else { - result.ArgMatchers[i] = oglematchers.Equals(x) - } - } - - return result -} - -func (e *InternalExpectation) Times(n uint) Expectation { - e.mutex.Lock() - defer e.mutex.Unlock() - - // It is illegal to call this more than once. - if e.ExpectedNumMatches != -1 { - e.reportFatalError("Times called more than once.") - return nil - } - - // It is illegal to call this after any actions are configured. - if len(e.OneTimeActions) != 0 { - e.reportFatalError("Times called after WillOnce.") - return nil - } - - if e.FallbackAction != nil { - e.reportFatalError("Times called after WillRepeatedly.") - return nil - } - - // Make sure the number is reasonable (and will fit in an int). - if n > 1000 { - e.reportFatalError("Expectation.Times: N must be at most 1000") - return nil - } - - e.ExpectedNumMatches = int(n) - return e -} - -func (e *InternalExpectation) WillOnce(a Action) Expectation { - e.mutex.Lock() - defer e.mutex.Unlock() - - // It is illegal to call this after WillRepeatedly. - if e.FallbackAction != nil { - e.reportFatalError("WillOnce called after WillRepeatedly.") - return nil - } - - // Tell the action about the method's signature. - if err := a.SetSignature(e.methodSignature); err != nil { - e.reportFatalError(fmt.Sprintf("WillOnce given invalid action: %v", err)) - return nil - } - - // Store the action. - e.OneTimeActions = append(e.OneTimeActions, a) - - return e -} - -func (e *InternalExpectation) WillRepeatedly(a Action) Expectation { - e.mutex.Lock() - defer e.mutex.Unlock() - - // It is illegal to call this twice. - if e.FallbackAction != nil { - e.reportFatalError("WillRepeatedly called more than once.") - return nil - } - - // Tell the action about the method's signature. - if err := a.SetSignature(e.methodSignature); err != nil { - e.reportFatalError(fmt.Sprintf("WillRepeatedly given invalid action: %v", err)) - return nil - } - - // Store the action. - e.FallbackAction = a - - return e -} - -func (e *InternalExpectation) reportFatalError(errorText string) { - e.errorReporter.ReportFatalError(e.FileName, e.LineNumber, errors.New(errorText)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/invoke.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/invoke.go deleted file mode 100644 index 07630cb..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/invoke.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "errors" - "fmt" - "reflect" -) - -// Create an Action that invokes the supplied function, returning whatever it -// returns. The signature of the function must match that of the mocked method -// exactly. -func Invoke(f interface{}) Action { - // Make sure f is a function. - fv := reflect.ValueOf(f) - fk := fv.Kind() - - if fk != reflect.Func { - desc := "" - if fk != reflect.Invalid { - desc = fv.Type().String() - } - - panic(fmt.Sprintf("Invoke: expected function, got %s", desc)) - } - - return &invokeAction{fv} -} - -type invokeAction struct { - f reflect.Value -} - -func (a *invokeAction) SetSignature(signature reflect.Type) error { - // The signature must match exactly. - ft := a.f.Type() - if ft != signature { - return errors.New(fmt.Sprintf("Invoke: expected %v, got %v", signature, ft)) - } - - return nil -} - -func (a *invokeAction) Invoke(vals []interface{}) []interface{} { - // Create a slice of args for the function. - in := make([]reflect.Value, len(vals)) - for i, x := range vals { - in[i] = reflect.ValueOf(x) - } - - // Call the function and return its return values. - out := a.f.Call(in) - result := make([]interface{}, len(out)) - for i, v := range out { - result[i] = v.Interface() - } - - return result -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/mock_object.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/mock_object.go deleted file mode 100644 index de995ef..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/mock_object.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -// MockObject is an interface that mock object implementations must conform to -// in order to register expectations with and hand off calls to a -// MockController. Users should not interact with this interface directly. -type MockObject interface { - // Oglemock_Id returns an identifier for the mock object that is guaranteed - // to be unique within the process at least until the mock object is garbage - // collected. - Oglemock_Id() uintptr - - // Oglemock_Description returns a description of the mock object that may be - // helpful in test failure messages. - Oglemock_Description() string -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/oglemock.goconvey b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/oglemock.goconvey deleted file mode 100644 index 7998285..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/oglemock.goconvey +++ /dev/null @@ -1,2 +0,0 @@ -#ignore --timeout=1s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/return.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/return.go deleted file mode 100644 index c66d248..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/return.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "errors" - "fmt" - "math" - "reflect" -) - -var intType = reflect.TypeOf(int(0)) -var float64Type = reflect.TypeOf(float64(0)) -var complex128Type = reflect.TypeOf(complex128(0)) - -// Return creates an Action that returns the values passed to Return as -// arguments, after suitable legal type conversions. The following rules apply. -// Given an argument x to Return and a corresponding type T in the method's -// signature, at least one of the following must hold: -// -// * x is assignable to T. (See "Assignability" in the language spec.) Note -// that this in particular applies that x may be a type that implements an -// interface T. It also implies that the nil literal can be used if T is a -// pointer, function, interface, slice, channel, or map type. -// -// * T is any numeric type, and x is an int that is in-range for that type. -// This facilities using raw integer constants: Return(17). -// -// * T is a floating-point or complex number type, and x is a float64. This -// facilities using raw floating-point constants: Return(17.5). -// -// * T is a complex number type, and x is a complex128. This facilities using -// raw complex constants: Return(17+2i). -// -func Return(vals ...interface{}) Action { - return &returnAction{vals, nil} -} - -type returnAction struct { - returnVals []interface{} - signature reflect.Type -} - -func (a *returnAction) Invoke(vals []interface{}) []interface{} { - if a.signature == nil { - panic("You must first call SetSignature with a valid signature.") - } - - res, err := a.buildInvokeResult(a.signature) - if err != nil { - panic(err) - } - - return res -} - -func (a *returnAction) SetSignature(signature reflect.Type) error { - if _, err := a.buildInvokeResult(signature); err != nil { - return err - } - - a.signature = signature - return nil -} - -// A version of Invoke that does error checking, used by both public methods. -func (a *returnAction) buildInvokeResult( - sig reflect.Type) (res []interface{}, err error) { - // Check the length of the return value. - numOut := sig.NumOut() - numVals := len(a.returnVals) - - if numOut != numVals { - err = errors.New( - fmt.Sprintf("Return given %d vals; expected %d.", numVals, numOut)) - return - } - - // Attempt to coerce each return value. - res = make([]interface{}, numOut) - - for i, val := range a.returnVals { - resType := sig.Out(i) - res[i], err = a.coerce(val, resType) - - if err != nil { - res = nil - err = errors.New(fmt.Sprintf("Return: arg %d: %v", i, err)) - return - } - } - - return -} - -func (a *returnAction) coerce(x interface{}, t reflect.Type) (interface{}, error) { - xv := reflect.ValueOf(x) - rv := reflect.New(t).Elem() - - // Special case: the language spec says that the predeclared identifier nil - // is assignable to pointers, functions, interface, slices, channels, and map - // types. However, reflect.ValueOf(nil) returns an invalid value that will - // not cooperate below. So handle invalid values here, assuming that they - // resulted from Return(nil). - if !xv.IsValid() { - switch t.Kind() { - case reflect.Ptr, reflect.Func, reflect.Interface, reflect.Chan, reflect.Slice, reflect.Map, reflect.UnsafePointer: - return rv.Interface(), nil - } - - return nil, errors.New(fmt.Sprintf("expected %v, given ", t)) - } - - // If x is assignable to type t, let the reflect package do the heavy - // lifting. - if reflect.TypeOf(x).AssignableTo(t) { - rv.Set(xv) - return rv.Interface(), nil - } - - // Handle numeric types as described in the documentation on Return. - switch { - case xv.Type() == intType && a.isNumeric(t): - return a.coerceInt(xv.Int(), t) - - case xv.Type() == float64Type && (a.isFloatingPoint(t) || a.isComplex(t)): - return a.coerceFloat(xv.Float(), t) - - case xv.Type() == complex128Type && a.isComplex(t): - return a.coerceComplex(xv.Complex(), t) - } - - // The value wasn't of a legal type. - return nil, errors.New(fmt.Sprintf("expected %v, given %v", t, xv.Type())) -} - -func (a *returnAction) isNumeric(t reflect.Type) bool { - return (t.Kind() >= reflect.Int && t.Kind() <= reflect.Uint64) || - a.isFloatingPoint(t) || - a.isComplex(t) -} - -func (a *returnAction) isFloatingPoint(t reflect.Type) bool { - return t.Kind() == reflect.Float32 || t.Kind() == reflect.Float64 -} - -func (a *returnAction) isComplex(t reflect.Type) bool { - return t.Kind() == reflect.Complex64 || t.Kind() == reflect.Complex128 -} - -func (a *returnAction) coerceInt(x int64, t reflect.Type) (interface{}, error) { - k := t.Kind() - - // Floating point and complex numbers: promote appropriately. - if a.isFloatingPoint(t) || a.isComplex(t) { - return a.coerceFloat(float64(x), t) - } - - // Integers: range check. - var min, max int64 - unsigned := false - - switch k { - case reflect.Int8: - min = math.MinInt8 - max = math.MaxInt8 - - case reflect.Int16: - min = math.MinInt16 - max = math.MaxInt16 - - case reflect.Int32: - min = math.MinInt32 - max = math.MaxInt32 - - case reflect.Int64: - min = math.MinInt64 - max = math.MaxInt64 - - case reflect.Uint: - unsigned = true - min = 0 - max = math.MaxUint32 - - case reflect.Uint8: - unsigned = true - min = 0 - max = math.MaxUint8 - - case reflect.Uint16: - unsigned = true - min = 0 - max = math.MaxUint16 - - case reflect.Uint32: - unsigned = true - min = 0 - max = math.MaxUint32 - - case reflect.Uint64: - unsigned = true - min = 0 - max = math.MaxInt64 - - default: - panic(fmt.Sprintf("Unexpected type: %v", t)) - } - - if x < min || x > max { - return nil, errors.New("int value out of range") - } - - rv := reflect.New(t).Elem() - if unsigned { - rv.SetUint(uint64(x)) - } else { - rv.SetInt(x) - } - - return rv.Interface(), nil -} - -func (a *returnAction) coerceFloat(x float64, t reflect.Type) (interface{}, error) { - // Promote complex numbers. - if a.isComplex(t) { - return a.coerceComplex(complex(x, 0), t) - } - - rv := reflect.New(t).Elem() - rv.SetFloat(x) - return rv.Interface(), nil -} - -func (a *returnAction) coerceComplex(x complex128, t reflect.Type) (interface{}, error) { - rv := reflect.New(t).Elem() - rv.SetComplex(x) - return rv.Interface(), nil -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/sample/README.markdown b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/sample/README.markdown deleted file mode 100644 index 60d5d2c..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/sample/README.markdown +++ /dev/null @@ -1,6 +0,0 @@ -This directory contains sample code generated with the `createmock` command. For -example, the file `mock_io.go` can be regenerated with: - - createmock io Reader > sample/mock_io/mock_io.go - -The files are also used by `integration_test.go`. diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/sample/mock_io/mock_io.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/sample/mock_io/mock_io.go deleted file mode 100644 index d08466c..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock/sample/mock_io/mock_io.go +++ /dev/null @@ -1,72 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package mock_io - -import ( - fmt "fmt" - io "io" - runtime "runtime" - unsafe "unsafe" - - oglemock "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock" -) - -type MockReader interface { - io.Reader - oglemock.MockObject -} - -type mockReader struct { - controller oglemock.Controller - description string -} - -func NewMockReader( - c oglemock.Controller, - desc string) MockReader { - return &mockReader{ - controller: c, - description: desc, - } -} - -func (m *mockReader) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockReader) Oglemock_Description() string { - return m.description -} - -func (m *mockReader) Read(p0 []uint8) (o0 int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Read", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockReader.Read: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/.gitignore b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/.gitignore deleted file mode 100644 index dd8fc74..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.6 -6.out -_obj/ -_test/ -_testmain.go diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/LICENSE b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/LICENSE deleted file mode 100644 index d645695..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/README.markdown b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/README.markdown deleted file mode 100644 index 7f7b6c2..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/README.markdown +++ /dev/null @@ -1,149 +0,0 @@ -`ogletest` is a unit testing framework for Go with the following features: - - * An extensive and extensible set of matchers for expressing expectations. - * Automatic failure messages; no need to say `t.Errorf("Expected %v, got - %v"...)`. - * Clean, readable output that tells you exactly what you need to know. - * Built-in support for mocking through the [oglemock][] package. - * Style and semantics similar to [Google Test][googletest] and - [Google JS Test][google-js-test]. - -It integrates with Go's built-in `testing` package, so it works with the -`go test` command, and even with other types of test within your package. Unlike -the `testing` package which offers only basic capabilities for signalling -failures, it offers ways to express expectations and get nice failure messages -automatically. - - -Installation ------------- - -First, make sure you have installed Go 1.0.2 or newer. See -[here][golang-install] for instructions. - -Use the following command to install `ogletest` and its dependencies, and to -keep them up to date: - - go get -u github.com/smartystreets/assertions/internal/ogletest - - -Documentation -------------- - -See [here][reference] for package documentation hosted on GoPkgDoc containing an -exhaustive list of exported symbols. Alternatively, you can install the package -and then use `go doc`: - - go doc github.com/smartystreets/assertions/internal/ogletest - -An important part of `ogletest` is its use of matchers provided by the -[oglematchers][matcher-reference] package. See that package's documentation -for information on the built-in matchers available, and check out the -`oglematchers.Matcher` interface if you want to define your own. - - -Example -------- - -Let's say you have a function in your package `people` with the following -signature: - -```go -// GetRandomPerson returns the name and phone number of Tony, Dennis, or Scott. -func GetRandomPerson() (name, phone string) { - [...] -} -``` - -A silly function, but it will do for an example. You can write a couple of tests -for it as follows: - -```go -package people - -import ( - "github.com/smartystreets/assertions/internal/oglematchers" - "github.com/smartystreets/assertions/internal/ogletest" - "testing" -) - -// Give ogletest a chance to run your tests when invoked by 'go test'. -func TestOgletest(t *testing.T) { ogletest.RunTests(t) } - -// Create a test suite, which groups together logically related test methods -// (defined below). You can share common setup and teardown code here; see the -// package docs for more info. -type PeopleTest struct {} -func init() { ogletest.RegisterTestSuite(&PeopleTest{}) } - -func (t *PeopleTest) ReturnsCorrectNames() { - // Call the function a few times, and make sure it never strays from the set - // of expected names. - for i := 0; i < 25; i++ { - name, _ := GetRandomPerson() - ogletest.ExpectThat(name, oglematchers.AnyOf("Tony", "Dennis", "Scott")) - } -} - -func (t *PeopleTest) FormatsPhoneNumbersCorrectly() { - // Call the function a few times, and make sure it returns phone numbers in a - // standard US format. - for i := 0; i < 25; i++ { - _, phone := GetRandomPerson() - ogletest.ExpectThat(phone, oglematchers.MatchesRegexp(`^\(\d{3}\) \d{3}-\d{4}$`)) -} -``` - -Note that test control functions (`RunTests`, `ExpectThat`, and so on) are part -of the `ogletest` package, whereas built-in matchers (`AnyOf`, `MatchesRegexp`, -and more) are part of the [oglematchers][matcher-reference] library. You can of -course use dot imports so that you don't need to prefix each function with its -package name: - -```go -import ( - . "github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/smartystreets/assertions/internal/ogletest" -) -``` - -If you save the test in a file whose name ends in `_test.go`, you can run your -tests by simply invoking the following in your package directory: - - go test - -Here's what the failure output of ogletest looks like, if your function's -implementation is bad. - - [----------] Running tests from PeopleTest - [ RUN ] PeopleTest.FormatsPhoneNumbersCorrectly - people_test.go:32: - Expected: matches regexp "^\(\d{3}\) \d{3}-\d{4}$" - Actual: +1 800 555 5555 - - [ FAILED ] PeopleTest.FormatsPhoneNumbersCorrectly - [ RUN ] PeopleTest.ReturnsCorrectNames - people_test.go:23: - Expected: or(Tony, Dennis, Scott) - Actual: Bart - - [ FAILED ] PeopleTest.ReturnsCorrectNames - [----------] Finished with tests from PeopleTest - -And if the test passes: - - [----------] Running tests from PeopleTest - [ RUN ] PeopleTest.FormatsPhoneNumbersCorrectly - [ OK ] PeopleTest.FormatsPhoneNumbersCorrectly - [ RUN ] PeopleTest.ReturnsCorrectNames - [ OK ] PeopleTest.ReturnsCorrectNames - [----------] Finished with tests from PeopleTest - - -[reference]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/assertions/internal/ogletest -[matcher-reference]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/assertions/internal/oglematchers -[golang-install]: http://golang.org/doc/install.html -[googletest]: http://code.google.com/p/googletest/ -[google-js-test]: http://code.google.com/p/google-js-test/ -[howtowrite]: http://golang.org/doc/code.html -[oglemock]: https://github.com/smartystreets/assertions/internal/oglemock diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/assert_aliases.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/assert_aliases.go deleted file mode 100644 index 6dca34f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/assert_aliases.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" -) - -// AssertEq(e, a) is equivalent to AssertThat(a, oglematchers.Equals(e)). -func AssertEq(expected, actual interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(actual, oglematchers.Equals(expected), errorParts...) - res.SetCaller(getCallerForAlias()) - - matcherErr := res.MatchResult() - if matcherErr != nil { - panic(&assertThatError{}) - } - - return res -} - -// AssertNe(e, a) is equivalent to AssertThat(a, oglematchers.Not(oglematchers.Equals(e))). -func AssertNe(expected, actual interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(actual, oglematchers.Not(oglematchers.Equals(expected)), errorParts...) - res.SetCaller(getCallerForAlias()) - - matcherErr := res.MatchResult() - if matcherErr != nil { - panic(&assertThatError{}) - } - - return res -} - -// AssertLt(x, y) is equivalent to AssertThat(x, oglematchers.LessThan(y)). -func AssertLt(x, y interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(x, oglematchers.LessThan(y), errorParts...) - res.SetCaller(getCallerForAlias()) - - matcherErr := res.MatchResult() - if matcherErr != nil { - panic(&assertThatError{}) - } - - return res -} - -// AssertLe(x, y) is equivalent to AssertThat(x, oglematchers.LessOrEqual(y)). -func AssertLe(x, y interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(x, oglematchers.LessOrEqual(y), errorParts...) - res.SetCaller(getCallerForAlias()) - - matcherErr := res.MatchResult() - if matcherErr != nil { - panic(&assertThatError{}) - } - - return res -} - -// AssertGt(x, y) is equivalent to AssertThat(x, oglematchers.GreaterThan(y)). -func AssertGt(x, y interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(x, oglematchers.GreaterThan(y), errorParts...) - res.SetCaller(getCallerForAlias()) - - matcherErr := res.MatchResult() - if matcherErr != nil { - panic(&assertThatError{}) - } - - return res -} - -// AssertGe(x, y) is equivalent to AssertThat(x, oglematchers.GreaterOrEqual(y)). -func AssertGe(x, y interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(x, oglematchers.GreaterOrEqual(y), errorParts...) - res.SetCaller(getCallerForAlias()) - - matcherErr := res.MatchResult() - if matcherErr != nil { - panic(&assertThatError{}) - } - - return res -} - -// AssertTrue(b) is equivalent to AssertThat(b, oglematchers.Equals(true)). -func AssertTrue(b interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(b, oglematchers.Equals(true), errorParts...) - res.SetCaller(getCallerForAlias()) - - matcherErr := res.MatchResult() - if matcherErr != nil { - panic(&assertThatError{}) - } - - return res -} - -// AssertFalse(b) is equivalent to AssertThat(b, oglematchers.Equals(false)). -func AssertFalse(b interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(b, oglematchers.Equals(false), errorParts...) - res.SetCaller(getCallerForAlias()) - - matcherErr := res.MatchResult() - if matcherErr != nil { - panic(&assertThatError{}) - } - - return res -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/assert_that.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/assert_that.go deleted file mode 100644 index 97ac69b..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/assert_that.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" -) - -// AssertThat is identical to ExpectThat, except that in the event of failure -// it halts the currently running test immediately. It is thus useful for -// things like bounds checking: -// -// someSlice := [...] -// AssertEq(1, len(someSlice)) // Protects next line from panicking. -// ExpectEq("taco", someSlice[0]) -// -func AssertThat( - x interface{}, - m oglematchers.Matcher, - errorParts ...interface{}) ExpectationResult { - res := ExpectThat(x, m, errorParts...) - res.SetCaller(getCallerForAlias()) - - matcherErr := res.MatchResult() - if matcherErr != nil { - panic(&assertThatError{}) - } - - return res -} - -// assertThatError is a sentinel type that is used in a conspiracy between -// AssertThat and runTests. If runTests sees a *assertThatError as the value -// given to a panic() call, it will avoid printing the panic error. -type assertThatError struct { -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/doc.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/doc.go deleted file mode 100644 index bf6507f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/doc.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package ogletest provides a framework for writing expressive unit tests. It -// integrates with the builtin testing package, so it works with the gotest -// command. Unlike the testing package which offers only basic capabilities for -// signalling failures, it offers ways to express expectations and get nice -// failure messages automatically. -// -// For example: -// -// //////////////////////////////////////////////////////////////////////// -// // testing package test -// //////////////////////////////////////////////////////////////////////// -// -// someStr, err := ComputeSomeString() -// if err != nil { -// t.Errorf("ComputeSomeString: expected nil error, got %v", err) -// } -// -// !strings.Contains(someStr, "foo") { -// t.Errorf("ComputeSomeString: expected substring foo, got %v", someStr) -// } -// -// //////////////////////////////////////////////////////////////////////// -// // ogletest test -// //////////////////////////////////////////////////////////////////////// -// -// someStr, err := ComputeSomeString() -// ExpectEq(nil, err) -// ExpectThat(someStr, HasSubstr("foo") -// -// Failure messages require no work from the user, and look like the following: -// -// foo_test.go:103: -// Expected: has substring "foo" -// Actual: "bar baz" -// -package ogletest diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/expect_aliases.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/expect_aliases.go deleted file mode 100644 index 8cedc43..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/expect_aliases.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "path" - "runtime" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" -) - -func getCallerForAlias() (fileName string, lineNumber int) { - _, fileName, lineNumber, _ = runtime.Caller(2) - fileName = path.Base(fileName) - return -} - -// ExpectEq(e, a) is equivalent to ExpectThat(a, oglematchers.Equals(e)). -func ExpectEq(expected, actual interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(actual, oglematchers.Equals(expected), errorParts...) - res.SetCaller(getCallerForAlias()) - return res -} - -// ExpectNe(e, a) is equivalent to ExpectThat(a, oglematchers.Not(oglematchers.Equals(e))). -func ExpectNe(expected, actual interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(actual, oglematchers.Not(oglematchers.Equals(expected)), errorParts...) - res.SetCaller(getCallerForAlias()) - return res -} - -// ExpectLt(x, y) is equivalent to ExpectThat(x, oglematchers.LessThan(y)). -func ExpectLt(x, y interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(x, oglematchers.LessThan(y), errorParts...) - res.SetCaller(getCallerForAlias()) - return res -} - -// ExpectLe(x, y) is equivalent to ExpectThat(x, oglematchers.LessOrEqual(y)). -func ExpectLe(x, y interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(x, oglematchers.LessOrEqual(y), errorParts...) - res.SetCaller(getCallerForAlias()) - return res -} - -// ExpectGt(x, y) is equivalent to ExpectThat(x, oglematchers.GreaterThan(y)). -func ExpectGt(x, y interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(x, oglematchers.GreaterThan(y), errorParts...) - res.SetCaller(getCallerForAlias()) - return res -} - -// ExpectGe(x, y) is equivalent to ExpectThat(x, oglematchers.GreaterOrEqual(y)). -func ExpectGe(x, y interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(x, oglematchers.GreaterOrEqual(y), errorParts...) - res.SetCaller(getCallerForAlias()) - return res -} - -// ExpectTrue(b) is equivalent to ExpectThat(b, oglematchers.Equals(true)). -func ExpectTrue(b interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(b, oglematchers.Equals(true), errorParts...) - res.SetCaller(getCallerForAlias()) - return res -} - -// ExpectFalse(b) is equivalent to ExpectThat(b, oglematchers.Equals(false)). -func ExpectFalse(b interface{}, errorParts ...interface{}) ExpectationResult { - res := ExpectThat(b, oglematchers.Equals(false), errorParts...) - res.SetCaller(getCallerForAlias()) - return res -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/expect_call.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/expect_call.go deleted file mode 100644 index 7db6954..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/expect_call.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "runtime" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock" -) - -// ExpectCall expresses an expectation that the method of the given name -// should be called on the supplied mock object. It returns a function that -// should be called with the expected arguments, matchers for the arguments, -// or a mix of both. -// -// For example: -// -// mockWriter := [...] -// ogletest.ExpectCall(mockWriter, "Write")(oglematchers.ElementsAre(0x1)) -// .WillOnce(oglemock.Return(1, nil)) -// -// This is a shortcut for calling i.MockController.ExpectCall, where i is the -// TestInfo struct for the currently-running test. Unlike that direct approach, -// this function automatically sets the correct file name and line number for -// the expectation. -func ExpectCall(o oglemock.MockObject, method string) oglemock.PartialExpecation { - // Get information about the call site. - _, file, lineNumber, ok := runtime.Caller(1) - if !ok { - panic("ExpectCall: runtime.Caller") - } - - // Grab the current test info. - info := currentlyRunningTest - if info == nil { - panic("ExpectCall: no test info.") - } - - // Grab the mock controller. - controller := currentlyRunningTest.MockController - if controller == nil { - panic("ExpectCall: no mock controller.") - } - - // Report the expectation. - return controller.ExpectCall(o, method, file, lineNumber) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/expect_that.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/expect_that.go deleted file mode 100644 index 717e9d0..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/expect_that.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "fmt" - "path" - "reflect" - "runtime" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" -) - -// ExpectationResult is an interface returned by ExpectThat that allows callers -// to get information about the result of the expectation and set their own -// custom information. This is not useful to the average consumer, but may be -// helpful if you're writing widely used test utility functions. -type ExpectationResult interface { - // SetCaller updates the file name and line number associated with the - // expectation. This allows, for example, a utility function to express that - // *its* caller should have its line number printed if the expectation fails, - // instead of the line number of the ExpectThat call within the utility - // function. - SetCaller(fileName string, lineNumber int) - - // MatchResult returns the result returned by the expectation's matcher for - // the supplied candidate. - MatchResult() error -} - -// ExpectThat confirms that the supplied matcher matches the value x, adding a -// failure record to the currently running test if it does not. If additional -// parameters are supplied, the first will be used as a format string for the -// later ones, and the user-supplied error message will be added to the test -// output in the event of a failure. -// -// For example: -// -// ExpectThat(userName, Equals("jacobsa")) -// ExpectThat(users[i], Equals("jacobsa"), "while processing user %d", i) -// -func ExpectThat( - x interface{}, - m oglematchers.Matcher, - errorParts ...interface{}) ExpectationResult { - res := &expectationResultImpl{} - - // Get information about the call site. - _, file, lineNumber, ok := runtime.Caller(1) - if !ok { - panic("ExpectThat: runtime.Caller") - } - - // Assemble the user error, if any. - userError := "" - if len(errorParts) != 0 { - v := reflect.ValueOf(errorParts[0]) - if v.Kind() != reflect.String { - panic(fmt.Sprintf("ExpectThat: invalid format string type %v", v.Kind())) - } - - userError = fmt.Sprintf(v.String(), errorParts[1:]...) - } - - // Grab the current test info. - info := currentlyRunningTest - if info == nil { - panic("ExpectThat: no test info.") - } - - // Check whether the value matches. - matcherErr := m.Matches(x) - res.matchError = matcherErr - - // Return immediately on success. - if matcherErr == nil { - return res - } - - // Form an appropriate failure message. Make sure that the expected and - // actual values align properly. - var record failureRecord - relativeClause := "" - if matcherErr.Error() != "" { - relativeClause = fmt.Sprintf(", %s", matcherErr.Error()) - } - - record.GeneratedError = fmt.Sprintf( - "Expected: %s\nActual: %v%s", - m.Description(), - x, - relativeClause) - - // Record additional failure info. - record.FileName = path.Base(file) - record.LineNumber = lineNumber - record.UserError = userError - - // Store the failure. - info.mutex.Lock() - defer info.mutex.Unlock() - - info.failureRecords = append(info.failureRecords, &record) - res.failureRecord = &record - - return res -} - -type expectationResultImpl struct { - // The failure record created by the expectation, or nil if none. - failureRecord *failureRecord - - // The result of the matcher. - matchError error -} - -func (r *expectationResultImpl) SetCaller(fileName string, lineNumber int) { - if r.failureRecord == nil { - return - } - - r.failureRecord.FileName = fileName - r.failureRecord.LineNumber = lineNumber -} - -func (r *expectationResultImpl) MatchResult() error { - return r.matchError -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/methods.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/methods.go deleted file mode 100644 index ad58dd8..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/methods.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "fmt" - "reflect" - "runtime" - "sort" -) - -func getLine(m reflect.Method) int { - pc := m.Func.Pointer() - - f := runtime.FuncForPC(pc) - if f == nil { - panic(fmt.Sprintf("Couldn't get runtime func for method (pc=%d): %v", pc, m)) - } - - _, line := f.FileLine(pc) - return line -} - -type sortableMethodSet []reflect.Method - -func (s sortableMethodSet) Len() int { - return len(s) -} - -func (s sortableMethodSet) Less(i, j int) bool { - return getLine(s[i]) < getLine(s[j]) -} - -func (s sortableMethodSet) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -// Given a type t, return all of the methods of t sorted such that source file -// order is preserved. Order across files is undefined. Order within lines is -// undefined. -func getMethodsInSourceOrder(t reflect.Type) []reflect.Method { - // Build the list of methods. - methods := sortableMethodSet{} - for i := 0; i < t.NumMethod(); i++ { - methods = append(methods, t.Method(i)) - } - - // Sort it. - sort.Sort(methods) - - return methods -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/ogletest.goconvey b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/ogletest.goconvey deleted file mode 100644 index 7998285..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/ogletest.goconvey +++ /dev/null @@ -1,2 +0,0 @@ -#ignore --timeout=1s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/register_test_suite.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/register_test_suite.go deleted file mode 100644 index 0e253a2..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/register_test_suite.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -// RegisterTestSuite tells ogletest about a test suite containing tests that it -// should run. Any exported method on the type pointed to by the supplied -// prototype value will be treated as test methods, with the exception of the -// following methods (which need not be present): -// -// * SetUpTestSuite() -- called exactly once, before the first test method is -// run. The receiver of this method will be a zero value of the test suite -// type, and is not shared with any other methods. Use this method to set -// up any necessary global state shared by all of the test methods. -// -// * TearDownTestSuite() -- called exactly once, after the last test method -// is run. The receiver of this method will be a zero value of the test -// suite type, and is not shared with any other methods. Use this method to -// clean up after any necessary global state shared by all of the test -// methods. -// -// * SetUp(testInfo) -- called before each test method is invoked, with the -// same receiver as that test method, and with a TestInfo arg. At the time -// this method is invoked, the receiver is a zero value for the test suite -// type. Use this method for common setup code that works on data not -// shared across tests. -// -// * TearDown() -- called after each test method is invoked, with the same -// receiver as that test method. Use this method for common cleanup code -// that works on data not shared across tests. -// -// Each test method is invoked on a different receiver, which is initially a -// zero value of the test suite type. -// -// Example: -// -// // Some value that is needed by the tests but is expensive to compute. -// var someExpensiveThing uint -// -// type FooTest struct { -// // Path to a temporary file used by the tests. Each test gets a -// // different temporary file. -// tempFile string -// } -// func init() { ogletest.RegisterTestSuite(&FooTest{}) } -// -// func (t *FooTest) SetUpTestSuite() { -// someExpensiveThing = ComputeSomeExpensiveThing() -// } -// -// func (t *FooTest) SetUp() { -// t.tempFile = CreateTempFile() -// } -// -// func (t *FooTest) TearDown() { -// DeleteTempFile(t.tempFile) -// } -// -// func (t *FooTest) FrobinicatorIsSuccessfullyTweaked() { -// res := DoSomethingWithExpensiveThing(someExpensiveThing, t.tempFile) -// ExpectThat(res, Equals(true)) -// } -// -func RegisterTestSuite(p interface{}) { - if p == nil { - panic("RegisterTestSuite called with nil suite.") - } - - testSuites = append(testSuites, p) -} - -// The set of test suites previously registered. -var testSuites = make([]interface{}, 0) diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/run_tests.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/run_tests.go deleted file mode 100644 index dc56ce3..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/run_tests.go +++ /dev/null @@ -1,336 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "bytes" - "flag" - "fmt" - "path" - "reflect" - "regexp" - "runtime" - "sync" - "testing" - "time" -) - -var testFilter = flag.String("ogletest.run", "", "Regexp for matching tests to run.") - -// runTestsOnce protects RunTests from executing multiple times. -var runTestsOnce sync.Once - -func isAssertThatError(x interface{}) bool { - _, ok := x.(*assertThatError) - return ok -} - -// runTest runs a single test, returning a slice of failure records for that test. -func runTest(suite interface{}, method reflect.Method) (failures []*failureRecord) { - suiteValue := reflect.ValueOf(suite) - suiteType := suiteValue.Type() - - // Set up a clean slate for this test. Make sure to reset it after everything - // below is finished, so we don't accidentally use it elsewhere. - currentlyRunningTest = newTestInfo() - defer func() { - currentlyRunningTest = nil - }() - - // Create a receiver. - suiteInstance := reflect.New(suiteType.Elem()) - - // Run the SetUp method, paying attention to whether it panics. - setUpPanicked := runWithProtection( - func() { - runMethodIfExists(suiteInstance, "SetUp", currentlyRunningTest) - }, - ) - - // Run the test method itself, but only if the SetUp method didn't panic. - // (This includes AssertThat errors.) - if !setUpPanicked { - runWithProtection( - func() { - runMethodIfExists(suiteInstance, method.Name) - }, - ) - } - - // Run the TearDown method unconditionally. - runWithProtection( - func() { - runMethodIfExists(suiteInstance, "TearDown") - }, - ) - - // Tell the mock controller for the tests to report any errors it's sitting - // on. - currentlyRunningTest.MockController.Finish() - - return currentlyRunningTest.failureRecords -} - -// RunTests runs the test suites registered with ogletest, communicating -// failures to the supplied testing.T object. This is the bridge between -// ogletest and the testing package (and gotest); you should ensure that it's -// called at least once by creating a gotest-compatible test function and -// calling it there. -// -// For example: -// -// import ( -// "github.com/smartystreets/assertions/internal/ogletest" -// "testing" -// ) -// -// func TestOgletest(t *testing.T) { -// ogletest.RunTests(t) -// } -// -func RunTests(t *testing.T) { - runTestsOnce.Do(func() { runTestsInternal(t) }) -} - -// runTestsInternal does the real work of RunTests, which simply wraps it in a -// sync.Once. -func runTestsInternal(t *testing.T) { - // Process each registered suite. - for _, suite := range testSuites { - val := reflect.ValueOf(suite) - typ := val.Type() - suiteName := typ.Elem().Name() - - // Grab methods for the suite, filtering them to just the ones that we - // don't need to skip. - testMethods := filterMethods(suiteName, getMethodsInSourceOrder(typ)) - - // Is there anything left to do? - if len(testMethods) == 0 { - continue - } - - fmt.Printf("[----------] Running tests from %s\n", suiteName) - - // Run the SetUpTestSuite method, if any. - runMethodIfExists(val, "SetUpTestSuite") - - // Run each method. - for _, method := range testMethods { - // Print a banner for the start of this test. - fmt.Printf("[ RUN ] %s.%s\n", suiteName, method.Name) - - // Run the test. - startTime := time.Now() - failures := runTest(suite, method) - runDuration := time.Since(startTime) - - // Print any failures, and mark the test as having failed if there are any. - for _, record := range failures { - t.Fail() - userErrorSection := "" - if record.UserError != "" { - userErrorSection = record.UserError + "\n" - } - - fmt.Printf( - "%s:%d:\n%s\n%s\n", - record.FileName, - record.LineNumber, - record.GeneratedError, - userErrorSection) - } - - // Print a banner for the end of the test. - bannerMessage := "[ OK ]" - if len(failures) != 0 { - bannerMessage = "[ FAILED ]" - } - - // Print a summary of the time taken, if long enough. - var timeMessage string - if runDuration >= 25*time.Millisecond { - timeMessage = fmt.Sprintf(" (%s)", runDuration.String()) - } - - fmt.Printf( - "%s %s.%s%s\n", - bannerMessage, - suiteName, - method.Name, - timeMessage) - } - - // Run the TearDownTestSuite method, if any. - runMethodIfExists(val, "TearDownTestSuite") - - fmt.Printf("[----------] Finished with tests from %s\n", suiteName) - } -} - -// Run the supplied function, catching panics (including AssertThat errors) and -// reporting them to the currently-running test as appropriate. Return true iff -// the function panicked. -func runWithProtection(f func()) (panicked bool) { - defer func() { - // If the test didn't panic, we're done. - r := recover() - if r == nil { - return - } - - panicked = true - - // We modify the currently running test below. - currentlyRunningTest.mutex.Lock() - defer currentlyRunningTest.mutex.Unlock() - - // If the function panicked (and the panic was not due to an AssertThat - // failure), add a failure for the panic. - if !isAssertThatError(r) { - // The stack looks like this: - // - // - // panic(r) - // - // - _, fileName, lineNumber, ok := runtime.Caller(2) - var panicRecord failureRecord - if ok { - panicRecord.FileName = path.Base(fileName) - panicRecord.LineNumber = lineNumber - } - - panicRecord.GeneratedError = fmt.Sprintf( - "panic: %v\n\n%s", r, formatPanicStack()) - - currentlyRunningTest.failureRecords = append( - currentlyRunningTest.failureRecords, - &panicRecord) - } - }() - - f() - return -} - -func runMethodIfExists(v reflect.Value, name string, args ...interface{}) { - method := v.MethodByName(name) - if method.Kind() == reflect.Invalid { - return - } - - if method.Type().NumIn() != len(args) { - panic(fmt.Sprintf( - "%s: expected %d args, actually %d.", - name, - len(args), - method.Type().NumIn())) - } - - // Create a slice of reflect.Values to pass to the method. Simultaneously - // check types. - argVals := make([]reflect.Value, len(args)) - for i, arg := range args { - argVal := reflect.ValueOf(arg) - - if argVal.Type() != method.Type().In(i) { - panic(fmt.Sprintf( - "%s: expected arg %d to have type %v.", - name, - i, - argVal.Type())) - } - - argVals[i] = argVal - } - - method.Call(argVals) -} - -func formatPanicStack() string { - buf := new(bytes.Buffer) - - // Walk the stack from top to bottom. - panicPassed := false - for i := 0; ; i++ { - pc, file, line, ok := runtime.Caller(i) - if !ok { - break - } - - // Choose a function name to display. - funcName := "(unknown)" - if f := runtime.FuncForPC(pc); f != nil { - funcName = f.Name() - } - - // Avoid stack frames at panic and above. - if funcName == "runtime.panic" { - panicPassed = true - continue - } - - if !panicPassed { - continue - } - - // Stop if we've gotten as far as the test runner code. - if funcName == "github.com/smartystreets/assertions/internal/ogletest.runMethodIfExists" { - break - } - - // Add an entry for this frame. - fmt.Fprintf(buf, "%s\n\t%s:%d\n", funcName, file, line) - } - - return buf.String() -} - -func filterMethods(suiteName string, in []reflect.Method) (out []reflect.Method) { - for _, m := range in { - // Skip set up, tear down, and unexported methods. - if isSpecialMethod(m.Name) || !isExportedMethod(m.Name) { - continue - } - - // Has the user told us to skip this method? - fullName := fmt.Sprintf("%s.%s", suiteName, m.Name) - matched, err := regexp.MatchString(*testFilter, fullName) - if err != nil { - panic("Invalid value for --ogletest.run: " + err.Error()) - } - - if !matched { - continue - } - - out = append(out, m) - } - - return -} - -func isSpecialMethod(name string) bool { - return (name == "SetUpTestSuite") || - (name == "TearDownTestSuite") || - (name == "SetUp") || - (name == "TearDown") -} - -func isExportedMethod(name string) bool { - return len(name) > 0 && name[0] >= 'A' && name[0] <= 'Z' -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/failing.test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/failing.test.go deleted file mode 100644 index 455969b..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/failing.test.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -func TestFailingTest(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Usual failures -//////////////////////////////////////////////////////////////////////// - -type FailingTest struct { -} - -func init() { RegisterTestSuite(&FailingTest{}) } - -func (t *FailingTest) TearDown() { - fmt.Println("TearDown running.") -} - -func (t *FailingTest) PassingMethod() { -} - -func (t *FailingTest) Equals() { - ExpectThat(17, Equals(17.5)) - ExpectThat(17, Equals("taco")) -} - -func (t *FailingTest) LessThan() { - ExpectThat(18, LessThan(17)) - ExpectThat(18, LessThan("taco")) -} - -func (t *FailingTest) HasSubstr() { - ExpectThat("taco", HasSubstr("ac")) - ExpectThat(17, HasSubstr("ac")) -} - -func (t *FailingTest) ExpectWithUserErrorMessages() { - ExpectThat(17, Equals(19), "foo bar: %d", 112) - ExpectEq(17, 17.5, "foo bar: %d", 112) - ExpectLe(17, 16.9, "foo bar: %d", 112) - ExpectLt(17, 16.9, "foo bar: %d", 112) - ExpectGe(17, 17.1, "foo bar: %d", 112) - ExpectGt(17, "taco", "foo bar: %d", 112) - ExpectNe(17, 17.0, "foo bar: %d", 112) - ExpectFalse(true, "foo bar: %d", 112) - ExpectTrue(false, "foo bar: %d", 112) -} - -func (t *FailingTest) AssertWithUserErrorMessages() { - AssertThat(17, Equals(19), "foo bar: %d", 112) -} - -func (t *FailingTest) ModifiedExpectation() { - ExpectThat(17, HasSubstr("ac")).SetCaller("foo.go", 112) - ExpectEq(17, 19).SetCaller("bar.go", 117) -} - -func (t *FailingTest) ExpectationAliases() { - ExpectEq(17, 17.5) - ExpectEq("taco", 17.5) - - ExpectLe(17, 16.9) - ExpectLt(17, 16.9) - ExpectLt(17, "taco") - - ExpectGe(17, 17.1) - ExpectGt(17, 17.1) - ExpectGt(17, "taco") - - ExpectNe(17, 17.0) - ExpectNe(17, "taco") - - ExpectFalse(true) - ExpectFalse("taco") - - ExpectTrue(false) - ExpectTrue("taco") -} - -func (t *FailingTest) AssertThatFailure() { - AssertThat(17, Equals(19)) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertEqFailure() { - AssertEq(19, 17) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertNeFailure() { - AssertNe(19, 19) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertLeFailure() { - AssertLe(19, 17) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertLtFailure() { - AssertLt(19, 17) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertGeFailure() { - AssertGe(17, 19) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertGtFailure() { - AssertGt(17, 19) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertTrueFailure() { - AssertTrue("taco") - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertFalseFailure() { - AssertFalse("taco") - panic("Shouldn't get here.") -} - -//////////////////////////////////////////////////////////////////////// -// Expectation failure during SetUp -//////////////////////////////////////////////////////////////////////// - -type ExpectFailDuringSetUpTest struct { -} - -func init() { RegisterTestSuite(&ExpectFailDuringSetUpTest{}) } - -func (t *ExpectFailDuringSetUpTest) SetUp(i *TestInfo) { - ExpectFalse(true) -} - -func (t *ExpectFailDuringSetUpTest) TearDown() { - fmt.Println("TearDown running.") -} - -func (t *ExpectFailDuringSetUpTest) PassingMethod() { - fmt.Println("Method running.") -} - -//////////////////////////////////////////////////////////////////////// -// Assertion failure during SetUp -//////////////////////////////////////////////////////////////////////// - -type AssertFailDuringSetUpTest struct { -} - -func init() { RegisterTestSuite(&AssertFailDuringSetUpTest{}) } - -func (t *AssertFailDuringSetUpTest) SetUp(i *TestInfo) { - AssertFalse(true) -} - -func (t *AssertFailDuringSetUpTest) TearDown() { - fmt.Println("TearDown running.") -} - -func (t *AssertFailDuringSetUpTest) PassingMethod() { - fmt.Println("Method running.") -} - -//////////////////////////////////////////////////////////////////////// -// Expectation failure during TearDown -//////////////////////////////////////////////////////////////////////// - -type ExpectFailDuringTearDownTest struct { -} - -func init() { RegisterTestSuite(&ExpectFailDuringTearDownTest{}) } - -func (t *ExpectFailDuringTearDownTest) SetUp(i *TestInfo) { - fmt.Println("SetUp running.") -} - -func (t *ExpectFailDuringTearDownTest) TearDown() { - ExpectFalse(true) -} - -func (t *ExpectFailDuringTearDownTest) PassingMethod() { - fmt.Println("Method running.") -} - -//////////////////////////////////////////////////////////////////////// -// Assertion failure during TearDown -//////////////////////////////////////////////////////////////////////// - -type AssertFailDuringTearDownTest struct { -} - -func init() { RegisterTestSuite(&AssertFailDuringTearDownTest{}) } - -func (t *AssertFailDuringTearDownTest) SetUp(i *TestInfo) { - fmt.Println("SetUp running.") -} - -func (t *AssertFailDuringTearDownTest) TearDown() { - AssertFalse(true) -} - -func (t *AssertFailDuringTearDownTest) PassingMethod() { - fmt.Println("Method running.") -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/filtered.test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/filtered.test.go deleted file mode 100644 index 945b338..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/filtered.test.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -func TestFiltered(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Partially filtered out -//////////////////////////////////////////////////////////////////////// - -type PartiallyFilteredTest struct { -} - -func init() { RegisterTestSuite(&PartiallyFilteredTest{}) } - -func (t *PartiallyFilteredTest) PassingTestFoo() { - ExpectThat(19, Equals(19)) -} - -func (t *PartiallyFilteredTest) PassingTestBar() { - ExpectThat(17, Equals(17)) -} - -func (t *PartiallyFilteredTest) PartiallyFilteredTestFoo() { - ExpectThat(18, LessThan(17)) -} - -func (t *PartiallyFilteredTest) PartiallyFilteredTestBar() { - ExpectThat("taco", HasSubstr("blah")) -} - -func (t *PartiallyFilteredTest) PartiallyFilteredTestBaz() { - ExpectThat(18, LessThan(17)) -} - -//////////////////////////////////////////////////////////////////////// -// Completely filtered out -//////////////////////////////////////////////////////////////////////// - -type CompletelyFilteredTest struct { -} - -func init() { RegisterTestSuite(&CompletelyFilteredTest{}) } - -func (t *CompletelyFilteredTest) SetUpTestSuite() { - fmt.Println("SetUpTestSuite run!") -} - -func (t *CompletelyFilteredTest) TearDownTestSuite() { - fmt.Println("TearDownTestSuite run!") -} - -func (t *PartiallyFilteredTest) SomePassingTest() { - ExpectThat(19, Equals(19)) -} - -func (t *PartiallyFilteredTest) SomeFailingTest() { - ExpectThat(19, Equals(17)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.failing_test b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.failing_test deleted file mode 100644 index de89466..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.failing_test +++ /dev/null @@ -1,266 +0,0 @@ -[----------] Running tests from FailingTest -[ RUN ] FailingTest.PassingMethod -TearDown running. -[ OK ] FailingTest.PassingMethod -[ RUN ] FailingTest.Equals -TearDown running. -failing_test.go:44: -Expected: 17.5 -Actual: 17 - -failing_test.go:45: -Expected: taco -Actual: 17, which is not a string - -[ FAILED ] FailingTest.Equals -[ RUN ] FailingTest.LessThan -TearDown running. -failing_test.go:49: -Expected: less than 17 -Actual: 18 - -failing_test.go:50: -Expected: less than "taco" -Actual: 18, which is not comparable - -[ FAILED ] FailingTest.LessThan -[ RUN ] FailingTest.HasSubstr -TearDown running. -failing_test.go:55: -Expected: has substring "ac" -Actual: 17, which is not a string - -[ FAILED ] FailingTest.HasSubstr -[ RUN ] FailingTest.ExpectWithUserErrorMessages -TearDown running. -failing_test.go:59: -Expected: 19 -Actual: 17 -foo bar: 112 - -failing_test.go:60: -Expected: 17 -Actual: 17.5 -foo bar: 112 - -failing_test.go:61: -Expected: less than or equal to 16.9 -Actual: 17 -foo bar: 112 - -failing_test.go:62: -Expected: less than 16.9 -Actual: 17 -foo bar: 112 - -failing_test.go:63: -Expected: greater than or equal to 17.1 -Actual: 17 -foo bar: 112 - -failing_test.go:64: -Expected: greater than "taco" -Actual: 17, which is not comparable -foo bar: 112 - -failing_test.go:65: -Expected: not(17) -Actual: 17 -foo bar: 112 - -failing_test.go:66: -Expected: false -Actual: true -foo bar: 112 - -failing_test.go:67: -Expected: true -Actual: false -foo bar: 112 - -[ FAILED ] FailingTest.ExpectWithUserErrorMessages -[ RUN ] FailingTest.AssertWithUserErrorMessages -TearDown running. -failing_test.go:71: -Expected: 19 -Actual: 17 -foo bar: 112 - -[ FAILED ] FailingTest.AssertWithUserErrorMessages -[ RUN ] FailingTest.ModifiedExpectation -TearDown running. -foo.go:112: -Expected: has substring "ac" -Actual: 17, which is not a string - -bar.go:117: -Expected: 17 -Actual: 19 - -[ FAILED ] FailingTest.ModifiedExpectation -[ RUN ] FailingTest.ExpectationAliases -TearDown running. -failing_test.go:80: -Expected: 17 -Actual: 17.5 - -failing_test.go:81: -Expected: taco -Actual: 17.5, which is not a string - -failing_test.go:83: -Expected: less than or equal to 16.9 -Actual: 17 - -failing_test.go:84: -Expected: less than 16.9 -Actual: 17 - -failing_test.go:85: -Expected: less than "taco" -Actual: 17, which is not comparable - -failing_test.go:87: -Expected: greater than or equal to 17.1 -Actual: 17 - -failing_test.go:88: -Expected: greater than 17.1 -Actual: 17 - -failing_test.go:89: -Expected: greater than "taco" -Actual: 17, which is not comparable - -failing_test.go:91: -Expected: not(17) -Actual: 17 - -failing_test.go:92: -Expected: not(17) -Actual: taco, which is not numeric - -failing_test.go:94: -Expected: false -Actual: true - -failing_test.go:95: -Expected: false -Actual: taco, which is not a bool - -failing_test.go:97: -Expected: true -Actual: false - -failing_test.go:98: -Expected: true -Actual: taco, which is not a bool - -[ FAILED ] FailingTest.ExpectationAliases -[ RUN ] FailingTest.AssertThatFailure -TearDown running. -failing_test.go:102: -Expected: 19 -Actual: 17 - -[ FAILED ] FailingTest.AssertThatFailure -[ RUN ] FailingTest.AssertEqFailure -TearDown running. -failing_test.go:107: -Expected: 19 -Actual: 17 - -[ FAILED ] FailingTest.AssertEqFailure -[ RUN ] FailingTest.AssertNeFailure -TearDown running. -failing_test.go:112: -Expected: not(19) -Actual: 19 - -[ FAILED ] FailingTest.AssertNeFailure -[ RUN ] FailingTest.AssertLeFailure -TearDown running. -failing_test.go:117: -Expected: less than or equal to 17 -Actual: 19 - -[ FAILED ] FailingTest.AssertLeFailure -[ RUN ] FailingTest.AssertLtFailure -TearDown running. -failing_test.go:122: -Expected: less than 17 -Actual: 19 - -[ FAILED ] FailingTest.AssertLtFailure -[ RUN ] FailingTest.AssertGeFailure -TearDown running. -failing_test.go:127: -Expected: greater than or equal to 19 -Actual: 17 - -[ FAILED ] FailingTest.AssertGeFailure -[ RUN ] FailingTest.AssertGtFailure -TearDown running. -failing_test.go:132: -Expected: greater than 19 -Actual: 17 - -[ FAILED ] FailingTest.AssertGtFailure -[ RUN ] FailingTest.AssertTrueFailure -TearDown running. -failing_test.go:137: -Expected: true -Actual: taco, which is not a bool - -[ FAILED ] FailingTest.AssertTrueFailure -[ RUN ] FailingTest.AssertFalseFailure -TearDown running. -failing_test.go:142: -Expected: false -Actual: taco, which is not a bool - -[ FAILED ] FailingTest.AssertFalseFailure -[----------] Finished with tests from FailingTest -[----------] Running tests from ExpectFailDuringSetUpTest -[ RUN ] ExpectFailDuringSetUpTest.PassingMethod -Method running. -TearDown running. -failing_test.go:156: -Expected: false -Actual: true - -[ FAILED ] ExpectFailDuringSetUpTest.PassingMethod -[----------] Finished with tests from ExpectFailDuringSetUpTest -[----------] Running tests from AssertFailDuringSetUpTest -[ RUN ] AssertFailDuringSetUpTest.PassingMethod -TearDown running. -failing_test.go:177: -Expected: false -Actual: true - -[ FAILED ] AssertFailDuringSetUpTest.PassingMethod -[----------] Finished with tests from AssertFailDuringSetUpTest -[----------] Running tests from ExpectFailDuringTearDownTest -[ RUN ] ExpectFailDuringTearDownTest.PassingMethod -SetUp running. -Method running. -failing_test.go:202: -Expected: false -Actual: true - -[ FAILED ] ExpectFailDuringTearDownTest.PassingMethod -[----------] Finished with tests from ExpectFailDuringTearDownTest -[----------] Running tests from AssertFailDuringTearDownTest -[ RUN ] AssertFailDuringTearDownTest.PassingMethod -SetUp running. -Method running. -failing_test.go:223: -Expected: false -Actual: true - -[ FAILED ] AssertFailDuringTearDownTest.PassingMethod -[----------] Finished with tests from AssertFailDuringTearDownTest ---- FAIL: somepkg (1.23 seconds) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.filtered_test b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.filtered_test deleted file mode 100644 index 9e99dc3..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.filtered_test +++ /dev/null @@ -1,20 +0,0 @@ -[----------] Running tests from PartiallyFilteredTest -[ RUN ] PartiallyFilteredTest.PassingTestBar -[ OK ] PartiallyFilteredTest.PassingTestBar -[ RUN ] PartiallyFilteredTest.PartiallyFilteredTestBar -filtered_test.go:49: -Expected: has substring "blah" -Actual: taco - -[ FAILED ] PartiallyFilteredTest.PartiallyFilteredTestBar -[ RUN ] PartiallyFilteredTest.PartiallyFilteredTestBaz -filtered_test.go:53: -Expected: less than 17 -Actual: 18 - -[ FAILED ] PartiallyFilteredTest.PartiallyFilteredTestBaz -[----------] Finished with tests from PartiallyFilteredTest ---- FAIL: somepkg (1.23 seconds) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.mock_test b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.mock_test deleted file mode 100644 index e9f3b11..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.mock_test +++ /dev/null @@ -1,25 +0,0 @@ -[----------] Running tests from MockTest -[ RUN ] MockTest.ExpectationSatisfied -[ OK ] MockTest.ExpectationSatisfied -[ RUN ] MockTest.MockExpectationNotSatisfied -/some/path/mock_test.go:56: -Unsatisfied expectation; expected At to be called at least 1 times; called 0 times. - -[ FAILED ] MockTest.MockExpectationNotSatisfied -[ RUN ] MockTest.ExpectCallForUnknownMethod -/some/path/mock_test.go:61: -Unknown method: FooBar - -[ FAILED ] MockTest.ExpectCallForUnknownMethod -[ RUN ] MockTest.UnexpectedCall -/some/path/mock_test.go:65: -Unexpected call to At with args: [11 23] - -[ FAILED ] MockTest.UnexpectedCall -[ RUN ] MockTest.InvokeFunction -[ OK ] MockTest.InvokeFunction -[----------] Finished with tests from MockTest ---- FAIL: somepkg (1.23 seconds) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.no_cases_test b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.no_cases_test deleted file mode 100644 index f8161ad..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.no_cases_test +++ /dev/null @@ -1,2 +0,0 @@ -PASS -ok somepkg 1.234s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.panicking_test b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.panicking_test deleted file mode 100644 index c726dd0..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.panicking_test +++ /dev/null @@ -1,23 +0,0 @@ -[----------] Running tests from PanickingTest -[ RUN ] PanickingTest.PanickingTest -TearDown running. -panicking_test.go:44: -panic: foobar - -github.com/smartystreets/assertions/internal/ogletest/somepkg_test.(*PanickingTest).PanickingTest - some_file.txt:0 -reflect.Value.call - some_file.txt:0 -reflect.Value.Call - some_file.txt:0 - - -[ FAILED ] PanickingTest.PanickingTest -[ RUN ] PanickingTest.ZzzSomeOtherTest -TearDown running. -[ OK ] PanickingTest.ZzzSomeOtherTest -[----------] Finished with tests from PanickingTest ---- FAIL: somepkg (1.23 seconds) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.passing_test b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.passing_test deleted file mode 100644 index 5204c2f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.passing_test +++ /dev/null @@ -1,14 +0,0 @@ -[----------] Running tests from PassingTest -[ RUN ] PassingTest.EmptyTestMethod -[ OK ] PassingTest.EmptyTestMethod -[ RUN ] PassingTest.SuccessfullMatches -[ OK ] PassingTest.SuccessfullMatches -[ RUN ] PassingTest.ExpectAliases -[ OK ] PassingTest.ExpectAliases -[ RUN ] PassingTest.AssertAliases -[ OK ] PassingTest.AssertAliases -[ RUN ] PassingTest.SlowTest -[ OK ] PassingTest.SlowTest (1234ms) -[----------] Finished with tests from PassingTest -PASS -ok somepkg 1.234s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.run_twice_test b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.run_twice_test deleted file mode 100644 index db3a198..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.run_twice_test +++ /dev/null @@ -1,14 +0,0 @@ -[----------] Running tests from RunTwiceTest -[ RUN ] RunTwiceTest.PassingMethod -[ OK ] RunTwiceTest.PassingMethod -[ RUN ] RunTwiceTest.FailingMethod -run_twice_test.go:46: -Expected: 17.5 -Actual: 17 - -[ FAILED ] RunTwiceTest.FailingMethod -[----------] Finished with tests from RunTwiceTest ---- FAIL: somepkg (1.23 seconds) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.unexported_test b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.unexported_test deleted file mode 100644 index 765e437..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.unexported_test +++ /dev/null @@ -1,12 +0,0 @@ -[----------] Running tests from UnexportedTest -[ RUN ] UnexportedTest.SomeTest -unexported_test.go:42: -Expected: 4 -Actual: 3 - -[ FAILED ] UnexportedTest.SomeTest -[----------] Finished with tests from UnexportedTest ---- FAIL: somepkg (1.23 seconds) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock.test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock.test.go deleted file mode 100644 index 1f9a895..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock.test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "image/color" - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock_image" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type MockTest struct { - controller oglemock.Controller - image mock_image.MockImage -} - -func init() { RegisterTestSuite(&MockTest{}) } -func TestMockTest(t *testing.T) { RunTests(t) } - -func (t *MockTest) SetUp(i *TestInfo) { - t.controller = i.MockController - t.image = mock_image.NewMockImage(t.controller, "some mock image") -} - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *MockTest) ExpectationSatisfied() { - ExpectCall(t.image, "At")(11, GreaterThan(19)). - WillOnce(oglemock.Return(color.Gray{0})) - - ExpectThat(t.image.At(11, 23), IdenticalTo(color.Gray{0})) -} - -func (t *MockTest) MockExpectationNotSatisfied() { - ExpectCall(t.image, "At")(11, GreaterThan(19)). - WillOnce(oglemock.Return(color.Gray{0})) -} - -func (t *MockTest) ExpectCallForUnknownMethod() { - ExpectCall(t.image, "FooBar")(11) -} - -func (t *MockTest) UnexpectedCall() { - t.image.At(11, 23) -} - -func (t *MockTest) InvokeFunction() { - var suppliedX, suppliedY int - f := func(x, y int) color.Color { - suppliedX = x - suppliedY = y - return color.Gray{17} - } - - ExpectCall(t.image, "At")(Any(), Any()). - WillOnce(oglemock.Invoke(f)) - - ExpectThat(t.image.At(-1, 12), IdenticalTo(color.Gray{17})) - ExpectEq(-1, suppliedX) - ExpectEq(12, suppliedY) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock_image/mock_image.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock_image/mock_image.go deleted file mode 100644 index 786fef4..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock_image/mock_image.go +++ /dev/null @@ -1,116 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package mock_image - -import ( - fmt "fmt" - image "image" - color "image/color" - runtime "runtime" - unsafe "unsafe" - - oglemock "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock" -) - -type MockImage interface { - image.Image - oglemock.MockObject -} - -type mockImage struct { - controller oglemock.Controller - description string -} - -func NewMockImage( - c oglemock.Controller, - desc string) MockImage { - return &mockImage{ - controller: c, - description: desc, - } -} - -func (m *mockImage) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockImage) Oglemock_Description() string { - return m.description -} - -func (m *mockImage) At(p0 int, p1 int) (o0 color.Color) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "At", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.At: invalid return values: %v", retVals)) - } - - // o0 color.Color - if retVals[0] != nil { - o0 = retVals[0].(color.Color) - } - - return -} - -func (m *mockImage) Bounds() (o0 image.Rectangle) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Bounds", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.Bounds: invalid return values: %v", retVals)) - } - - // o0 image.Rectangle - if retVals[0] != nil { - o0 = retVals[0].(image.Rectangle) - } - - return -} - -func (m *mockImage) ColorModel() (o0 color.Model) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "ColorModel", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.ColorModel: invalid return values: %v", retVals)) - } - - // o0 color.Model - if retVals[0] != nil { - o0 = retVals[0].(color.Model) - } - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/no_cases.test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/no_cases.test.go deleted file mode 100644 index 215c8c8..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/no_cases.test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -func TestNoCases(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type NoCasesTest struct { -} - -func init() { RegisterTestSuite(&NoCasesTest{}) } - -func (t *NoCasesTest) SetUpTestSuite() { - fmt.Println("SetUpTestSuite run!") -} - -func (t *NoCasesTest) TearDownTestSuite() { - fmt.Println("TearDownTestSuite run!") -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/panicking.test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/panicking.test.go deleted file mode 100644 index c627fb4..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/panicking.test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type PanickingTest struct { -} - -func init() { RegisterTestSuite(&PanickingTest{}) } -func TestPanickingTest(t *testing.T) { RunTests(t) } - -func (t *PanickingTest) TearDown() { - fmt.Println("TearDown running.") -} - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *PanickingTest) PanickingTest() { - panic("foobar") -} - -func (t *PanickingTest) ZzzSomeOtherTest() { - ExpectThat(17, Equals(17.0)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/passing.test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/passing.test.go deleted file mode 100644 index bce215b..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/passing.test.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "testing" - "time" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type PassingTest struct { -} - -func init() { RegisterTestSuite(&PassingTest{}) } -func TestPassingTest(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *PassingTest) EmptyTestMethod() { -} - -func (t *PassingTest) SuccessfullMatches() { - ExpectThat(17, Equals(17.0)) - ExpectThat(16.9, LessThan(17)) - ExpectThat("taco", HasSubstr("ac")) - - AssertThat(17, Equals(17.0)) - AssertThat(16.9, LessThan(17)) - AssertThat("taco", HasSubstr("ac")) -} - -func (t *PassingTest) ExpectAliases() { - ExpectEq(17, 17.0) - - ExpectLe(17, 17.0) - ExpectLe(17, 18.0) - ExpectLt(17, 18.0) - - ExpectGe(17, 17.0) - ExpectGe(17, 16.0) - ExpectGt(17, 16.0) - - ExpectNe(17, 18.0) - - ExpectTrue(true) - ExpectFalse(false) -} - -func (t *PassingTest) AssertAliases() { - AssertEq(17, 17.0) - - AssertLe(17, 17.0) - AssertLe(17, 18.0) - AssertLt(17, 18.0) - - AssertGe(17, 17.0) - AssertGe(17, 16.0) - AssertGt(17, 16.0) - - AssertNe(17, 18.0) - - AssertTrue(true) - AssertFalse(false) -} - -func (t *PassingTest) SlowTest() { - time.Sleep(37 * time.Millisecond) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/run_twice.test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/run_twice.test.go deleted file mode 100644 index a28edd5..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/run_twice.test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type RunTwiceTest struct { -} - -func init() { RegisterTestSuite(&RunTwiceTest{}) } - -// Set up two helpers that call RunTests. The test should still only be run -// once. -func TestOgletest(t *testing.T) { RunTests(t) } -func TestOgletest2(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *RunTwiceTest) PassingMethod() { -} - -func (t *RunTwiceTest) FailingMethod() { - ExpectThat(17, Equals(17.5)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/unexported.test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/unexported.test.go deleted file mode 100644 index 9682122..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_cases/unexported.test.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type UnexportedTest struct { -} - -func init() { RegisterTestSuite(&UnexportedTest{}) } -func TestUnexportedTest(t *testing.T) { RunTests(t) } - -func (t *UnexportedTest) someUnexportedMethod() { -} - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *UnexportedTest) SomeTest() { - ExpectThat(3, Equals(4)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_info.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_info.go deleted file mode 100644 index 9666583..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/ogletest/test_info.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "sync" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglemock" -) - -// TestInfo represents information about a currently running or previously-run -// test. -type TestInfo struct { - // A mock controller that is set up to report errors to the ogletest test - // runner. This can be used for setting up mock expectations and handling - // mock calls. The Finish method should not be run by the user; ogletest will - // do that automatically after the test's TearDown method is run. - // - // Note that this feature is still experimental, and is subject to change. - MockController oglemock.Controller - - // A mutex protecting shared state. - mutex sync.RWMutex - - // A set of failure records that the test has produced. - failureRecords []*failureRecord // Protected by mutex -} - -// currentlyRunningTest is the state for the currently running test, if any. -var currentlyRunningTest *TestInfo - -// newTestInfo creates a valid but empty TestInfo struct. -func newTestInfo() *TestInfo { - info := &TestInfo{} - info.failureRecords = make([]*failureRecord, 0) - info.MockController = oglemock.NewController(&testInfoErrorReporter{info}) - return info -} - -// failureRecord represents a single failed expectation for a test. -type failureRecord struct { - // The file name within which the expectation failed, e.g. "foo_test.go". - FileName string - - // The line number at which the expectation failed. - LineNumber int - - // The error generated by the testing framework. For example: - // - // Expected: 17 - // Actual: "taco", which is not numeric - // - GeneratedError string - - // A user-specified string to print out with the error, if any. - UserError string -} - -// testInfoErrorReporter is an oglemock.ErrorReporter that writes failure -// records into a test info struct. -type testInfoErrorReporter struct { - testInfo *TestInfo -} - -func (r *testInfoErrorReporter) ReportError( - fileName string, - lineNumber int, - err error) { - r.testInfo.mutex.Lock() - defer r.testInfo.mutex.Unlock() - - record := &failureRecord{ - FileName: fileName, - LineNumber: lineNumber, - GeneratedError: err.Error(), - } - - r.testInfo.failureRecords = append(r.testInfo.failureRecords, record) -} - -func (r *testInfoErrorReporter) ReportFatalError( - fileName string, - lineNumber int, - err error) { - r.ReportError(fileName, lineNumber, err) - panic(&assertThatError{}) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/messages.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/messages.go deleted file mode 100644 index c11de06..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/messages.go +++ /dev/null @@ -1,86 +0,0 @@ -package assertions - -const ( // equality - shouldHaveBeenEqual = "Expected: '%v'\nActual: '%v'\n(Should be equal)" - shouldNotHaveBeenEqual = "Expected '%v'\nto NOT equal '%v'\n(but it did)!" - shouldHaveBeenAlmostEqual = "Expected '%v' to almost equal '%v' (but it didn't)!" - shouldHaveNotBeenAlmostEqual = "Expected '%v' to NOT almost equal '%v' (but it did)!" - shouldHaveResembled = "Expected: '%#v'\nActual: '%#v'\n(Should resemble)!" - shouldHaveResembledTypeMismatch = "Expected: '%#v'\nActual: '%#v'\n(Type mismatch: '%T' vs '%T')!" - shouldNotHaveResembled = "Expected '%#v'\nto NOT resemble '%#v'\n(but it did)!" - shouldBePointers = "Both arguments should be pointers " - shouldHaveBeenNonNilPointer = shouldBePointers + "(the %s was %s)!" - shouldHavePointedTo = "Expected '%+v' (address: '%v') and '%+v' (address: '%v') to be the same address (but their weren't)!" - shouldNotHavePointedTo = "Expected '%+v' and '%+v' to be different references (but they matched: '%v')!" - shouldHaveBeenNil = "Expected: nil\nActual: '%v'" - shouldNotHaveBeenNil = "Expected '%+v' to NOT be nil (but it was)!" - shouldHaveBeenTrue = "Expected: true\nActual: %v" - shouldHaveBeenFalse = "Expected: false\nActual: %v" - shouldHaveBeenZeroValue = "'%+v' should have been the zero value" //"Expected: (zero value)\nActual: %v" -) - -const ( // quantity comparisons - shouldHaveBeenGreater = "Expected '%v' to be greater than '%v' (but it wasn't)!" - shouldHaveBeenGreaterOrEqual = "Expected '%v' to be greater than or equal to '%v' (but it wasn't)!" - shouldHaveBeenLess = "Expected '%v' to be less than '%v' (but it wasn't)!" - shouldHaveBeenLessOrEqual = "Expected '%v' to be less than or equal to '%v' (but it wasn't)!" - shouldHaveBeenBetween = "Expected '%v' to be between '%v' and '%v' (but it wasn't)!" - shouldNotHaveBeenBetween = "Expected '%v' NOT to be between '%v' and '%v' (but it was)!" - shouldHaveDifferentUpperAndLower = "The lower and upper bounds must be different values (they were both '%v')." - shouldHaveBeenBetweenOrEqual = "Expected '%v' to be between '%v' and '%v' or equal to one of them (but it wasn't)!" - shouldNotHaveBeenBetweenOrEqual = "Expected '%v' NOT to be between '%v' and '%v' or equal to one of them (but it was)!" -) - -const ( // collections - shouldHaveContained = "Expected the container (%v) to contain: '%v' (but it didn't)!" - shouldNotHaveContained = "Expected the container (%v) NOT to contain: '%v' (but it did)!" - shouldHaveBeenIn = "Expected '%v' to be in the container (%v, but it wasn't)!" - shouldNotHaveBeenIn = "Expected '%v' NOT to be in the container (%v, but it was)!" - shouldHaveBeenAValidCollection = "You must provide a valid container (was %v)!" - shouldHaveBeenEmpty = "Expected %+v to be empty (but it wasn't)!" - shouldNotHaveBeenEmpty = "Expected %+v to NOT be empty (but it was)!" -) - -const ( // strings - shouldHaveStartedWith = "Expected '%v'\nto start with '%v'\n(but it didn't)!" - shouldNotHaveStartedWith = "Expected '%v'\nNOT to start with '%v'\n(but it did)!" - shouldHaveEndedWith = "Expected '%v'\nto end with '%v'\n(but it didn't)!" - shouldNotHaveEndedWith = "Expected '%v'\nNOT to end with '%v'\n(but it did)!" - shouldBothBeStrings = "Both arguments to this assertion must be strings (you provided %v and %v)." - shouldBeString = "The argument to this assertion must be a string (you provided %v)." - shouldHaveContainedSubstring = "Expected '%s' to contain substring '%s' (but it didn't)!" - shouldNotHaveContainedSubstring = "Expected '%s' NOT to contain substring '%s' (but it didn't)!" - shouldHaveBeenBlank = "Expected '%s' to be blank (but it wasn't)!" - shouldNotHaveBeenBlank = "Expected value to NOT be blank (but it was)!" -) - -const ( // panics - shouldUseVoidNiladicFunction = "You must provide a void, niladic function as the first argument!" - shouldHavePanickedWith = "Expected func() to panic with '%v' (but it panicked with '%v')!" - shouldHavePanicked = "Expected func() to panic (but it didn't)!" - shouldNotHavePanicked = "Expected func() NOT to panic (error: '%+v')!" - shouldNotHavePanickedWith = "Expected func() NOT to panic with '%v' (but it did)!" -) - -const ( // type checking - shouldHaveBeenA = "Expected '%v' to be: '%v' (but was: '%v')!" - shouldNotHaveBeenA = "Expected '%v' to NOT be: '%v' (but it was)!" - - shouldHaveImplemented = "Expected: '%v interface support'\nActual: '%v' does not implement the interface!" - shouldNotHaveImplemented = "Expected '%v'\nto NOT implement '%v'\n(but it did)!" - shouldCompareWithInterfacePointer = "The expected value must be a pointer to an interface type (eg. *fmt.Stringer)" - shouldNotBeNilActual = "The actual value was 'nil' and should be a value or a pointer to a value!" -) - -const ( // time comparisons - shouldUseTimes = "You must provide time instances as arguments to this assertion." - shouldUseTimeSlice = "You must provide a slice of time instances as the first argument to this assertion." - shouldUseDurationAndTime = "You must provide a duration and a time as arguments to this assertion." - shouldHaveHappenedBefore = "Expected '%v' to happen before '%v' (it happened '%v' after)!" - shouldHaveHappenedAfter = "Expected '%v' to happen after '%v' (it happened '%v' before)!" - shouldHaveHappenedBetween = "Expected '%v' to happen between '%v' and '%v' (it happened '%v' outside threshold)!" - shouldNotHaveHappenedOnOrBetween = "Expected '%v' to NOT happen on or between '%v' and '%v' (but it did)!" - - // format params: incorrect-index, previous-index, previous-time, incorrect-index, incorrect-time - shouldHaveBeenChronological = "The 'Time' at index [%d] should have happened after the previous one (but it didn't!):\n [%d]: %s\n [%d]: %s (see, it happened before!)" -) diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/panic.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/panic.go deleted file mode 100644 index 7e75db1..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/panic.go +++ /dev/null @@ -1,115 +0,0 @@ -package assertions - -import "fmt" - -// ShouldPanic receives a void, niladic function and expects to recover a panic. -func ShouldPanic(actual interface{}, expected ...interface{}) (message string) { - if fail := need(0, expected); fail != success { - return fail - } - - action, _ := actual.(func()) - - if action == nil { - message = shouldUseVoidNiladicFunction - return - } - - defer func() { - recovered := recover() - if recovered == nil { - message = shouldHavePanicked - } else { - message = success - } - }() - action() - - return -} - -// ShouldNotPanic receives a void, niladic function and expects to execute the function without any panic. -func ShouldNotPanic(actual interface{}, expected ...interface{}) (message string) { - if fail := need(0, expected); fail != success { - return fail - } - - action, _ := actual.(func()) - - if action == nil { - message = shouldUseVoidNiladicFunction - return - } - - defer func() { - recovered := recover() - if recovered != nil { - message = fmt.Sprintf(shouldNotHavePanicked, recovered) - } else { - message = success - } - }() - action() - - return -} - -// ShouldPanicWith receives a void, niladic function and expects to recover a panic with the second argument as the content. -func ShouldPanicWith(actual interface{}, expected ...interface{}) (message string) { - if fail := need(1, expected); fail != success { - return fail - } - - action, _ := actual.(func()) - - if action == nil { - message = shouldUseVoidNiladicFunction - return - } - - defer func() { - recovered := recover() - if recovered == nil { - message = shouldHavePanicked - } else { - if equal := ShouldEqual(recovered, expected[0]); equal != success { - message = serializer.serialize(expected[0], recovered, fmt.Sprintf(shouldHavePanickedWith, expected[0], recovered)) - } else { - message = success - } - } - }() - action() - - return -} - -// ShouldNotPanicWith receives a void, niladic function and expects to recover a panic whose content differs from the second argument. -func ShouldNotPanicWith(actual interface{}, expected ...interface{}) (message string) { - if fail := need(1, expected); fail != success { - return fail - } - - action, _ := actual.(func()) - - if action == nil { - message = shouldUseVoidNiladicFunction - return - } - - defer func() { - recovered := recover() - if recovered == nil { - message = success - } else { - if equal := ShouldEqual(recovered, expected[0]); equal == success { - message = fmt.Sprintf(shouldNotHavePanickedWith, expected[0]) - } else { - message = success - } - } - }() - action() - - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/panic_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/panic_test.go deleted file mode 100644 index 15eafac..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/panic_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package assertions - -import ( - "fmt" - "testing" -) - -func TestShouldPanic(t *testing.T) { - fail(t, so(func() {}, ShouldPanic, 1), "This assertion requires exactly 0 comparison values (you provided 1).") - fail(t, so(func() {}, ShouldPanic, 1, 2, 3), "This assertion requires exactly 0 comparison values (you provided 3).") - - fail(t, so(1, ShouldPanic), shouldUseVoidNiladicFunction) - fail(t, so(func(i int) {}, ShouldPanic), shouldUseVoidNiladicFunction) - fail(t, so(func() int { panic("hi") }, ShouldPanic), shouldUseVoidNiladicFunction) - - fail(t, so(func() {}, ShouldPanic), shouldHavePanicked) - pass(t, so(func() { panic("hi") }, ShouldPanic)) -} - -func TestShouldNotPanic(t *testing.T) { - fail(t, so(func() {}, ShouldNotPanic, 1), "This assertion requires exactly 0 comparison values (you provided 1).") - fail(t, so(func() {}, ShouldNotPanic, 1, 2, 3), "This assertion requires exactly 0 comparison values (you provided 3).") - - fail(t, so(1, ShouldNotPanic), shouldUseVoidNiladicFunction) - fail(t, so(func(i int) {}, ShouldNotPanic), shouldUseVoidNiladicFunction) - - fail(t, so(func() { panic("hi") }, ShouldNotPanic), fmt.Sprintf(shouldNotHavePanicked, "hi")) - pass(t, so(func() {}, ShouldNotPanic)) -} - -func TestShouldPanicWith(t *testing.T) { - fail(t, so(func() {}, ShouldPanicWith), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(func() {}, ShouldPanicWith, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(1, ShouldPanicWith, 1), shouldUseVoidNiladicFunction) - fail(t, so(func(i int) {}, ShouldPanicWith, "hi"), shouldUseVoidNiladicFunction) - fail(t, so(func() {}, ShouldPanicWith, "bye"), shouldHavePanicked) - fail(t, so(func() { panic("hi") }, ShouldPanicWith, "bye"), "bye|hi|Expected func() to panic with 'bye' (but it panicked with 'hi')!") - - pass(t, so(func() { panic("hi") }, ShouldPanicWith, "hi")) -} - -func TestShouldNotPanicWith(t *testing.T) { - fail(t, so(func() {}, ShouldNotPanicWith), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(func() {}, ShouldNotPanicWith, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(1, ShouldNotPanicWith, 1), shouldUseVoidNiladicFunction) - fail(t, so(func(i int) {}, ShouldNotPanicWith, "hi"), shouldUseVoidNiladicFunction) - fail(t, so(func() { panic("hi") }, ShouldNotPanicWith, "hi"), "Expected func() NOT to panic with 'hi' (but it did)!") - - pass(t, so(func() {}, ShouldNotPanicWith, "bye")) - pass(t, so(func() { panic("hi") }, ShouldNotPanicWith, "bye")) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/quantity.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/quantity.go deleted file mode 100644 index 382da22..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/quantity.go +++ /dev/null @@ -1,141 +0,0 @@ -package assertions - -import ( - "fmt" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions/internal/oglematchers" -) - -// ShouldBeGreaterThan receives exactly two parameters and ensures that the first is greater than the second. -func ShouldBeGreaterThan(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - if matchError := oglematchers.GreaterThan(expected[0]).Matches(actual); matchError != nil { - return fmt.Sprintf(shouldHaveBeenGreater, actual, expected[0]) - } - return success -} - -// ShouldBeGreaterThanOrEqualTo receives exactly two parameters and ensures that the first is greater than or equal to the second. -func ShouldBeGreaterThanOrEqualTo(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } else if matchError := oglematchers.GreaterOrEqual(expected[0]).Matches(actual); matchError != nil { - return fmt.Sprintf(shouldHaveBeenGreaterOrEqual, actual, expected[0]) - } - return success -} - -// ShouldBeLessThan receives exactly two parameters and ensures that the first is less than the second. -func ShouldBeLessThan(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } else if matchError := oglematchers.LessThan(expected[0]).Matches(actual); matchError != nil { - return fmt.Sprintf(shouldHaveBeenLess, actual, expected[0]) - } - return success -} - -// ShouldBeLessThan receives exactly two parameters and ensures that the first is less than or equal to the second. -func ShouldBeLessThanOrEqualTo(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } else if matchError := oglematchers.LessOrEqual(expected[0]).Matches(actual); matchError != nil { - return fmt.Sprintf(shouldHaveBeenLess, actual, expected[0]) - } - return success -} - -// ShouldBeBetween receives exactly three parameters: an actual value, a lower bound, and an upper bound. -// It ensures that the actual value is between both bounds (but not equal to either of them). -func ShouldBeBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - lower, upper, fail := deriveBounds(expected) - - if fail != success { - return fail - } else if !isBetween(actual, lower, upper) { - return fmt.Sprintf(shouldHaveBeenBetween, actual, lower, upper) - } - return success -} - -// ShouldNotBeBetween receives exactly three parameters: an actual value, a lower bound, and an upper bound. -// It ensures that the actual value is NOT between both bounds. -func ShouldNotBeBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - lower, upper, fail := deriveBounds(expected) - - if fail != success { - return fail - } else if isBetween(actual, lower, upper) { - return fmt.Sprintf(shouldNotHaveBeenBetween, actual, lower, upper) - } - return success -} -func deriveBounds(values []interface{}) (lower interface{}, upper interface{}, fail string) { - lower = values[0] - upper = values[1] - - if ShouldNotEqual(lower, upper) != success { - return nil, nil, fmt.Sprintf(shouldHaveDifferentUpperAndLower, lower) - } else if ShouldBeLessThan(lower, upper) != success { - lower, upper = upper, lower - } - return lower, upper, success -} -func isBetween(value, lower, upper interface{}) bool { - if ShouldBeGreaterThan(value, lower) != success { - return false - } else if ShouldBeLessThan(value, upper) != success { - return false - } - return true -} - -// ShouldBeBetweenOrEqual receives exactly three parameters: an actual value, a lower bound, and an upper bound. -// It ensures that the actual value is between both bounds or equal to one of them. -func ShouldBeBetweenOrEqual(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - lower, upper, fail := deriveBounds(expected) - - if fail != success { - return fail - } else if !isBetweenOrEqual(actual, lower, upper) { - return fmt.Sprintf(shouldHaveBeenBetweenOrEqual, actual, lower, upper) - } - return success -} - -// ShouldNotBeBetweenOrEqual receives exactly three parameters: an actual value, a lower bound, and an upper bound. -// It ensures that the actual value is nopt between the bounds nor equal to either of them. -func ShouldNotBeBetweenOrEqual(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - lower, upper, fail := deriveBounds(expected) - - if fail != success { - return fail - } else if isBetweenOrEqual(actual, lower, upper) { - return fmt.Sprintf(shouldNotHaveBeenBetweenOrEqual, actual, lower, upper) - } - return success -} - -func isBetweenOrEqual(value, lower, upper interface{}) bool { - if ShouldBeGreaterThanOrEqualTo(value, lower) != success { - return false - } else if ShouldBeLessThanOrEqualTo(value, upper) != success { - return false - } - return true -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/quantity_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/quantity_test.go deleted file mode 100644 index 7546e72..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/quantity_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package assertions - -import "testing" - -func TestShouldBeGreaterThan(t *testing.T) { - fail(t, so(1, ShouldBeGreaterThan), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(1, ShouldBeGreaterThan, 0, 0), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so(1, ShouldBeGreaterThan, 0)) - pass(t, so(1.1, ShouldBeGreaterThan, 1)) - pass(t, so(1, ShouldBeGreaterThan, uint(0))) - pass(t, so("b", ShouldBeGreaterThan, "a")) - - fail(t, so(0, ShouldBeGreaterThan, 1), "Expected '0' to be greater than '1' (but it wasn't)!") - fail(t, so(1, ShouldBeGreaterThan, 1.1), "Expected '1' to be greater than '1.1' (but it wasn't)!") - fail(t, so(uint(0), ShouldBeGreaterThan, 1.1), "Expected '0' to be greater than '1.1' (but it wasn't)!") - fail(t, so("a", ShouldBeGreaterThan, "b"), "Expected 'a' to be greater than 'b' (but it wasn't)!") -} - -func TestShouldBeGreaterThanOrEqual(t *testing.T) { - fail(t, so(1, ShouldBeGreaterThanOrEqualTo), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(1, ShouldBeGreaterThanOrEqualTo, 0, 0), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so(1, ShouldBeGreaterThanOrEqualTo, 1)) - pass(t, so(1.1, ShouldBeGreaterThanOrEqualTo, 1.1)) - pass(t, so(1, ShouldBeGreaterThanOrEqualTo, uint(1))) - pass(t, so("b", ShouldBeGreaterThanOrEqualTo, "b")) - - pass(t, so(1, ShouldBeGreaterThanOrEqualTo, 0)) - pass(t, so(1.1, ShouldBeGreaterThanOrEqualTo, 1)) - pass(t, so(1, ShouldBeGreaterThanOrEqualTo, uint(0))) - pass(t, so("b", ShouldBeGreaterThanOrEqualTo, "a")) - - fail(t, so(0, ShouldBeGreaterThanOrEqualTo, 1), "Expected '0' to be greater than or equal to '1' (but it wasn't)!") - fail(t, so(1, ShouldBeGreaterThanOrEqualTo, 1.1), "Expected '1' to be greater than or equal to '1.1' (but it wasn't)!") - fail(t, so(uint(0), ShouldBeGreaterThanOrEqualTo, 1.1), "Expected '0' to be greater than or equal to '1.1' (but it wasn't)!") - fail(t, so("a", ShouldBeGreaterThanOrEqualTo, "b"), "Expected 'a' to be greater than or equal to 'b' (but it wasn't)!") -} - -func TestShouldBeLessThan(t *testing.T) { - fail(t, so(1, ShouldBeLessThan), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(1, ShouldBeLessThan, 0, 0), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so(0, ShouldBeLessThan, 1)) - pass(t, so(1, ShouldBeLessThan, 1.1)) - pass(t, so(uint(0), ShouldBeLessThan, 1)) - pass(t, so("a", ShouldBeLessThan, "b")) - - fail(t, so(1, ShouldBeLessThan, 0), "Expected '1' to be less than '0' (but it wasn't)!") - fail(t, so(1.1, ShouldBeLessThan, 1), "Expected '1.1' to be less than '1' (but it wasn't)!") - fail(t, so(1.1, ShouldBeLessThan, uint(0)), "Expected '1.1' to be less than '0' (but it wasn't)!") - fail(t, so("b", ShouldBeLessThan, "a"), "Expected 'b' to be less than 'a' (but it wasn't)!") -} - -func TestShouldBeLessThanOrEqualTo(t *testing.T) { - fail(t, so(1, ShouldBeLessThanOrEqualTo), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(1, ShouldBeLessThanOrEqualTo, 0, 0), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so(1, ShouldBeLessThanOrEqualTo, 1)) - pass(t, so(1.1, ShouldBeLessThanOrEqualTo, 1.1)) - pass(t, so(uint(1), ShouldBeLessThanOrEqualTo, 1)) - pass(t, so("b", ShouldBeLessThanOrEqualTo, "b")) - - pass(t, so(0, ShouldBeLessThanOrEqualTo, 1)) - pass(t, so(1, ShouldBeLessThanOrEqualTo, 1.1)) - pass(t, so(uint(0), ShouldBeLessThanOrEqualTo, 1)) - pass(t, so("a", ShouldBeLessThanOrEqualTo, "b")) - - fail(t, so(1, ShouldBeLessThanOrEqualTo, 0), "Expected '1' to be less than '0' (but it wasn't)!") - fail(t, so(1.1, ShouldBeLessThanOrEqualTo, 1), "Expected '1.1' to be less than '1' (but it wasn't)!") - fail(t, so(1.1, ShouldBeLessThanOrEqualTo, uint(0)), "Expected '1.1' to be less than '0' (but it wasn't)!") - fail(t, so("b", ShouldBeLessThanOrEqualTo, "a"), "Expected 'b' to be less than 'a' (but it wasn't)!") -} - -func TestShouldBeBetween(t *testing.T) { - fail(t, so(1, ShouldBeBetween), "This assertion requires exactly 2 comparison values (you provided 0).") - fail(t, so(1, ShouldBeBetween, 1, 2, 3), "This assertion requires exactly 2 comparison values (you provided 3).") - - fail(t, so(4, ShouldBeBetween, 1, 1), "The lower and upper bounds must be different values (they were both '1').") - - fail(t, so(7, ShouldBeBetween, 8, 12), "Expected '7' to be between '8' and '12' (but it wasn't)!") - fail(t, so(8, ShouldBeBetween, 8, 12), "Expected '8' to be between '8' and '12' (but it wasn't)!") - pass(t, so(9, ShouldBeBetween, 8, 12)) - pass(t, so(10, ShouldBeBetween, 8, 12)) - pass(t, so(11, ShouldBeBetween, 8, 12)) - fail(t, so(12, ShouldBeBetween, 8, 12), "Expected '12' to be between '8' and '12' (but it wasn't)!") - fail(t, so(13, ShouldBeBetween, 8, 12), "Expected '13' to be between '8' and '12' (but it wasn't)!") - - pass(t, so(1, ShouldBeBetween, 2, 0)) - fail(t, so(-1, ShouldBeBetween, 2, 0), "Expected '-1' to be between '0' and '2' (but it wasn't)!") -} - -func TestShouldNotBeBetween(t *testing.T) { - fail(t, so(1, ShouldNotBeBetween), "This assertion requires exactly 2 comparison values (you provided 0).") - fail(t, so(1, ShouldNotBeBetween, 1, 2, 3), "This assertion requires exactly 2 comparison values (you provided 3).") - - fail(t, so(4, ShouldNotBeBetween, 1, 1), "The lower and upper bounds must be different values (they were both '1').") - - pass(t, so(7, ShouldNotBeBetween, 8, 12)) - pass(t, so(8, ShouldNotBeBetween, 8, 12)) - fail(t, so(9, ShouldNotBeBetween, 8, 12), "Expected '9' NOT to be between '8' and '12' (but it was)!") - fail(t, so(10, ShouldNotBeBetween, 8, 12), "Expected '10' NOT to be between '8' and '12' (but it was)!") - fail(t, so(11, ShouldNotBeBetween, 8, 12), "Expected '11' NOT to be between '8' and '12' (but it was)!") - pass(t, so(12, ShouldNotBeBetween, 8, 12)) - pass(t, so(13, ShouldNotBeBetween, 8, 12)) - - pass(t, so(-1, ShouldNotBeBetween, 2, 0)) - fail(t, so(1, ShouldNotBeBetween, 2, 0), "Expected '1' NOT to be between '0' and '2' (but it was)!") -} - -func TestShouldBeBetweenOrEqual(t *testing.T) { - fail(t, so(1, ShouldBeBetweenOrEqual), "This assertion requires exactly 2 comparison values (you provided 0).") - fail(t, so(1, ShouldBeBetweenOrEqual, 1, 2, 3), "This assertion requires exactly 2 comparison values (you provided 3).") - - fail(t, so(4, ShouldBeBetweenOrEqual, 1, 1), "The lower and upper bounds must be different values (they were both '1').") - - fail(t, so(7, ShouldBeBetweenOrEqual, 8, 12), "Expected '7' to be between '8' and '12' or equal to one of them (but it wasn't)!") - pass(t, so(8, ShouldBeBetweenOrEqual, 8, 12)) - pass(t, so(9, ShouldBeBetweenOrEqual, 8, 12)) - pass(t, so(10, ShouldBeBetweenOrEqual, 8, 12)) - pass(t, so(11, ShouldBeBetweenOrEqual, 8, 12)) - pass(t, so(12, ShouldBeBetweenOrEqual, 8, 12)) - fail(t, so(13, ShouldBeBetweenOrEqual, 8, 12), "Expected '13' to be between '8' and '12' or equal to one of them (but it wasn't)!") - - pass(t, so(1, ShouldBeBetweenOrEqual, 2, 0)) - fail(t, so(-1, ShouldBeBetweenOrEqual, 2, 0), "Expected '-1' to be between '0' and '2' or equal to one of them (but it wasn't)!") -} - -func TestShouldNotBeBetweenOrEqual(t *testing.T) { - fail(t, so(1, ShouldNotBeBetweenOrEqual), "This assertion requires exactly 2 comparison values (you provided 0).") - fail(t, so(1, ShouldNotBeBetweenOrEqual, 1, 2, 3), "This assertion requires exactly 2 comparison values (you provided 3).") - - fail(t, so(4, ShouldNotBeBetweenOrEqual, 1, 1), "The lower and upper bounds must be different values (they were both '1').") - - pass(t, so(7, ShouldNotBeBetweenOrEqual, 8, 12)) - fail(t, so(8, ShouldNotBeBetweenOrEqual, 8, 12), "Expected '8' NOT to be between '8' and '12' or equal to one of them (but it was)!") - fail(t, so(9, ShouldNotBeBetweenOrEqual, 8, 12), "Expected '9' NOT to be between '8' and '12' or equal to one of them (but it was)!") - fail(t, so(10, ShouldNotBeBetweenOrEqual, 8, 12), "Expected '10' NOT to be between '8' and '12' or equal to one of them (but it was)!") - fail(t, so(11, ShouldNotBeBetweenOrEqual, 8, 12), "Expected '11' NOT to be between '8' and '12' or equal to one of them (but it was)!") - fail(t, so(12, ShouldNotBeBetweenOrEqual, 8, 12), "Expected '12' NOT to be between '8' and '12' or equal to one of them (but it was)!") - pass(t, so(13, ShouldNotBeBetweenOrEqual, 8, 12)) - - pass(t, so(-1, ShouldNotBeBetweenOrEqual, 2, 0)) - fail(t, so(1, ShouldNotBeBetweenOrEqual, 2, 0), "Expected '1' NOT to be between '0' and '2' or equal to one of them (but it was)!") -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/serializer.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/serializer.go deleted file mode 100644 index 02ea708..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/serializer.go +++ /dev/null @@ -1,59 +0,0 @@ -package assertions - -import ( - "encoding/json" - "fmt" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting" -) - -type Serializer interface { - serialize(expected, actual interface{}, message string) string - serializeDetailed(expected, actual interface{}, message string) string -} - -type failureSerializer struct{} - -func (self *failureSerializer) serializeDetailed(expected, actual interface{}, message string) string { - view := self.format(expected, actual, message, "%#v") - serialized, err := json.Marshal(view) - if err != nil { - return message - } - return string(serialized) -} - -func (self *failureSerializer) serialize(expected, actual interface{}, message string) string { - view := self.format(expected, actual, message, "%+v") - serialized, err := json.Marshal(view) - if err != nil { - return message - } - return string(serialized) -} - -func (self *failureSerializer) format(expected, actual interface{}, message string, format string) reporting.FailureView { - return reporting.FailureView{ - Message: message, - Expected: fmt.Sprintf(format, expected), - Actual: fmt.Sprintf(format, actual), - } -} - -func newSerializer() *failureSerializer { - return &failureSerializer{} -} - -/////////////////////////////////////////////////////// - -// noopSerializer just gives back the original message. This is useful when we are using -// the assertions from a context other than the web UI, that requires the JSON structure -// provided by the failureSerializer. -type noopSerializer struct{} - -func (self *noopSerializer) serialize(expected, actual interface{}, message string) string { - return message -} -func (self *noopSerializer) serializeDetailed(expected, actual interface{}, message string) string { - return message -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/serializer_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/serializer_test.go deleted file mode 100644 index 34e143d..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/serializer_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package assertions - -import ( - "encoding/json" - "fmt" - "testing" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting" -) - -func TestSerializerCreatesSerializedVersionOfAssertionResult(t *testing.T) { - thing1 := Thing1{"Hi"} - thing2 := Thing2{"Bye"} - message := "Super-hip failure message." - serializer := newSerializer() - - actualResult := serializer.serialize(thing1, thing2, message) - - expectedResult, _ := json.Marshal(reporting.FailureView{ - Message: message, - Expected: fmt.Sprintf("%+v", thing1), - Actual: fmt.Sprintf("%+v", thing2), - }) - - if actualResult != string(expectedResult) { - t.Errorf("\nExpected: %s\nActual: %s", string(expectedResult), actualResult) - } - - actualResult = serializer.serializeDetailed(thing1, thing2, message) - expectedResult, _ = json.Marshal(reporting.FailureView{ - Message: message, - Expected: fmt.Sprintf("%#v", thing1), - Actual: fmt.Sprintf("%#v", thing2), - }) - if actualResult != string(expectedResult) { - t.Errorf("\nExpected: %s\nActual: %s", string(expectedResult), actualResult) - } -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/strings.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/strings.go deleted file mode 100644 index 1b887b1..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/strings.go +++ /dev/null @@ -1,183 +0,0 @@ -package assertions - -import ( - "fmt" - "reflect" - "strings" -) - -// ShouldStartWith receives exactly 2 string parameters and ensures that the first starts with the second. -func ShouldStartWith(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - value, valueIsString := actual.(string) - prefix, prefixIsString := expected[0].(string) - - if !valueIsString || !prefixIsString { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - return shouldStartWith(value, prefix) -} -func shouldStartWith(value, prefix string) string { - if !strings.HasPrefix(value, prefix) { - shortval := value - if len(shortval) > len(prefix) { - shortval = shortval[:len(prefix)] + "..." - } - return serializer.serialize(prefix, shortval, fmt.Sprintf(shouldHaveStartedWith, value, prefix)) - } - return success -} - -// ShouldNotStartWith receives exactly 2 string parameters and ensures that the first does not start with the second. -func ShouldNotStartWith(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - value, valueIsString := actual.(string) - prefix, prefixIsString := expected[0].(string) - - if !valueIsString || !prefixIsString { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - return shouldNotStartWith(value, prefix) -} -func shouldNotStartWith(value, prefix string) string { - if strings.HasPrefix(value, prefix) { - if value == "" { - value = "" - } - if prefix == "" { - prefix = "" - } - return fmt.Sprintf(shouldNotHaveStartedWith, value, prefix) - } - return success -} - -// ShouldEndWith receives exactly 2 string parameters and ensures that the first ends with the second. -func ShouldEndWith(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - value, valueIsString := actual.(string) - suffix, suffixIsString := expected[0].(string) - - if !valueIsString || !suffixIsString { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - return shouldEndWith(value, suffix) -} -func shouldEndWith(value, suffix string) string { - if !strings.HasSuffix(value, suffix) { - shortval := value - if len(shortval) > len(suffix) { - shortval = "..." + shortval[len(shortval)-len(suffix):] - } - return serializer.serialize(suffix, shortval, fmt.Sprintf(shouldHaveEndedWith, value, suffix)) - } - return success -} - -// ShouldEndWith receives exactly 2 string parameters and ensures that the first does not end with the second. -func ShouldNotEndWith(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - value, valueIsString := actual.(string) - suffix, suffixIsString := expected[0].(string) - - if !valueIsString || !suffixIsString { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - return shouldNotEndWith(value, suffix) -} -func shouldNotEndWith(value, suffix string) string { - if strings.HasSuffix(value, suffix) { - if value == "" { - value = "" - } - if suffix == "" { - suffix = "" - } - return fmt.Sprintf(shouldNotHaveEndedWith, value, suffix) - } - return success -} - -// ShouldContainSubstring receives exactly 2 string parameters and ensures that the first contains the second as a substring. -func ShouldContainSubstring(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - long, longOk := actual.(string) - short, shortOk := expected[0].(string) - - if !longOk || !shortOk { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - if !strings.Contains(long, short) { - return serializer.serialize(expected[0], actual, fmt.Sprintf(shouldHaveContainedSubstring, long, short)) - } - return success -} - -// ShouldNotContainSubstring receives exactly 2 string parameters and ensures that the first does NOT contain the second as a substring. -func ShouldNotContainSubstring(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - long, longOk := actual.(string) - short, shortOk := expected[0].(string) - - if !longOk || !shortOk { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - if strings.Contains(long, short) { - return fmt.Sprintf(shouldNotHaveContainedSubstring, long, short) - } - return success -} - -// ShouldBeBlank receives exactly 1 string parameter and ensures that it is equal to "". -func ShouldBeBlank(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - value, ok := actual.(string) - if !ok { - return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual)) - } - if value != "" { - return serializer.serialize("", value, fmt.Sprintf(shouldHaveBeenBlank, value)) - } - return success -} - -// ShouldNotBeBlank receives exactly 1 string parameter and ensures that it is equal to "". -func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - value, ok := actual.(string) - if !ok { - return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual)) - } - if value == "" { - return shouldNotHaveBeenBlank - } - return success -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/strings_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/strings_test.go deleted file mode 100644 index eec9440..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/strings_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package assertions - -import "testing" - -func TestShouldStartWith(t *testing.T) { - serializer = newFakeSerializer() - - fail(t, so("", ShouldStartWith), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so("", ShouldStartWith, "asdf", "asdf"), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so("", ShouldStartWith, "")) - fail(t, so("", ShouldStartWith, "x"), "x||Expected '' to start with 'x' (but it didn't)!") - pass(t, so("abc", ShouldStartWith, "abc")) - fail(t, so("abc", ShouldStartWith, "abcd"), "abcd|abc|Expected 'abc' to start with 'abcd' (but it didn't)!") - - pass(t, so("superman", ShouldStartWith, "super")) - fail(t, so("superman", ShouldStartWith, "bat"), "bat|sup...|Expected 'superman' to start with 'bat' (but it didn't)!") - fail(t, so("superman", ShouldStartWith, "man"), "man|sup...|Expected 'superman' to start with 'man' (but it didn't)!") - - fail(t, so(1, ShouldStartWith, 2), "Both arguments to this assertion must be strings (you provided int and int).") -} - -func TestShouldNotStartWith(t *testing.T) { - fail(t, so("", ShouldNotStartWith), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so("", ShouldNotStartWith, "asdf", "asdf"), "This assertion requires exactly 1 comparison values (you provided 2).") - - fail(t, so("", ShouldNotStartWith, ""), "Expected '' NOT to start with '' (but it did)!") - fail(t, so("superman", ShouldNotStartWith, "super"), "Expected 'superman' NOT to start with 'super' (but it did)!") - pass(t, so("superman", ShouldNotStartWith, "bat")) - pass(t, so("superman", ShouldNotStartWith, "man")) - - fail(t, so(1, ShouldNotStartWith, 2), "Both arguments to this assertion must be strings (you provided int and int).") -} - -func TestShouldEndWith(t *testing.T) { - serializer = newFakeSerializer() - - fail(t, so("", ShouldEndWith), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so("", ShouldEndWith, "", ""), "This assertion requires exactly 1 comparison values (you provided 2).") - - pass(t, so("", ShouldEndWith, "")) - fail(t, so("", ShouldEndWith, "z"), "z||Expected '' to end with 'z' (but it didn't)!") - pass(t, so("xyz", ShouldEndWith, "xyz")) - fail(t, so("xyz", ShouldEndWith, "wxyz"), "wxyz|xyz|Expected 'xyz' to end with 'wxyz' (but it didn't)!") - - pass(t, so("superman", ShouldEndWith, "man")) - fail(t, so("superman", ShouldEndWith, "super"), "super|...erman|Expected 'superman' to end with 'super' (but it didn't)!") - fail(t, so("superman", ShouldEndWith, "blah"), "blah|...rman|Expected 'superman' to end with 'blah' (but it didn't)!") - - fail(t, so(1, ShouldEndWith, 2), "Both arguments to this assertion must be strings (you provided int and int).") -} - -func TestShouldNotEndWith(t *testing.T) { - fail(t, so("", ShouldNotEndWith), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so("", ShouldNotEndWith, "", ""), "This assertion requires exactly 1 comparison values (you provided 2).") - - fail(t, so("", ShouldNotEndWith, ""), "Expected '' NOT to end with '' (but it did)!") - fail(t, so("superman", ShouldNotEndWith, "man"), "Expected 'superman' NOT to end with 'man' (but it did)!") - pass(t, so("superman", ShouldNotEndWith, "super")) - - fail(t, so(1, ShouldNotEndWith, 2), "Both arguments to this assertion must be strings (you provided int and int).") -} - -func TestShouldContainSubstring(t *testing.T) { - serializer = newFakeSerializer() - - fail(t, so("asdf", ShouldContainSubstring), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so("asdf", ShouldContainSubstring, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(123, ShouldContainSubstring, 23), "Both arguments to this assertion must be strings (you provided int and int).") - - pass(t, so("asdf", ShouldContainSubstring, "sd")) - fail(t, so("qwer", ShouldContainSubstring, "sd"), "sd|qwer|Expected 'qwer' to contain substring 'sd' (but it didn't)!") -} - -func TestShouldNotContainSubstring(t *testing.T) { - fail(t, so("asdf", ShouldNotContainSubstring), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so("asdf", ShouldNotContainSubstring, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(123, ShouldNotContainSubstring, 23), "Both arguments to this assertion must be strings (you provided int and int).") - - pass(t, so("qwer", ShouldNotContainSubstring, "sd")) - fail(t, so("asdf", ShouldNotContainSubstring, "sd"), "Expected 'asdf' NOT to contain substring 'sd' (but it didn't)!") -} - -func TestShouldBeBlank(t *testing.T) { - serializer = newFakeSerializer() - - fail(t, so("", ShouldBeBlank, "adsf"), "This assertion requires exactly 0 comparison values (you provided 1).") - fail(t, so(1, ShouldBeBlank), "The argument to this assertion must be a string (you provided int).") - - fail(t, so("asdf", ShouldBeBlank), "|asdf|Expected 'asdf' to be blank (but it wasn't)!") - pass(t, so("", ShouldBeBlank)) -} - -func TestShouldNotBeBlank(t *testing.T) { - fail(t, so("", ShouldNotBeBlank, "adsf"), "This assertion requires exactly 0 comparison values (you provided 1).") - fail(t, so(1, ShouldNotBeBlank), "The argument to this assertion must be a string (you provided int).") - - fail(t, so("", ShouldNotBeBlank), "Expected value to NOT be blank (but it was)!") - pass(t, so("asdf", ShouldNotBeBlank)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/time.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/time.go deleted file mode 100644 index 7e05026..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/time.go +++ /dev/null @@ -1,202 +0,0 @@ -package assertions - -import ( - "fmt" - "time" -) - -// ShouldHappenBefore receives exactly 2 time.Time arguments and asserts that the first happens before the second. -func ShouldHappenBefore(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - expectedTime, secondOk := expected[0].(time.Time) - - if !firstOk || !secondOk { - return shouldUseTimes - } - - if !actualTime.Before(expectedTime) { - return fmt.Sprintf(shouldHaveHappenedBefore, actualTime, expectedTime, actualTime.Sub(expectedTime)) - } - - return success -} - -// ShouldHappenOnOrBefore receives exactly 2 time.Time arguments and asserts that the first happens on or before the second. -func ShouldHappenOnOrBefore(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - expectedTime, secondOk := expected[0].(time.Time) - - if !firstOk || !secondOk { - return shouldUseTimes - } - - if actualTime.Equal(expectedTime) { - return success - } - return ShouldHappenBefore(actualTime, expectedTime) -} - -// ShouldHappenAfter receives exactly 2 time.Time arguments and asserts that the first happens after the second. -func ShouldHappenAfter(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - expectedTime, secondOk := expected[0].(time.Time) - - if !firstOk || !secondOk { - return shouldUseTimes - } - if !actualTime.After(expectedTime) { - return fmt.Sprintf(shouldHaveHappenedAfter, actualTime, expectedTime, expectedTime.Sub(actualTime)) - } - return success -} - -// ShouldHappenOnOrAfter receives exactly 2 time.Time arguments and asserts that the first happens on or after the second. -func ShouldHappenOnOrAfter(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - expectedTime, secondOk := expected[0].(time.Time) - - if !firstOk || !secondOk { - return shouldUseTimes - } - if actualTime.Equal(expectedTime) { - return success - } - return ShouldHappenAfter(actualTime, expectedTime) -} - -// ShouldHappenBetween receives exactly 3 time.Time arguments and asserts that the first happens between (not on) the second and third. -func ShouldHappenBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - min, secondOk := expected[0].(time.Time) - max, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseTimes - } - - if !actualTime.After(min) { - return fmt.Sprintf(shouldHaveHappenedBetween, actualTime, min, max, min.Sub(actualTime)) - } - if !actualTime.Before(max) { - return fmt.Sprintf(shouldHaveHappenedBetween, actualTime, min, max, actualTime.Sub(max)) - } - return success -} - -// ShouldHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that the first happens between or on the second and third. -func ShouldHappenOnOrBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - min, secondOk := expected[0].(time.Time) - max, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseTimes - } - if actualTime.Equal(min) || actualTime.Equal(max) { - return success - } - return ShouldHappenBetween(actualTime, min, max) -} - -// ShouldNotHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that the first -// does NOT happen between or on the second or third. -func ShouldNotHappenOnOrBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - min, secondOk := expected[0].(time.Time) - max, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseTimes - } - if actualTime.Equal(min) || actualTime.Equal(max) { - return fmt.Sprintf(shouldNotHaveHappenedOnOrBetween, actualTime, min, max) - } - if actualTime.After(min) && actualTime.Before(max) { - return fmt.Sprintf(shouldNotHaveHappenedOnOrBetween, actualTime, min, max) - } - return success -} - -// ShouldHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 arguments) -// and asserts that the first time.Time happens within or on the duration specified relative to -// the other time.Time. -func ShouldHappenWithin(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - tolerance, secondOk := expected[0].(time.Duration) - threshold, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseDurationAndTime - } - - min := threshold.Add(-tolerance) - max := threshold.Add(tolerance) - return ShouldHappenOnOrBetween(actualTime, min, max) -} - -// ShouldNotHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 arguments) -// and asserts that the first time.Time does NOT happen within or on the duration specified relative to -// the other time.Time. -func ShouldNotHappenWithin(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - tolerance, secondOk := expected[0].(time.Duration) - threshold, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseDurationAndTime - } - - min := threshold.Add(-tolerance) - max := threshold.Add(tolerance) - return ShouldNotHappenOnOrBetween(actualTime, min, max) -} - -// ShouldBeChronological receives a []time.Time slice and asserts that the are -// in chronological order starting with the first time.Time as the earliest. -func ShouldBeChronological(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - - times, ok := actual.([]time.Time) - if !ok { - return shouldUseTimeSlice - } - - var previous time.Time - for i, current := range times { - if i > 0 && current.Before(previous) { - return fmt.Sprintf(shouldHaveBeenChronological, - i, i-1, previous.String(), i, current.String()) - } - previous = current - } - return "" -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/time_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/time_test.go deleted file mode 100644 index f9dda8f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/time_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package assertions - -import ( - "fmt" - "testing" - "time" -) - -func TestShouldHappenBefore(t *testing.T) { - fail(t, so(0, ShouldHappenBefore), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(0, ShouldHappenBefore, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(0, ShouldHappenBefore, 1), shouldUseTimes) - fail(t, so(0, ShouldHappenBefore, time.Now()), shouldUseTimes) - fail(t, so(time.Now(), ShouldHappenBefore, 0), shouldUseTimes) - - fail(t, so(january3, ShouldHappenBefore, january1), fmt.Sprintf("Expected '%s' to happen before '%s' (it happened '48h0m0s' after)!", pretty(january3), pretty(january1))) - fail(t, so(january3, ShouldHappenBefore, january3), fmt.Sprintf("Expected '%s' to happen before '%s' (it happened '0' after)!", pretty(january3), pretty(january3))) - pass(t, so(january1, ShouldHappenBefore, january3)) -} - -func TestShouldHappenOnOrBefore(t *testing.T) { - fail(t, so(0, ShouldHappenOnOrBefore), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(0, ShouldHappenOnOrBefore, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(0, ShouldHappenOnOrBefore, 1), shouldUseTimes) - fail(t, so(0, ShouldHappenOnOrBefore, time.Now()), shouldUseTimes) - fail(t, so(time.Now(), ShouldHappenOnOrBefore, 0), shouldUseTimes) - - fail(t, so(january3, ShouldHappenOnOrBefore, january1), fmt.Sprintf("Expected '%s' to happen before '%s' (it happened '48h0m0s' after)!", pretty(january3), pretty(january1))) - pass(t, so(january3, ShouldHappenOnOrBefore, january3)) - pass(t, so(january1, ShouldHappenOnOrBefore, january3)) -} - -func TestShouldHappenAfter(t *testing.T) { - fail(t, so(0, ShouldHappenAfter), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(0, ShouldHappenAfter, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(0, ShouldHappenAfter, 1), shouldUseTimes) - fail(t, so(0, ShouldHappenAfter, time.Now()), shouldUseTimes) - fail(t, so(time.Now(), ShouldHappenAfter, 0), shouldUseTimes) - - fail(t, so(january1, ShouldHappenAfter, january2), fmt.Sprintf("Expected '%s' to happen after '%s' (it happened '24h0m0s' before)!", pretty(january1), pretty(january2))) - fail(t, so(january1, ShouldHappenAfter, january1), fmt.Sprintf("Expected '%s' to happen after '%s' (it happened '0' before)!", pretty(january1), pretty(january1))) - pass(t, so(january3, ShouldHappenAfter, january1)) -} - -func TestShouldHappenOnOrAfter(t *testing.T) { - fail(t, so(0, ShouldHappenOnOrAfter), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(0, ShouldHappenOnOrAfter, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(0, ShouldHappenOnOrAfter, 1), shouldUseTimes) - fail(t, so(0, ShouldHappenOnOrAfter, time.Now()), shouldUseTimes) - fail(t, so(time.Now(), ShouldHappenOnOrAfter, 0), shouldUseTimes) - - fail(t, so(january1, ShouldHappenOnOrAfter, january2), fmt.Sprintf("Expected '%s' to happen after '%s' (it happened '24h0m0s' before)!", pretty(january1), pretty(january2))) - pass(t, so(january1, ShouldHappenOnOrAfter, january1)) - pass(t, so(january3, ShouldHappenOnOrAfter, january1)) -} - -func TestShouldHappenBetween(t *testing.T) { - fail(t, so(0, ShouldHappenBetween), "This assertion requires exactly 2 comparison values (you provided 0).") - fail(t, so(0, ShouldHappenBetween, 1, 2, 3), "This assertion requires exactly 2 comparison values (you provided 3).") - - fail(t, so(0, ShouldHappenBetween, 1, 2), shouldUseTimes) - fail(t, so(0, ShouldHappenBetween, time.Now(), time.Now()), shouldUseTimes) - fail(t, so(time.Now(), ShouldHappenBetween, 0, time.Now()), shouldUseTimes) - fail(t, so(time.Now(), ShouldHappenBetween, time.Now(), 9), shouldUseTimes) - - fail(t, so(january1, ShouldHappenBetween, january2, january4), fmt.Sprintf("Expected '%s' to happen between '%s' and '%s' (it happened '24h0m0s' outside threshold)!", pretty(january1), pretty(january2), pretty(january4))) - fail(t, so(january2, ShouldHappenBetween, january2, january4), fmt.Sprintf("Expected '%s' to happen between '%s' and '%s' (it happened '0' outside threshold)!", pretty(january2), pretty(january2), pretty(january4))) - pass(t, so(january3, ShouldHappenBetween, january2, january4)) - fail(t, so(january4, ShouldHappenBetween, january2, january4), fmt.Sprintf("Expected '%s' to happen between '%s' and '%s' (it happened '0' outside threshold)!", pretty(january4), pretty(january2), pretty(january4))) - fail(t, so(january5, ShouldHappenBetween, january2, january4), fmt.Sprintf("Expected '%s' to happen between '%s' and '%s' (it happened '24h0m0s' outside threshold)!", pretty(january5), pretty(january2), pretty(january4))) -} - -func TestShouldHappenOnOrBetween(t *testing.T) { - fail(t, so(0, ShouldHappenOnOrBetween), "This assertion requires exactly 2 comparison values (you provided 0).") - fail(t, so(0, ShouldHappenOnOrBetween, 1, 2, 3), "This assertion requires exactly 2 comparison values (you provided 3).") - - fail(t, so(0, ShouldHappenOnOrBetween, 1, time.Now()), shouldUseTimes) - fail(t, so(0, ShouldHappenOnOrBetween, time.Now(), 1), shouldUseTimes) - fail(t, so(time.Now(), ShouldHappenOnOrBetween, 0, 1), shouldUseTimes) - - fail(t, so(january1, ShouldHappenOnOrBetween, january2, january4), fmt.Sprintf("Expected '%s' to happen between '%s' and '%s' (it happened '24h0m0s' outside threshold)!", pretty(january1), pretty(january2), pretty(january4))) - pass(t, so(january2, ShouldHappenOnOrBetween, january2, january4)) - pass(t, so(january3, ShouldHappenOnOrBetween, january2, january4)) - pass(t, so(january4, ShouldHappenOnOrBetween, january2, january4)) - fail(t, so(january5, ShouldHappenOnOrBetween, january2, january4), fmt.Sprintf("Expected '%s' to happen between '%s' and '%s' (it happened '24h0m0s' outside threshold)!", pretty(january5), pretty(january2), pretty(january4))) -} - -func TestShouldNotHappenOnOrBetween(t *testing.T) { - fail(t, so(0, ShouldNotHappenOnOrBetween), "This assertion requires exactly 2 comparison values (you provided 0).") - fail(t, so(0, ShouldNotHappenOnOrBetween, 1, 2, 3), "This assertion requires exactly 2 comparison values (you provided 3).") - - fail(t, so(0, ShouldNotHappenOnOrBetween, 1, time.Now()), shouldUseTimes) - fail(t, so(0, ShouldNotHappenOnOrBetween, time.Now(), 1), shouldUseTimes) - fail(t, so(time.Now(), ShouldNotHappenOnOrBetween, 0, 1), shouldUseTimes) - - pass(t, so(january1, ShouldNotHappenOnOrBetween, january2, january4)) - fail(t, so(january2, ShouldNotHappenOnOrBetween, january2, january4), fmt.Sprintf("Expected '%s' to NOT happen on or between '%s' and '%s' (but it did)!", pretty(january2), pretty(january2), pretty(january4))) - fail(t, so(january3, ShouldNotHappenOnOrBetween, january2, january4), fmt.Sprintf("Expected '%s' to NOT happen on or between '%s' and '%s' (but it did)!", pretty(january3), pretty(january2), pretty(january4))) - fail(t, so(january4, ShouldNotHappenOnOrBetween, january2, january4), fmt.Sprintf("Expected '%s' to NOT happen on or between '%s' and '%s' (but it did)!", pretty(january4), pretty(january2), pretty(january4))) - pass(t, so(january5, ShouldNotHappenOnOrBetween, january2, january4)) -} - -func TestShouldHappenWithin(t *testing.T) { - fail(t, so(0, ShouldHappenWithin), "This assertion requires exactly 2 comparison values (you provided 0).") - fail(t, so(0, ShouldHappenWithin, 1, 2, 3), "This assertion requires exactly 2 comparison values (you provided 3).") - - fail(t, so(0, ShouldHappenWithin, 1, 2), shouldUseDurationAndTime) - fail(t, so(0, ShouldHappenWithin, oneDay, time.Now()), shouldUseDurationAndTime) - fail(t, so(time.Now(), ShouldHappenWithin, 0, time.Now()), shouldUseDurationAndTime) - - fail(t, so(january1, ShouldHappenWithin, oneDay, january3), fmt.Sprintf("Expected '%s' to happen between '%s' and '%s' (it happened '24h0m0s' outside threshold)!", pretty(january1), pretty(january2), pretty(january4))) - pass(t, so(january2, ShouldHappenWithin, oneDay, january3)) - pass(t, so(january3, ShouldHappenWithin, oneDay, january3)) - pass(t, so(january4, ShouldHappenWithin, oneDay, january3)) - fail(t, so(january5, ShouldHappenWithin, oneDay, january3), fmt.Sprintf("Expected '%s' to happen between '%s' and '%s' (it happened '24h0m0s' outside threshold)!", pretty(january5), pretty(january2), pretty(january4))) -} - -func TestShouldNotHappenWithin(t *testing.T) { - fail(t, so(0, ShouldNotHappenWithin), "This assertion requires exactly 2 comparison values (you provided 0).") - fail(t, so(0, ShouldNotHappenWithin, 1, 2, 3), "This assertion requires exactly 2 comparison values (you provided 3).") - - fail(t, so(0, ShouldNotHappenWithin, 1, 2), shouldUseDurationAndTime) - fail(t, so(0, ShouldNotHappenWithin, oneDay, time.Now()), shouldUseDurationAndTime) - fail(t, so(time.Now(), ShouldNotHappenWithin, 0, time.Now()), shouldUseDurationAndTime) - - pass(t, so(january1, ShouldNotHappenWithin, oneDay, january3)) - fail(t, so(january2, ShouldNotHappenWithin, oneDay, january3), fmt.Sprintf("Expected '%s' to NOT happen on or between '%s' and '%s' (but it did)!", pretty(january2), pretty(january2), pretty(january4))) - fail(t, so(january3, ShouldNotHappenWithin, oneDay, january3), fmt.Sprintf("Expected '%s' to NOT happen on or between '%s' and '%s' (but it did)!", pretty(january3), pretty(january2), pretty(january4))) - fail(t, so(january4, ShouldNotHappenWithin, oneDay, january3), fmt.Sprintf("Expected '%s' to NOT happen on or between '%s' and '%s' (but it did)!", pretty(january4), pretty(january2), pretty(january4))) - pass(t, so(january5, ShouldNotHappenWithin, oneDay, january3)) -} - -func TestShouldBeChronological(t *testing.T) { - fail(t, so(0, ShouldBeChronological, 1, 2, 3), "This assertion requires exactly 0 comparison values (you provided 3).") - fail(t, so(0, ShouldBeChronological), shouldUseTimeSlice) - fail(t, so([]time.Time{january5, january1}, ShouldBeChronological), - "The 'Time' at index [1] should have happened after the previous one (but it didn't!):\n [0]: 2013-01-05 00:00:00 +0000 UTC\n [1]: 2013-01-01 00:00:00 +0000 UTC (see, it happened before!)") - - pass(t, so([]time.Time{january1, january2, january3, january4, january5}, ShouldBeChronological)) -} - -const layout = "2006-01-02 15:04" - -var january1, _ = time.Parse(layout, "2013-01-01 00:00") -var january2, _ = time.Parse(layout, "2013-01-02 00:00") -var january3, _ = time.Parse(layout, "2013-01-03 00:00") -var january4, _ = time.Parse(layout, "2013-01-04 00:00") -var january5, _ = time.Parse(layout, "2013-01-05 00:00") - -var oneDay, _ = time.ParseDuration("24h0m0s") -var twoDays, _ = time.ParseDuration("48h0m0s") - -func pretty(t time.Time) string { - return fmt.Sprintf("%v", t) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/type.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/type.go deleted file mode 100644 index 3fc00f6..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/type.go +++ /dev/null @@ -1,112 +0,0 @@ -package assertions - -import ( - "fmt" - "reflect" -) - -// ShouldHaveSameTypeAs receives exactly two parameters and compares their underlying types for equality. -func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - first := reflect.TypeOf(actual) - second := reflect.TypeOf(expected[0]) - - if equal := ShouldEqual(first, second); equal != success { - return serializer.serialize(second, first, fmt.Sprintf(shouldHaveBeenA, actual, second, first)) - } - return success -} - -// ShouldNotHaveSameTypeAs receives exactly two parameters and compares their underlying types for inequality. -func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - first := reflect.TypeOf(actual) - second := reflect.TypeOf(expected[0]) - - if equal := ShouldEqual(first, second); equal == success { - return fmt.Sprintf(shouldNotHaveBeenA, actual, second) - } - return success -} - -// ShouldImplement receives exactly two parameters and ensures -// that the first implements the interface type of the second. -func ShouldImplement(actual interface{}, expectedList ...interface{}) string { - if fail := need(1, expectedList); fail != success { - return fail - } - - expected := expectedList[0] - if fail := ShouldBeNil(expected); fail != success { - return shouldCompareWithInterfacePointer - } - - if fail := ShouldNotBeNil(actual); fail != success { - return shouldNotBeNilActual - } - - var actualType reflect.Type - if reflect.TypeOf(actual).Kind() != reflect.Ptr { - actualType = reflect.PtrTo(reflect.TypeOf(actual)) - } else { - actualType = reflect.TypeOf(actual) - } - - expectedType := reflect.TypeOf(expected) - if fail := ShouldNotBeNil(expectedType); fail != success { - return shouldCompareWithInterfacePointer - } - - expectedInterface := expectedType.Elem() - - if actualType == nil { - return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actual) - } - - if !actualType.Implements(expectedInterface) { - return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType) - } - return success -} - -// ShouldNotImplement receives exactly two parameters and ensures -// that the first does NOT implement the interface type of the second. -func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string { - if fail := need(1, expectedList); fail != success { - return fail - } - - expected := expectedList[0] - if fail := ShouldBeNil(expected); fail != success { - return shouldCompareWithInterfacePointer - } - - if fail := ShouldNotBeNil(actual); fail != success { - return shouldNotBeNilActual - } - - var actualType reflect.Type - if reflect.TypeOf(actual).Kind() != reflect.Ptr { - actualType = reflect.PtrTo(reflect.TypeOf(actual)) - } else { - actualType = reflect.TypeOf(actual) - } - - expectedType := reflect.TypeOf(expected) - if fail := ShouldNotBeNil(expectedType); fail != success { - return shouldCompareWithInterfacePointer - } - - expectedInterface := expectedType.Elem() - - if actualType.Implements(expectedInterface) { - return fmt.Sprintf(shouldNotHaveImplemented, actualType, expectedInterface) - } - return success -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/type_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/type_test.go deleted file mode 100644 index 4b8d198..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/type_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package assertions - -import ( - "bytes" - "io" - "net/http" - "testing" -) - -func TestShouldHaveSameTypeAs(t *testing.T) { - serializer = newFakeSerializer() - - fail(t, so(1, ShouldHaveSameTypeAs), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(1, ShouldHaveSameTypeAs, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(nil, ShouldHaveSameTypeAs, 0), "int||Expected '' to be: 'int' (but was: '')!") - fail(t, so(1, ShouldHaveSameTypeAs, "asdf"), "string|int|Expected '1' to be: 'string' (but was: 'int')!") - - pass(t, so(1, ShouldHaveSameTypeAs, 0)) - pass(t, so(nil, ShouldHaveSameTypeAs, nil)) -} - -func TestShouldNotHaveSameTypeAs(t *testing.T) { - fail(t, so(1, ShouldNotHaveSameTypeAs), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(1, ShouldNotHaveSameTypeAs, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(1, ShouldNotHaveSameTypeAs, 0), "Expected '1' to NOT be: 'int' (but it was)!") - fail(t, so(nil, ShouldNotHaveSameTypeAs, nil), "Expected '' to NOT be: '' (but it was)!") - - pass(t, so(nil, ShouldNotHaveSameTypeAs, 0)) - pass(t, so(1, ShouldNotHaveSameTypeAs, "asdf")) -} - -func TestShouldImplement(t *testing.T) { - var ioReader *io.Reader = nil - var response http.Response = http.Response{} - var responsePtr *http.Response = new(http.Response) - var reader = bytes.NewBufferString("") - - fail(t, so(reader, ShouldImplement), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(reader, ShouldImplement, ioReader, ioReader), "This assertion requires exactly 1 comparison values (you provided 2).") - fail(t, so(reader, ShouldImplement, ioReader, ioReader, ioReader), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(reader, ShouldImplement, "foo"), shouldCompareWithInterfacePointer) - fail(t, so(reader, ShouldImplement, 1), shouldCompareWithInterfacePointer) - fail(t, so(reader, ShouldImplement, nil), shouldCompareWithInterfacePointer) - - fail(t, so(nil, ShouldImplement, ioReader), shouldNotBeNilActual) - fail(t, so(1, ShouldImplement, ioReader), "Expected: 'io.Reader interface support'\nActual: '*int' does not implement the interface!") - - fail(t, so(response, ShouldImplement, ioReader), "Expected: 'io.Reader interface support'\nActual: '*http.Response' does not implement the interface!") - fail(t, so(responsePtr, ShouldImplement, ioReader), "Expected: 'io.Reader interface support'\nActual: '*http.Response' does not implement the interface!") - pass(t, so(reader, ShouldImplement, ioReader)) - pass(t, so(reader, ShouldImplement, (*io.Reader)(nil))) -} - -func TestShouldNotImplement(t *testing.T) { - var ioReader *io.Reader = nil - var response http.Response = http.Response{} - var responsePtr *http.Response = new(http.Response) - var reader io.Reader = bytes.NewBufferString("") - - fail(t, so(reader, ShouldNotImplement), "This assertion requires exactly 1 comparison values (you provided 0).") - fail(t, so(reader, ShouldNotImplement, ioReader, ioReader), "This assertion requires exactly 1 comparison values (you provided 2).") - fail(t, so(reader, ShouldNotImplement, ioReader, ioReader, ioReader), "This assertion requires exactly 1 comparison values (you provided 3).") - - fail(t, so(reader, ShouldNotImplement, "foo"), shouldCompareWithInterfacePointer) - fail(t, so(reader, ShouldNotImplement, 1), shouldCompareWithInterfacePointer) - fail(t, so(reader, ShouldNotImplement, nil), shouldCompareWithInterfacePointer) - - fail(t, so(reader, ShouldNotImplement, ioReader), "Expected '*bytes.Buffer'\nto NOT implement 'io.Reader' (but it did)!") - fail(t, so(nil, ShouldNotImplement, ioReader), shouldNotBeNilActual) - pass(t, so(1, ShouldNotImplement, ioReader)) - pass(t, so(response, ShouldNotImplement, ioReader)) - pass(t, so(responsePtr, ShouldNotImplement, ioReader)) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/assertions/utilities_for_test.go b/Godeps/_workspace/src/github.com/smartystreets/assertions/utilities_for_test.go deleted file mode 100644 index 7243ebc..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/assertions/utilities_for_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package assertions - -import ( - "fmt" - "path" - "runtime" - "strings" - "testing" -) - -func pass(t *testing.T, result string) { - if result != success { - _, file, line, _ := runtime.Caller(1) - base := path.Base(file) - t.Errorf("Expectation should have passed but failed (see %s: line %d): '%s'", base, line, result) - } -} - -func fail(t *testing.T, actual string, expected string) { - actual = format(actual) - expected = format(expected) - - if actual != expected { - if actual == "" { - actual = "(empty)" - } - _, file, line, _ := runtime.Caller(1) - base := path.Base(file) - t.Errorf("Expectation should have failed but passed (see %s: line %d). \nExpected: %s\nActual: %s\n", - base, line, expected, actual) - } -} -func format(message string) string { - message = strings.Replace(message, "\n", " ", -1) - for strings.Contains(message, " ") { - message = strings.Replace(message, " ", " ", -1) - } - return message -} - -type Thing1 struct { - a string -} -type Thing2 struct { - a string -} - -type Thinger interface { - Hi() -} - -type Thing struct{} - -func (self *Thing) Hi() {} - -type IntAlias int -type StringAlias string -type StringSliceAlias []string -type StringStringMapAlias map[string]string - -/******** FakeSerialzier ********/ - -type fakeSerializer struct{} - -func (self *fakeSerializer) serialize(expected, actual interface{}, message string) string { - return fmt.Sprintf("%v|%v|%s", expected, actual, message) -} - -func (self *fakeSerializer) serializeDetailed(expected, actual interface{}, message string) string { - return fmt.Sprintf("%v|%v|%s", expected, actual, message) -} - -func newFakeSerializer() *fakeSerializer { - return new(fakeSerializer) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/assertions.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/assertions.go deleted file mode 100644 index 784cb0a..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/assertions.go +++ /dev/null @@ -1,65 +0,0 @@ -package convey - -import "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions" - -var ( - ShouldEqual = assertions.ShouldEqual - ShouldNotEqual = assertions.ShouldNotEqual - ShouldAlmostEqual = assertions.ShouldAlmostEqual - ShouldNotAlmostEqual = assertions.ShouldNotAlmostEqual - ShouldResemble = assertions.ShouldResemble - ShouldNotResemble = assertions.ShouldNotResemble - ShouldPointTo = assertions.ShouldPointTo - ShouldNotPointTo = assertions.ShouldNotPointTo - ShouldBeNil = assertions.ShouldBeNil - ShouldNotBeNil = assertions.ShouldNotBeNil - ShouldBeTrue = assertions.ShouldBeTrue - ShouldBeFalse = assertions.ShouldBeFalse - ShouldBeZeroValue = assertions.ShouldBeZeroValue - - ShouldBeGreaterThan = assertions.ShouldBeGreaterThan - ShouldBeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo - ShouldBeLessThan = assertions.ShouldBeLessThan - ShouldBeLessThanOrEqualTo = assertions.ShouldBeLessThanOrEqualTo - ShouldBeBetween = assertions.ShouldBeBetween - ShouldNotBeBetween = assertions.ShouldNotBeBetween - ShouldBeBetweenOrEqual = assertions.ShouldBeBetweenOrEqual - ShouldNotBeBetweenOrEqual = assertions.ShouldNotBeBetweenOrEqual - - ShouldContain = assertions.ShouldContain - ShouldNotContain = assertions.ShouldNotContain - ShouldBeIn = assertions.ShouldBeIn - ShouldNotBeIn = assertions.ShouldNotBeIn - ShouldBeEmpty = assertions.ShouldBeEmpty - ShouldNotBeEmpty = assertions.ShouldNotBeEmpty - - ShouldStartWith = assertions.ShouldStartWith - ShouldNotStartWith = assertions.ShouldNotStartWith - ShouldEndWith = assertions.ShouldEndWith - ShouldNotEndWith = assertions.ShouldNotEndWith - ShouldBeBlank = assertions.ShouldBeBlank - ShouldNotBeBlank = assertions.ShouldNotBeBlank - ShouldContainSubstring = assertions.ShouldContainSubstring - ShouldNotContainSubstring = assertions.ShouldNotContainSubstring - - ShouldPanic = assertions.ShouldPanic - ShouldNotPanic = assertions.ShouldNotPanic - ShouldPanicWith = assertions.ShouldPanicWith - ShouldNotPanicWith = assertions.ShouldNotPanicWith - - ShouldHaveSameTypeAs = assertions.ShouldHaveSameTypeAs - ShouldNotHaveSameTypeAs = assertions.ShouldNotHaveSameTypeAs - ShouldImplement = assertions.ShouldImplement - ShouldNotImplement = assertions.ShouldNotImplement - - ShouldHappenBefore = assertions.ShouldHappenBefore - ShouldHappenOnOrBefore = assertions.ShouldHappenOnOrBefore - ShouldHappenAfter = assertions.ShouldHappenAfter - ShouldHappenOnOrAfter = assertions.ShouldHappenOnOrAfter - ShouldHappenBetween = assertions.ShouldHappenBetween - ShouldHappenOnOrBetween = assertions.ShouldHappenOnOrBetween - ShouldNotHappenOnOrBetween = assertions.ShouldNotHappenOnOrBetween - ShouldHappenWithin = assertions.ShouldHappenWithin - ShouldNotHappenWithin = assertions.ShouldNotHappenWithin - ShouldBeChronological = assertions.ShouldBeChronological -) diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/context.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/context.go deleted file mode 100644 index 27f5436..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/context.go +++ /dev/null @@ -1,272 +0,0 @@ -package convey - -import ( - "fmt" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/jtolds/gls" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting" -) - -type conveyErr struct { - fmt string - params []interface{} -} - -func (e *conveyErr) Error() string { - return fmt.Sprintf(e.fmt, e.params...) -} - -func conveyPanic(fmt string, params ...interface{}) { - panic(&conveyErr{fmt, params}) -} - -const ( - missingGoTest = `Top-level calls to Convey(...) need a reference to the *testing.T. - Hint: Convey("description here", t, func() { /* notice that the second argument was the *testing.T (t)! */ }) ` - extraGoTest = `Only the top-level call to Convey(...) needs a reference to the *testing.T.` - noStackContext = "Convey operation made without context on goroutine stack.\n" + - "Hint: Perhaps you meant to use `Convey(..., func(c C){...})` ?" - differentConveySituations = "Different set of Convey statements on subsequent pass!\nDid not expect %#v." - multipleIdenticalConvey = "Multiple convey suites with identical names: %#v" -) - -const ( - failureHalt = "___FAILURE_HALT___" - - nodeKey = "node" -) - -///////////////////////////////// Stack Context ///////////////////////////////// - -func getCurrentContext() *context { - ctx, ok := ctxMgr.GetValue(nodeKey) - if ok { - return ctx.(*context) - } - return nil -} - -func mustGetCurrentContext() *context { - ctx := getCurrentContext() - if ctx == nil { - conveyPanic(noStackContext) - } - return ctx -} - -//////////////////////////////////// Context //////////////////////////////////// - -// context magically handles all coordination of Convey's and So assertions. -// -// It is tracked on the stack as goroutine-local-storage with the gls package, -// or explicitly if the user decides to call convey like: -// -// Convey(..., func(c C) { -// c.So(...) -// }) -// -// This implements the `C` interface. -type context struct { - reporter reporting.Reporter - - children map[string]*context - - resets []func() - - executedOnce bool - expectChildRun *bool - complete bool - - focus bool - failureMode FailureMode -} - -// rootConvey is the main entry point to a test suite. This is called when -// there's no context in the stack already, and items must contain a `t` object, -// or this panics. -func rootConvey(items ...interface{}) { - entry := discover(items) - - if entry.Test == nil { - conveyPanic(missingGoTest) - } - - expectChildRun := true - ctx := &context{ - reporter: buildReporter(), - - children: make(map[string]*context), - - expectChildRun: &expectChildRun, - - focus: entry.Focus, - failureMode: defaultFailureMode.combine(entry.FailMode), - } - ctxMgr.SetValues(gls.Values{nodeKey: ctx}, func() { - ctx.reporter.BeginStory(reporting.NewStoryReport(entry.Test)) - defer ctx.reporter.EndStory() - - for ctx.shouldVisit() { - ctx.conveyInner(entry.Situation, entry.Func) - expectChildRun = true - } - }) -} - -//////////////////////////////////// Methods //////////////////////////////////// - -func (ctx *context) SkipConvey(items ...interface{}) { - ctx.Convey(items, skipConvey) -} - -func (ctx *context) FocusConvey(items ...interface{}) { - ctx.Convey(items, focusConvey) -} - -func (ctx *context) Convey(items ...interface{}) { - entry := discover(items) - - // we're a branch, or leaf (on the wind) - if entry.Test != nil { - conveyPanic(extraGoTest) - } - if ctx.focus && !entry.Focus { - return - } - - var inner_ctx *context - if ctx.executedOnce { - var ok bool - inner_ctx, ok = ctx.children[entry.Situation] - if !ok { - conveyPanic(differentConveySituations, entry.Situation) - } - } else { - if _, ok := ctx.children[entry.Situation]; ok { - conveyPanic(multipleIdenticalConvey, entry.Situation) - } - inner_ctx = &context{ - reporter: ctx.reporter, - - children: make(map[string]*context), - - expectChildRun: ctx.expectChildRun, - - focus: entry.Focus, - failureMode: ctx.failureMode.combine(entry.FailMode), - } - ctx.children[entry.Situation] = inner_ctx - } - - if inner_ctx.shouldVisit() { - ctxMgr.SetValues(gls.Values{nodeKey: inner_ctx}, func() { - inner_ctx.conveyInner(entry.Situation, entry.Func) - }) - } -} - -func (ctx *context) SkipSo(stuff ...interface{}) { - ctx.assertionReport(reporting.NewSkipReport()) -} - -func (ctx *context) So(actual interface{}, assert assertion, expected ...interface{}) { - if result := assert(actual, expected...); result == assertionSuccess { - ctx.assertionReport(reporting.NewSuccessReport()) - } else { - ctx.assertionReport(reporting.NewFailureReport(result)) - } -} - -func (ctx *context) Reset(action func()) { - /* TODO: Failure mode configuration */ - ctx.resets = append(ctx.resets, action) -} - -func (ctx *context) Print(items ...interface{}) (int, error) { - fmt.Fprint(ctx.reporter, items...) - return fmt.Print(items...) -} - -func (ctx *context) Println(items ...interface{}) (int, error) { - fmt.Fprintln(ctx.reporter, items...) - return fmt.Println(items...) -} - -func (ctx *context) Printf(format string, items ...interface{}) (int, error) { - fmt.Fprintf(ctx.reporter, format, items...) - return fmt.Printf(format, items...) -} - -//////////////////////////////////// Private //////////////////////////////////// - -// shouldVisit returns true iff we should traverse down into a Convey. Note -// that just because we don't traverse a Convey this time, doesn't mean that -// we may not traverse it on a subsequent pass. -func (c *context) shouldVisit() bool { - return !c.complete && *c.expectChildRun -} - -// conveyInner is the function which actually executes the user's anonymous test -// function body. At this point, Convey or RootConvey has decided that this -// function should actually run. -func (ctx *context) conveyInner(situation string, f func(C)) { - // Record/Reset state for next time. - defer func() { - ctx.executedOnce = true - - // This is only needed at the leaves, but there's no harm in also setting it - // when returning from branch Convey's - *ctx.expectChildRun = false - }() - - // Set up+tear down our scope for the reporter - ctx.reporter.Enter(reporting.NewScopeReport(situation)) - defer ctx.reporter.Exit() - - // Recover from any panics in f, and assign the `complete` status for this - // node of the tree. - defer func() { - ctx.complete = true - if problem := recover(); problem != nil { - if problem, ok := problem.(*conveyErr); ok { - panic(problem) - } - if problem != failureHalt { - ctx.reporter.Report(reporting.NewErrorReport(problem)) - } - } else { - for _, child := range ctx.children { - if !child.complete { - ctx.complete = false - return - } - } - } - }() - - // Resets are registered as the `f` function executes, so nil them here. - // All resets are run in registration order (FIFO). - ctx.resets = []func(){} - defer func() { - for _, r := range ctx.resets { - // panics handled by the previous defer - r() - } - }() - - if f == nil { - // if f is nil, this was either a Convey(..., nil), or a SkipConvey - ctx.reporter.Report(reporting.NewSkipReport()) - } else { - f(ctx) - } -} - -// assertionReport is a helper for So and SkipSo which makes the report and -// then possibly panics, depending on the current context's failureMode. -func (ctx *context) assertionReport(r *reporting.AssertionResult) { - ctx.reporter.Report(r) - if r.Failure != "" && ctx.failureMode == FailureHalts { - panic(failureHalt) - } -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/convey.goconvey b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/convey.goconvey deleted file mode 100644 index a2d9327..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/convey.goconvey +++ /dev/null @@ -1,4 +0,0 @@ -#ignore --timeout=1s -#-covermode=count -#-coverpkg=github.com/smartystreets/goconvey/convey,github.com/smartystreets/goconvey/convey/gotest,github.com/smartystreets/goconvey/convey/reporting \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/discovery.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/discovery.go deleted file mode 100644 index eb8d4cb..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/discovery.go +++ /dev/null @@ -1,103 +0,0 @@ -package convey - -type actionSpecifier uint8 - -const ( - noSpecifier actionSpecifier = iota - skipConvey - focusConvey -) - -type suite struct { - Situation string - Test t - Focus bool - Func func(C) // nil means skipped - FailMode FailureMode -} - -func newSuite(situation string, failureMode FailureMode, f func(C), test t, specifier actionSpecifier) *suite { - ret := &suite{ - Situation: situation, - Test: test, - Func: f, - FailMode: failureMode, - } - switch specifier { - case skipConvey: - ret.Func = nil - case focusConvey: - ret.Focus = true - } - return ret -} - -func discover(items []interface{}) *suite { - name, items := parseName(items) - test, items := parseGoTest(items) - failure, items := parseFailureMode(items) - action, items := parseAction(items) - specifier, items := parseSpecifier(items) - - if len(items) != 0 { - conveyPanic(parseError) - } - - return newSuite(name, failure, action, test, specifier) -} -func item(items []interface{}) interface{} { - if len(items) == 0 { - conveyPanic(parseError) - } - return items[0] -} -func parseName(items []interface{}) (string, []interface{}) { - if name, parsed := item(items).(string); parsed { - return name, items[1:] - } - conveyPanic(parseError) - panic("never get here") -} -func parseGoTest(items []interface{}) (t, []interface{}) { - if test, parsed := item(items).(t); parsed { - return test, items[1:] - } - return nil, items -} -func parseFailureMode(items []interface{}) (FailureMode, []interface{}) { - if mode, parsed := item(items).(FailureMode); parsed { - return mode, items[1:] - } - return FailureInherits, items -} -func parseAction(items []interface{}) (func(C), []interface{}) { - switch x := item(items).(type) { - case nil: - return nil, items[1:] - case func(C): - return x, items[1:] - case func(): - return func(C) { x() }, items[1:] - } - conveyPanic(parseError) - panic("never get here") -} -func parseSpecifier(items []interface{}) (actionSpecifier, []interface{}) { - if len(items) == 0 { - return noSpecifier, items - } - if spec, ok := items[0].(actionSpecifier); ok { - return spec, items[1:] - } - conveyPanic(parseError) - panic("never get here") -} - -// This interface allows us to pass the *testing.T struct -// throughout the internals of this package without ever -// having to import the "testing" package. -type t interface { - Fail() -} - -const parseError = "You must provide a name (string), then a *testing.T (if in outermost scope), an optional FailureMode, and then an action (func())." diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/doc.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/doc.go deleted file mode 100644 index 3670e4c..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/doc.go +++ /dev/null @@ -1,193 +0,0 @@ -// Package convey contains all of the public-facing entry points to this project. -// This means that it should never be required of the user to import any other -// packages from this project as they serve internal purposes. -package convey - -////////////////////////////////// suite ////////////////////////////////// - -// C is the Convey context which you can optionally obtain in your action -// by calling Convey like: -// -// Convey(..., func(c C) { -// ... -// }) -// -// See the documentation on Convey for more details. -// -// All methods in this context behave identically to the global functions of the -// same name in this package. -type C interface { - Convey(items ...interface{}) - SkipConvey(items ...interface{}) - FocusConvey(items ...interface{}) - - So(actual interface{}, assert assertion, expected ...interface{}) - SkipSo(stuff ...interface{}) - - Reset(action func()) - - Println(items ...interface{}) (int, error) - Print(items ...interface{}) (int, error) - Printf(format string, items ...interface{}) (int, error) -} - -// Convey is the method intended for use when declaring the scopes of -// a specification. Each scope has a description and a func() which may contain -// other calls to Convey(), Reset() or Should-style assertions. Convey calls can -// be nested as far as you see fit. -// -// IMPORTANT NOTE: The top-level Convey() within a Test method -// must conform to the following signature: -// -// Convey(description string, t *testing.T, action func()) -// -// All other calls should look like this (no need to pass in *testing.T): -// -// Convey(description string, action func()) -// -// Don't worry, goconvey will panic if you get it wrong so you can fix it. -// -// Additionally, you may explicitly obtain access to the Convey context by doing: -// -// Convey(description string, action func(c C)) -// -// You may need to do this if you want to pass the context through to a -// goroutine, or to close over the context in a handler to a library which -// calls your handler in a goroutine (httptest comes to mind). -// -// All Convey()-blocks also accept an optional parameter of FailureMode which sets -// how goconvey should treat failures for So()-assertions in the block and -// nested blocks. See the constants in this file for the available options. -// -// By default it will inherit from its parent block and the top-level blocks -// default to the FailureHalts setting. -// -// This parameter is inserted before the block itself: -// -// Convey(description string, t *testing.T, mode FailureMode, action func()) -// Convey(description string, mode FailureMode, action func()) -// -// See the examples package for, well, examples. -func Convey(items ...interface{}) { - if ctx := getCurrentContext(); ctx == nil { - rootConvey(items...) - } else { - ctx.Convey(items...) - } -} - -// SkipConvey is analagous to Convey except that the scope is not executed -// (which means that child scopes defined within this scope are not run either). -// The reporter will be notified that this step was skipped. -func SkipConvey(items ...interface{}) { - Convey(append(items, skipConvey)...) -} - -// FocusConvey is has the inverse effect of SkipConvey. If the top-level -// Convey is changed to `FocusConvey`, only nested scopes that are defined -// with FocusConvey will be run. The rest will be ignored completely. This -// is handy when debugging a large suite that runs a misbehaving function -// repeatedly as you can disable all but one of that function -// without swaths of `SkipConvey` calls, just a targeted chain of calls -// to FocusConvey. -func FocusConvey(items ...interface{}) { - Convey(append(items, focusConvey)...) -} - -// Reset registers a cleanup function to be run after each Convey() -// in the same scope. See the examples package for a simple use case. -func Reset(action func()) { - mustGetCurrentContext().Reset(action) -} - -/////////////////////////////////// Assertions /////////////////////////////////// - -// assertion is an alias for a function with a signature that the convey.So() -// method can handle. Any future or custom assertions should conform to this -// method signature. The return value should be an empty string if the assertion -// passes and a well-formed failure message if not. -type assertion func(actual interface{}, expected ...interface{}) string - -const assertionSuccess = "" - -// So is the means by which assertions are made against the system under test. -// The majority of exported names in the assertions package begin with the word -// 'Should' and describe how the first argument (actual) should compare with any -// of the final (expected) arguments. How many final arguments are accepted -// depends on the particular assertion that is passed in as the assert argument. -// See the examples package for use cases and the assertions package for -// documentation on specific assertion methods. A failing assertion will -// cause t.Fail() to be invoked--you should never call this method (or other -// failure-inducing methods) in your test code. Leave that to GoConvey. -func So(actual interface{}, assert assertion, expected ...interface{}) { - mustGetCurrentContext().So(actual, assert, expected...) -} - -// SkipSo is analagous to So except that the assertion that would have been passed -// to So is not executed and the reporter is notified that the assertion was skipped. -func SkipSo(stuff ...interface{}) { - mustGetCurrentContext().SkipSo() -} - -// FailureMode is a type which determines how the So() blocks should fail -// if their assertion fails. See constants further down for acceptable values -type FailureMode string - -const ( - - // FailureContinues is a failure mode which prevents failing - // So()-assertions from halting Convey-block execution, instead - // allowing the test to continue past failing So()-assertions. - FailureContinues FailureMode = "continue" - - // FailureHalts is the default setting for a top-level Convey()-block - // and will cause all failing So()-assertions to halt further execution - // in that test-arm and continue on to the next arm. - FailureHalts FailureMode = "halt" - - // FailureInherits is the default setting for failure-mode, it will - // default to the failure-mode of the parent block. You should never - // need to specify this mode in your tests.. - FailureInherits FailureMode = "inherits" -) - -func (f FailureMode) combine(other FailureMode) FailureMode { - if other == FailureInherits { - return f - } - return other -} - -var defaultFailureMode FailureMode = FailureHalts - -// SetDefaultFailureMode allows you to specify the default failure mode -// for all Convey blocks. It is meant to be used in an init function to -// allow the default mode to be changdd across all tests for an entire packgae -// but it can be used anywhere. -func SetDefaultFailureMode(mode FailureMode) { - if mode == FailureContinues || mode == FailureHalts { - defaultFailureMode = mode - } else { - panic("You may only use the constants named 'FailureContinues' and 'FailureHalts' as default failure modes.") - } -} - -//////////////////////////////////// Print functions //////////////////////////////////// - -// Print is analogous to fmt.Print (and it even calls fmt.Print). It ensures that -// output is aligned with the corresponding scopes in the web UI. -func Print(items ...interface{}) (written int, err error) { - return mustGetCurrentContext().Print(items...) -} - -// Print is analogous to fmt.Println (and it even calls fmt.Println). It ensures that -// output is aligned with the corresponding scopes in the web UI. -func Println(items ...interface{}) (written int, err error) { - return mustGetCurrentContext().Println(items...) -} - -// Print is analogous to fmt.Printf (and it even calls fmt.Printf). It ensures that -// output is aligned with the corresponding scopes in the web UI. -func Printf(format string, items ...interface{}) (written int, err error) { - return mustGetCurrentContext().Printf(format, items...) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/focused_execution_test.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/focused_execution_test.go deleted file mode 100644 index 294e32f..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/focused_execution_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package convey - -import "testing" - -func TestFocusOnlyAtTopLevel(t *testing.T) { - output := prepare() - - FocusConvey("hi", t, func() { - output += "done" - }) - - expectEqual(t, "done", output) -} - -func TestFocus(t *testing.T) { - output := prepare() - - FocusConvey("hi", t, func() { - output += "1" - - Convey("bye", func() { - output += "2" - }) - }) - - expectEqual(t, "1", output) -} - -func TestNestedFocus(t *testing.T) { - output := prepare() - - FocusConvey("hi", t, func() { - output += "1" - - Convey("This shouldn't run", func() { - output += "boink!" - }) - - FocusConvey("This should run", func() { - output += "2" - - FocusConvey("The should run too", func() { - output += "3" - - }) - - Convey("The should NOT run", func() { - output += "blah blah blah!" - }) - }) - }) - - expectEqual(t, "123", output) -} - -func TestForgotTopLevelFocus(t *testing.T) { - output := prepare() - - Convey("1", t, func() { - output += "1" - - FocusConvey("This will be run because the top-level lacks Focus", func() { - output += "2" - }) - - Convey("3", func() { - output += "3" - }) - }) - - expectEqual(t, "1213", output) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/gotest/utils.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/gotest/utils.go deleted file mode 100644 index b370f1e..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/gotest/utils.go +++ /dev/null @@ -1,37 +0,0 @@ -// Package gotest contains internal functionality. Although this package -// contains one or more exported names it is not intended for public -// consumption. See the examples package for how to use this project. -package gotest - -import ( - "fmt" - "runtime" - "strings" -) - -func FormatExternalFileAndLine() string { - file, line, _ := ResolveExternalCaller() - if line == -1 { - return "" // panic? - } - return fmt.Sprintf("%s:%d", file, line) -} - -func ResolveExternalCaller() (file string, line int, name string) { - var caller_id uintptr - callers := runtime.Callers(0, callStack) - - for x := 0; x < callers; x++ { - caller_id, file, line, _ = runtime.Caller(x) - if strings.HasSuffix(file, "_test.go") { - name = runtime.FuncForPC(caller_id).Name() - return - } - } - file, line, name = "", -1, "" - return // panic? -} - -const maxStackDepth = 100 // This had better be enough... - -var callStack []uintptr = make([]uintptr, maxStackDepth, maxStackDepth) diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/init.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/init.go deleted file mode 100644 index c7e10c3..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/init.go +++ /dev/null @@ -1,76 +0,0 @@ -package convey - -import ( - "flag" - "os" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/jtolds/gls" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/assertions" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting" -) - -func init() { - assertions.GoConveyMode(true) - - declareFlags() - - ctxMgr = gls.NewContextManager() -} - -func declareFlags() { - flag.BoolVar(&json, "json", false, "When true, emits results in JSON blocks. Default: 'false'") - flag.BoolVar(&silent, "silent", false, "When true, all output from GoConvey is suppressed.") - flag.BoolVar(&story, "story", false, "When true, emits story output, otherwise emits dot output. When not provided, this flag mirros the value of the '-test.v' flag") - - if noStoryFlagProvided() { - story = verboseEnabled - } - - // FYI: flag.Parse() is called from the testing package. -} - -func noStoryFlagProvided() bool { - return !story && !storyDisabled -} - -func buildReporter() reporting.Reporter { - switch { - case testReporter != nil: - return testReporter - case json: - return reporting.BuildJsonReporter() - case silent: - return reporting.BuildSilentReporter() - case story: - return reporting.BuildStoryReporter() - default: - return reporting.BuildDotReporter() - } -} - -var ( - ctxMgr *gls.ContextManager - - // only set by internal tests - testReporter reporting.Reporter -) - -var ( - json bool - silent bool - story bool - - verboseEnabled = flagFound("-test.v=true") - storyDisabled = flagFound("-story=false") -) - -// flagFound parses the command line args manually for flags defined in other -// packages. Like the '-v' flag from the "testing" package, for instance. -func flagFound(flagValue string) bool { - for _, arg := range os.Args { - if arg == flagValue { - return true - } - } - return false -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/isolated_execution_test.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/isolated_execution_test.go deleted file mode 100644 index 7e22b3c..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/isolated_execution_test.go +++ /dev/null @@ -1,774 +0,0 @@ -package convey - -import ( - "strconv" - "testing" - "time" -) - -func TestSingleScope(t *testing.T) { - output := prepare() - - Convey("hi", t, func() { - output += "done" - }) - - expectEqual(t, "done", output) -} - -func TestSingleScopeWithMultipleConveys(t *testing.T) { - output := prepare() - - Convey("1", t, func() { - output += "1" - }) - - Convey("2", t, func() { - output += "2" - }) - - expectEqual(t, "12", output) -} - -func TestNestedScopes(t *testing.T) { - output := prepare() - - Convey("a", t, func() { - output += "a " - - Convey("bb", func() { - output += "bb " - - Convey("ccc", func() { - output += "ccc | " - }) - }) - }) - - expectEqual(t, "a bb ccc | ", output) -} - -func TestNestedScopesWithIsolatedExecution(t *testing.T) { - output := prepare() - - Convey("a", t, func() { - output += "a " - - Convey("aa", func() { - output += "aa " - - Convey("aaa", func() { - output += "aaa | " - }) - - Convey("aaa1", func() { - output += "aaa1 | " - }) - }) - - Convey("ab", func() { - output += "ab " - - Convey("abb", func() { - output += "abb | " - }) - }) - }) - - expectEqual(t, "a aa aaa | a aa aaa1 | a ab abb | ", output) -} - -func TestSingleScopeWithConveyAndNestedReset(t *testing.T) { - output := prepare() - - Convey("1", t, func() { - output += "1" - - Reset(func() { - output += "a" - }) - }) - - expectEqual(t, "1a", output) -} - -func TestPanicingReset(t *testing.T) { - output := prepare() - - Convey("1", t, func() { - output += "1" - - Reset(func() { - panic("nooo") - }) - - Convey("runs since the reset hasn't yet", func() { - output += "a" - }) - - Convey("but this doesnt", func() { - output += "nope" - }) - }) - - expectEqual(t, "1a", output) -} - -func TestSingleScopeWithMultipleRegistrationsAndReset(t *testing.T) { - output := prepare() - - Convey("reset after each nested convey", t, func() { - Convey("first output", func() { - output += "1" - }) - - Convey("second output", func() { - output += "2" - }) - - Reset(func() { - output += "a" - }) - }) - - expectEqual(t, "1a2a", output) -} - -func TestSingleScopeWithMultipleRegistrationsAndMultipleResets(t *testing.T) { - output := prepare() - - Convey("each reset is run at end of each nested convey", t, func() { - Convey("1", func() { - output += "1" - }) - - Convey("2", func() { - output += "2" - }) - - Reset(func() { - output += "a" - }) - - Reset(func() { - output += "b" - }) - }) - - expectEqual(t, "1ab2ab", output) -} - -func Test_Failure_AtHigherLevelScopePreventsChildScopesFromRunning(t *testing.T) { - output := prepare() - - Convey("This step fails", t, func() { - So(1, ShouldEqual, 2) - - Convey("this should NOT be executed", func() { - output += "a" - }) - }) - - expectEqual(t, "", output) -} - -func Test_Panic_AtHigherLevelScopePreventsChildScopesFromRunning(t *testing.T) { - output := prepare() - - Convey("This step panics", t, func() { - Convey("this happens, because the panic didn't happen yet", func() { - output += "1" - }) - - output += "a" - - Convey("this should NOT be executed", func() { - output += "2" - }) - - output += "b" - - panic("Hi") - - output += "nope" - }) - - expectEqual(t, "1ab", output) -} - -func Test_Panic_InChildScopeDoes_NOT_PreventExecutionOfSiblingScopes(t *testing.T) { - output := prepare() - - Convey("This is the parent", t, func() { - Convey("This step panics", func() { - panic("Hi") - output += "1" - }) - - Convey("This sibling should execute", func() { - output += "2" - }) - }) - - expectEqual(t, "2", output) -} - -func Test_Failure_InChildScopeDoes_NOT_PreventExecutionOfSiblingScopes(t *testing.T) { - output := prepare() - - Convey("This is the parent", t, func() { - Convey("This step fails", func() { - So(1, ShouldEqual, 2) - output += "1" - }) - - Convey("This sibling should execute", func() { - output += "2" - }) - }) - - expectEqual(t, "2", output) -} - -func TestResetsAreAlwaysExecutedAfterScope_Panics(t *testing.T) { - output := prepare() - - Convey("This is the parent", t, func() { - Convey("This step panics", func() { - panic("Hi") - output += "1" - }) - - Convey("This sibling step does not panic", func() { - output += "a" - - Reset(func() { - output += "b" - }) - }) - - Reset(func() { - output += "2" - }) - }) - - expectEqual(t, "2ab2", output) -} - -func TestResetsAreAlwaysExecutedAfterScope_Failures(t *testing.T) { - output := prepare() - - Convey("This is the parent", t, func() { - Convey("This step fails", func() { - So(1, ShouldEqual, 2) - output += "1" - }) - - Convey("This sibling step does not fail", func() { - output += "a" - - Reset(func() { - output += "b" - }) - }) - - Reset(func() { - output += "2" - }) - }) - - expectEqual(t, "2ab2", output) -} - -func TestSkipTopLevel(t *testing.T) { - output := prepare() - - SkipConvey("hi", t, func() { - output += "This shouldn't be executed!" - }) - - expectEqual(t, "", output) -} - -func TestSkipNestedLevel(t *testing.T) { - output := prepare() - - Convey("hi", t, func() { - output += "yes" - - SkipConvey("bye", func() { - output += "no" - }) - }) - - expectEqual(t, "yes", output) -} - -func TestSkipNestedLevelSkipsAllChildLevels(t *testing.T) { - output := prepare() - - Convey("hi", t, func() { - output += "yes" - - SkipConvey("bye", func() { - output += "no" - - Convey("byebye", func() { - output += "no-no" - }) - }) - }) - - expectEqual(t, "yes", output) -} - -func TestIterativeConveys(t *testing.T) { - output := prepare() - - Convey("Test", t, func() { - for x := 0; x < 10; x++ { - y := strconv.Itoa(x) - - Convey(y, func() { - output += y - }) - } - }) - - expectEqual(t, "0123456789", output) -} - -func TestClosureVariables(t *testing.T) { - output := prepare() - - i := 0 - - Convey("A", t, func() { - i = i + 1 - j := i - - output += "A" + strconv.Itoa(i) + " " - - Convey("B", func() { - k := j - j = j + 1 - - output += "B" + strconv.Itoa(k) + " " - - Convey("C", func() { - output += "C" + strconv.Itoa(k) + strconv.Itoa(j) + " " - }) - - Convey("D", func() { - output += "D" + strconv.Itoa(k) + strconv.Itoa(j) + " " - }) - }) - - Convey("C", func() { - output += "C" + strconv.Itoa(j) + " " - }) - }) - - output += "D" + strconv.Itoa(i) + " " - - expectEqual(t, "A1 B1 C12 A2 B2 D23 A3 C3 D3 ", output) -} - -func TestClosureVariablesWithReset(t *testing.T) { - output := prepare() - - i := 0 - - Convey("A", t, func() { - i = i + 1 - j := i - - output += "A" + strconv.Itoa(i) + " " - - Reset(func() { - output += "R" + strconv.Itoa(i) + strconv.Itoa(j) + " " - }) - - Convey("B", func() { - output += "B" + strconv.Itoa(j) + " " - }) - - Convey("C", func() { - output += "C" + strconv.Itoa(j) + " " - }) - }) - - output += "D" + strconv.Itoa(i) + " " - - expectEqual(t, "A1 B1 R11 A2 C2 R22 D2 ", output) -} - -func TestWrappedSimple(t *testing.T) { - prepare() - output := resetTestString{""} - - Convey("A", t, func() { - func() { - output.output += "A " - - Convey("B", func() { - output.output += "B " - - Convey("C", func() { - output.output += "C " - }) - - }) - - Convey("D", func() { - output.output += "D " - }) - }() - }) - - expectEqual(t, "A B C A D ", output.output) -} - -type resetTestString struct { - output string -} - -func addReset(o *resetTestString, f func()) func() { - return func() { - Reset(func() { - o.output += "R " - }) - - f() - } -} - -func TestWrappedReset(t *testing.T) { - prepare() - output := resetTestString{""} - - Convey("A", t, addReset(&output, func() { - output.output += "A " - - Convey("B", func() { - output.output += "B " - }) - - Convey("C", func() { - output.output += "C " - }) - })) - - expectEqual(t, "A B R A C R ", output.output) -} - -func TestWrappedReset2(t *testing.T) { - prepare() - output := resetTestString{""} - - Convey("A", t, func() { - Reset(func() { - output.output += "R " - }) - - func() { - output.output += "A " - - Convey("B", func() { - output.output += "B " - - Convey("C", func() { - output.output += "C " - }) - }) - - Convey("D", func() { - output.output += "D " - }) - }() - }) - - expectEqual(t, "A B C R A D R ", output.output) -} - -func TestInfiniteLoopWithTrailingFail(t *testing.T) { - done := make(chan int) - - go func() { - Convey("This fails", t, func() { - Convey("and this is run", func() { - So(true, ShouldEqual, true) - }) - - /* And this prevents the whole block to be marked as run */ - So(false, ShouldEqual, true) - }) - - done <- 1 - }() - - select { - case <-done: - return - case <-time.After(1 * time.Millisecond): - t.Fail() - } -} - -func TestOutermostResetInvokedForGrandchildren(t *testing.T) { - output := prepare() - - Convey("A", t, func() { - output += "A " - - Reset(func() { - output += "rA " - }) - - Convey("B", func() { - output += "B " - - Reset(func() { - output += "rB " - }) - - Convey("C", func() { - output += "C " - - Reset(func() { - output += "rC " - }) - }) - - Convey("D", func() { - output += "D " - - Reset(func() { - output += "rD " - }) - }) - }) - }) - - expectEqual(t, "A B C rC rB rA A B D rD rB rA ", output) -} - -func TestFailureOption(t *testing.T) { - output := prepare() - - Convey("A", t, FailureHalts, func() { - output += "A " - So(true, ShouldEqual, true) - output += "B " - So(false, ShouldEqual, true) - output += "C " - }) - - expectEqual(t, "A B ", output) -} - -func TestFailureOption2(t *testing.T) { - output := prepare() - - Convey("A", t, func() { - output += "A " - So(true, ShouldEqual, true) - output += "B " - So(false, ShouldEqual, true) - output += "C " - }) - - expectEqual(t, "A B ", output) -} - -func TestFailureOption3(t *testing.T) { - output := prepare() - - Convey("A", t, FailureContinues, func() { - output += "A " - So(true, ShouldEqual, true) - output += "B " - So(false, ShouldEqual, true) - output += "C " - }) - - expectEqual(t, "A B C ", output) -} - -func TestFailureOptionInherit(t *testing.T) { - output := prepare() - - Convey("A", t, FailureContinues, func() { - output += "A1 " - So(false, ShouldEqual, true) - output += "A2 " - - Convey("B", func() { - output += "B1 " - So(true, ShouldEqual, true) - output += "B2 " - So(false, ShouldEqual, true) - output += "B3 " - }) - }) - - expectEqual(t, "A1 A2 B1 B2 B3 ", output) -} - -func TestFailureOptionInherit2(t *testing.T) { - output := prepare() - - Convey("A", t, FailureHalts, func() { - output += "A1 " - So(false, ShouldEqual, true) - output += "A2 " - - Convey("B", func() { - output += "A1 " - So(true, ShouldEqual, true) - output += "A2 " - So(false, ShouldEqual, true) - output += "A3 " - }) - }) - - expectEqual(t, "A1 ", output) -} - -func TestFailureOptionInherit3(t *testing.T) { - output := prepare() - - Convey("A", t, FailureHalts, func() { - output += "A1 " - So(true, ShouldEqual, true) - output += "A2 " - - Convey("B", func() { - output += "B1 " - So(true, ShouldEqual, true) - output += "B2 " - So(false, ShouldEqual, true) - output += "B3 " - }) - }) - - expectEqual(t, "A1 A2 B1 B2 ", output) -} - -func TestFailureOptionNestedOverride(t *testing.T) { - output := prepare() - - Convey("A", t, FailureContinues, func() { - output += "A " - So(false, ShouldEqual, true) - output += "B " - - Convey("C", FailureHalts, func() { - output += "C " - So(true, ShouldEqual, true) - output += "D " - So(false, ShouldEqual, true) - output += "E " - }) - }) - - expectEqual(t, "A B C D ", output) -} - -func TestFailureOptionNestedOverride2(t *testing.T) { - output := prepare() - - Convey("A", t, FailureHalts, func() { - output += "A " - So(true, ShouldEqual, true) - output += "B " - - Convey("C", FailureContinues, func() { - output += "C " - So(true, ShouldEqual, true) - output += "D " - So(false, ShouldEqual, true) - output += "E " - }) - }) - - expectEqual(t, "A B C D E ", output) -} - -func TestMultipleInvocationInheritance(t *testing.T) { - output := prepare() - - Convey("A", t, FailureHalts, func() { - output += "A1 " - So(true, ShouldEqual, true) - output += "A2 " - - Convey("B", FailureContinues, func() { - output += "B1 " - So(true, ShouldEqual, true) - output += "B2 " - So(false, ShouldEqual, true) - output += "B3 " - }) - - Convey("C", func() { - output += "C1 " - So(true, ShouldEqual, true) - output += "C2 " - So(false, ShouldEqual, true) - output += "C3 " - }) - }) - - expectEqual(t, "A1 A2 B1 B2 B3 A1 A2 C1 C2 ", output) -} - -func TestMultipleInvocationInheritance2(t *testing.T) { - output := prepare() - - Convey("A", t, FailureContinues, func() { - output += "A1 " - So(true, ShouldEqual, true) - output += "A2 " - So(false, ShouldEqual, true) - output += "A3 " - - Convey("B", FailureHalts, func() { - output += "B1 " - So(true, ShouldEqual, true) - output += "B2 " - So(false, ShouldEqual, true) - output += "B3 " - }) - - Convey("C", func() { - output += "C1 " - So(true, ShouldEqual, true) - output += "C2 " - So(false, ShouldEqual, true) - output += "C3 " - }) - }) - - expectEqual(t, "A1 A2 A3 B1 B2 A1 A2 A3 C1 C2 C3 ", output) -} - -func TestSetDefaultFailureMode(t *testing.T) { - output := prepare() - - SetDefaultFailureMode(FailureContinues) // the default is normally FailureHalts - defer SetDefaultFailureMode(FailureHalts) - - Convey("A", t, func() { - output += "A1 " - So(true, ShouldBeFalse) - output += "A2 " - }) - - expectEqual(t, "A1 A2 ", output) -} - -func prepare() string { - testReporter = newNilReporter() - return "" -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/nilReporter.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/nilReporter.go deleted file mode 100644 index 906043c..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/nilReporter.go +++ /dev/null @@ -1,15 +0,0 @@ -package convey - -import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting" -) - -type nilReporter struct{} - -func (self *nilReporter) BeginStory(story *reporting.StoryReport) {} -func (self *nilReporter) Enter(scope *reporting.ScopeReport) {} -func (self *nilReporter) Report(report *reporting.AssertionResult) {} -func (self *nilReporter) Exit() {} -func (self *nilReporter) EndStory() {} -func (self *nilReporter) Write(p []byte) (int, error) { return len(p), nil } -func newNilReporter() *nilReporter { return &nilReporter{} } diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/console.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/console.go deleted file mode 100644 index 7bf67db..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/console.go +++ /dev/null @@ -1,16 +0,0 @@ -package reporting - -import ( - "fmt" - "io" -) - -type console struct{} - -func (self *console) Write(p []byte) (n int, err error) { - return fmt.Print(string(p)) -} - -func NewConsole() io.Writer { - return new(console) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/doc.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/doc.go deleted file mode 100644 index a37d001..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package reporting contains internal functionality related -// to console reporting and output. Although this package has -// exported names is not intended for public consumption. See the -// examples package for how to use this project. -package reporting diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/dot.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/dot.go deleted file mode 100644 index 47d57c6..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/dot.go +++ /dev/null @@ -1,40 +0,0 @@ -package reporting - -import "fmt" - -type dot struct{ out *Printer } - -func (self *dot) BeginStory(story *StoryReport) {} - -func (self *dot) Enter(scope *ScopeReport) {} - -func (self *dot) Report(report *AssertionResult) { - if report.Error != nil { - fmt.Print(redColor) - self.out.Insert(dotError) - } else if report.Failure != "" { - fmt.Print(yellowColor) - self.out.Insert(dotFailure) - } else if report.Skipped { - fmt.Print(yellowColor) - self.out.Insert(dotSkip) - } else { - fmt.Print(greenColor) - self.out.Insert(dotSuccess) - } - fmt.Print(resetColor) -} - -func (self *dot) Exit() {} - -func (self *dot) EndStory() {} - -func (self *dot) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewDotReporter(out *Printer) *dot { - self := new(dot) - self.out = out - return self -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/dot_test.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/dot_test.go deleted file mode 100644 index a8d20d4..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/dot_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package reporting - -import ( - "errors" - "testing" -) - -func TestDotReporterAssertionPrinting(t *testing.T) { - monochrome() - file := newMemoryFile() - printer := NewPrinter(file) - reporter := NewDotReporter(printer) - - reporter.Report(NewSuccessReport()) - reporter.Report(NewFailureReport("failed")) - reporter.Report(NewErrorReport(errors.New("error"))) - reporter.Report(NewSkipReport()) - - expected := dotSuccess + dotFailure + dotError + dotSkip - - if file.buffer != expected { - t.Errorf("\nExpected: '%s'\nActual: '%s'", expected, file.buffer) - } -} - -func TestDotReporterOnlyReportsAssertions(t *testing.T) { - monochrome() - file := newMemoryFile() - printer := NewPrinter(file) - reporter := NewDotReporter(printer) - - reporter.BeginStory(nil) - reporter.Enter(nil) - reporter.Exit() - reporter.EndStory() - - if file.buffer != "" { - t.Errorf("\nExpected: '(blank)'\nActual: '%s'", file.buffer) - } -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/gotest.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/gotest.go deleted file mode 100644 index c396e16..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/gotest.go +++ /dev/null @@ -1,33 +0,0 @@ -package reporting - -type gotestReporter struct{ test T } - -func (self *gotestReporter) BeginStory(story *StoryReport) { - self.test = story.Test -} - -func (self *gotestReporter) Enter(scope *ScopeReport) {} - -func (self *gotestReporter) Report(r *AssertionResult) { - if !passed(r) { - self.test.Fail() - } -} - -func (self *gotestReporter) Exit() {} - -func (self *gotestReporter) EndStory() { - self.test = nil -} - -func (self *gotestReporter) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewGoTestReporter() *gotestReporter { - return new(gotestReporter) -} - -func passed(r *AssertionResult) bool { - return r.Error == nil && r.Failure == "" -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/gotest_test.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/gotest_test.go deleted file mode 100644 index fda1894..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/gotest_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package reporting - -import "testing" - -func TestReporterReceivesSuccessfulReport(t *testing.T) { - reporter := NewGoTestReporter() - test := new(fakeTest) - reporter.BeginStory(NewStoryReport(test)) - reporter.Report(NewSuccessReport()) - - if test.failed { - t.Errorf("Should have have marked test as failed--the report reflected success.") - } -} - -func TestReporterReceivesFailureReport(t *testing.T) { - reporter := NewGoTestReporter() - test := new(fakeTest) - reporter.BeginStory(NewStoryReport(test)) - reporter.Report(NewFailureReport("This is a failure.")) - - if !test.failed { - t.Errorf("Test should have been marked as failed (but it wasn't).") - } -} - -func TestReporterReceivesErrorReport(t *testing.T) { - reporter := NewGoTestReporter() - test := new(fakeTest) - reporter.BeginStory(NewStoryReport(test)) - reporter.Report(NewErrorReport("This is an error.")) - - if !test.failed { - t.Errorf("Test should have been marked as failed (but it wasn't).") - } -} - -func TestReporterIsResetAtTheEndOfTheStory(t *testing.T) { - defer catch(t) - reporter := NewGoTestReporter() - test := new(fakeTest) - reporter.BeginStory(NewStoryReport(test)) - reporter.EndStory() - - reporter.Report(NewSuccessReport()) -} - -func TestReporterNoopMethods(t *testing.T) { - reporter := NewGoTestReporter() - reporter.Enter(NewScopeReport("title")) - reporter.Exit() -} - -func catch(t *testing.T) { - if r := recover(); r != nil { - t.Log("Getting to this point means we've passed (because we caught a panic appropriately).") - } -} - -type fakeTest struct { - failed bool -} - -func (self *fakeTest) Fail() { - self.failed = true -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/init.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/init.go deleted file mode 100644 index ea7a4be..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/init.go +++ /dev/null @@ -1,94 +0,0 @@ -package reporting - -import ( - "fmt" - "os" - "runtime" - "strings" -) - -func init() { - if !isXterm() { - monochrome() - } - - if runtime.GOOS == "windows" { - success, failure, error_ = dotSuccess, dotFailure, dotError - } -} - -func BuildJsonReporter() Reporter { - out := NewPrinter(NewConsole()) - return NewReporters( - NewGoTestReporter(), - NewJsonReporter(out)) -} -func BuildDotReporter() Reporter { - out := NewPrinter(NewConsole()) - return NewReporters( - NewGoTestReporter(), - NewDotReporter(out), - NewProblemReporter(out), - consoleStatistics) -} -func BuildStoryReporter() Reporter { - out := NewPrinter(NewConsole()) - return NewReporters( - NewGoTestReporter(), - NewStoryReporter(out), - NewProblemReporter(out), - consoleStatistics) -} -func BuildSilentReporter() Reporter { - out := NewPrinter(NewConsole()) - return NewReporters( - NewGoTestReporter(), - NewProblemReporter(out)) -} - -var ( - newline = "\n" - success = "✔" - failure = "✘" - error_ = "🔥" - skip = "⚠" - dotSuccess = "." - dotFailure = "x" - dotError = "E" - dotSkip = "S" - errorTemplate = "* %s \nLine %d: - %v \n%s\n" - failureTemplate = "* %s \nLine %d:\n%s\n" -) - -var ( - greenColor = "\033[32m" - yellowColor = "\033[33m" - redColor = "\033[31m" - resetColor = "\033[0m" -) - -var consoleStatistics = NewStatisticsReporter(NewPrinter(NewConsole())) - -// QuiteMode disables all console output symbols. This is only meant to be used -// for tests that are internal to goconvey where the output is distracting or -// otherwise not needed in the test output. -func QuietMode() { - success, failure, error_, skip, dotSuccess, dotFailure, dotError, dotSkip = "", "", "", "", "", "", "", "" -} - -func monochrome() { - greenColor, yellowColor, redColor, resetColor = "", "", "", "" -} - -func isXterm() bool { - env := fmt.Sprintf("%v", os.Environ()) - return strings.Contains(env, " TERM=isXterm") || - strings.Contains(env, " TERM=xterm") -} - -// This interface allows us to pass the *testing.T struct -// throughout the internals of this tool without ever -// having to import the "testing" package. -type T interface { - Fail() -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/json.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/json.go deleted file mode 100644 index f852697..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/json.go +++ /dev/null @@ -1,88 +0,0 @@ -// TODO: under unit test - -package reporting - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" -) - -type JsonReporter struct { - out *Printer - currentKey []string - current *ScopeResult - index map[string]*ScopeResult - scopes []*ScopeResult -} - -func (self *JsonReporter) depth() int { return len(self.currentKey) } - -func (self *JsonReporter) BeginStory(story *StoryReport) {} - -func (self *JsonReporter) Enter(scope *ScopeReport) { - self.currentKey = append(self.currentKey, scope.Title) - ID := strings.Join(self.currentKey, "|") - if _, found := self.index[ID]; !found { - next := newScopeResult(scope.Title, self.depth(), scope.File, scope.Line) - self.scopes = append(self.scopes, next) - self.index[ID] = next - } - self.current = self.index[ID] -} - -func (self *JsonReporter) Report(report *AssertionResult) { - self.current.Assertions = append(self.current.Assertions, report) -} - -func (self *JsonReporter) Exit() { - self.currentKey = self.currentKey[:len(self.currentKey)-1] -} - -func (self *JsonReporter) EndStory() { - self.report() - self.reset() -} -func (self *JsonReporter) report() { - scopes := []string{} - for _, scope := range self.scopes { - serialized, err := json.Marshal(scope) - if err != nil { - self.out.Println(jsonMarshalFailure) - panic(err) - } - var buffer bytes.Buffer - json.Indent(&buffer, serialized, "", " ") - scopes = append(scopes, buffer.String()) - } - self.out.Print(fmt.Sprintf("%s\n%s,\n%s\n", OpenJson, strings.Join(scopes, ","), CloseJson)) -} -func (self *JsonReporter) reset() { - self.scopes = []*ScopeResult{} - self.index = map[string]*ScopeResult{} - self.currentKey = nil -} - -func (self *JsonReporter) Write(content []byte) (written int, err error) { - self.current.Output += string(content) - return len(content), nil -} - -func NewJsonReporter(out *Printer) *JsonReporter { - self := new(JsonReporter) - self.out = out - self.reset() - return self -} - -const OpenJson = ">->->OPEN-JSON->->->" // "⌦" -const CloseJson = "<-<-<-CLOSE-JSON<-<-<" // "⌫" -const jsonMarshalFailure = ` - -GOCONVEY_JSON_MARSHALL_FAILURE: There was an error when attempting to convert test results to JSON. -Please file a bug report and reference the code that caused this failure if possible. - -Here's the panic: - -` diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/printer.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/printer.go deleted file mode 100644 index 6d4a879..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/printer.go +++ /dev/null @@ -1,57 +0,0 @@ -package reporting - -import ( - "fmt" - "io" - "strings" -) - -type Printer struct { - out io.Writer - prefix string -} - -func (self *Printer) Println(message string, values ...interface{}) { - formatted := self.format(message, values...) + newline - self.out.Write([]byte(formatted)) -} - -func (self *Printer) Print(message string, values ...interface{}) { - formatted := self.format(message, values...) - self.out.Write([]byte(formatted)) -} - -func (self *Printer) Insert(text string) { - self.out.Write([]byte(text)) -} - -func (self *Printer) format(message string, values ...interface{}) string { - var formatted string - if len(values) == 0 { - formatted = self.prefix + message - } else { - formatted = self.prefix + fmt.Sprintf(message, values...) - } - indented := strings.Replace(formatted, newline, newline+self.prefix, -1) - return strings.TrimRight(indented, space) -} - -func (self *Printer) Indent() { - self.prefix += pad -} - -func (self *Printer) Dedent() { - if len(self.prefix) >= padLength { - self.prefix = self.prefix[:len(self.prefix)-padLength] - } -} - -func NewPrinter(out io.Writer) *Printer { - self := new(Printer) - self.out = out - return self -} - -const space = " " -const pad = space + space -const padLength = len(pad) diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/printer_test.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/printer_test.go deleted file mode 100644 index 94202d5..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/printer_test.go +++ /dev/null @@ -1,181 +0,0 @@ -package reporting - -import "testing" - -func TestPrint(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - const expected = "Hello, World!" - - printer.Print(expected) - - if file.buffer != expected { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestPrintFormat(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - template := "Hi, %s" - name := "Ralph" - expected := "Hi, Ralph" - - printer.Print(template, name) - - if file.buffer != expected { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestPrintPreservesEncodedStrings(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - const expected = "= -> %3D" - printer.Print(expected) - - if file.buffer != expected { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestPrintln(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - const expected = "Hello, World!" - - printer.Println(expected) - - if file.buffer != expected+"\n" { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestPrintlnFormat(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - template := "Hi, %s" - name := "Ralph" - expected := "Hi, Ralph\n" - - printer.Println(template, name) - - if file.buffer != expected { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestPrintlnPreservesEncodedStrings(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - const expected = "= -> %3D" - printer.Println(expected) - - if file.buffer != expected+"\n" { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestPrintIndented(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - const message = "Hello, World!\nGoodbye, World!" - const expected = " Hello, World!\n Goodbye, World!" - - printer.Indent() - printer.Print(message) - - if file.buffer != expected { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestPrintDedented(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - const expected = "Hello, World!\nGoodbye, World!" - - printer.Indent() - printer.Dedent() - printer.Print(expected) - - if file.buffer != expected { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestPrintlnIndented(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - const message = "Hello, World!\nGoodbye, World!" - const expected = " Hello, World!\n Goodbye, World!\n" - - printer.Indent() - printer.Println(message) - - if file.buffer != expected { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestPrintlnDedented(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - const expected = "Hello, World!\nGoodbye, World!" - - printer.Indent() - printer.Dedent() - printer.Println(expected) - - if file.buffer != expected+"\n" { - t.Errorf("Expected '%s' to equal '%s'.", expected, file.buffer) - } -} - -func TestDedentTooFarShouldNotPanic(t *testing.T) { - defer func() { - if r := recover(); r != nil { - t.Error("Should not have panicked!") - } - }() - file := newMemoryFile() - printer := NewPrinter(file) - - printer.Dedent() - - t.Log("Getting to this point without panicking means we passed.") -} - -func TestInsert(t *testing.T) { - file := newMemoryFile() - printer := NewPrinter(file) - - printer.Indent() - printer.Print("Hi") - printer.Insert(" there") - printer.Dedent() - - expected := " Hi there" - if file.buffer != expected { - t.Errorf("Should have written '%s' but instead wrote '%s'.", expected, file.buffer) - } -} - -////////////////// memoryFile //////////////////// - -type memoryFile struct { - buffer string -} - -func (self *memoryFile) Write(p []byte) (n int, err error) { - self.buffer += string(p) - return len(p), nil -} - -func (self *memoryFile) String() string { - return self.buffer -} - -func newMemoryFile() *memoryFile { - return new(memoryFile) -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/problems.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/problems.go deleted file mode 100644 index c610ba8..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/problems.go +++ /dev/null @@ -1,68 +0,0 @@ -package reporting - -import "fmt" - -type problem struct { - out *Printer - errors []*AssertionResult - failures []*AssertionResult -} - -func (self *problem) BeginStory(story *StoryReport) {} - -func (self *problem) Enter(scope *ScopeReport) {} - -func (self *problem) Report(report *AssertionResult) { - if report.Error != nil { - self.errors = append(self.errors, report) - } else if report.Failure != "" { - self.failures = append(self.failures, report) - } -} - -func (self *problem) Exit() {} - -func (self *problem) EndStory() { - self.show(self.showErrors, redColor) - self.show(self.showFailures, yellowColor) - self.prepareForNextStory() -} -func (self *problem) show(display func(), color string) { - fmt.Print(color) - display() - fmt.Print(resetColor) - self.out.Dedent() -} -func (self *problem) showErrors() { - for i, e := range self.errors { - if i == 0 { - self.out.Println("\nErrors:\n") - self.out.Indent() - } - self.out.Println(errorTemplate, e.File, e.Line, e.Error, e.StackTrace) - } -} -func (self *problem) showFailures() { - for i, f := range self.failures { - if i == 0 { - self.out.Println("\nFailures:\n") - self.out.Indent() - } - self.out.Println(failureTemplate, f.File, f.Line, f.Failure) - } -} - -func (self *problem) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewProblemReporter(out *Printer) *problem { - self := new(problem) - self.out = out - self.prepareForNextStory() - return self -} -func (self *problem) prepareForNextStory() { - self.errors = []*AssertionResult{} - self.failures = []*AssertionResult{} -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/problems_test.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/problems_test.go deleted file mode 100644 index 92f0ca3..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/problems_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package reporting - -import ( - "strings" - "testing" -) - -func TestNoopProblemReporterActions(t *testing.T) { - file, reporter := setup() - reporter.BeginStory(nil) - reporter.Enter(nil) - reporter.Exit() - expected := "" - actual := file.String() - if expected != actual { - t.Errorf("Expected: '(blank)'\nActual: '%s'", actual) - } -} - -func TestReporterPrintsFailuresAndErrorsAtTheEndOfTheStory(t *testing.T) { - file, reporter := setup() - reporter.Report(NewFailureReport("failed")) - reporter.Report(NewErrorReport("error")) - reporter.Report(NewSuccessReport()) - reporter.EndStory() - - result := file.String() - if !strings.Contains(result, "Errors:\n") { - t.Errorf("Expected errors, found none.") - } - if !strings.Contains(result, "Failures:\n") { - t.Errorf("Expected failures, found none.") - } - - // Each stack trace looks like: `* /path/to/file.go`, so look for `* `. - // With go 1.4+ there is a line in some stack traces that looks like this: - // `testing.(*M).Run(0x2082d60a0, 0x25b7c0)` - // So we can't just look for "*" anymore. - problemCount := strings.Count(result, "* ") - if problemCount != 2 { - t.Errorf("Expected one failure and one error (total of 2 '*' characters). Got %d", problemCount) - } -} - -func setup() (file *memoryFile, reporter *problem) { - monochrome() - file = newMemoryFile() - printer := NewPrinter(file) - reporter = NewProblemReporter(printer) - return -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reporter.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reporter.go deleted file mode 100644 index cce6c5e..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reporter.go +++ /dev/null @@ -1,39 +0,0 @@ -package reporting - -import "io" - -type Reporter interface { - BeginStory(story *StoryReport) - Enter(scope *ScopeReport) - Report(r *AssertionResult) - Exit() - EndStory() - io.Writer -} - -type reporters struct{ collection []Reporter } - -func (self *reporters) BeginStory(s *StoryReport) { self.foreach(func(r Reporter) { r.BeginStory(s) }) } -func (self *reporters) Enter(s *ScopeReport) { self.foreach(func(r Reporter) { r.Enter(s) }) } -func (self *reporters) Report(a *AssertionResult) { self.foreach(func(r Reporter) { r.Report(a) }) } -func (self *reporters) Exit() { self.foreach(func(r Reporter) { r.Exit() }) } -func (self *reporters) EndStory() { self.foreach(func(r Reporter) { r.EndStory() }) } - -func (self *reporters) Write(contents []byte) (written int, err error) { - self.foreach(func(r Reporter) { - written, err = r.Write(contents) - }) - return written, err -} - -func (self *reporters) foreach(action func(Reporter)) { - for _, r := range self.collection { - action(r) - } -} - -func NewReporters(collection ...Reporter) *reporters { - self := new(reporters) - self.collection = collection - return self -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reporter_test.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reporter_test.go deleted file mode 100644 index 4e5caf6..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reporter_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package reporting - -import ( - "runtime" - "testing" -) - -func TestEachNestedReporterReceivesTheCallFromTheContainingReporter(t *testing.T) { - fake1 := newFakeReporter() - fake2 := newFakeReporter() - reporter := NewReporters(fake1, fake2) - - reporter.BeginStory(nil) - assertTrue(t, fake1.begun) - assertTrue(t, fake2.begun) - - reporter.Enter(NewScopeReport("scope")) - assertTrue(t, fake1.entered) - assertTrue(t, fake2.entered) - - reporter.Report(NewSuccessReport()) - assertTrue(t, fake1.reported) - assertTrue(t, fake2.reported) - - reporter.Exit() - assertTrue(t, fake1.exited) - assertTrue(t, fake2.exited) - - reporter.EndStory() - assertTrue(t, fake1.ended) - assertTrue(t, fake2.ended) - - content := []byte("hi") - written, err := reporter.Write(content) - assertTrue(t, fake1.written) - assertTrue(t, fake2.written) - assertEqual(t, written, len(content)) - assertNil(t, err) - -} - -func assertTrue(t *testing.T, value bool) { - if !value { - _, _, line, _ := runtime.Caller(1) - t.Errorf("Value should have been true (but was false). See line %d", line) - } -} - -func assertEqual(t *testing.T, expected, actual int) { - if actual != expected { - _, _, line, _ := runtime.Caller(1) - t.Errorf("Value should have been %d (but was %d). See line %d", expected, actual, line) - } -} - -func assertNil(t *testing.T, err error) { - if err != nil { - _, _, line, _ := runtime.Caller(1) - t.Errorf("Error should have been (but wasn't). See line %d", err, line) - } -} - -type fakeReporter struct { - begun bool - entered bool - reported bool - exited bool - ended bool - written bool -} - -func newFakeReporter() *fakeReporter { - return &fakeReporter{} -} - -func (self *fakeReporter) BeginStory(story *StoryReport) { - self.begun = true -} -func (self *fakeReporter) Enter(scope *ScopeReport) { - self.entered = true -} -func (self *fakeReporter) Report(report *AssertionResult) { - self.reported = true -} -func (self *fakeReporter) Exit() { - self.exited = true -} -func (self *fakeReporter) EndStory() { - self.ended = true -} -func (self *fakeReporter) Write(content []byte) (int, error) { - self.written = true - return len(content), nil -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey deleted file mode 100644 index 7998285..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey +++ /dev/null @@ -1,2 +0,0 @@ -#ignore --timeout=1s diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reports.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reports.go deleted file mode 100644 index 1c213f8..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/reports.go +++ /dev/null @@ -1,177 +0,0 @@ -package reporting - -import ( - "encoding/json" - "fmt" - "runtime" - "strings" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/gotest" -) - -////////////////// ScopeReport //////////////////// - -type ScopeReport struct { - Title string - File string - Line int -} - -func NewScopeReport(title string) *ScopeReport { - file, line, _ := gotest.ResolveExternalCaller() - self := new(ScopeReport) - self.Title = title - self.File = file - self.Line = line - return self -} - -////////////////// ScopeResult //////////////////// - -type ScopeResult struct { - Title string - File string - Line int - Depth int - Assertions []*AssertionResult - Output string -} - -func newScopeResult(title string, depth int, file string, line int) *ScopeResult { - self := new(ScopeResult) - self.Title = title - self.Depth = depth - self.File = file - self.Line = line - self.Assertions = []*AssertionResult{} - return self -} - -/////////////////// StoryReport ///////////////////// - -type StoryReport struct { - Test T - Name string - File string - Line int -} - -func NewStoryReport(test T) *StoryReport { - file, line, name := gotest.ResolveExternalCaller() - name = removePackagePath(name) - self := new(StoryReport) - self.Test = test - self.Name = name - self.File = file - self.Line = line - return self -} - -// name comes in looking like "github.com/smartystreets/goconvey/examples.TestName". -// We only want the stuff after the last '.', which is the name of the test function. -func removePackagePath(name string) string { - parts := strings.Split(name, ".") - return parts[len(parts)-1] -} - -/////////////////// FailureView //////////////////////// - -type FailureView struct { - Message string - Expected string - Actual string -} - -////////////////////AssertionResult ////////////////////// - -type AssertionResult struct { - File string - Line int - Expected string - Actual string - Failure string - Error interface{} - StackTrace string - Skipped bool -} - -func NewFailureReport(failure string) *AssertionResult { - report := new(AssertionResult) - report.File, report.Line = caller() - report.StackTrace = stackTrace() - parseFailure(failure, report) - return report -} -func parseFailure(failure string, report *AssertionResult) { - view := new(FailureView) - err := json.Unmarshal([]byte(failure), view) - if err == nil { - report.Failure = view.Message - report.Expected = view.Expected - report.Actual = view.Actual - } else { - report.Failure = failure - } -} -func NewErrorReport(err interface{}) *AssertionResult { - report := new(AssertionResult) - report.File, report.Line = caller() - report.StackTrace = fullStackTrace() - report.Error = fmt.Sprintf("%v", err) - return report -} -func NewSuccessReport() *AssertionResult { - return new(AssertionResult) -} -func NewSkipReport() *AssertionResult { - report := new(AssertionResult) - report.File, report.Line = caller() - report.StackTrace = fullStackTrace() - report.Skipped = true - return report -} - -func caller() (file string, line int) { - file, line, _ = gotest.ResolveExternalCaller() - return -} - -func stackTrace() string { - buffer := make([]byte, 1024*64) - n := runtime.Stack(buffer, false) - return removeInternalEntries(string(buffer[:n])) -} -func fullStackTrace() string { - buffer := make([]byte, 1024*64) - n := runtime.Stack(buffer, true) - return removeInternalEntries(string(buffer[:n])) -} -func removeInternalEntries(stack string) string { - lines := strings.Split(stack, newline) - filtered := []string{} - for _, line := range lines { - if !isExternal(line) { - filtered = append(filtered, line) - } - } - return strings.Join(filtered, newline) -} -func isExternal(line string) bool { - for _, p := range internalPackages { - if strings.Contains(line, p) { - return true - } - } - return false -} - -// NOTE: any new packages that host goconvey packages will need to be added here! -// An alternative is to scan the goconvey directory and then exclude stuff like -// the examples package but that's nasty too. -var internalPackages = []string{ - "goconvey/assertions", - "goconvey/convey", - "goconvey/execution", - "goconvey/gotest", - "goconvey/reporting", -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/statistics.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/statistics.go deleted file mode 100644 index e015031..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/statistics.go +++ /dev/null @@ -1,79 +0,0 @@ -package reporting - -import "fmt" - -func (self *statistics) BeginStory(story *StoryReport) {} - -func (self *statistics) Enter(scope *ScopeReport) {} - -func (self *statistics) Report(report *AssertionResult) { - if !self.failing && report.Failure != "" { - self.failing = true - } - if !self.erroring && report.Error != nil { - self.erroring = true - } - if report.Skipped { - self.skipped += 1 - } else { - self.total++ - } -} - -func (self *statistics) Exit() {} - -func (self *statistics) EndStory() { - self.reportAssertions() - self.reportSkippedSections() - self.completeReport() -} -func (self *statistics) reportAssertions() { - self.decideColor() - self.out.Print("\n%d %s thus far", self.total, plural("assertion", self.total)) -} -func (self *statistics) decideColor() { - if self.failing && !self.erroring { - fmt.Print(yellowColor) - } else if self.erroring { - fmt.Print(redColor) - } else { - fmt.Print(greenColor) - } -} -func (self *statistics) reportSkippedSections() { - if self.skipped > 0 { - fmt.Print(yellowColor) - self.out.Print(" (one or more sections skipped)") - self.skipped = 0 - } -} -func (self *statistics) completeReport() { - fmt.Print(resetColor) - self.out.Print("\n") - self.out.Print("\n") -} - -func (self *statistics) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewStatisticsReporter(out *Printer) *statistics { - self := statistics{} - self.out = out - return &self -} - -type statistics struct { - out *Printer - total int - failing bool - erroring bool - skipped int -} - -func plural(word string, count int) string { - if count == 1 { - return word - } - return word + "s" -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/story.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/story.go deleted file mode 100644 index 9e73c97..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting/story.go +++ /dev/null @@ -1,73 +0,0 @@ -// TODO: in order for this reporter to be completely honest -// we need to retrofit to be more like the json reporter such that: -// 1. it maintains ScopeResult collections, which count assertions -// 2. it reports only after EndStory(), so that all tick marks -// are placed near the appropriate title. -// 3. Under unit test - -package reporting - -import ( - "fmt" - "strings" -) - -type story struct { - out *Printer - titlesById map[string]string - currentKey []string -} - -func (self *story) BeginStory(story *StoryReport) {} - -func (self *story) Enter(scope *ScopeReport) { - self.out.Indent() - - self.currentKey = append(self.currentKey, scope.Title) - ID := strings.Join(self.currentKey, "|") - - if _, found := self.titlesById[ID]; !found { - self.out.Println("") - self.out.Print(scope.Title) - self.out.Insert(" ") - self.titlesById[ID] = scope.Title - } -} - -func (self *story) Report(report *AssertionResult) { - if report.Error != nil { - fmt.Print(redColor) - self.out.Insert(error_) - } else if report.Failure != "" { - fmt.Print(yellowColor) - self.out.Insert(failure) - } else if report.Skipped { - fmt.Print(yellowColor) - self.out.Insert(skip) - } else { - fmt.Print(greenColor) - self.out.Insert(success) - } - fmt.Print(resetColor) -} - -func (self *story) Exit() { - self.out.Dedent() - self.currentKey = self.currentKey[:len(self.currentKey)-1] -} - -func (self *story) EndStory() { - self.titlesById = make(map[string]string) - self.out.Println("\n") -} - -func (self *story) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewStoryReporter(out *Printer) *story { - self := new(story) - self.out = out - self.titlesById = make(map[string]string) - return self -} diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting_hooks_test.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting_hooks_test.go deleted file mode 100644 index c4e4365..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting_hooks_test.go +++ /dev/null @@ -1,317 +0,0 @@ -package convey - -import ( - "fmt" - "net/http" - "net/http/httptest" - "path" - "runtime" - "strconv" - "strings" - "testing" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/reporting" -) - -func TestSingleScopeReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - So(1, ShouldEqual, 1) - }) - - expectEqual(t, "Begin|A|Success|Exit|End", myReporter.wholeStory()) -} - -func TestNestedScopeReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - Convey("B", func() { - So(1, ShouldEqual, 1) - }) - }) - - expectEqual(t, "Begin|A|B|Success|Exit|Exit|End", myReporter.wholeStory()) -} - -func TestFailureReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - So(1, ShouldBeNil) - }) - - expectEqual(t, "Begin|A|Failure|Exit|End", myReporter.wholeStory()) -} - -func TestFirstFailureEndsScopeExecution(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - So(1, ShouldBeNil) - So(nil, ShouldBeNil) - }) - - expectEqual(t, "Begin|A|Failure|Exit|End", myReporter.wholeStory()) -} - -func TestComparisonFailureDeserializedAndReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - So("hi", ShouldEqual, "bye") - }) - - expectEqual(t, "Begin|A|Failure(bye/hi)|Exit|End", myReporter.wholeStory()) -} - -func TestNestedFailureReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - Convey("B", func() { - So(2, ShouldBeNil) - }) - }) - - expectEqual(t, "Begin|A|B|Failure|Exit|Exit|End", myReporter.wholeStory()) -} - -func TestSuccessAndFailureReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - So(nil, ShouldBeNil) - So(1, ShouldBeNil) - }) - - expectEqual(t, "Begin|A|Success|Failure|Exit|End", myReporter.wholeStory()) -} - -func TestIncompleteActionReportedAsSkipped(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - Convey("B", nil) - }) - - expectEqual(t, "Begin|A|B|Skipped|Exit|Exit|End", myReporter.wholeStory()) -} - -func TestSkippedConveyReportedAsSkipped(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - SkipConvey("B", func() { - So(1, ShouldEqual, 1) - }) - }) - - expectEqual(t, "Begin|A|B|Skipped|Exit|Exit|End", myReporter.wholeStory()) -} - -func TestMultipleSkipsAreReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - Convey("0", func() { - So(nil, ShouldBeNil) - }) - - SkipConvey("1", func() {}) - SkipConvey("2", func() {}) - - Convey("3", nil) - Convey("4", nil) - - Convey("5", func() { - So(nil, ShouldBeNil) - }) - }) - - expected := "Begin" + - "|A|0|Success|Exit|Exit" + - "|A|1|Skipped|Exit|Exit" + - "|A|2|Skipped|Exit|Exit" + - "|A|3|Skipped|Exit|Exit" + - "|A|4|Skipped|Exit|Exit" + - "|A|5|Success|Exit|Exit" + - "|End" - - expectEqual(t, expected, myReporter.wholeStory()) -} - -func TestSkippedAssertionIsNotReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - SkipSo(1, ShouldEqual, 1) - }) - - expectEqual(t, "Begin|A|Skipped|Exit|End", myReporter.wholeStory()) -} - -func TestMultipleSkippedAssertionsAreNotReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - SkipSo(1, ShouldEqual, 1) - So(1, ShouldEqual, 1) - SkipSo(1, ShouldEqual, 1) - }) - - expectEqual(t, "Begin|A|Skipped|Success|Skipped|Exit|End", myReporter.wholeStory()) -} - -func TestErrorByManualPanicReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - panic("Gopher alert!") - }) - - expectEqual(t, "Begin|A|Error|Exit|End", myReporter.wholeStory()) -} - -func TestIterativeConveysReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - for x := 0; x < 3; x++ { - Convey(strconv.Itoa(x), func() { - So(x, ShouldEqual, x) - }) - } - }) - - expectEqual(t, "Begin|A|0|Success|Exit|Exit|A|1|Success|Exit|Exit|A|2|Success|Exit|Exit|End", myReporter.wholeStory()) -} - -func TestNestedIterativeConveysReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func() { - for x := 0; x < 3; x++ { - Convey(strconv.Itoa(x), func() { - for y := 0; y < 3; y++ { - Convey("< "+strconv.Itoa(y), func() { - So(x, ShouldBeLessThan, y) - }) - } - }) - } - }) - - expectEqual(t, ("Begin|" + - "A|0|< 0|Failure|Exit|Exit|Exit|" + - "A|0|< 1|Success|Exit|Exit|Exit|" + - "A|0|< 2|Success|Exit|Exit|Exit|" + - "A|1|< 0|Failure|Exit|Exit|Exit|" + - "A|1|< 1|Failure|Exit|Exit|Exit|" + - "A|1|< 2|Success|Exit|Exit|Exit|" + - "A|2|< 0|Failure|Exit|Exit|Exit|" + - "A|2|< 1|Failure|Exit|Exit|Exit|" + - "A|2|< 2|Failure|Exit|Exit|Exit|" + - "End"), myReporter.wholeStory()) -} - -func TestEmbeddedAssertionReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - Convey("A", test, func(c C) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - c.So(r.FormValue("msg"), ShouldEqual, "ping") - })) - http.DefaultClient.Get(ts.URL + "?msg=ping") - }) - - expectEqual(t, "Begin|A|Success|Exit|End", myReporter.wholeStory()) -} - -func TestEmbeddedContextHelperReported(t *testing.T) { - myReporter, test := setupFakeReporter() - - helper := func(c C) http.HandlerFunc { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - c.Convey("Embedded", func() { - So(r.FormValue("msg"), ShouldEqual, "ping") - }) - }) - } - - Convey("A", test, func(c C) { - ts := httptest.NewServer(helper(c)) - http.DefaultClient.Get(ts.URL + "?msg=ping") - }) - - expectEqual(t, "Begin|A|Embedded|Success|Exit|Exit|End", myReporter.wholeStory()) -} - -func expectEqual(t *testing.T, expected interface{}, actual interface{}) { - if expected != actual { - _, file, line, _ := runtime.Caller(1) - t.Errorf("Expected '%v' to be '%v' but it wasn't. See '%s' at line %d.", - actual, expected, path.Base(file), line) - } -} - -func setupFakeReporter() (*fakeReporter, *fakeGoTest) { - myReporter := new(fakeReporter) - myReporter.calls = []string{} - testReporter = myReporter - return myReporter, new(fakeGoTest) -} - -type fakeReporter struct { - calls []string -} - -func (self *fakeReporter) BeginStory(story *reporting.StoryReport) { - self.calls = append(self.calls, "Begin") -} - -func (self *fakeReporter) Enter(scope *reporting.ScopeReport) { - self.calls = append(self.calls, scope.Title) -} - -func (self *fakeReporter) Report(report *reporting.AssertionResult) { - if report.Error != nil { - self.calls = append(self.calls, "Error") - } else if report.Failure != "" { - message := "Failure" - if report.Expected != "" || report.Actual != "" { - message += fmt.Sprintf("(%s/%s)", report.Expected, report.Actual) - } - self.calls = append(self.calls, message) - } else if report.Skipped { - self.calls = append(self.calls, "Skipped") - } else { - self.calls = append(self.calls, "Success") - } -} - -func (self *fakeReporter) Exit() { - self.calls = append(self.calls, "Exit") -} - -func (self *fakeReporter) EndStory() { - self.calls = append(self.calls, "End") -} - -func (self *fakeReporter) Write(content []byte) (int, error) { - return len(content), nil // no-op -} - -func (self *fakeReporter) wholeStory() string { - return strings.Join(self.calls, "|") -} - -//////////////////////////////// - -type fakeGoTest struct{} - -func (self *fakeGoTest) Fail() {} -func (self *fakeGoTest) Fatalf(format string, args ...interface{}) {} - -var test t = new(fakeGoTest) diff --git a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/story_conventions_test.go b/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/story_conventions_test.go deleted file mode 100644 index ff3a4e6..0000000 --- a/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/story_conventions_test.go +++ /dev/null @@ -1,184 +0,0 @@ -package convey - -import ( - "reflect" - "testing" -) - -func expectPanic(t *testing.T, f string) interface{} { - r := recover() - if r != nil { - if cp, ok := r.(*conveyErr); ok { - if cp.fmt != f { - t.Error("Incorrect panic message.") - } - } else { - t.Errorf("Incorrect panic type. %s", reflect.TypeOf(r)) - } - } else { - t.Error("Expected panic but none occured") - } - return r -} - -func TestMissingTopLevelGoTestReferenceCausesPanic(t *testing.T) { - output := map[string]bool{} - - defer expectEqual(t, false, output["good"]) - defer expectPanic(t, missingGoTest) - - Convey("Hi", func() { - output["bad"] = true // this shouldn't happen - }) -} - -func requireGoTestReference(t *testing.T) { - err := recover() - if err == nil { - t.Error("We should have recovered a panic here (because of a missing *testing.T reference)!") - } else { - expectEqual(t, missingGoTest, err) - } -} - -func TestMissingTopLevelGoTestReferenceAfterGoodExample(t *testing.T) { - output := map[string]bool{} - - defer func() { - expectEqual(t, true, output["good"]) - expectEqual(t, false, output["bad"]) - }() - defer expectPanic(t, missingGoTest) - - Convey("Good example", t, func() { - output["good"] = true - }) - - Convey("Bad example", func() { - output["bad"] = true // shouldn't happen - }) -} - -func TestExtraReferencePanics(t *testing.T) { - output := map[string]bool{} - - defer expectEqual(t, false, output["bad"]) - defer expectPanic(t, extraGoTest) - - Convey("Good example", t, func() { - Convey("Bad example - passing in *testing.T a second time!", t, func() { - output["bad"] = true // shouldn't happen - }) - }) -} - -func TestParseRegistrationMissingRequiredElements(t *testing.T) { - defer expectPanic(t, parseError) - - Convey() -} - -func TestParseRegistration_MissingNameString(t *testing.T) { - defer expectPanic(t, parseError) - - Convey(func() {}) -} - -func TestParseRegistration_MissingActionFunc(t *testing.T) { - defer expectPanic(t, parseError) - - Convey("Hi there", 12345) -} - -func TestFailureModeNoContext(t *testing.T) { - Convey("Foo", t, func() { - done := make(chan int, 1) - go func() { - defer func() { done <- 1 }() - defer expectPanic(t, noStackContext) - So(len("I have no context"), ShouldBeGreaterThan, 0) - }() - <-done - }) -} - -func TestFailureModeDuplicateSuite(t *testing.T) { - Convey("cool", t, func() { - defer expectPanic(t, multipleIdenticalConvey) - - Convey("dup", nil) - Convey("dup", nil) - }) -} - -func TestFailureModeIndeterminentSuiteNames(t *testing.T) { - defer expectPanic(t, differentConveySituations) - - name := "bob" - Convey("cool", t, func() { - for i := 0; i < 3; i++ { - Convey(name, func() {}) - name += "bob" - } - }) -} - -func TestFailureModeNestedIndeterminentSuiteNames(t *testing.T) { - defer expectPanic(t, differentConveySituations) - - name := "bob" - Convey("cool", t, func() { - Convey("inner", func() { - for i := 0; i < 3; i++ { - Convey(name, func() {}) - name += "bob" - } - }) - }) -} - -func TestFailureModeParameterButMissing(t *testing.T) { - defer expectPanic(t, parseError) - - prepare() - - Convey("Foobar", t, FailureHalts) -} - -func TestFailureModeParameterWithAction(t *testing.T) { - prepare() - - Convey("Foobar", t, FailureHalts, func() {}) -} - -func TestExtraConveyParameters(t *testing.T) { - defer expectPanic(t, parseError) - - prepare() - - Convey("Foobar", t, FailureHalts, func() {}, "This is not supposed to be here") -} - -func TestExtraConveyParameters2(t *testing.T) { - defer expectPanic(t, parseError) - - prepare() - - Convey("Foobar", t, func() {}, "This is not supposed to be here") -} - -func TestExtraConveyParameters3(t *testing.T) { - defer expectPanic(t, parseError) - - output := prepare() - - Convey("A", t, func() { - output += "A " - - Convey("B", func() { - output += "B " - }, "This is not supposed to be here") - }) - - expectEqual(t, "A ", output) -} diff --git a/README.md b/README.md index 3d9afae..ebcdfc1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Bamboo [![Build Status](https://travis-ci.org/QubitProducts/bamboo.svg?branch=master)](https://travis-ci.org/QubitProducts/bamboo) [![Coverage Status](https://coveralls.io/repos/QubitProducts/bamboo/badge.svg?branch=coverage&service=github)](https://coveralls.io/github/QubitProducts/bamboo?branch=coverage) +# Bamboo [![Build Status](https://travis-ci.org/QubitProducts/bamboo.svg?branch=master)](https://travis-ci.org/QubitProducts/bamboo) [![Coverage Status](https://coveralls.io/repos/QubitProducts/bamboo/badge.svg?branch=master&service=github)](https://coveralls.io/github/QubitProducts/bamboo?branch=coverage) ![bamboo-logo](https://cloud.githubusercontent.com/assets/37033/4110258/a8cc58bc-31ef-11e4-87c9-dd20bd2468c2.png) @@ -135,6 +135,32 @@ The default template shipped with Bamboo is aware of `BAMBOO_TCP_PORT`. When thi In this example, both `BAMBOO_TCP_PORT` and `MY_CUSTOM_ENV` can be accessed in HAProxy template. This enables flexible template customization depending on your preferences. +#### Default Haproxy Template ACL + +The default acl rule in the `haproxy_template.cfg` uses the full +marathon app id, which may include slash-separated groups. + +``` + # This is the default proxy criteria + acl {{ $app.EscapedId }}-aclrule path_beg -i {{ $app.Id }} +``` + +For example if your app is named "/mygroup/appname", your default acl +will be `path_beg -i /mygroup/appname`. This can always be changed +using the bamboo web UI. + +There is also a DNS friendly version of your marathon app Id which can +be used instead of the slash-separated one. `MesosDnsId` includes the +groups as hyphenated suffixes. For example, if your appname is +"/another/group/app" then the `MesosDnsId` will be "app-group-another". + +You can edit the `haproxy_template.cfg` and use the DNS friendly name +for your default ACL instead. + +``` + acl {{ $app.EscapedId }}-aclrule hdr_dom(host) -i {{ $app.MesosDnsId }} +``` + ### Environment Variables Configuration in the `production.json` file can be overridden with environment variables below. This is generally useful when you are building a Docker image for Bamboo and HAProxy. If they are not specified then the values from the configuration file will be used. @@ -298,7 +324,7 @@ Bamboo is started by supervisord in this Docker image. The [default Supervisord We use [godep](https://github.com/tools/godep) managing Go package dependencies; Goconvey for unit testing; CommonJS and SASS for frontend development and build distribution. -* Golang 1.3 +* Golang 1.7 * Node.js 0.10.x+ Golang: @@ -314,7 +340,7 @@ cd $GOPATH/src/github.com/QubitProducts/bamboo # Build your binary go build -# Run test +# Run test (requires a local zookeeper running) goconvey ``` diff --git a/VERSION b/VERSION index 9097948..3bfb9a4 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.2.16 +0.2.20 diff --git a/api/service.go b/api/service.go index acb07bc..4926480 100644 --- a/api/service.go +++ b/api/service.go @@ -5,68 +5,70 @@ import ( "errors" "io/ioutil" "net/http" + "strings" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/go-martini/martini" - zk "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" conf "github.com/QubitProducts/bamboo/configuration" "github.com/QubitProducts/bamboo/services/service" + "github.com/go-martini/martini" ) type ServiceAPI struct { - Config *conf.Configuration - Zookeeper *zk.Conn + Config *conf.Configuration + Storage service.Storage } func (d *ServiceAPI) All(w http.ResponseWriter, r *http.Request) { - services, err := service.All(d.Zookeeper, d.Config.Bamboo.Zookeeper) + services, err := d.Storage.All() if err != nil { responseError(w, err.Error()) return } - responseJSON(w, services) + byId := make(map[string]service.Service, len(services)) + for _, s := range services { + byId[s.Id] = s + } + + responseJSON(w, byId) } func (d *ServiceAPI) Create(w http.ResponseWriter, r *http.Request) { - serviceModel, err := extractServiceModel(r) + d.updateService(w, r) +} + +func (d *ServiceAPI) Put(params martini.Params, w http.ResponseWriter, r *http.Request) { + d.updateService(w, r) +} +func (d *ServiceAPI) updateService(w http.ResponseWriter, r *http.Request) { + service, err := extractService(r) if err != nil { responseError(w, err.Error()) return } - _, err = service.Create(d.Zookeeper, d.Config.Bamboo.Zookeeper, serviceModel.Id, serviceModel.Acl) + err = d.Storage.Upsert(service) if err != nil { responseError(w, err.Error()) return } - responseJSON(w, serviceModel) + responseJSON(w, service) } -func (d *ServiceAPI) Put(params martini.Params, w http.ResponseWriter, r *http.Request) { - - identity := params["_1"] - println(identity) - - serviceModel, err := extractServiceModel(r) - if err != nil { - responseError(w, err.Error()) +func (d *ServiceAPI) Delete(params martini.Params, w http.ResponseWriter, r *http.Request) { + serviceID := params["_1"] + if len(serviceID) == 0 { + responseError(w, "can not use empty ID") return } - _, err = service.Put(d.Zookeeper, d.Config.Bamboo.Zookeeper, identity, serviceModel.Acl) - if err != nil { - responseError(w, err.Error()) - return + if !strings.HasPrefix(serviceID, "/") { + serviceID = "/" + serviceID } - responseJSON(w, serviceModel) -} - -func (d *ServiceAPI) Delete(params martini.Params, w http.ResponseWriter, r *http.Request) { - err := service.Delete(d.Zookeeper, d.Config.Bamboo.Zookeeper, params["_1"]) + err := d.Storage.Delete(serviceID) if err != nil { responseError(w, err.Error()) return @@ -75,7 +77,7 @@ func (d *ServiceAPI) Delete(params martini.Params, w http.ResponseWriter, r *htt responseJSON(w, new(map[string]string)) } -func extractServiceModel(r *http.Request) (service.Service, error) { +func extractService(r *http.Request) (service.Service, error) { var serviceModel service.Service payload, _ := ioutil.ReadAll(r.Body) @@ -84,6 +86,14 @@ func extractServiceModel(r *http.Request) (service.Service, error) { return serviceModel, errors.New("Unable to decode JSON request") } + if len(serviceModel.Id) == 0 { + return serviceModel, errors.New("can not use empty ID") + } + + if !strings.HasPrefix(serviceModel.Id, "/") { + serviceModel.Id = "/" + serviceModel.Id + } + return serviceModel, nil } diff --git a/api/service_test.go b/api/service_test.go new file mode 100644 index 0000000..414dc56 --- /dev/null +++ b/api/service_test.go @@ -0,0 +1,282 @@ +package api + +import ( + "errors" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + conf "github.com/QubitProducts/bamboo/configuration" + "github.com/QubitProducts/bamboo/services/service" +) + +type testStorage struct { + services []service.Service + err error + upsertChan chan service.Service + upsertResultChan chan error + deleteChan chan string + deleteResultChan chan error +} + +func newTestStorage(services []service.Service, err error) *testStorage { + return &testStorage{ + services: services, + err: err, + upsertChan: make(chan service.Service), + upsertResultChan: make(chan error), + deleteChan: make(chan string), + deleteResultChan: make(chan error), + } +} + +func (s *testStorage) All() ([]service.Service, error) { + return s.services, s.err +} + +func (s *testStorage) Upsert(service service.Service) error { + s.upsertChan <- service + return <-s.upsertResultChan +} + +func (s *testStorage) Delete(serviceID string) error { + s.deleteChan <- serviceID + return <-s.deleteResultChan +} + +func TestServiceAll(t *testing.T) { + for _, test := range []struct { + services []service.Service + err error + status int + output string + }{ + { + services: []service.Service{}, + err: nil, + status: http.StatusOK, + output: "{}", + }, + { + services: []service.Service{}, + err: errors.New("test error"), + status: http.StatusBadRequest, + output: "test error\n", + }, + { + services: []service.Service{ + service.Service{ + Id: "/some/service", + Acl: "path_beg /some/service", + Config: make(map[string]string), + }, + }, + err: nil, + status: http.StatusOK, + output: `{"/some/service":{"Id":"/some/service","Acl":"path_beg /some/service","Config":{}}}`, + }, + } { + c := &conf.Configuration{} + store := newTestStorage(test.services, test.err) + s := &ServiceAPI{ + Config: c, + Storage: store, + } + + r, err := http.NewRequest("GET", "/api/services", nil) + if err != nil { + t.Fatalf("Error creating request: %s", err) + } + w := httptest.NewRecorder() + + s.All(w, r) + + if w.Code != test.status { + t.Errorf("got %d, wanted %d", w.Code, test.status) + } + + if w.Body.String() != test.output { + t.Errorf("got '%s', wanted '%s'", w.Body.String(), test.output) + } + } +} + +type serviceUpdateFunc func(s *ServiceAPI, w http.ResponseWriter, r *http.Request) + +func TestServiceUpdate(t *testing.T) { + for _, call := range []serviceUpdateFunc{ + func(s *ServiceAPI, w http.ResponseWriter, r *http.Request) { + s.Create(w, r) + }, + func(s *ServiceAPI, w http.ResponseWriter, r *http.Request) { + params := make(map[string]string) + s.Put(params, w, r) + }, + } { + for _, test := range []struct { + body string + expected *service.Service + err error + status int + output string + }{ + { + body: "", + status: http.StatusBadRequest, + output: "Unable to decode JSON request\n", + }, + { + body: `{}`, + status: http.StatusBadRequest, + output: "can not use empty ID\n", + }, + { + body: `{"Id":"/some/service","Acl":"path_beg /some/service"}`, + expected: &service.Service{ + Id: "/some/service", + Acl: "path_beg /some/service", + Config: nil, + }, + status: http.StatusOK, + output: `{"Id":"/some/service","Acl":"path_beg /some/service","Config":null}`, + }, + { + body: `{"Id":"some/service","Acl":"path_beg /some/service"}`, + expected: &service.Service{ + Id: "/some/service", + Acl: "path_beg /some/service", + Config: nil, + }, + status: http.StatusOK, + output: `{"Id":"/some/service","Acl":"path_beg /some/service","Config":null}`, + }, + { + body: `{"Id":"/some/service","Acl":"path_beg /some/service"}`, + expected: &service.Service{ + Id: "/some/service", + Acl: "path_beg /some/service", + Config: nil, + }, + err: errors.New("test error"), + status: http.StatusBadRequest, + output: "test error\n", + }, + } { + c := &conf.Configuration{} + store := newTestStorage([]service.Service{}, nil) + s := &ServiceAPI{ + Config: c, + Storage: store, + } + + r, err := http.NewRequest("POST", "/api/services", strings.NewReader(test.body)) + if err != nil { + t.Fatalf("Error creating request: %s", err) + } + w := httptest.NewRecorder() + + join := make(chan bool) + go func() { + if test.expected != nil { + service := <-store.upsertChan + if !reflect.DeepEqual(service, *test.expected) { + t.Errorf("got %#v, wanted %#v", service, test.expected) + } + store.upsertResultChan <- test.err + } + join <- true + }() + + // call update function + call(s, w, r) + + if w.Code != test.status { + t.Errorf("got %d, wanted %d", w.Code, test.status) + } + + if w.Body.String() != test.output { + t.Errorf("got '%s', wanted '%s'", w.Body.String(), test.output) + } + <-join + } + } +} + +func TestServiceDelete(t *testing.T) { + for _, test := range []struct { + path string + expected string + err error + status int + output string + }{ + { + path: "", + expected: "", + err: nil, + status: http.StatusBadRequest, + output: "can not use empty ID\n", + }, + { + path: "some/service", + expected: "/some/service", + err: nil, + status: http.StatusOK, + output: "null", + }, + { + path: "/some/service", + expected: "/some/service", + err: nil, + status: http.StatusOK, + output: "null", + }, + { + path: "/some/service", + expected: "/some/service", + err: errors.New("test error"), + status: http.StatusBadRequest, + output: "test error\n", + }, + } { + c := &conf.Configuration{} + store := newTestStorage([]service.Service{}, nil) + s := &ServiceAPI{ + Config: c, + Storage: store, + } + + r, err := http.NewRequest("POST", "/api/services/"+test.path, nil) + if err != nil { + t.Fatalf("Error creating request: %s", err) + } + w := httptest.NewRecorder() + params := make(map[string]string) + params["_1"] = test.path + + join := make(chan bool) + go func() { + if len(test.expected) > 0 { + id := <-store.deleteChan + if id != test.expected { + t.Errorf("got '%s', wanted '%s'", id, test.expected) + } + store.deleteResultChan <- test.err + } + join <- true + }() + + s.Delete(params, w, r) + + if w.Code != test.status { + t.Errorf("got %d, wanted %d", w.Code, test.status) + } + + if w.Body.String() != test.output { + t.Errorf("got '%s', wanted '%s'", w.Body.String(), test.output) + } + <-join + } +} diff --git a/api/state.go b/api/state.go index 5e81969..717af66 100644 --- a/api/state.go +++ b/api/state.go @@ -5,18 +5,18 @@ import ( "io" "net/http" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" "github.com/QubitProducts/bamboo/configuration" "github.com/QubitProducts/bamboo/services/haproxy" + "github.com/QubitProducts/bamboo/services/service" ) type StateAPI struct { - Config *configuration.Configuration - Zookeeper *zk.Conn + Config *configuration.Configuration + Storage service.Storage } func (state *StateAPI) Get(w http.ResponseWriter, r *http.Request) { - templateData, _ := haproxy.GetTemplateData(state.Config, state.Zookeeper) + templateData, _ := haproxy.GetTemplateData(state.Config, state.Storage) payload, _ := json.Marshal(templateData) io.WriteString(w, string(payload)) } diff --git a/builder/build.sh b/builder/build.sh index 42aeda2..4f11d62 100755 --- a/builder/build.sh +++ b/builder/build.sh @@ -2,7 +2,7 @@ set -e set -u name=bamboo -version=${_BAMBOO_VERSION:-"1.0.0"} +version=${_BAMBOO_VERSION:-"0.2.20"} description="Bamboo is a DNS based HAProxy auto configuration and auto service discovery for Mesos Marathon." url="https://github.com/QuBitProducts/bamboo" arch="all" diff --git a/config/haproxy_template.cfg b/config/haproxy_template.cfg index a928736..0098d7b 100644 --- a/config/haproxy_template.cfg +++ b/config/haproxy_template.cfg @@ -56,6 +56,8 @@ frontend http-in # This is the default proxy criteria acl {{ $app.EscapedId }}-aclrule path_beg -i {{ $app.Id }} + # another possible default using DNS-friendly MesosDnsId: + #acl {{ $app.EscapedId }}-aclrule hdr_dom(host) -i {{ $app.MesosDnsId }} use_backend {{ $app.EscapedId }}-cluster if {{ $app.EscapedId }}-aclrule {{ end }} {{ end }} @@ -79,7 +81,7 @@ backend {{ $app.EscapedId }}-cluster{{ if $app.HealthCheckPath }} option httpclose option forwardfor {{ range $page, $task := .Tasks }} - server {{ $app.EscapedId}}-{{ $task.Host }}-{{ $task.Port }} {{ $task.Host }}:{{ $task.Port }} {{ if $app.HealthCheckPath }} check inter 30000 {{ end }} {{ end }} + server {{ $app.EscapedId}}-{{ $task.Host }}-{{ $task.Port }} {{ $task.Host }}:{{ $task.Port }} {{ if $app.HealthCheckPath }} check inter 30000 {{ end }} {{ if eq $app.HealthCheckProtocol "HTTPS" }} ssl verify none {{ end }} {{ end }} {{ end }} ## @@ -98,6 +100,6 @@ backend {{ $app.EscapedId }}-cluster{{ if $app.HealthCheckPath }} ## balance leastconn ## option forwardfor ## {{ range $page, $task := $app.Tasks }} -## server {{ $app.EscapedId }}-{{ $task.Host }}-{{ index $task.Ports $serviceIndex }} {{ $task.Host }}:{{ index $task.Ports $serviceIndex }} {{ if $app.HealthCheckPath }} check inter 30000 {{ end }} {{ end }} +## server {{ $app.EscapedId }}-{{ $task.Host }}-{{ index $task.Ports $serviceIndex }} {{ $task.Host }}:{{ index $task.Ports $serviceIndex }} {{ if $app.HealthCheckPath }} check inter 30000 {{ end }} {{ if eq $app.HealthCheckProtocol "HTTPS" }} ssl verify none {{ end }} {{ end }} ## {{ end }} ## {{ end }} diff --git a/configuration/marathon.go b/configuration/marathon.go index 5f076c1..dbbfc63 100644 --- a/configuration/marathon.go +++ b/configuration/marathon.go @@ -1,7 +1,7 @@ package configuration import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" + "github.com/samuel/go-zookeeper/zk" "strings" "time" ) diff --git a/configuration/statsd.go b/configuration/statsd.go index f2eac42..cce38df 100644 --- a/configuration/statsd.go +++ b/configuration/statsd.go @@ -1,7 +1,7 @@ package configuration import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/peterbourgon/g2s" + "github.com/peterbourgon/g2s" "log" "strings" "time" diff --git a/main/bamboo/bamboo.go b/main/bamboo/bamboo.go index 0e171bf..108bc87 100644 --- a/main/bamboo/bamboo.go +++ b/main/bamboo/bamboo.go @@ -14,14 +14,15 @@ import ( "syscall" "time" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/go-martini/martini" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/kardianos/osext" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/natefinch/lumberjack" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" "github.com/QubitProducts/bamboo/api" "github.com/QubitProducts/bamboo/configuration" "github.com/QubitProducts/bamboo/qzk" "github.com/QubitProducts/bamboo/services/event_bus" + "github.com/QubitProducts/bamboo/services/service" + "github.com/go-martini/martini" + "github.com/kardianos/osext" + "github.com/natefinch/lumberjack" + "github.com/samuel/go-zookeeper/zk" ) /* @@ -68,8 +69,14 @@ func main() { // Create Zookeeper connection zkConn := listenToZookeeper(conf, eventBus) + // Create the storage backend + storage, err := service.NewZKStorage(zkConn, conf.Bamboo.Zookeeper) + if err != nil { + log.Panicf("Failed to create ZK storage: %v", err) + } + // Register handlers - handlers := event_bus.Handlers{Conf: &conf, Zookeeper: zkConn} + handlers := event_bus.Handlers{Conf: &conf, Storage: storage} eventBus.Register(handlers.MarathonEventHandler) eventBus.Register(handlers.ServiceEventHandler) eventBus.Publish(event_bus.MarathonEvent{EventType: "bamboo_startup", Timestamp: time.Now().Format(time.RFC3339)}) @@ -78,12 +85,12 @@ func main() { registerOSSignals(&conf, eventBus) // Start server - initServer(&conf, zkConn, eventBus) + initServer(&conf, storage, eventBus) } -func initServer(conf *configuration.Configuration, conn *zk.Conn, eventBus *event_bus.EventBus) { - stateAPI := api.StateAPI{Config: conf, Zookeeper: conn} - serviceAPI := api.ServiceAPI{Config: conf, Zookeeper: conn} +func initServer(conf *configuration.Configuration, storage service.Storage, eventBus *event_bus.EventBus) { + stateAPI := api.StateAPI{Config: conf, Storage: storage} + serviceAPI := api.ServiceAPI{Config: conf, Storage: storage} eventSubAPI := api.EventSubscriptionAPI{Conf: conf, EventBus: eventBus} conf.StatsD.Increment(1.0, "restart", 1) diff --git a/main/zk-test/zk-test.go b/main/zk-test/zk-test.go index 0d2bd24..9606129 100644 --- a/main/zk-test/zk-test.go +++ b/main/zk-test/zk-test.go @@ -6,9 +6,9 @@ import ( "fmt" "os" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" conf "github.com/QubitProducts/bamboo/configuration" "github.com/QubitProducts/bamboo/qzk" + "github.com/samuel/go-zookeeper/zk" ) func showEvents(evts chan zk.Event) { diff --git a/qzk/qzk.go b/qzk/qzk.go index ac0662f..5b678fa 100644 --- a/qzk/qzk.go +++ b/qzk/qzk.go @@ -7,8 +7,8 @@ import ( "strings" "time" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" c "github.com/QubitProducts/bamboo/configuration" + "github.com/samuel/go-zookeeper/zk" ) var logger = log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile) diff --git a/services/event_bus/event_handler.go b/services/event_bus/event_handler.go index 505d565..b979deb 100644 --- a/services/event_bus/event_handler.go +++ b/services/event_bus/event_handler.go @@ -1,9 +1,9 @@ package event_bus import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" "github.com/QubitProducts/bamboo/configuration" "github.com/QubitProducts/bamboo/services/haproxy" + "github.com/QubitProducts/bamboo/services/service" "github.com/QubitProducts/bamboo/services/template" "io/ioutil" "log" @@ -29,8 +29,8 @@ type ServiceEvent struct { } type Handlers struct { - Conf *configuration.Configuration - Zookeeper *zk.Conn + Conf *configuration.Configuration + Storage service.Storage } func (h *Handlers) MarathonEventHandler(event MarathonEvent) { @@ -52,7 +52,7 @@ func init() { log.Println("Starting update loop") for { h := <-updateChan - handleHAPUpdate(h.Conf, h.Zookeeper) + handleHAPUpdate(h.Conf, h.Storage) } }() } @@ -73,9 +73,9 @@ func queueUpdate(h *Handlers) { <-queueUpdateSem } -func handleHAPUpdate(conf *configuration.Configuration, conn *zk.Conn) { +func handleHAPUpdate(conf *configuration.Configuration, storage service.Storage) { reloadStart := time.Now() - reloaded, err := ensureLatestConfig(conf, conn) + reloaded, err := ensureLatestConfig(conf, storage) if err != nil { conf.StatsD.Increment(1.0, "haproxy.reload.error", 1) @@ -91,8 +91,8 @@ func handleHAPUpdate(conf *configuration.Configuration, conn *zk.Conn) { } // For values of 'latest' conforming to general relativity. -func ensureLatestConfig(conf *configuration.Configuration, conn *zk.Conn) (reloaded bool, err error) { - content, err := generateConfig(conf.HAProxy.TemplatePath, conf, conn) +func ensureLatestConfig(conf *configuration.Configuration, storage service.Storage) (reloaded bool, err error) { + content, err := generateConfig(conf.HAProxy.TemplatePath, conf, storage) if err != nil { return } @@ -118,14 +118,14 @@ func ensureLatestConfig(conf *configuration.Configuration, conn *zk.Conn) (reloa } // Generates the new config to be written -func generateConfig(templatePath string, conf *configuration.Configuration, conn *zk.Conn) (config string, err error) { +func generateConfig(templatePath string, conf *configuration.Configuration, storage service.Storage) (config string, err error) { templateContent, err := ioutil.ReadFile(templatePath) if err != nil { log.Println("Failed to read template contents") return } - templateData, err := haproxy.GetTemplateData(conf, conn) + templateData, err := haproxy.GetTemplateData(conf, storage) if err != nil { log.Println("Failed to retrieve template data") return diff --git a/services/event_bus/event_handler_test.go b/services/event_bus/event_handler_test.go index 91d519a..3749c02 100644 --- a/services/event_bus/event_handler_test.go +++ b/services/event_bus/event_handler_test.go @@ -6,7 +6,7 @@ import ( "math/rand" "testing" - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey" + . "github.com/smartystreets/goconvey/convey" "github.com/QubitProducts/bamboo/configuration" ) diff --git a/services/haproxy/haproxy.go b/services/haproxy/haproxy.go index 4a02dca..4e2c19f 100644 --- a/services/haproxy/haproxy.go +++ b/services/haproxy/haproxy.go @@ -1,7 +1,6 @@ package haproxy import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" conf "github.com/QubitProducts/bamboo/configuration" "github.com/QubitProducts/bamboo/services/marathon" "github.com/QubitProducts/bamboo/services/service" @@ -13,7 +12,7 @@ type templateData struct { HAProxy conf.HAProxy } -func GetTemplateData(config *conf.Configuration, conn *zk.Conn) (*templateData, error) { +func GetTemplateData(config *conf.Configuration, storage service.Storage) (*templateData, error) { apps, err := marathon.FetchApps(config.Marathon, config) @@ -21,11 +20,15 @@ func GetTemplateData(config *conf.Configuration, conn *zk.Conn) (*templateData, return nil, err } - services, err := service.All(conn, config.Bamboo.Zookeeper) - + services, err := storage.All() if err != nil { return nil, err } - return &templateData{apps, services, config.HAProxy}, nil + byName := make(map[string]service.Service) + for _, service := range services { + byName[service.Id] = service + } + + return &templateData{apps, byName, config.HAProxy}, nil } diff --git a/services/marathon/marathon.go b/services/marathon/marathon.go index 1d68f49..88e078b 100644 --- a/services/marathon/marathon.go +++ b/services/marathon/marathon.go @@ -13,9 +13,11 @@ import ( // Describes an app process running type Task struct { + Id string Host string Port int Ports []int + Alive bool } // A health check on the application @@ -30,15 +32,18 @@ type HealthCheck struct { // An app may have multiple processes type App struct { - Id string - EscapedId string - HealthCheckPath string - HealthChecks []HealthCheck - Tasks []Task - ServicePort int - ServicePorts []int - Env map[string]string - Labels map[string]string + Id string + MesosDnsId string + EscapedId string + HealthCheckPath string + HealthCheckProtocol string + HealthChecks []HealthCheck + Tasks []Task + ServicePort int + ServicePorts []int + Env map[string]string + Labels map[string]string + SplitId []string } // hostnameLabels is the label that contains bamboo hostname configuratiuon that @@ -91,15 +96,20 @@ type marathonTasks struct { Tasks marathonTaskList `json:"tasks"` } +type HealthCheckResult struct { + Alive bool +} + type marathonTask struct { - AppId string - Id string - Host string - Ports []int - ServicePorts []int - StartedAt string - StagedAt string - Version string + AppId string + Id string + Host string + Ports []int + ServicePorts []int + StartedAt string + StagedAt string + Version string + HealthCheckResults []HealthCheckResult } func (slice marathonTaskList) Len() int { @@ -213,8 +223,20 @@ func fetchTasks(endpoint string, conf *conf.Configuration) (map[string]marathonT return tasksById, nil } -func createApps(tasksById map[string]marathonTaskList, marathonApps map[string]marathonApp) AppList { +func calculateTaskHealth(healthCheckResults []HealthCheckResult, healthChecks []marathonHealthCheck) bool { + //If we don't even have health check results for every health check, don't count the task as healthy + if len(healthChecks) > len(healthCheckResults) { + return false + } + for _, healthCheck := range healthCheckResults { + if !healthCheck.Alive { + return false + } + } + return true +} +func createApps(tasksById map[string]marathonTaskList, marathonApps map[string]marathonApp) AppList { apps := AppList{} for appId, mApp := range marathonApps { @@ -227,11 +249,14 @@ func createApps(tasksById map[string]marathonTaskList, marathonApps map[string]m // build App from marathonApp app := App{ - Id: appPath, - EscapedId: strings.Replace(appId, "/", "::", -1), - HealthCheckPath: parseHealthCheckPath(mApp.HealthChecks), - Env: mApp.Env, - Labels: mApp.Labels, + Id: appPath, + MesosDnsId: getMesosDnsId(appPath), + EscapedId: strings.Replace(appId, "/", "::", -1), + HealthCheckPath: parseHealthCheckPath(mApp.HealthChecks), + HealthCheckProtocol: parseHealthCheckProtocol(mApp.HealthChecks), + Env: mApp.Env, + Labels: mApp.Labels, + SplitId: strings.Split(appId, "/"), } app.HealthChecks = make([]HealthCheck, 0, len(mApp.HealthChecks)) @@ -254,9 +279,11 @@ func createApps(tasksById map[string]marathonTaskList, marathonApps map[string]m for _, mTask := range tasksById[appId] { if len(mTask.Ports) > 0 { t := Task{ + Id: mTask.Id, Host: mTask.Host, Port: mTask.Ports[0], Ports: mTask.Ports, + Alive: calculateTaskHealth(mTask.HealthCheckResults, mApp.HealthChecks), } tasks = append(tasks, t) } @@ -268,9 +295,22 @@ func createApps(tasksById map[string]marathonTaskList, marathonApps map[string]m return apps } +func getMesosDnsId(appPath string) string { + // split up groups and recombine for how mesos-dns/consul/etc use service name + // "/nested/group/app" -> "app-group-nested" + groups := strings.Split(appPath, "/") + reverseGroups := []string{} + for i := len(groups) - 1; i >= 0; i-- { + if groups[i] != "" { + reverseGroups = append(reverseGroups, groups[i]) + } + } + return strings.Join(reverseGroups, "-") +} + func parseHealthCheckPath(checks []marathonHealthCheck) string { for _, check := range checks { - if check.Protocol != "HTTP" { + if check.Protocol != "HTTP" && check.Protocol != "HTTPS" { continue } return check.Path @@ -278,6 +318,17 @@ func parseHealthCheckPath(checks []marathonHealthCheck) string { return "" } +/* maybe combine this with the above? */ +func parseHealthCheckProtocol(checks []marathonHealthCheck) string { + for _, check := range checks { + if check.Protocol != "HTTP" && check.Protocol != "HTTPS" { + continue + } + return check.Protocol + } + return "" +} + /* Apps returns a struct that describes Marathon current app and their sub tasks information. diff --git a/services/marathon/marathon_test.go b/services/marathon/marathon_test.go index 5d26fbd..ff097cb 100644 --- a/services/marathon/marathon_test.go +++ b/services/marathon/marathon_test.go @@ -1,11 +1,8 @@ package marathon import ( + . "github.com/smartystreets/goconvey/convey" "testing" - - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey" - conf "github.com/QubitProducts/bamboo/configuration" - "github.com/QubitProducts/bamboo/services/service" ) func TestAcl(t *testing.T) { diff --git a/services/service/representation.go b/services/service/representation.go new file mode 100644 index 0000000..6ee1400 --- /dev/null +++ b/services/service/representation.go @@ -0,0 +1,105 @@ +package service + +import ( + "encoding/json" + "fmt" +) + +type ServiceRepr interface { + Service() Service + Serialize() ([]byte, error) +} + +// ParseServiceRepr attempts parse using each of the ReprParsers in turn. Returns the first +// result to not error, or the error from the last parser +func ParseServiceRepr(body []byte, path string) (repr ServiceRepr, err error) { + reprParsers := [](func([]byte, string) (ServiceRepr, error)){ + ParseV2ServiceRepr, + ParseV1ServiceRepr, + } + + for _, parser := range reprParsers { + repr, err = parser(body, path) + + if err == nil { + return + } + } + return nil, err +} + +type V1ServiceRepr struct { + ID string + Acl string +} + +func ParseV1ServiceRepr(body []byte, path string) (repr ServiceRepr, err error) { + return &V1ServiceRepr{ + ID: path, + Acl: string(body), + }, nil +} + +func (v1 *V1ServiceRepr) Service() Service { + return Service{ + Id: v1.ID, + Acl: v1.Acl, + Config: map[string]string{"Acl": v1.Acl}, + } +} + +func (v1 *V1ServiceRepr) Serialize() ([]byte, error) { + return []byte(v1.Acl), nil +} + +type V2ServiceRepr struct { + ID string `json:"-"` + Version string `json:"version"` // 2 is only valid version for V2ServiceRepr + Config map[string]string `json:"config"` +} + +func MakeV2ServiceRepr(service Service) *V2ServiceRepr { + config := make(map[string]string, len(service.Config)+1) + for k, v := range service.Config { + config[k] = v + } + if service.Acl != "" { + config["Acl"] = service.Acl + } + return NewV2ServiceRepr(service.Id, config) +} + +func NewV2ServiceRepr(appID string, config map[string]string) *V2ServiceRepr { + return &V2ServiceRepr{ + ID: appID, + Version: "2", + Config: config, + } +} + +func ParseV2ServiceRepr(body []byte, path string) (ServiceRepr, error) { + var repr V2ServiceRepr + err := json.Unmarshal(body, &repr) + if err != nil { + return nil, err + } + if repr.Version != "2" { + return nil, fmt.Errorf("Service version is not 2 (%s)", repr.Version) + } + repr.ID = path + + return &repr, nil +} + +func (v2 *V2ServiceRepr) Service() Service { + acl, _ := v2.Config["Acl"] + return Service{ + Id: v2.ID, + Acl: acl, + Config: v2.Config, + } +} + +func (v2 *V2ServiceRepr) Serialize() ([]byte, error) { + return json.Marshal(&v2) +} diff --git a/services/service/representation_test.go b/services/service/representation_test.go new file mode 100644 index 0000000..11a6f0d --- /dev/null +++ b/services/service/representation_test.go @@ -0,0 +1,241 @@ +package service + +import ( + "fmt" + "math/rand" + "reflect" + "testing" + "testing/quick" + + . "github.com/smartystreets/goconvey/convey" +) + +// Yanked off http://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang +const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +const ( + letterIdxBits = 6 + letterIdxMask = 1<= 0; { + if remain == 0 { + cache, remain = rand.Int63(), letterIdxMax + } + if idx := int(cache & letterIdxMask); idx < len(letterBytes) { + b[i] = letterBytes[idx] + i-- + } + cache >>= letterIdxBits + remain-- + } + + return string(b) +} + +func orPanic(err error) { + if err != nil { + panic(fmt.Sprintf("Error! %s", err)) + } +} + +func TestV1ServiceRepr(t *testing.T) { + Convey("#ParseV1ServiceRepr", t, func() { + Convey("when we parse an arbitrary string", func() { + str := randString(128) + path := randString(8) + + repr, err := ParseV1ServiceRepr([]byte(str), path) + + Convey("it should not error", func() { + So(err, ShouldBeNil) + }) + + Convey("it should be a V1ServiceRepr", func() { + So(repr, ShouldHaveSameTypeAs, &V1ServiceRepr{}) + }) + + Convey("when we create a service from the repr", func() { + service := repr.Service() + + Convey("it should have the same id as the passed path", func() { + So(service.Id, ShouldEqual, path) + }) + + Convey("it should have the same ACL as the passed body", func() { + So(service.Acl, ShouldEqual, str) + }) + + Convey("it should have no other config entries", func() { + acl, ok := service.Config["Acl"] + So(ok, ShouldBeTrue) + So(acl, ShouldNotBeBlank) + So(len(service.Config), ShouldEqual, 1) + }) + }) + + }) + }) +} + +func TestV2ServiceRepr(t *testing.T) { + Convey("#ParseV1ServiceRepr", t, func() { + Convey("when we parse an invalid string", func() { + str := "}{" + randString(128) + path := randString(8) + + _, err := ParseV2ServiceRepr([]byte(str), path) + + Convey("it should error", func() { + So(err, ShouldNotBeNil) + }) + }) + + Convey("when we parse a json blob with an incorrect version", func() { + path := randString(8) + body := []byte(`{"version": "3", "config": {}}`) + _, err := ParseV2ServiceRepr(body, path) + + Convey("it should error", func() { + So(err, ShouldNotBeNil) + }) + }) + + Convey("when we parse a json blob with a correct version and no config", func() { + path := randString(8) + body := []byte(`{"version": "2", "config": {}}`) + repr, err := ParseV2ServiceRepr(body, path) + + Convey("it should not error", func() { + So(err, ShouldBeNil) + }) + + Convey("when we create a service from the repr", func() { + service := repr.Service() + + Convey("it should have the same id as the passed path", func() { + So(service.Id, ShouldEqual, path) + }) + + Convey("it should have no ACL", func() { + So(service.Acl, ShouldBeBlank) + }) + + Convey("it should have no config value", func() { + So(len(service.Config), ShouldEqual, 0) + }) + }) + }) + + Convey("when we parse a json blob with a correct version and a complete config", func() { + path := randString(8) + body := []byte(`{"version": "2", "config": {"Acl": "foo", "arb": "barb"}}`) + repr, err := ParseV2ServiceRepr(body, path) + + Convey("it should not error", func() { + So(err, ShouldBeNil) + }) + + Convey("when we create a service from the repr", func() { + service := repr.Service() + + Convey("it should have the same id as the passed path", func() { + So(service.Id, ShouldEqual, path) + }) + + Convey("it should have an ACL", func() { + So(service.Acl, ShouldEqual, "foo") + }) + + Convey("it should have an additional config value", func() { + So(len(service.Config), ShouldEqual, 2) + So(service.Config["arb"], ShouldEqual, "barb") + }) + }) + }) + }) + + Convey("#MakeV2ServiceRepr", t, func() { + Convey("MakeV2ServiceRepr and V2ServiceRepr.Service should compose to identity", func() { + property := func(s Service) bool { + // The generator may create services with different .Acl and .Conf["Acl"] + s.Config["Acl"] = s.Acl + s2 := MakeV2ServiceRepr(s).Service() + return reflect.DeepEqual(s, s2) + } + + err := quick.Check(property, nil) + So(err, ShouldBeNil) + }) + }) +} + +func TestParseServiceRepr(t *testing.T) { + Convey("#ParseServiceRepr", t, func() { + Convey("when we parse an invalid json string", func() { + path := randString(8) + body := []byte("}{" + randString(128)) + + repr, err := ParseServiceRepr([]byte(body), path) + + Convey("it should not error", func() { + So(err, ShouldBeNil) + }) + + Convey("it should be a V1ServiceRepr", func() { + So(repr, ShouldHaveSameTypeAs, &V1ServiceRepr{}) + }) + + Convey("when we create a service from the repr", func() { + service := repr.Service() + + Convey("it should ave the same id as the passed path", func() { + So(service.Id, ShouldEqual, path) + }) + + Convey("its acl should be the body", func() { + So(service.Acl, ShouldEqual, string(body)) + }) + + Convey("it should have no other config values", func() { + So(len(service.Config), ShouldEqual, 1) + }) + }) + }) + + Convey("when we parse a v2 repr", func() { + path := randString(8) + body := []byte(`{"version": "2", "config": {"Acl": "foo", "arb": "barb"}}`) + + repr, err := ParseServiceRepr(body, path) + + Convey("it should not error", func() { + So(err, ShouldBeNil) + }) + + Convey("it should be a V2ServiceRepr", func() { + So(repr, ShouldHaveSameTypeAs, &V2ServiceRepr{}) + }) + + Convey("when we create a service from the repr", func() { + service := repr.Service() + + Convey("it should have the same id as the passed path", func() { + So(service.Id, ShouldEqual, path) + }) + + Convey("its acl should be foo", func() { + So(service.Acl, ShouldEqual, "foo") + }) + + Convey("it should have one other config value", func() { + So(len(service.Config), ShouldEqual, 2) + So(service.Config["arb"], ShouldEqual, "barb") + }) + }) + }) + }) +} diff --git a/services/service/service.go b/services/service/service.go index 41b968a..9ff68ec 100644 --- a/services/service/service.go +++ b/services/service/service.go @@ -1,113 +1,16 @@ package service -import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" - conf "github.com/QubitProducts/bamboo/configuration" - "net/url" - "strings" -) - type Service struct { - Id string `param:"id"` - Acl string `param:"acl"` -} - -func All(conn *zk.Conn, zkConf conf.Zookeeper) (map[string]Service, error) { - - err := ensurePathExists(conn, zkConf.Path) - if err != nil { - return nil, err - } - - services := map[string]Service{} - keys, _, err2 := conn.Children(zkConf.Path) - - if err2 != nil { - return nil, err2 - } - - for _, childPath := range keys { - bite, _, e := conn.Get(zkConf.Path + "/" + childPath) - if e != nil { - return nil, e - } - appId, _ := unescapeSlashes(childPath) - services[appId] = Service{Id: appId, Acl: string(bite)} - } - return services, nil -} - -/* - Read ZK ACL: - http://zookeeper.apache.org/doc/trunk/zookeeperProgrammers.html#sc_ACLPermissions -*/ -func Create(conn *zk.Conn, zkConf conf.Zookeeper, appId string, domainValue string) (string, error) { - path := concatPath(zkConf.Path, validateAppId(appId)) - resPath, err := conn.Create(path, []byte(domainValue), 0, defaultACL()) - if err != nil { - return "", err - } - - return resPath, nil -} - -func Put(conn *zk.Conn, zkConf conf.Zookeeper, appId string, domainValue string) (*zk.Stat, error) { - path := concatPath(zkConf.Path, validateAppId(appId)) - err := ensurePathExists(conn, path) - if err != nil { - return nil, err - } - - stats, err := conn.Set(path, []byte(domainValue), -1) - if err != nil { - return nil, err - } - - // Force triger an event on parent - conn.Set(zkConf.Path, []byte{}, -1) - - return stats, nil -} - -func Delete(conn *zk.Conn, zkConf conf.Zookeeper, appId string) error { - path := concatPath(zkConf.Path, validateAppId(appId)) - return conn.Delete(path, -1) -} - -func concatPath(parentPath string, appId string) string { - return parentPath + "/" + escapeSlashes(appId) -} - -func ensurePathExists(conn *zk.Conn, path string) error { - pathExists, _, _ := conn.Exists(path) - if pathExists { - return nil - } - - _, err := conn.Create(path, []byte{}, 0, defaultACL()) - if err != nil { - return err - } - - return nil -} - -func defaultACL() []zk.ACL { - return []zk.ACL{zk.ACL{Perms: zk.PermAll, Scheme: "world", ID: "anyone"}} -} - -func validateAppId(appId string) string { - if strings.HasPrefix(appId, "/") { - return appId - } else { - return "/" + appId - } -} - -func escapeSlashes(id string) string { - return url.QueryEscape(id) -} - -func unescapeSlashes(id string) (string, error) { - return url.QueryUnescape(id) + Id string `param:"id"` + // Acl is present for backwards compatability, and should not be written to. + // Instead, write to the "Acl" key in Config + Acl string `param:"acl"` + Config map[string]string `param:"config"` +} + +// The storage primitives required by Bamboo from the storage backend +type Storage interface { + All() ([]Service, error) + Upsert(service Service) error + Delete(serviceId string) error } diff --git a/services/service/zookeeper.go b/services/service/zookeeper.go new file mode 100644 index 0000000..8feeefe --- /dev/null +++ b/services/service/zookeeper.go @@ -0,0 +1,141 @@ +package service + +import ( + conf "github.com/QubitProducts/bamboo/configuration" + "github.com/samuel/go-zookeeper/zk" + "log" + "net/url" +) + +type ZKStorage struct { + conn *zk.Conn + conf conf.Zookeeper + acl []zk.ACL +} + +func NewZKStorage(conn *zk.Conn, conf conf.Zookeeper) (s *ZKStorage, err error) { + s = &ZKStorage{ + conn: conn, + conf: conf, + acl: defaultACL(), + } + err = s.ensurePathExists() + return s, err +} + +func (z *ZKStorage) All() (services []Service, err error) { + err = z.ensurePathExists() + if err != nil { + return + } + + keys, _, err := z.conn.Children(z.conf.Path) + if err != nil { + return + } + + services = make([]Service, 0, len(keys)) + for _, childPath := range keys { + body, _, err := z.conn.Get(z.conf.Path + "/" + childPath) + if err != nil { + return nil, err + } + + path, err := unescapePath(childPath) + if err != nil { + return nil, err + } + + // We tolerate being unable to decode a service body, as may be new version running simultaneously + repr, err := ParseServiceRepr(body, path) + if err != nil { + log.Printf("Failed to parse service at %v: %v", path, err) + continue + } + + services = append(services, repr.Service()) + } + + return +} + +func (z *ZKStorage) Upsert(service Service) (err error) { + repr := MakeV2ServiceRepr(service) + + body, err := repr.Serialize() + if err != nil { + return + } + + err = z.ensurePathExists() + if err != nil { + return err + } + + path := z.servicePath(service.Id) + + ok, _, err := z.conn.Exists(path) + if err != nil { + return + } + + if ok { + _, err = z.conn.Set(path, body, -1) + if err != nil { + log.Print("Failed to set path", err) + return + } + + // Trigger an event on the parent + _, err = z.conn.Set(z.conf.Path, []byte{}, -1) + if err != nil { + log.Print("Failed to trigger event on parent", err) + err = nil + } + + } else { + _, err = z.conn.Create(path, body, 0, z.acl) + if err != nil { + log.Print("Failed to set create", err) + return + } + } + return +} + +func (z *ZKStorage) Delete(serviceId string) error { + path := z.servicePath(serviceId) + return z.conn.Delete(path, -1) +} + +func (z *ZKStorage) servicePath(id string) string { + return z.conf.Path + "/" + escapePath(id) +} + +func (z *ZKStorage) ensurePathExists() error { + pathExists, _, _ := z.conn.Exists(z.conf.Path) + if pathExists { + return nil + } + + // This is a fairly rare, and fairly critical, operation, so I'm going to be verbose + log.Print("Creating base zk path", z.conf.Path) + _, err := z.conn.Create(z.conf.Path, []byte{}, 0, z.acl) + if err != nil { + log.Print("Failed to create base zk path", err) + } + + return err +} + +func defaultACL() []zk.ACL { + return []zk.ACL{zk.ACL{Perms: zk.PermAll, Scheme: "world", ID: "anyone"}} +} + +func escapePath(path string) string { + return url.QueryEscape(path) +} + +func unescapePath(path string) (string, error) { + return url.QueryUnescape(path) +} diff --git a/services/service/zookeeper_test.go b/services/service/zookeeper_test.go new file mode 100644 index 0000000..81bb0b8 --- /dev/null +++ b/services/service/zookeeper_test.go @@ -0,0 +1,268 @@ +package service + +import ( + . "github.com/smartystreets/goconvey/convey" + "testing" + + "log" + "time" + + "github.com/QubitProducts/bamboo/configuration" + "github.com/samuel/go-zookeeper/zk" +) + +var zkTimeout = time.Second +var zkConf = configuration.Zookeeper{ + Host: "localhost:2181", + Path: "/test-bamboo", + ReportingDelay: 1, +} + +func cleanZK(conn *zk.Conn) { + deleteRecursive(conn, zkConf.Path) +} + +func deleteRecursive(conn *zk.Conn, path string) { + children, _, err := conn.Children(path) + if err != nil { + log.Printf("failed to get children %s: %s", path, err) + return + } + for _, child := range children { + deleteRecursive(conn, path+"/"+child) + } + err = conn.Delete(path, -1) + if err != nil { + log.Printf("failed to delete %s: %s", path, err) + } +} + +func loadToZK(conn *zk.Conn, data [][2]string) { + for _, entry := range data { + k := entry[0] + v := entry[1] + _, err := conn.Create(k, []byte(v), 0, defaultACL()) + orPanic(err) + } +} + +func TestZKStorage(t *testing.T) { + conn, _, err := zk.Connect(zkConf.ConnectionString(), zkTimeout) + orPanic(err) + + Convey("#NewZKStorage", t, func() { + cleanZK(conn) + s, err := NewZKStorage(conn, zkConf) + + So(err, ShouldBeNil) + + Convey("it should implement the Storage interface", func() { + _, ok := interface{}(s).(Storage) + So(ok, ShouldBeTrue) + }) + + Convey("it should have created the base path", func() { + exists, _, err := conn.Exists(zkConf.Path) + + So(err, ShouldBeNil) + So(exists, ShouldBeTrue) + }) + }) + + Convey("#ZKStorage.All", t, func() { + s, err := NewZKStorage(conn, zkConf) + So(err, ShouldBeNil) + + Convey("when I get all in an empty zookeeper", func() { + cleanZK(conn) + entries, err := s.All() + + So(err, ShouldBeNil) + + Convey("there should be no entries", func() { + So(len(entries), ShouldEqual, 0) + }) + }) + + Convey("when I get all in a legacy/v1 zookeeper", func() { + cleanZK(conn) + loadToZK(conn, [][2]string{ + [2]string{zkConf.Path, ""}, + [2]string{zkConf.Path + "/test", "hdr(host) -i foo"}, + [2]string{zkConf.Path + "/test2", "fozbaz"}, + }) + + entries, err := s.All() + + So(err, ShouldBeNil) + + Convey("there should be the correct number of entries", func() { + So(len(entries), ShouldEqual, 2) + }) + + Convey("there should be an entry with the id test", func() { + var test Service + found := false + for _, i := range entries { + if i.Id == "test" { + test = i + found = true + break + } + } + So(found, ShouldBeTrue) + + Convey("which should have an acl 'hdr(host) -i foo'", func() { + So(test.Acl, ShouldEqual, "hdr(host) -i foo") + So(test.Config["Acl"], ShouldEqual, "hdr(host) -i foo") + }) + }) + }) + + Convey("when I get all in a mixed v1/v2 zookeeper", func() { + cleanZK(conn) + loadToZK(conn, [][2]string{ + [2]string{zkConf.Path, ""}, + [2]string{zkConf.Path + "/test", `{"version": "2", "config": {"Acl": "foo", "arb": "barb"}}`}, + [2]string{zkConf.Path + "/test2", "fozbaz"}, + }) + + entries, err := s.All() + + So(err, ShouldBeNil) + + Convey("there should be the correct number of entries", func() { + So(len(entries), ShouldEqual, 2) + }) + + Convey("there should be an entry with the id test", func() { + var test Service + found := false + for _, i := range entries { + if i.Id == "test" { + test = i + found = true + break + } + } + So(found, ShouldBeTrue) + + Convey("which should have an acl 'foo'", func() { + So(test.Acl, ShouldEqual, "foo") + So(test.Config["Acl"], ShouldEqual, "foo") + }) + + Convey("which should have a config entry 'arb'", func() { + So(test.Config["arb"], ShouldEqual, "barb") + }) + }) + }) + }) + + Convey("#ZKStorage.Upsert", t, func() { + s, err := NewZKStorage(conn, zkConf) + So(err, ShouldBeNil) + + testService := Service{ + Id: "test", + Config: map[string]string{ + "Acl": "foo", + "barst": "carst", + }, + } + + Convey("when I insert into an empty key", func() { + cleanZK(conn) + err := s.Upsert(testService) + So(err, ShouldBeNil) + + entries, err := s.All() + So(err, ShouldBeNil) + + Convey("there should be 1 entry", func() { + So(len(entries), ShouldEqual, 1) + + readEntry := entries[0] + + Convey("which should have an Acl 'foo'", func() { + So(readEntry.Acl, ShouldEqual, "foo") + So(readEntry.Config["Acl"], ShouldEqual, "foo") + }) + + Convey("which should have a config entry 'barst'", func() { + So(readEntry.Config["barst"], ShouldEqual, "carst") + }) + }) + }) + + Convey("when I insert into an existing key", func() { + cleanZK(conn) + loadToZK(conn, [][2]string{ + [2]string{zkConf.Path, ""}, + [2]string{zkConf.Path + "/test", "fozbaz"}, + }) + + err := s.Upsert(testService) + So(err, ShouldBeNil) + + entries, err := s.All() + So(err, ShouldBeNil) + + Convey("there should be 1 entry", func() { + So(len(entries), ShouldEqual, 1) + + readEntry := entries[0] + + Convey("which should have an Acl 'foo'", func() { + So(readEntry.Acl, ShouldEqual, "foo") + So(readEntry.Config["Acl"], ShouldEqual, "foo") + }) + + Convey("which should have a config entry 'barst'", func() { + So(readEntry.Config["barst"], ShouldEqual, "carst") + }) + }) + }) + }) + + Convey("#ZKStorage.Delete", t, func() { + s, err := NewZKStorage(conn, zkConf) + So(err, ShouldBeNil) + + Convey("when I delete the only service", func() { + cleanZK(conn) + loadToZK(conn, [][2]string{ + [2]string{zkConf.Path, ""}, + [2]string{zkConf.Path + "/test", "fozbaz"}, + }) + + err := s.Delete("test") + So(err, ShouldBeNil) + + Convey("there should be zero entries", func() { + entries, err := s.All() + So(err, ShouldBeNil) + + So(len(entries), ShouldEqual, 0) + }) + }) + + Convey("when I delete an non-existant service", func() { + cleanZK(conn) + + err := s.Delete("test") + + Convey("it should error", func() { + So(err, ShouldNotBeNil) + }) + So(err, ShouldNotBeNil) + + Convey("there should be zero entries", func() { + entries, err := s.All() + So(err, ShouldBeNil) + + So(len(entries), ShouldEqual, 0) + }) + }) + }) +} diff --git a/services/template/template.go b/services/template/template.go index 1de7c89..b01079b 100644 --- a/services/template/template.go +++ b/services/template/template.go @@ -2,11 +2,10 @@ package template import ( "bytes" - "strings" - "text/template" - "github.com/QubitProducts/bamboo/services/marathon" "github.com/QubitProducts/bamboo/services/service" + "strings" + "text/template" ) func hasKey(data map[string]service.Service, appId string) bool { diff --git a/services/template/template_test.go b/services/template/template_test.go index 66576dc..63f65bc 100644 --- a/services/template/template_test.go +++ b/services/template/template_test.go @@ -1,7 +1,7 @@ package template import ( - . "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/smartystreets/goconvey/convey" + . "github.com/smartystreets/goconvey/convey" "testing" ) diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/.gitignore b/vendor/github.com/codegangsta/inject/.gitignore similarity index 100% rename from Godeps/_workspace/src/github.com/codegangsta/inject/.gitignore rename to vendor/github.com/codegangsta/inject/.gitignore diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/LICENSE b/vendor/github.com/codegangsta/inject/LICENSE similarity index 100% rename from Godeps/_workspace/src/github.com/codegangsta/inject/LICENSE rename to vendor/github.com/codegangsta/inject/LICENSE diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/README.md b/vendor/github.com/codegangsta/inject/README.md similarity index 100% rename from Godeps/_workspace/src/github.com/codegangsta/inject/README.md rename to vendor/github.com/codegangsta/inject/README.md diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/inject.go b/vendor/github.com/codegangsta/inject/inject.go similarity index 100% rename from Godeps/_workspace/src/github.com/codegangsta/inject/inject.go rename to vendor/github.com/codegangsta/inject/inject.go diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/update_readme.sh b/vendor/github.com/codegangsta/inject/update_readme.sh similarity index 100% rename from Godeps/_workspace/src/github.com/codegangsta/inject/update_readme.sh rename to vendor/github.com/codegangsta/inject/update_readme.sh diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/.gitignore b/vendor/github.com/go-martini/martini/.gitignore similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/.gitignore rename to vendor/github.com/go-martini/martini/.gitignore diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/Godeps b/vendor/github.com/go-martini/martini/Godeps similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/Godeps rename to vendor/github.com/go-martini/martini/Godeps diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/LICENSE b/vendor/github.com/go-martini/martini/LICENSE similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/LICENSE rename to vendor/github.com/go-martini/martini/LICENSE diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/README.md b/vendor/github.com/go-martini/martini/README.md similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/README.md rename to vendor/github.com/go-martini/martini/README.md diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/env.go b/vendor/github.com/go-martini/martini/env.go similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/env.go rename to vendor/github.com/go-martini/martini/env.go diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/go_version.go b/vendor/github.com/go-martini/martini/go_version.go similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/go_version.go rename to vendor/github.com/go-martini/martini/go_version.go diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/logger.go b/vendor/github.com/go-martini/martini/logger.go similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/logger.go rename to vendor/github.com/go-martini/martini/logger.go diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/martini.go b/vendor/github.com/go-martini/martini/martini.go similarity index 98% rename from Godeps/_workspace/src/github.com/go-martini/martini/martini.go rename to vendor/github.com/go-martini/martini/martini.go index d9bd41f..44dbb8c 100644 --- a/Godeps/_workspace/src/github.com/go-martini/martini/martini.go +++ b/vendor/github.com/go-martini/martini/martini.go @@ -23,7 +23,7 @@ import ( "os" "reflect" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" + "github.com/codegangsta/inject" ) // Martini represents the top level web application. inject.Injector methods can be invoked to map services on a global level. diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/recovery.go b/vendor/github.com/go-martini/martini/recovery.go similarity index 97% rename from Godeps/_workspace/src/github.com/go-martini/martini/recovery.go rename to vendor/github.com/go-martini/martini/recovery.go index 4d0ee3f..fe0d918 100644 --- a/Godeps/_workspace/src/github.com/go-martini/martini/recovery.go +++ b/vendor/github.com/go-martini/martini/recovery.go @@ -8,7 +8,7 @@ import ( "net/http" "runtime" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" + "github.com/codegangsta/inject" ) const ( diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/response_writer.go b/vendor/github.com/go-martini/martini/response_writer.go similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/response_writer.go rename to vendor/github.com/go-martini/martini/response_writer.go diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/return_handler.go b/vendor/github.com/go-martini/martini/return_handler.go similarity index 93% rename from Godeps/_workspace/src/github.com/go-martini/martini/return_handler.go rename to vendor/github.com/go-martini/martini/return_handler.go index 8301753..4ea8f34 100644 --- a/Godeps/_workspace/src/github.com/go-martini/martini/return_handler.go +++ b/vendor/github.com/go-martini/martini/return_handler.go @@ -1,7 +1,7 @@ package martini import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" + "github.com/codegangsta/inject" "net/http" "reflect" ) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/router.go b/vendor/github.com/go-martini/martini/router.go similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/router.go rename to vendor/github.com/go-martini/martini/router.go diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/static.go b/vendor/github.com/go-martini/martini/static.go similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/static.go rename to vendor/github.com/go-martini/martini/static.go diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/wercker.yml b/vendor/github.com/go-martini/martini/wercker.yml similarity index 100% rename from Godeps/_workspace/src/github.com/go-martini/martini/wercker.yml rename to vendor/github.com/go-martini/martini/wercker.yml diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/LICENSE b/vendor/github.com/kardianos/osext/LICENSE similarity index 100% rename from Godeps/_workspace/src/github.com/kardianos/osext/LICENSE rename to vendor/github.com/kardianos/osext/LICENSE diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/osext.go b/vendor/github.com/kardianos/osext/osext.go similarity index 100% rename from Godeps/_workspace/src/github.com/kardianos/osext/osext.go rename to vendor/github.com/kardianos/osext/osext.go diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/osext_plan9.go b/vendor/github.com/kardianos/osext/osext_plan9.go similarity index 100% rename from Godeps/_workspace/src/github.com/kardianos/osext/osext_plan9.go rename to vendor/github.com/kardianos/osext/osext_plan9.go diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/osext_procfs.go b/vendor/github.com/kardianos/osext/osext_procfs.go similarity index 100% rename from Godeps/_workspace/src/github.com/kardianos/osext/osext_procfs.go rename to vendor/github.com/kardianos/osext/osext_procfs.go diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/osext_sysctl.go b/vendor/github.com/kardianos/osext/osext_sysctl.go similarity index 100% rename from Godeps/_workspace/src/github.com/kardianos/osext/osext_sysctl.go rename to vendor/github.com/kardianos/osext/osext_sysctl.go diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/osext_windows.go b/vendor/github.com/kardianos/osext/osext_windows.go similarity index 100% rename from Godeps/_workspace/src/github.com/kardianos/osext/osext_windows.go rename to vendor/github.com/kardianos/osext/osext_windows.go diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/.gitignore b/vendor/github.com/natefinch/lumberjack/.gitignore similarity index 100% rename from Godeps/_workspace/src/github.com/natefinch/lumberjack/.gitignore rename to vendor/github.com/natefinch/lumberjack/.gitignore diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/LICENSE b/vendor/github.com/natefinch/lumberjack/LICENSE similarity index 100% rename from Godeps/_workspace/src/github.com/natefinch/lumberjack/LICENSE rename to vendor/github.com/natefinch/lumberjack/LICENSE diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/README.md b/vendor/github.com/natefinch/lumberjack/README.md similarity index 100% rename from Godeps/_workspace/src/github.com/natefinch/lumberjack/README.md rename to vendor/github.com/natefinch/lumberjack/README.md diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/chown.go b/vendor/github.com/natefinch/lumberjack/chown.go similarity index 100% rename from Godeps/_workspace/src/github.com/natefinch/lumberjack/chown.go rename to vendor/github.com/natefinch/lumberjack/chown.go diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/chown_linux.go b/vendor/github.com/natefinch/lumberjack/chown_linux.go similarity index 100% rename from Godeps/_workspace/src/github.com/natefinch/lumberjack/chown_linux.go rename to vendor/github.com/natefinch/lumberjack/chown_linux.go diff --git a/Godeps/_workspace/src/github.com/natefinch/lumberjack/lumberjack.go b/vendor/github.com/natefinch/lumberjack/lumberjack.go similarity index 100% rename from Godeps/_workspace/src/github.com/natefinch/lumberjack/lumberjack.go rename to vendor/github.com/natefinch/lumberjack/lumberjack.go diff --git a/Godeps/_workspace/src/github.com/peterbourgon/g2s/.gitignore b/vendor/github.com/peterbourgon/g2s/.gitignore similarity index 100% rename from Godeps/_workspace/src/github.com/peterbourgon/g2s/.gitignore rename to vendor/github.com/peterbourgon/g2s/.gitignore diff --git a/Godeps/_workspace/src/github.com/peterbourgon/g2s/.travis.yml b/vendor/github.com/peterbourgon/g2s/.travis.yml similarity index 100% rename from Godeps/_workspace/src/github.com/peterbourgon/g2s/.travis.yml rename to vendor/github.com/peterbourgon/g2s/.travis.yml diff --git a/Godeps/_workspace/src/github.com/peterbourgon/g2s/LICENSE b/vendor/github.com/peterbourgon/g2s/LICENSE similarity index 100% rename from Godeps/_workspace/src/github.com/peterbourgon/g2s/LICENSE rename to vendor/github.com/peterbourgon/g2s/LICENSE diff --git a/Godeps/_workspace/src/github.com/peterbourgon/g2s/README.md b/vendor/github.com/peterbourgon/g2s/README.md similarity index 100% rename from Godeps/_workspace/src/github.com/peterbourgon/g2s/README.md rename to vendor/github.com/peterbourgon/g2s/README.md diff --git a/Godeps/_workspace/src/github.com/peterbourgon/g2s/fix.bash b/vendor/github.com/peterbourgon/g2s/fix.bash old mode 100644 new mode 100755 similarity index 100% rename from Godeps/_workspace/src/github.com/peterbourgon/g2s/fix.bash rename to vendor/github.com/peterbourgon/g2s/fix.bash diff --git a/Godeps/_workspace/src/github.com/peterbourgon/g2s/g2s.go b/vendor/github.com/peterbourgon/g2s/g2s.go similarity index 100% rename from Godeps/_workspace/src/github.com/peterbourgon/g2s/g2s.go rename to vendor/github.com/peterbourgon/g2s/g2s.go diff --git a/Godeps/_workspace/src/github.com/peterbourgon/g2s/safe.go b/vendor/github.com/peterbourgon/g2s/safe.go similarity index 100% rename from Godeps/_workspace/src/github.com/peterbourgon/g2s/safe.go rename to vendor/github.com/peterbourgon/g2s/safe.go diff --git a/Godeps/_workspace/src/github.com/peterbourgon/g2s/types.go b/vendor/github.com/peterbourgon/g2s/types.go similarity index 100% rename from Godeps/_workspace/src/github.com/peterbourgon/g2s/types.go rename to vendor/github.com/peterbourgon/g2s/types.go diff --git a/vendor/github.com/samuel/go-zookeeper/LICENSE b/vendor/github.com/samuel/go-zookeeper/LICENSE new file mode 100644 index 0000000..bc00498 --- /dev/null +++ b/vendor/github.com/samuel/go-zookeeper/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2013, Samuel Stauffer +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of the author nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/conn.go b/vendor/github.com/samuel/go-zookeeper/zk/conn.go similarity index 100% rename from Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/conn.go rename to vendor/github.com/samuel/go-zookeeper/zk/conn.go diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/constants.go b/vendor/github.com/samuel/go-zookeeper/zk/constants.go similarity index 100% rename from Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/constants.go rename to vendor/github.com/samuel/go-zookeeper/zk/constants.go diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock.go b/vendor/github.com/samuel/go-zookeeper/zk/lock.go similarity index 100% rename from Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock.go rename to vendor/github.com/samuel/go-zookeeper/zk/lock.go diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/server_help.go b/vendor/github.com/samuel/go-zookeeper/zk/server_help.go similarity index 100% rename from Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/server_help.go rename to vendor/github.com/samuel/go-zookeeper/zk/server_help.go diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/server_java.go b/vendor/github.com/samuel/go-zookeeper/zk/server_java.go similarity index 100% rename from Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/server_java.go rename to vendor/github.com/samuel/go-zookeeper/zk/server_java.go diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs.go b/vendor/github.com/samuel/go-zookeeper/zk/structs.go similarity index 100% rename from Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs.go rename to vendor/github.com/samuel/go-zookeeper/zk/structs.go diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/tracer.go b/vendor/github.com/samuel/go-zookeeper/zk/tracer.go similarity index 100% rename from Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/tracer.go rename to vendor/github.com/samuel/go-zookeeper/zk/tracer.go diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/util.go b/vendor/github.com/samuel/go-zookeeper/zk/util.go similarity index 100% rename from Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/util.go rename to vendor/github.com/samuel/go-zookeeper/zk/util.go diff --git a/webapp/app/components/service-form/service-form-ctrl.js b/webapp/app/components/service-form/service-form-ctrl.js index 80a32e4..d64a18b 100644 --- a/webapp/app/components/service-form/service-form-ctrl.js +++ b/webapp/app/components/service-form/service-form-ctrl.js @@ -30,7 +30,9 @@ module.exports = ["$scope", "$modal", "$rootScope", function ($scope, $modal, $r $scope.loading = true; $scope.makeRequest({ id: $scope.service.id, - acl: $scope.service.acl + config: { + Acl: $scope.service.acl + } }) .then(handleSuccess, handleError); };